diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fd00f05..ec5c216 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -32,4 +32,15 @@ jobs: node-version: 24 - run: corepack enable && corepack install - run: command -v xcodegen >/dev/null || brew install xcodegen + # The runner image ships several Xcodes and defaults to an older one than + # developer machines use. That skew is what let a Sendable data-race error + # reach main-bound code while compiling clean locally, so pick the newest + # installed and print it — a native failure should never be a mystery about + # which compiler ran. + - name: Select and report the Xcode in use + run: | + latest=$(ls -d /Applications/Xcode*.app | sort -V | tail -1) + echo "Selecting $latest" + sudo xcode-select -s "$latest" + xcodebuild -version - run: pnpm quality:native diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml new file mode 100644 index 0000000..ce806ad --- /dev/null +++ b/.github/workflows/pages.yml @@ -0,0 +1,37 @@ +name: Pages + +# The public site is static files. GitHub Pages serves them so the project keeps +# no infrastructure of its own; the iPhone app depends on none of this. +on: + push: + branches: [main] + paths: + - "public/**" + - ".github/workflows/pages.yml" + workflow_dispatch: + +permissions: + contents: read + pages: write + id-token: write + +# One deployment at a time, and never cancel one midway. +concurrency: + group: pages + cancel-in-progress: false + +jobs: + deploy: + runs-on: ubuntu-latest + timeout-minutes: 10 + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + steps: + - uses: actions/checkout@v6 + - uses: actions/configure-pages@v5 + - uses: actions/upload-pages-artifact@v4 + with: + path: public + - id: deployment + uses: actions/deploy-pages@v4 diff --git a/.gitignore b/.gitignore index 774f152..89e83cd 100644 --- a/.gitignore +++ b/.gitignore @@ -42,3 +42,6 @@ next-env.d.ts /outputs/ /work/ *.tsbuildinfo + +# xcode build output +/ios/build/ diff --git a/.prettierignore b/.prettierignore deleted file mode 100644 index 4b56525..0000000 --- a/.prettierignore +++ /dev/null @@ -1,3 +0,0 @@ -worker-configuration.d.ts -worker/agent-edge.mjs -worker/agent-edge.d.mts diff --git a/AGENTS.md b/AGENTS.md index 0679158..f4916c0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,6 +11,10 @@ - Keep recorded, calculated, authored, adjusted, and unavailable values visibly distinct. - Use pnpm and the committed `pnpm-lock.yaml`. -- Run `pnpm run check` before broader release validation. -- Do not deploy, migrate D1, change OAuth configuration, or change production - secrets without explicit approval. +- Run `pnpm run check` before broader release validation. For any change under + `ios/`, run `pnpm quality:native` too — it is the gate CI runs on macOS + (xcodegen, simulator unit and UI tests, release build, coverage floor). +- Setline has no backend. Do not reintroduce an account, a server, or a + network call in the workout path. +- Setline uses no Cloudflare, no database and no hosting account. Do not add one. +- Do not change DNS or publish a release without explicit approval. diff --git a/PROJECT_STATUS.md b/PROJECT_STATUS.md index 9bb9f92..0dcb372 100644 --- a/PROJECT_STATUS.md +++ b/PROJECT_STATUS.md @@ -4,26 +4,80 @@ Setline helps people execute a structured workout programme precisely without referring to another document or deciding what to do between sets. The user controls the programme; Setline presents the current action, records explicit results, controls rest, and separates recorded values from calculations. -The first release is an iOS-native workout player with a Cloudflare Worker API backend. It includes -Sarthak’s dated 12-week strength, cardio, and mobility programme, device-first -session execution, optional Google sign-in with a private account copy, basic -history, and progress. It excludes coaching, automatic programme generation, -social features, meal/recovery tracking, sensors, Apple Health, and Apple Watch. +The first release is an iOS-native workout player with no backend of its own. It +includes Sarthak’s dated 12-week strength, cardio, and mobility +programme resolved natively on device, structured set targets, multi-segment set +recording, a set timer alongside the rest timer, a bundled movement catalogue +spanning strength, stamina, mobility and flexibility, and per-exercise measured +current values against authored targets. It excludes coaching, automatic +programme generation, social features, meal/recovery tracking, and sensors. + +Apple Health, Apple Watch, CrossFit session formats, range-of-motion +assessments, iCloud sync, and on-device workout generation are planned rather than +shipped. Until iCloud sync lands, training lives only on the device that recorded +it, and the versioned JSON export is the only way to move or back it up. ## Dependencies -- SwiftUI native iPhone app for workout execution. -- Cloudflare Workers for the API backend (auth, state sync, MCP, agent surfaces). -- Vite for test module loading. -- Better Auth with Google OAuth and native Sign in with Apple for optional - identity; existing accounts use an explicit linking flow rather than - email-based implicit linking. -- Cloudflare Workers and D1 for authenticated, user-scoped state. -- Browser `localStorage`, Service Worker, vibration, and installation APIs where supported. -- No email provider, paid service, sensor, or native runtime dependency. +- SwiftUI native iPhone app for workout execution, with Swift Charts for trends + and local notifications for rest completion. +- A JSON document in the app’s own container. No database, no account, no request + during a workout. +- GitHub Pages for the static public site and its agent surfaces. Nothing the app + does depends on it, and it costs no account to maintain. +- Node’s built-in test runner for the static-surface contracts; XCTest for + everything the app does. +- No backend, email provider, paid service, sensor, or third-party runtime + dependency. ## Timeline +- 2026-08-16 — replaced the placeholder privacy notice, terms and changelog with + real pages on the tracked palette. The privacy notice had still claimed that + optional Google sign-in stores a private user-scoped copy, which the backend + removal had made false; it now states that the app collects nothing and makes + no network requests, and it discloses this website's PostHog and portfolio-strip + scripts for the first time. Terms gained the health disclaimer, the + recorded-versus-calculated distinction, and the bundled-programme caveat. + Restored the `quality:native` script that CI calls and raised its coverage floor + from 65.3% to 83.8% against a measured 84.1628%. The never-completed + Google-auth OpenSpec change and the account-data-deletion spec are archived. + +- 2026-08-16 — left Cloudflare entirely. Deleted the live `setline` Worker and the + `setline` D1 database, which held zero rows in every table because no one ever + signed in. Removed wrangler, the Cloudflare-only `_headers` and `_redirects`, and + the deploy script. The public site is now published by GitHub Pages from + `public/` with its own CNAME. Setline holds no Cloudflare resources and no + hosting account. `setline.significanthobbies.com` returns 530 until a CNAME to + `significant-hobbies.github.io` is added and Pages publishes. + +- 2026-08-16 — removed the Cloudflare Worker backend and every trace of the + account layer: Better Auth with Google and Apple sign-in, D1-backed private + state, the MCP read surface, the whole-document sync and conflict flow, 3,277 + lines of superseded TypeScript, and 12 test files covering it. Setline is now + device-first with no server of its own. The public site became static Pages + content carrying its own headers, and the service worker was replaced with one + that evicts the shell of the deleted web app. The sync invariant that the + removed cloud type used to guard is preserved as a document-level contract. + +- 2026-08-16 — replaced the placeholder landing page with a real one built to the + fleet landing standard on the app's own tracked palette: hero, product + screenshots, four-pillar breakdown, a refusals section, fit guidance and a FAQ, + with honest pre-release status and no store link. Agent-indexing surfaces were + rewritten to match, and a test now holds the sitemap, the agent catalogue and + the files on disk to one another so no surface can drift. Removed all six + duplicated blocks in the native sources and split the two longest new + functions; duplication is now zero. + +- 2026-08-16 — replaced free-text set targets with a structured target model and + ported the dated 12-week programme into the native app, which previously + shipped only a two-template placeholder. Added a bundled movement catalogue + across all four pillars, per-exercise measured current values with authored + targets and trend charts, repeatable multi-segment set recording with a + shorthand parser, a set timer independent of rest, rest-completion + notifications, and authored double-progression rules. Version 2 of the local + document reads version 1 without losing recorded work. + - 2026-08-15 — removed the Next.js web app and went iOS-first. The Cloudflare Worker API backend (auth, native state, MCP, agent-edge) remains unchanged. Static HTML pages in public/ replace the web UI. Shared business logic moved from app/lib/ to src/lib/. - 2026-08-12 — shipped the native account connection path on the personal @@ -90,13 +144,17 @@ social features, meal/recovery tracking, sensors, Apple Health, and Apple Watch. - `ios/` — native SwiftUI iPhone beta for local-first workout execution; App Store Connect/TestFlight transport remains manual. -- Static public pages (index, privacy, terms, changelog) served from public/ via the Worker ASSETS binding. +- Static public site in `public/` (landing, privacy, terms, changelog) plus the + agent surfaces `index.md`, `llms.txt`, `llms-full.txt`, `sitemap.xml`, + `robots.txt` and `/api/ai`, published by GitHub Pages on push to `main`. The + canonical hostname is dark until its DNS record points at GitHub Pages. - [Public GitHub repository](https://github.com/Significant-Hobbies/setline) — canonical source, product planning, and issue owner. -- `https://setline.significanthobbies.com` — live Cloudflare Worker production - surface. +- `https://setline.significanthobbies.com` — canonical public surface, pending a + DNS record to GitHub Pages. - [Private Sites deployment](https://setline-workout.sarthak927.chatgpt.site) — - owner-only rollback copy. + owner-gated (401) survivor of the removed web app. It is not a rollback path + for the iPhone app and nothing depends on it. ## Features (shipped) @@ -105,8 +163,28 @@ social features, meal/recovery tracking, sensors, Apple Health, and Apple Watch. timestamp-derived rest, relaunch recovery, planning, history, progression, data transfer, accessibility, simulator tests, and personal-team archiving. - Public editorial product changelog at `/changelog`. +- Landing page stating audience, outcome, the four pillars, what the product + refuses to do, poor-fit cases and real FAQs, with product screenshots and no + claim of App Store availability. - Dated seven-day schedule for the supplied 12-week strength, cardio, and - mobility programme. + mobility programme, resolved natively for every one of its 84 days. +- Structured set targets carrying rep ranges, absolute/relative/bodyweight/assisted + load, reps in reserve, tempo, per-side work, and rest as a band rather than a + scalar; warm-up sets are excluded from volume, records, and progression. +- Bundled movement catalogue with stable identities, muscle groups, equipment, + and per-movement measurable metrics across strength, stamina, mobility, and + flexibility, plus the CrossFit movement vocabulary. +- Per-exercise measured current values (estimated 1RM, top set load, max + repetitions, best hold, longest distance, best pace, range of motion), each + citing the session that produced it, against authored targets with progress, + weekly rate, projected arrival, and trend charts. +- Repeatable multi-segment set recording so `5 reps × 40 kg` followed by + `2 reps × 30 kg` records as one set, with a tested shorthand parser that shows + its interpretation before anything is recorded. +- Set timer recording time under load independently of the rest timer. +- Rest-completion local notification so the timer survives leaving the app. +- Authored double-progression rules per movement, including the plan's own + increments and its below-range regression case. - Exact authored exercise and set order across Upper, Lower, easy cardio, hard cardio, mobility, preparation, and cooldown work. - Week-aware RDL volume, hard-cardio rounds, and pull-up checkpoints. @@ -118,29 +196,23 @@ social features, meal/recovery tracking, sensors, Apple Health, and Apple Watch. - Device-local active-session continuity and workout history. - Versioned JSON download plus validated, bounded import preview and explicit whole-state replacement for local workout data. -- Optional Google sign-in with one private, user-scoped D1 state copy. -- Fresh-session-protected self-service account deletion that removes linked - auth records and the private workout copy through existing D1 cascades, then - reports browser cleanup separately. -- Device-first changes with offline retry and deterministic whole-state - reconciliation. - Explicit state validation that preserves authored exercise and set order. -- Public privacy notice and terms of use. +- Public privacy notice stating that the app collects nothing and disclosing the + website's own third-party scripts, terms of use carrying the health disclaimer, + and a dated changelog that records removals as well as releases. A test reads + the script origins out of the markup and fails if the notice does not name them. - Honest summary with separate warm-up/working volume and calculated provenance. -- Basic bench target context plus local recorded-volume signal. - Deterministic progression recommendations from the latest comparable completed session, with calculated provenance and explicit session-only Accept, Edit, or Keep current decisions. -- Responsive phone, tablet, and desktop layouts. -- PWA manifest, install metadata, service-worker shell, and offline-friendly local operation. - Immutable authored plans with a separate session execution queue. - Partial and drop-set segments such as `60 kg × 5` followed by `50 kg × 3`. - Session-only extra sets, explicit Do later deferral, and preserved planned and actual execution positions. - Authored, adjusted, and actual rest retained separately from wall-clock completion and next-start timestamps. -- Detailed per-set execution history preserved on device and in authenticated - cloud state. +- Detailed per-set execution history preserved on device, with a versioned JSON + export and a bounded import preview as the only way data leaves or enters. - Recorded-history analytics with normalized exercise identity, metric-aware newest-eight trends, lifetime bests and volume, workout aggregates, and represented bundled programme-week summaries; custom workouts stay separate @@ -148,14 +220,10 @@ social features, meal/recovery tracking, sensors, Apple Health, and Apple Watch. - Bounded custom workout templates with ordered exercise authoring, edit, independent duplication from bundled or custom workouts, confirmed deletion, and the existing offline-first workout player. -- Custom templates included in private whole-state sync and versioned JSON - backup/restore, while active sessions and history retain immutable snapshots. - One named 1–16 week custom programme with explicit seven-day assignments, confirmed copy/shrink/delete actions, and enabled or paused state. - Calendar-correct Today resolution for scheduled custom workouts and explicit unplanned days, with scheduled sessions retaining programme week/day context. -- Programme assignments reference custom templates, clear atomically when a - template is deleted, and travel in private sync and JSON backup/restore. ## Work queue diff --git a/README.md b/README.md index 538108d..191e57e 100644 --- a/README.md +++ b/README.md @@ -1,32 +1,52 @@ # Setline -Setline is a mobile-first workout execution tracker for following an authored -programme, recording actual sets, controlling rest, and preserving detailed -history without depending on a gym connection. Workouts remain device-first; -optional Google sign-in keeps one private, user-scoped D1 copy in sync. +Setline is an iPhone training tracker for following an authored programme, +recording actual sets, controlling rest, and measuring each exercise against a +target you set. It has no backend: everything runs and records on the device, and +the versioned JSON export is the only way data moves. -Production: [setline.significanthobbies.com](https://setline.significanthobbies.com) +The iPhone app lives in [`ios/`](./ios). The public site is static files in +[`public/`](./public) published by GitHub Pages, and nothing the app does depends +on it. There is no backend and no hosting account to maintain. + +Site: [setline.significanthobbies.com](https://setline.significanthobbies.com) — +dark until its DNS record points at GitHub Pages ([#43](https://github.com/Significant-Hobbies/setline/issues/43)). ## Local development +The app: + +```bash +./ios/scripts/check.sh # xcodegen, simulator tests, release build +``` + +The public site: + ```bash pnpm install -pnpm run dev +pnpm run check # static-surface contracts and code health +python3 -m http.server -d public 8080 ``` ## Checks ```bash -pnpm run check +pnpm run check # static surfaces and code health +pnpm quality:native # xcodegen, simulator tests, release build, coverage ``` -The release includes the owner-authored 12-week programme, custom workout -templates, one bounded multi-week custom programme, flexible execution, -device-local continuity, versioned whole-state backup/restore, optional private -account sync, history, progress, and explicit deterministic session-only -progression recommendations. Multiple programme libraries, arbitrary workout -import, reminders, coaching, sensors, health integrations, social features, -and full analytics remain deferred. +The release includes the owner-authored dated 12-week programme, structured set +targets, a bundled four-pillar movement catalogue, per-exercise measured current +values against authored targets, multi-segment set recording with a shorthand +parser, a set timer alongside rest, custom workout templates, one bounded +multi-week custom programme, device-local continuity, versioned whole-state +backup/restore, history, progress, and deterministic session-only progression +recommendations. + +Deferred: iCloud sync across devices, Apple Health, Apple Watch, CrossFit +session formats, range-of-motion assessments, on-device workout generation, +coaching, and social features. Until iCloud sync lands, training lives only on +the device that recorded it and the JSON export is the only backup. Source, product planning, and work tracking live in this repository. Fleet Workspace consumes only catalog and operational links. diff --git a/eslint.config.mjs b/eslint.config.mjs index c598cac..011c201 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -1,12 +1,7 @@ import { defineConfig, globalIgnores } from "eslint/config"; const eslintConfig = defineConfig([ - globalIgnores([ - "dist/**", - "node_modules/**", - "worker-configuration.d.ts", - "worker/agent-edge.d.mts", - ]), + globalIgnores(["dist/**", "node_modules/**"]), ]); export default eslintConfig; diff --git a/ios/Setline.xcodeproj/project.pbxproj b/ios/Setline.xcodeproj/project.pbxproj index 1cceeb3..e468508 100644 --- a/ios/Setline.xcodeproj/project.pbxproj +++ b/ios/Setline.xcodeproj/project.pbxproj @@ -8,23 +8,31 @@ /* Begin PBXBuildFile section */ 06B31DF75BFAA837FA9FAAA6 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 6BF346E7B39E1FEE8CD50C7C /* Assets.xcassets */; }; + 0C260E4D0C6C142C45B3AC6D /* HistoryViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 18C887472FBEDF36FD127C32 /* HistoryViews.swift */; }; + 0FA5FD50B707EF422848A2E6 /* Targets.swift in Sources */ = {isa = PBXBuildFile; fileRef = B888AC3A36F08B6334AE20CA /* Targets.swift */; }; + 171B1B9E0DDE084379BB9DF8 /* RestNotifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = C9B9735779088EF43C24F335 /* RestNotifier.swift */; }; 1FA5DF9F89B308A82207E40B /* SetlineCore.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 0DE14EAFD3C581FCA8D09CA7 /* SetlineCore.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; 309CBBBA2928642CBD999F67 /* Progression.swift in Sources */ = {isa = PBXBuildFile; fileRef = 594DC48A6CD7B68259549A12 /* Progression.swift */; }; + 326CD8AE0B8D86B2954E301E /* PlanViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 396D4D1100A1E0FACCD8953A /* PlanViews.swift */; }; + 3BBA35B8612998A8EB3205F2 /* ExerciseCatalogue.swift in Sources */ = {isa = PBXBuildFile; fileRef = 602F0E123ED63C93EDDBA179 /* ExerciseCatalogue.swift */; }; 3CE2DEDE101DA826A45AC5F8 /* Design.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3C2CB1821B5B5AE4C75873C6 /* Design.swift */; }; + 401D75E9685D1937CEA9AF16 /* SetEntryParser.swift in Sources */ = {isa = PBXBuildFile; fileRef = CE77BBBECF6D7ED1F7E8047E /* SetEntryParser.swift */; }; + 5FDD1235ADE7D25DC029C4F6 /* TwelveWeekProgramme.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4833E444B40BC982AC57AACC /* TwelveWeekProgramme.swift */; }; 66E5690BB3806C5D8CF41CF8 /* SetlineUITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FEE9CEC1CE889DCD183F4CF7 /* SetlineUITests.swift */; }; 677B5B2EB644215DBE6CE4D0 /* SetlineCoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1211B40E359F4BBD82A557A9 /* SetlineCoreTests.swift */; }; 7DFE7762F43344AFC746CDC6 /* Domain.swift in Sources */ = {isa = PBXBuildFile; fileRef = B0859DE334CC4D97FFE0DFDA /* Domain.swift */; }; 8AEB42E3793E01E4E40F67FF /* SetlineCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0DE14EAFD3C581FCA8D09CA7 /* SetlineCore.framework */; }; + 8CCC1E8C5F455AF8C9B8EFD7 /* ExercisesView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5D9600ED385C5C29CB0702D3 /* ExercisesView.swift */; }; + 905B35BB3B49C692703FAA7B /* TodayResolution.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6E6AEE25CFD26FE63620A033 /* TodayResolution.swift */; }; A748F947702FBF73CBE681AD /* WorkoutPlayerView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 818A8EDA05B5D0B4E9DE47B3 /* WorkoutPlayerView.swift */; }; A949A76428AB4118FB259A70 /* SecondaryViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = DFAE6EB21BC26F97140F4FEE /* SecondaryViews.swift */; }; BE5FDC83C2B64F526F64979C /* RootView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 824EFFB1023C857CE4F1FE1C /* RootView.swift */; }; C66AD84C2D8FAD24149B2445 /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = F52F5D64B932696BAEDEE0AC /* PrivacyInfo.xcprivacy */; }; C7E1EDD15D038B815CB78D27 /* SetlineApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 608F81A574360691A58B8581 /* SetlineApp.swift */; }; - C953D5949A40703738078819 /* CloudSync.swift in Sources */ = {isa = PBXBuildFile; fileRef = F51113C8A77901F17242774D /* CloudSync.swift */; }; D9647D921553DE22AB36226A /* SetlineCore.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = 0DE14EAFD3C581FCA8D09CA7 /* SetlineCore.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; }; + E5FAA9DE6E6F5CCBE9E4343F /* Goals.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02194DFCF1365CCD34525231 /* Goals.swift */; }; E85DFE444A157EC32C671B9B /* AppModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = B839442BFCCB000A563CD704 /* AppModel.swift */; }; EC589E605EEE16DA5E0F613E /* SetlineCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0DE14EAFD3C581FCA8D09CA7 /* SetlineCore.framework */; }; - EF0C5CDD67CA95C3309607B0 /* NativeAccountClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 27A4007C0EBCEA2C015905F8 /* NativeAccountClient.swift */; }; F5D0CC71C826F541575E7D99 /* Persistence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65E8358BE39000A0F7E1BB90 /* Persistence.swift */; }; /* End PBXBuildFile section */ @@ -78,25 +86,33 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + 02194DFCF1365CCD34525231 /* Goals.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Goals.swift; sourceTree = ""; }; 0DE14EAFD3C581FCA8D09CA7 /* SetlineCore.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = SetlineCore.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 1211B40E359F4BBD82A557A9 /* SetlineCoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SetlineCoreTests.swift; sourceTree = ""; }; 15268979096821BD9ABB22E0 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = ""; }; - 27A4007C0EBCEA2C015905F8 /* NativeAccountClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeAccountClient.swift; sourceTree = ""; }; + 18C887472FBEDF36FD127C32 /* HistoryViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HistoryViews.swift; sourceTree = ""; }; + 396D4D1100A1E0FACCD8953A /* PlanViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PlanViews.swift; sourceTree = ""; }; 3C2CB1821B5B5AE4C75873C6 /* Design.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Design.swift; sourceTree = ""; }; 40CADB4F69054A14B366A16D /* Setline.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Setline.entitlements; sourceTree = ""; }; + 4833E444B40BC982AC57AACC /* TwelveWeekProgramme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TwelveWeekProgramme.swift; sourceTree = ""; }; 594DC48A6CD7B68259549A12 /* Progression.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Progression.swift; sourceTree = ""; }; + 5D9600ED385C5C29CB0702D3 /* ExercisesView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExercisesView.swift; sourceTree = ""; }; + 602F0E123ED63C93EDDBA179 /* ExerciseCatalogue.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ExerciseCatalogue.swift; sourceTree = ""; }; 608F81A574360691A58B8581 /* SetlineApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SetlineApp.swift; sourceTree = ""; }; 65E8358BE39000A0F7E1BB90 /* Persistence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Persistence.swift; sourceTree = ""; }; 6BF346E7B39E1FEE8CD50C7C /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 6E6AEE25CFD26FE63620A033 /* TodayResolution.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TodayResolution.swift; sourceTree = ""; }; 818A8EDA05B5D0B4E9DE47B3 /* WorkoutPlayerView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WorkoutPlayerView.swift; sourceTree = ""; }; 824EFFB1023C857CE4F1FE1C /* RootView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RootView.swift; sourceTree = ""; }; B0859DE334CC4D97FFE0DFDA /* Domain.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Domain.swift; sourceTree = ""; }; B1F5DA4EB37759476E57B69F /* SetlineUITests.xctest */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.cfbundle; path = SetlineUITests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; B7B0A3E4EF45F3C038E3C265 /* SetlineCoreTests.xctest */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.cfbundle; path = SetlineCoreTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; }; B839442BFCCB000A563CD704 /* AppModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppModel.swift; sourceTree = ""; }; + B888AC3A36F08B6334AE20CA /* Targets.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Targets.swift; sourceTree = ""; }; BA87F29CCAE78D4F24E75B1F /* Setline.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = Setline.app; sourceTree = BUILT_PRODUCTS_DIR; }; + C9B9735779088EF43C24F335 /* RestNotifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RestNotifier.swift; sourceTree = ""; }; + CE77BBBECF6D7ED1F7E8047E /* SetEntryParser.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SetEntryParser.swift; sourceTree = ""; }; DFAE6EB21BC26F97140F4FEE /* SecondaryViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SecondaryViews.swift; sourceTree = ""; }; - F51113C8A77901F17242774D /* CloudSync.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CloudSync.swift; sourceTree = ""; }; F52F5D64B932696BAEDEE0AC /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; path = PrivacyInfo.xcprivacy; sourceTree = ""; }; FEE9CEC1CE889DCD183F4CF7 /* SetlineUITests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SetlineUITests.swift; sourceTree = ""; }; /* End PBXFileReference section */ @@ -135,8 +151,11 @@ children = ( B839442BFCCB000A563CD704 /* AppModel.swift */, 3C2CB1821B5B5AE4C75873C6 /* Design.swift */, + 5D9600ED385C5C29CB0702D3 /* ExercisesView.swift */, + 18C887472FBEDF36FD127C32 /* HistoryViews.swift */, 15268979096821BD9ABB22E0 /* Info.plist */, - 27A4007C0EBCEA2C015905F8 /* NativeAccountClient.swift */, + 396D4D1100A1E0FACCD8953A /* PlanViews.swift */, + C9B9735779088EF43C24F335 /* RestNotifier.swift */, 824EFFB1023C857CE4F1FE1C /* RootView.swift */, DFAE6EB21BC26F97140F4FEE /* SecondaryViews.swift */, 40CADB4F69054A14B366A16D /* Setline.entitlements */, @@ -162,10 +181,15 @@ 5745423AFF1E15935A399E22 /* SetlineCore */ = { isa = PBXGroup; children = ( - F51113C8A77901F17242774D /* CloudSync.swift */, B0859DE334CC4D97FFE0DFDA /* Domain.swift */, + 602F0E123ED63C93EDDBA179 /* ExerciseCatalogue.swift */, + 02194DFCF1365CCD34525231 /* Goals.swift */, 65E8358BE39000A0F7E1BB90 /* Persistence.swift */, 594DC48A6CD7B68259549A12 /* Progression.swift */, + CE77BBBECF6D7ED1F7E8047E /* SetEntryParser.swift */, + B888AC3A36F08B6334AE20CA /* Targets.swift */, + 6E6AEE25CFD26FE63620A033 /* TodayResolution.swift */, + 4833E444B40BC982AC57AACC /* TwelveWeekProgramme.swift */, ); name = SetlineCore; path = Sources/SetlineCore; @@ -356,7 +380,10 @@ files = ( E85DFE444A157EC32C671B9B /* AppModel.swift in Sources */, 3CE2DEDE101DA826A45AC5F8 /* Design.swift in Sources */, - EF0C5CDD67CA95C3309607B0 /* NativeAccountClient.swift in Sources */, + 8CCC1E8C5F455AF8C9B8EFD7 /* ExercisesView.swift in Sources */, + 0C260E4D0C6C142C45B3AC6D /* HistoryViews.swift in Sources */, + 326CD8AE0B8D86B2954E301E /* PlanViews.swift in Sources */, + 171B1B9E0DDE084379BB9DF8 /* RestNotifier.swift in Sources */, BE5FDC83C2B64F526F64979C /* RootView.swift in Sources */, A949A76428AB4118FB259A70 /* SecondaryViews.swift in Sources */, C7E1EDD15D038B815CB78D27 /* SetlineApp.swift in Sources */, @@ -376,10 +403,15 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( - C953D5949A40703738078819 /* CloudSync.swift in Sources */, 7DFE7762F43344AFC746CDC6 /* Domain.swift in Sources */, + 3BBA35B8612998A8EB3205F2 /* ExerciseCatalogue.swift in Sources */, + E5FAA9DE6E6F5CCBE9E4343F /* Goals.swift in Sources */, F5D0CC71C826F541575E7D99 /* Persistence.swift in Sources */, 309CBBBA2928642CBD999F67 /* Progression.swift in Sources */, + 401D75E9685D1937CEA9AF16 /* SetEntryParser.swift in Sources */, + 0FA5FD50B707EF422848A2E6 /* Targets.swift in Sources */, + 905B35BB3B49C692703FAA7B /* TodayResolution.swift in Sources */, + 5FDD1235ADE7D25DC029C4F6 /* TwelveWeekProgramme.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/ios/Sources/Setline/AppModel.swift b/ios/Sources/Setline/AppModel.swift index 4f51703..c3c5e88 100644 --- a/ios/Sources/Setline/AppModel.swift +++ b/ios/Sources/Setline/AppModel.swift @@ -1,113 +1,112 @@ -import AuthenticationServices import Foundation import Observation import SetlineCore +/// Owns the one Setline document and every action that changes it. +/// +/// Setline is device-first: there is no account, no server, and no request in the +/// middle of a set. Every mutation writes to local storage and nothing else. @MainActor @Observable final class AppModel { - private(set) var document: SetlineDocument = .sample + private(set) var document: SetlineDocument = .initial var isLoading = true var isWorkoutPresented = false var selectedTab = 0 var message: String? var importPreview: SetlineDocument? var isImportConfirmationPresented = false - var account: SetlineAccount? - var isAccountBusy = false - var cloudConflict: SetlineCloudSnapshot? - var accountMessage: String? + /// Set only by a launch argument, so a specific exercise can be opened for + /// screenshot capture without a person tapping through the interface. + private(set) var demoExerciseName: String? private let store: SetlineStore - private let accountClient: SetlineNativeAccountClient - private let webAuthenticator: SetlineWebAuthenticator - private var remoteRevision: Int? - private var syncRequested = false - private var isSyncing = false - private var deferredConflict: SetlineCloudSnapshot? + private let restNotifier: RestNotifier - init( - store: SetlineStore = SetlineStore(), - accountClient: SetlineNativeAccountClient = SetlineNativeAccountClient(), - webAuthenticator: SetlineWebAuthenticator = SetlineWebAuthenticator() - ) { + init(store: SetlineStore = SetlineStore(), restNotifier: RestNotifier = RestNotifier()) { self.store = store - self.accountClient = accountClient - self.webAuthenticator = webAuthenticator - if ProcessInfo.processInfo.arguments.contains("--plan-demo") { selectedTab = 1 } - if ProcessInfo.processInfo.arguments.contains("--history-demo") { selectedTab = 2 } - if ProcessInfo.processInfo.arguments.contains("--account-demo") || - ProcessInfo.processInfo.arguments.contains("--account-conflict-demo") { - selectedTab = 3 + self.restNotifier = restNotifier + let arguments = ProcessInfo.processInfo.arguments + if arguments.contains("--plan-demo") { selectedTab = 1 } + if arguments.contains("--history-demo") { selectedTab = 2 } + if arguments.contains("--exercises-demo") { selectedTab = 4 } + if let index = arguments.firstIndex(of: "--exercise-detail-demo"), + arguments.indices.contains(index + 1) { + selectedTab = 4 + demoExerciseName = arguments[index + 1] } } func load() async { defer { isLoading = false } + let arguments = ProcessInfo.processInfo.arguments do { - if ProcessInfo.processInfo.arguments.contains("--fresh-demo") { - var sample = SetlineDocument.sample - sample.programme = nil - document = sample + if arguments.contains("--evidence-demo") { + document = .demoWithEvidence + } else if arguments.contains("--ui-demo") { + // A fixed, date-independent fixture so interface tests do not + // depend on which day of the authored block today happens to be. + var demo = SetlineDocument.sample + demo.programme = .none + document = demo + } else if arguments.contains("--fresh-demo") { + document = .initial } else { document = try await store.load() } - if ProcessInfo.processInfo.arguments.contains("--active-demo"), document.activeSession == nil, - let first = document.templates.first { - try document.startWorkout(templateID: first.id) - isWorkoutPresented = true - } - if ProcessInfo.processInfo.arguments.contains("--rest-demo"), document.activeSession == nil, - let first = document.templates.first { - try document.startWorkout(templateID: first.id) - try document.completeCurrent(with: [SetSegment(weight: 40, repetitions: 8)]) - isWorkoutPresented = true - } - if ProcessInfo.processInfo.arguments.contains("--account-demo") { - account = SetlineAccount(name: "Sarthak", email: "sarthak@example.com", providers: ["google"]) - document.syncState = .synced - document.lastSyncedAt = Date().addingTimeInterval(-240) - } else if ProcessInfo.processInfo.arguments.contains("--account-conflict-demo") { - account = SetlineAccount(name: "Sarthak", email: "sarthak@example.com", providers: ["google"]) - document.syncState = .conflict - var accountDocument = document - if let template = accountDocument.templates.first { - accountDocument.history = [ - WorkoutSession( - templateID: template.id, - templateName: template.name, - startedAt: Date().addingTimeInterval(-3_600), - completedAt: Date().addingTimeInterval(-2_700), - steps: [] - ), - ] - } - cloudConflict = SetlineCloudSnapshot( - document: SetlineCloudDocument(document: accountDocument), - revision: 3 - ) - } else if !ProcessInfo.processInfo.arguments.contains("--fresh-demo") { - await restoreAccount() - } + try startDemoSessionIfRequested(arguments) } catch { - document = .sample + document = .initial message = error.localizedDescription } } - func startWorkout(_ template: WorkoutTemplate) async { + private func startDemoSessionIfRequested(_ arguments: [String]) throws { + guard arguments.contains("--active-demo") || arguments.contains("--rest-demo") else { return } + guard document.activeSession == nil, let resolved = document.session() else { return } + try document.startWorkout( + template: resolved.template, + programmeWeek: resolved.programmeWeek, + programmeDayIndex: resolved.programmeDayIndex + ) + if arguments.contains("--rest-demo") { + // Advance to the first step that authors a rest period, since + // preparation work deliberately flows straight through. + while document.activeSession?.rest == nil, document.activeSession?.currentStep != nil { + try document.completeCurrent( + with: [SetSegment(weight: 40, repetitions: 8, durationSeconds: 60)] + ) + } + } + isWorkoutPresented = true + } + + // MARK: - Session + + func startWorkout(_ resolved: ResolvedSession) async { await mutate { - try $0.startWorkout(templateID: template.id) + try $0.startWorkout( + template: resolved.template, + programmeWeek: resolved.programmeWeek, + programmeDayIndex: resolved.programmeDayIndex + ) } if document.activeSession != nil { isWorkoutPresented = true } } - func completeCurrent(segments: [SetSegment]) async { - await mutate { try $0.completeCurrent(with: segments) } + func startWorkout(_ template: WorkoutTemplate) async { + await mutate { try $0.startWorkout(template: template) } + if document.activeSession != nil { isWorkoutPresented = true } + } + + func completeCurrent(segments: [SetSegment], workSeconds: Int? = nil) async { + await mutate { try $0.completeCurrent(with: segments, workSeconds: workSeconds) } + await syncRestAlert() } func skipCurrent() async { await mutate { try $0.skipCurrent() } + await syncRestAlert() } func deferCurrent() async { @@ -120,17 +119,30 @@ final class AppModel { func adjustRest(by seconds: Int) async { await mutate { $0.adjustRest(by: seconds) } + await syncRestAlert() } func endRest() async { await mutate { $0.endRest() } + await syncRestAlert() } func finishWorkout() async { await mutate { try $0.finishWorkout() } + await syncRestAlert() if document.activeSession == nil { isWorkoutPresented = false } } + /// Keeps the queued rest notification matching the session's current rest. + private func syncRestAlert() async { + await restNotifier.update( + for: document.activeSession?.rest, + nextStep: document.activeSession?.currentStep + ) + } + + // MARK: - Planning + func duplicateTemplate(_ template: WorkoutTemplate) async { await mutate { try $0.duplicateTemplate(template.id) } message = "Independent copy created." @@ -151,21 +163,54 @@ final class AppModel { func assignTemplate(_ templateID: UUID?, to weekday: Int) async { await mutate { document in - guard let index = document.programme?.days.firstIndex(where: { $0.weekday == weekday }) else { return } - document.programme?.days[index].templateID = templateID + guard var programme = document.programme.customProgramme, + let index = programme.days.firstIndex(where: { $0.weekday == weekday }) + else { return } + programme.days[index].templateID = templateID + document.programme = .custom(programme) } } func setProgrammeWeeks(_ weekCount: Int) async { await mutate { document in - document.programme?.weekCount = min(16, max(1, weekCount)) + guard var programme = document.programme.customProgramme else { return } + programme.weekCount = min(16, max(1, weekCount)) + document.programme = .custom(programme) } } func toggleProgramme() async { - await mutate { $0.programme?.enabled.toggle() } + await mutate { document in + guard var programme = document.programme.customProgramme else { return } + programme.enabled.toggle() + document.programme = .custom(programme) + } + } + + /// Switches Today between the authored block and a device-authored programme. + func selectProgramme(_ selection: ProgrammeSelection) async { + await mutate { $0.programme = selection } + } + + func saveGoal(_ goal: ExerciseGoal) async { + await mutate { document in + if let index = document.goals.firstIndex(where: { $0.id == goal.id }) { + document.goals[index] = goal + } else { + document.goals.append(goal) + } + } + message = "Target saved." + } + + func deleteGoal(_ goal: ExerciseGoal) async { + await mutate { document in + document.goals.removeAll { $0.id == goal.id } + } } + // MARK: - Data transfer + func exportData() async -> Data? { do { return try await store.export(document) @@ -192,7 +237,6 @@ final class AppModel { self.importPreview = nil isImportConfirmationPresented = false message = "Setline data replaced." - try await markPendingAndSync() } catch { message = error.localizedDescription } @@ -201,206 +245,19 @@ final class AppModel { func resetLocalData() async { do { try await store.reset() - document = .sample + document = .initial message = "Local data reset." - try await markPendingAndSync() } catch { message = error.localizedDescription } } - func connectAccount() async { - isAccountBusy = true - accountMessage = nil - defer { isAccountBusy = false } - do { - let url = await accountClient.googleStartURL - let code = try await webAuthenticator.authenticate(at: url) - account = try await accountClient.exchangeHandoff(code) - try await reconcileAccountCopy() - } catch let error as NSError - where error.domain == ASWebAuthenticationSessionErrorDomain && error.code == 1 { - accountMessage = nil - } catch { - accountMessage = friendlyMessage(for: error) - } - } - - func completeAppleSignIn(_ payload: AppleIdentityPayload) async { - isAccountBusy = true - accountMessage = nil - defer { isAccountBusy = false } - do { - if let account, !account.hasApple { - self.account = try await accountClient.linkApple(payload) - accountMessage = "Apple sign-in added to this Setline account." - } else { - account = try await accountClient.signInWithApple(payload) - } - try await reconcileAccountCopy() - } catch { - accountMessage = friendlyMessage(for: error) - } - } - - func syncNow() async { - guard account != nil else { return } - if let deferredConflict { - self.deferredConflict = nil - cloudConflict = deferredConflict - return - } - await queueSync() - } - - func keepDeviceCopy() async { - guard let conflict = cloudConflict else { return } - cloudConflict = nil - deferredConflict = nil - remoteRevision = conflict.revision - await queueSync() - } - - func useAccountCopy() async { - guard let conflict = cloudConflict else { return } - do { - let restored = conflict.document.localDocument() - try await store.replace(with: restored) - document = restored - remoteRevision = conflict.revision - cloudConflict = nil - deferredConflict = nil - accountMessage = "Account copy restored on this iPhone." - } catch { - accountMessage = friendlyMessage(for: error) - } - } - - func decideConflictLater() { - deferredConflict = cloudConflict - cloudConflict = nil - document.syncState = .conflict - Task { try? await store.save(document) } - } - - func signOut() async { - await accountClient.signOut() - account = nil - remoteRevision = nil - cloudConflict = nil - deferredConflict = nil - document.syncState = .deviceOnly - try? await store.save(document) - accountMessage = "Signed out. Your workouts remain on this iPhone." - } - - func deleteAccount() async { - isAccountBusy = true - defer { isAccountBusy = false } - do { - try await accountClient.deleteAccount() - account = nil - remoteRevision = nil - cloudConflict = nil - deferredConflict = nil - document.syncState = .deviceOnly - try await store.save(document) - accountMessage = "Setline account and its private cloud copy were deleted." - } catch { - accountMessage = friendlyMessage(for: error) - } - } - - private func restoreAccount() async { - do { - account = try await accountClient.restoreAccount() - if account != nil { try await reconcileAccountCopy() } - } catch { - account = nil - document.syncState = .deviceOnly - accountMessage = friendlyMessage(for: error) - } - } - - private func reconcileAccountCopy() async throws { - let remote = try await accountClient.fetchState() - guard let remote else { - let saved = try await accountClient.pushState( - SetlineCloudDocument(document: document), - baseRevision: nil - ) - remoteRevision = saved.revision - await markSynced() - return - } - remoteRevision = remote.revision - if remote.document == SetlineCloudDocument(document: document) { - await markSynced() - } else { - document.syncState = .conflict - try await store.save(document) - cloudConflict = remote - } - } - - private func queueSync() async { - syncRequested = true - guard !isSyncing else { return } - isSyncing = true - defer { isSyncing = false } - while syncRequested { - syncRequested = false - document.syncState = .pending - try? await store.save(document) - do { - let saved = try await accountClient.pushState( - SetlineCloudDocument(document: document), - baseRevision: remoteRevision - ) - remoteRevision = saved.revision - await markSynced() - } catch let NativeAccountError.conflict(conflict) { - document.syncState = .conflict - try? await store.save(document) - cloudConflict = conflict - return - } catch { - document.syncState = .failed - try? await store.save(document) - accountMessage = friendlyMessage(for: error) - return - } - } - } - - private func markSynced() async { - document.syncState = .synced - document.lastSyncedAt = .now - try? await store.save(document) - accountMessage = "Private account copy is up to date." - } - - private func friendlyMessage(for error: Error) -> String { - if let native = error as? NativeAccountError { - return native.errorDescription ?? "Setline account service is unavailable." - } - return "Setline could not complete that account action. Try again." - } - - private func markPendingAndSync() async throws { - guard account != nil, deferredConflict == nil, cloudConflict == nil else { return } - document.syncState = .pending - try await store.save(document) - Task { await self.queueSync() } - } - private func mutate(_ operation: (inout SetlineDocument) throws -> Void) async { do { var next = document try operation(&next) try await store.save(next) document = next - try await markPendingAndSync() } catch { message = error.localizedDescription } diff --git a/ios/Sources/Setline/ExercisesView.swift b/ios/Sources/Setline/ExercisesView.swift new file mode 100644 index 0000000..ae49834 --- /dev/null +++ b/ios/Sources/Setline/ExercisesView.swift @@ -0,0 +1,648 @@ +import Charts +import SetlineCore +import SwiftUI + +/// Every exercise with recorded evidence, its measured current values, the ideal +/// you authored, and the distance between the two. +struct ExercisesView: View { + @Environment(AppModel.self) private var model + @State private var query = "" + @State private var isCatalogueShown = false + @State private var openedExercise: String? + + /// Movements you have actually trained, most recently trained first. + private var trainedExercises: [String] { + var seen = Set() + var names: [String] = [] + for session in model.document.history { + for step in session.steps where step.countsTowardVolume { + if seen.insert(ExerciseMetrics.normalise(step.exerciseName)).inserted { + names.append(step.exerciseName) + } + } + } + return names + } + + /// Goals whose movement has no recorded working set yet — still worth showing, + /// clearly marked as awaiting evidence. + private var goalsWithoutEvidence: [ExerciseGoal] { + let trained = Set(trainedExercises.map(ExerciseMetrics.normalise)) + return model.document.goals.filter { !trained.contains(ExerciseMetrics.normalise($0.exerciseName)) } + } + + private var filtered: [String] { + guard !query.isEmpty else { return trainedExercises } + let needle = ExerciseMetrics.normalise(query) + return trainedExercises.filter { ExerciseMetrics.normalise($0).contains(needle) } + } + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 24) { + pageHeader("Exercises", subtitle: "Measured current, authored ideal, and the gap between them.") + if !model.document.goals.isEmpty { + goalSummary + } + Button { + isCatalogueShown = true + } label: { + Label("Set a target from the catalogue", systemImage: "target") + } + .buttonStyle(ActionSlabStyle()) + if trainedExercises.isEmpty { + ContentUnavailableView( + "No recorded working sets", + systemImage: "chart.line.uptrend.xyaxis", + description: Text("Complete a working set and its measurements appear here. Setline will not estimate a starting point.") + ) + .frame(minHeight: 260) + } else { + VStack(alignment: .leading, spacing: 10) { + SectionLabel(text: "Trained movements") + ForEach(filtered, id: \.self) { name in + NavigationLink { + ExerciseDetailView(exerciseName: name) + } label: { + exerciseRow(name) + } + InkRule() + } + } + } + if !goalsWithoutEvidence.isEmpty { + VStack(alignment: .leading, spacing: 10) { + SectionLabel(text: "Targets awaiting evidence") + ForEach(goalsWithoutEvidence) { goal in + NavigationLink { + ExerciseDetailView(exerciseName: goal.exerciseName) + } label: { + HStack { + VStack(alignment: .leading, spacing: 3) { + Text(goal.exerciseName).font(.headline) + Text("\(goal.metric.title) target \(goal.metric.format(goal.targetValue))") + .font(.subheadline.monospacedDigit()) + .foregroundStyle(.secondary) + } + Spacer() + Image(systemName: "chevron.right") + } + .foregroundStyle(SetlinePalette.ink) + .padding(.vertical, 8) + } + InkRule() + } + } + } + } + .padding(20) + } + .searchable(text: $query, prompt: "Search trained movements") + .setlineBackground() + .navigationBarHidden(true) + .sheet(isPresented: $isCatalogueShown) { + CataloguePickerView() + } + .navigationDestination(item: $openedExercise) { name in + ExerciseDetailView(exerciseName: name) + } + .onAppear { openedExercise = model.demoExerciseName } + } + + private var goalSummary: some View { + let progresses = model.document.goals.map { + ExerciseMetrics.progress(for: $0, history: model.document.history) + } + let achieved = progresses.count(where: \.isAchieved) + return HStack(spacing: 10) { + summaryTile("TARGETS", "\(progresses.count)", SetlinePalette.blue) + summaryTile("REACHED", "\(achieved)", SetlinePalette.lime) + } + } + + private func summaryTile(_ label: String, _ value: String, _ colour: Color) -> some View { + VStack(alignment: .leading, spacing: 8) { + Text(value).font(.system(size: 34, weight: .black, design: .rounded).monospacedDigit()) + SectionLabel(text: label) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(16) + .background(colour) + .clipShape(RoundedRectangle(cornerRadius: 12)) + } + + private func exerciseRow(_ name: String) -> some View { + let metrics = ExerciseMetrics.availableMetrics(for: name, history: model.document.history) + let headline = metrics.first.flatMap { metric in + ExerciseMetrics.current(for: name, metric: metric, history: model.document.history) + .map { (metric, $0) } + } + let goal = model.document.goals.first { + ExerciseMetrics.normalise($0.exerciseName) == ExerciseMetrics.normalise(name) + } + return HStack(alignment: .top, spacing: 12) { + VStack(alignment: .leading, spacing: 4) { + Text(name).font(.headline.weight(.black)) + if let headline { + Text("\(headline.0.title): \(headline.0.format(headline.1.value))") + .font(.subheadline.monospacedDigit()) + .foregroundStyle(.secondary) + } + if let goal { + let progress = ExerciseMetrics.progress(for: goal, history: model.document.history) + HStack(spacing: 6) { + Text("Target \(goal.metric.format(goal.targetValue))") + .font(.caption.monospacedDigit().weight(.bold)) + if progress.isAchieved { + Text("REACHED") + .font(.system(size: 9, weight: .black)) + .padding(.horizontal, 5) + .padding(.vertical, 2) + .background(SetlinePalette.lime) + .clipShape(RoundedRectangle(cornerRadius: 4)) + } else if let fraction = progress.fraction { + Text("\(Int(fraction * 100))%") + .font(.caption.monospacedDigit().weight(.bold)) + .foregroundStyle(.secondary) + } + } + } + } + Spacer() + Image(systemName: "chevron.right").foregroundStyle(.secondary) + } + .foregroundStyle(SetlinePalette.ink) + .padding(.vertical, 8) + } +} + +/// One movement: what it measures, what you have measured, and what you want. +struct ExerciseDetailView: View { + @Environment(AppModel.self) private var model + let exerciseName: String + + @State private var isGoalEditorShown = false + @State private var editingGoal: ExerciseGoal? + + private var definition: ExerciseDefinition? { ExerciseCatalogue.match(name: exerciseName) } + + private var availableMetrics: [MetricKind] { + let measured = ExerciseMetrics.availableMetrics(for: exerciseName, history: model.document.history) + guard measured.isEmpty else { return measured } + return definition?.goalMetrics ?? [] + } + + private var goals: [ExerciseGoal] { + model.document.goals.filter { + ExerciseMetrics.normalise($0.exerciseName) == ExerciseMetrics.normalise(exerciseName) + } + } + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 26) { + heading + currentBlock + goalsBlock + progressionBlock + if let definition { detailsBlock(definition) } + } + .padding(20) + .padding(.bottom, 28) + } + .setlineBackground() + .navigationTitle(exerciseName) + .navigationBarTitleDisplayMode(.inline) + .sheet(isPresented: $isGoalEditorShown) { + GoalEditorView(exerciseName: exerciseName, metrics: metricsForGoal, existing: nil) + } + .sheet(item: $editingGoal) { goal in + GoalEditorView(exerciseName: exerciseName, metrics: metricsForGoal, existing: goal) + } + } + + private var metricsForGoal: [MetricKind] { + let candidates = definition?.goalMetrics ?? [] + let measured = ExerciseMetrics.availableMetrics(for: exerciseName, history: model.document.history) + let combined = candidates + measured.filter { !candidates.contains($0) } + return combined.isEmpty ? MetricKind.allCases : combined + } + + private var heading: some View { + VStack(alignment: .leading, spacing: 8) { + if let definition { + HStack(spacing: 6) { + ForEach(Pillar.allCases.filter { definition.pillars.contains($0) }, id: \.self) { pillar in + Text(pillar.title.uppercased()) + .font(.caption2.weight(.black)) + .padding(.horizontal, 8) + .padding(.vertical, 4) + .background(SetlinePalette.blue.opacity(0.7)) + .clipShape(Capsule()) + } + } + if !definition.cue.isEmpty { + Text(definition.cue) + .font(.subheadline) + .foregroundStyle(SetlinePalette.ink.opacity(0.7)) + } + } + } + } + + // MARK: - Current + + private var currentBlock: some View { + VStack(alignment: .leading, spacing: 12) { + SectionLabel(text: "Current · measured") + if availableMetrics.isEmpty { + Text("No comparable working set recorded yet.") + .font(.subheadline) + .foregroundStyle(.secondary) + } else { + ForEach(availableMetrics, id: \.self) { metric in + if let value = ExerciseMetrics.current( + for: exerciseName, + metric: metric, + history: model.document.history + ) { + VStack(alignment: .leading, spacing: 4) { + Text(metric.title) + .font(.caption.weight(.bold)) + .foregroundStyle(SetlinePalette.ink.opacity(0.6)) + Text(metric.format(value.value)) + .font(.system(size: 28, weight: .black, design: .rounded).monospacedDigit()) + Text(value.provenance) + .font(.caption) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(14) + .background(SetlinePalette.paper) + .clipShape(RoundedRectangle(cornerRadius: 12)) + } else { + VStack(alignment: .leading, spacing: 4) { + Text(metric.title) + .font(.caption.weight(.bold)) + .foregroundStyle(SetlinePalette.ink.opacity(0.6)) + Text("Unavailable") + .font(.headline) + .foregroundStyle(.secondary) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(14) + .background(SetlinePalette.paper.opacity(0.6)) + .clipShape(RoundedRectangle(cornerRadius: 12)) + } + } + } + } + } + + // MARK: - Goals + + private var goalsBlock: some View { + VStack(alignment: .leading, spacing: 12) { + HStack { + SectionLabel(text: "Ideal · authored") + Spacer() + Button { + isGoalEditorShown = true + } label: { + Label("Set target", systemImage: "plus") + .font(.caption.weight(.bold)) + } + .frame(minHeight: 32) + } + if goals.isEmpty { + Text("No target set. Setting one turns recorded numbers into a trajectory.") + .font(.subheadline) + .foregroundStyle(.secondary) + } else { + ForEach(goals) { goal in + goalCard(ExerciseMetrics.progress(for: goal, history: model.document.history)) + } + } + } + } + + private func goalCard(_ progress: GoalProgress) -> some View { + VStack(alignment: .leading, spacing: 12) { + HStack(alignment: .top) { + VStack(alignment: .leading, spacing: 3) { + Text(progress.goal.metric.title) + .font(.caption.weight(.bold)) + .foregroundStyle(SetlinePalette.ink.opacity(0.6)) + Text(progress.goal.metric.format(progress.goal.targetValue)) + .font(.system(size: 26, weight: .black, design: .rounded).monospacedDigit()) + } + Spacer() + if progress.isAchieved { + Text("REACHED") + .font(.caption2.weight(.black)) + .padding(.horizontal, 8) + .padding(.vertical, 5) + .background(SetlinePalette.lime) + .clipShape(Capsule()) + } + Menu { + Button("Edit target") { editingGoal = progress.goal } + Button("Remove target", role: .destructive) { + Task { await model.deleteGoal(progress.goal) } + } + } label: { + Image(systemName: "ellipsis.circle").frame(width: 32, height: 32) + } + } + if let fraction = progress.fraction { + ProgressView(value: fraction) + .tint(progress.isAchieved ? SetlinePalette.lime : SetlinePalette.ink) + } + HStack(spacing: 16) { + if let current = progress.current { + factColumn("NOW", progress.goal.metric.format(current.value)) + } + if let remaining = progress.remaining, remaining > 0 { + factColumn("TO GO", progress.goal.metric.format(remaining)) + } + if let rate = progress.ratePerWeek, abs(rate) > 0.001 { + factColumn("PER WEEK", progress.goal.metric.format(abs(rate))) + } + } + if let projected = progress.projectedDate { + Text("At the recorded rate, reached around \(projected.formatted(date: .abbreviated, time: .omitted)).") + .font(.caption) + .foregroundStyle(.secondary) + } else if progress.evidenceCount < 2 { + Text("A trend needs at least two comparable sessions.") + .font(.caption) + .foregroundStyle(.secondary) + } + trendChart(progress) + } + .padding(16) + .background(SetlinePalette.paper) + .clipShape(RoundedRectangle(cornerRadius: 14)) + } + + private func factColumn(_ label: String, _ value: String) -> some View { + VStack(alignment: .leading, spacing: 3) { + Text(label) + .font(.system(size: 9, weight: .black)) + .foregroundStyle(SetlinePalette.ink.opacity(0.55)) + Text(value).font(.subheadline.monospacedDigit().weight(.bold)) + } + } + + @ViewBuilder + private func trendChart(_ progress: GoalProgress) -> some View { + let points = ExerciseMetrics.series( + for: progress.goal.exerciseName, + metric: progress.goal.metric, + referenceRepetitions: progress.goal.referenceRepetitions, + history: model.document.history + ) + // Two points is the floor for a line that means anything. + if points.count >= 2 { + Chart { + ForEach(points) { point in + LineMark(x: .value("Date", point.achievedAt), y: .value(progress.goal.metric.title, point.value)) + .foregroundStyle(SetlinePalette.ink) + PointMark(x: .value("Date", point.achievedAt), y: .value(progress.goal.metric.title, point.value)) + .foregroundStyle(SetlinePalette.ink) + } + RuleMark(y: .value("Target", progress.goal.targetValue)) + .lineStyle(StrokeStyle(lineWidth: 1.5, dash: [5, 4])) + .foregroundStyle(SetlinePalette.coral) + .annotation(position: .top, alignment: .leading) { + Text("Target").font(.system(size: 9, weight: .black)).foregroundStyle(SetlinePalette.coral) + } + } + .chartYAxis { AxisMarks(position: .leading) } + .frame(height: 160) + .accessibilityLabel("\(progress.goal.metric.title) trend across \(points.count) sessions") + } + } + + // MARK: - Progression + + @ViewBuilder + private var progressionBlock: some View { + if let recommendation = ProgressionEngine.recommendation( + for: exerciseName, + rule: nil, + history: model.document.history + ), recommendation.action != .insufficientEvidence { + VStack(alignment: .leading, spacing: 8) { + SectionLabel(text: "Next session") + Text(actionTitle(recommendation)) + .font(.system(size: 22, weight: .black, design: .rounded).monospacedDigit()) + if let evidence = recommendation.evidenceSummary { + Text("Last session: \(evidence)") + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + } + Text(recommendation.rationale) + .font(.footnote) + .foregroundStyle(SetlinePalette.ink.opacity(0.72)) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(16) + .background(SetlinePalette.blue.opacity(0.45)) + .clipShape(RoundedRectangle(cornerRadius: 14)) + } + } + + private func actionTitle(_ recommendation: ProgressionRecommendation) -> String { + switch recommendation.action { + case .addLoad: + if let current = recommendation.currentLoad, let next = recommendation.recommendedLoad { + return "\(current.trimmedString) → \(next.trimmedString) kg" + } + return "Add load" + case .addRepetitions: + return "Hold the load, add repetitions" + case .reduceLoad: + if let current = recommendation.currentLoad, let next = recommendation.recommendedLoad { + return "\(current.trimmedString) → \(next.trimmedString) kg" + } + return "Reduce the load" + case .insufficientEvidence: + return "Not enough evidence" + } + } + + // MARK: - Reference + + private func detailsBlock(_ definition: ExerciseDefinition) -> some View { + VStack(alignment: .leading, spacing: 10) { + SectionLabel(text: "Movement") + LabeledContent("Trains", value: definition.primaryMuscles.map(\.title).joined(separator: ", ")) + if !definition.secondaryMuscles.isEmpty { + LabeledContent("Also", value: definition.secondaryMuscles.map(\.title).joined(separator: ", ")) + } + LabeledContent("Equipment", value: definition.equipment.map(\.title).joined(separator: ", ")) + LabeledContent("Default rest", value: definition.defaultRest.displayString) + if let rule = TwelveWeekProgramme.rule(forSlug: definition.slug) { + InkRule() + SectionLabel(text: "Authored progression") + Text("\(rule.repsLow)–\(rule.repsHigh) reps. \(rule.specialRule)") + .font(.footnote) + .foregroundStyle(SetlinePalette.ink.opacity(0.72)) + } + } + .font(.subheadline) + .padding(16) + .background(SetlinePalette.paper) + .clipShape(RoundedRectangle(cornerRadius: 14)) + } +} + +/// Authors an ideal for one exercise and metric. +private struct GoalEditorView: View { + @Environment(AppModel.self) private var model + @Environment(\.dismiss) private var dismiss + + let exerciseName: String + let metrics: [MetricKind] + let existing: ExerciseGoal? + + @State private var metric: MetricKind + @State private var value = "" + @State private var referenceRepetitions = "" + @State private var hasTargetDate = false + @State private var targetDate = Date.now.addingTimeInterval(60 * 60 * 24 * 84) + @State private var note = "" + + init(exerciseName: String, metrics: [MetricKind], existing: ExerciseGoal?) { + self.exerciseName = exerciseName + self.metrics = metrics + self.existing = existing + _metric = State(initialValue: existing?.metric ?? metrics.first ?? .estimatedOneRepMax) + _value = State(initialValue: existing.map { $0.targetValue.trimmedString } ?? "") + _referenceRepetitions = State(initialValue: existing?.referenceRepetitions.map(String.init) ?? "") + _hasTargetDate = State(initialValue: existing?.targetDate != nil) + _targetDate = State(initialValue: existing?.targetDate ?? Date.now.addingTimeInterval(60 * 60 * 24 * 84)) + _note = State(initialValue: existing?.note ?? "") + } + + var body: some View { + NavigationStack { + Form { + Section("Movement") { + LabeledContent("Exercise", value: exerciseName) + Picker("Measure", selection: $metric) { + ForEach(metrics, id: \.self) { option in + Text(option.title).tag(option) + } + } + } + Section("Ideal") { + HStack { + TextField("Target", text: $value) + .keyboardType(.decimalPad) + Text(metric.unit).foregroundStyle(.secondary) + } + if metric == .topSetLoad { + HStack { + TextField("For at least", text: $referenceRepetitions) + .keyboardType(.numberPad) + Text("reps").foregroundStyle(.secondary) + } + } + if metric == .bestPaceSecondsPerKilometre { + Text("Enter seconds per kilometre. Lower is better.") + .font(.caption) + .foregroundStyle(.secondary) + } + Toggle("Set a target date", isOn: $hasTargetDate) + if hasTargetDate { + DatePicker("By", selection: $targetDate, displayedComponents: .date) + } + } + Section("Note") { + TextField("Optional", text: $note, axis: .vertical) + } + } + .navigationTitle(existing == nil ? "New target" : "Edit target") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { dismiss() } + } + ToolbarItem(placement: .confirmationAction) { + Button("Save") { save() } + .disabled(Double(value) == nil) + } + } + } + } + + private func save() { + guard let targetValue = Double(value) else { return } + let goal = ExerciseGoal( + id: existing?.id ?? UUID(), + exerciseName: exerciseName, + metric: metric, + targetValue: targetValue, + referenceRepetitions: metric == .topSetLoad ? Int(referenceRepetitions) : nil, + targetDate: hasTargetDate ? targetDate : nil, + createdAt: existing?.createdAt ?? .now, + note: note.isEmpty ? nil : note + ) + Task { + await model.saveGoal(goal) + dismiss() + } + } +} + +/// Browse the bundled movement library to set a target for something not yet trained. +private struct CataloguePickerView: View { + @Environment(\.dismiss) private var dismiss + @State private var query = "" + @State private var pillar: Pillar? + + private var results: [ExerciseDefinition] { + let base = pillar.map { ExerciseCatalogue.definitions(for: $0) } ?? ExerciseCatalogue.search(query) + guard pillar != nil, !query.isEmpty else { return base } + let needle = ExerciseMetrics.normalise(query) + return base.filter { ExerciseMetrics.normalise($0.name).contains(needle) } + } + + var body: some View { + NavigationStack { + List { + Section { + Picker("Pillar", selection: $pillar) { + Text("All").tag(Pillar?.none) + ForEach(Pillar.allCases, id: \.self) { option in + Text(option.title).tag(Pillar?.some(option)) + } + } + .pickerStyle(.segmented) + } + ForEach(results) { definition in + NavigationLink { + ExerciseDetailView(exerciseName: definition.name) + } label: { + VStack(alignment: .leading, spacing: 3) { + Text(definition.name).font(.headline) + Text(definition.equipment.map(\.title).joined(separator: " · ")) + .font(.caption) + .foregroundStyle(.secondary) + } + } + } + } + .searchable(text: $query, prompt: "Search \(ExerciseCatalogue.all.count) movements") + .navigationTitle("Movement library") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .confirmationAction) { + Button("Done") { dismiss() } + } + } + } + } +} diff --git a/ios/Sources/Setline/HistoryViews.swift b/ios/Sources/Setline/HistoryViews.swift new file mode 100644 index 0000000..1b3a18e --- /dev/null +++ b/ios/Sources/Setline/HistoryViews.swift @@ -0,0 +1,228 @@ +import SetlineCore +import SwiftUI + +struct HistoryView: View { + @Environment(AppModel.self) private var model + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 26) { + pageHeader("History", subtitle: "Recorded, calculated, and unavailable stay distinct.") + totals + pillarDose + progressionSection + if model.document.history.isEmpty { + ContentUnavailableView( + "No recorded workouts", + systemImage: "clock.arrow.circlepath", + description: Text("Complete a workout to create evidence. Setline will not invent a chart first.") + ) + .frame(minHeight: 320) + } else { + ForEach(model.document.history) { session in + NavigationLink { + SessionDetailView(session: session) + } label: { + sessionRow(session) + } + InkRule() + } + } + } + .padding(20) + } + .setlineBackground() + .navigationBarHidden(true) + } + + private var totals: some View { + let sessions = model.document.history + let workingSets = sessions.reduce(0) { $0 + $1.completedWorkingSetCount } + let tonnage = sessions.reduce(0.0) { $0 + $1.tonnage } + return HStack(spacing: 10) { + historyMetric("SESSIONS", "\(sessions.count)", SetlinePalette.blue) + historyMetric("WORKING SETS", "\(workingSets)", SetlinePalette.lime) + historyMetric("TONNAGE", tonnage > 0 ? "\(Int(tonnage)) kg" : "—", SetlinePalette.steel) + } + } + + /// How many sessions in the last seven days touched each pillar. Recorded, not scored. + private var pillarDose: some View { + let cutoff = Calendar.current.date(byAdding: .day, value: -7, to: .now) ?? .now + let recent = model.document.history.filter { ($0.completedAt ?? $0.startedAt) >= cutoff } + return VStack(alignment: .leading, spacing: 10) { + SectionLabel(text: "Last 7 days by pillar") + if recent.isEmpty { + Text("No sessions recorded in the last seven days.") + .font(.subheadline) + .foregroundStyle(.secondary) + } else { + ForEach(Pillar.allCases, id: \.self) { pillar in + let count = recent.count { $0.pillars.contains(pillar) } + HStack { + Text(pillar.title).font(.subheadline.weight(.semibold)) + Spacer() + Text("\(count) session\(count == 1 ? "" : "s")") + .font(.subheadline.monospacedDigit()) + .foregroundStyle(count == 0 ? SetlinePalette.coral : SetlinePalette.ink) + } + .padding(.vertical, 2) + } + } + } + .padding(16) + .background(SetlinePalette.paper) + .clipShape(RoundedRectangle(cornerRadius: 14)) + } + + private var progressionSection: some View { + let recommendations = ProgressionEngine.recommendations(history: model.document.history) + return VStack(alignment: .leading, spacing: 10) { + SectionLabel(text: "Next-session suggestions") + if recommendations.isEmpty { + Text("Unavailable until a completed working set establishes evidence against an authored rep range.") + .font(.subheadline) + .foregroundStyle(.secondary) + } else { + ForEach(recommendations, id: \.exerciseName) { recommendation in + VStack(alignment: .leading, spacing: 5) { + HStack { + Text(recommendation.exerciseName).font(.headline) + Spacer() + Text(actionLabel(recommendation.action)) + .font(.system(size: 9, weight: .black)) + .padding(.horizontal, 6) + .padding(.vertical, 3) + .background(actionColour(recommendation.action)) + .clipShape(RoundedRectangle(cornerRadius: 4)) + } + if let current = recommendation.currentLoad, let next = recommendation.recommendedLoad, + current != next { + Text("\(current.trimmedString) → \(next.trimmedString) kg") + .font(.title3.monospacedDigit().weight(.black)) + } + if let evidence = recommendation.evidenceSummary { + Text("Last session: \(evidence)") + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + } + Text(recommendation.rationale).font(.caption).foregroundStyle(.secondary) + } + .padding(14) + .background(SetlinePalette.paper) + .clipShape(RoundedRectangle(cornerRadius: 12)) + } + } + } + } + + private func actionLabel(_ action: ProgressionAction) -> String { + switch action { + case .addLoad: "ADD LOAD" + case .addRepetitions: "ADD REPS" + case .reduceLoad: "REDUCE" + case .insufficientEvidence: "NO EVIDENCE" + } + } + + private func actionColour(_ action: ProgressionAction) -> Color { + switch action { + case .addLoad: SetlinePalette.lime + case .addRepetitions: SetlinePalette.blue + case .reduceLoad: SetlinePalette.coral.opacity(0.6) + case .insufficientEvidence: SetlinePalette.steel + } + } + + private func sessionRow(_ session: WorkoutSession) -> some View { + HStack(alignment: .top, spacing: 14) { + VStack(spacing: 3) { + Text(session.completedAt?.formatted(.dateTime.day()) ?? "–") + .font(.title2.monospacedDigit().weight(.black)) + Text(session.completedAt?.formatted(.dateTime.month(.abbreviated)) ?? "") + .font(.caption.weight(.bold)) + } + .frame(width: 52, height: 58) + .background(SetlinePalette.blue) + .clipShape(RoundedRectangle(cornerRadius: 8)) + VStack(alignment: .leading, spacing: 5) { + Text(session.templateName).font(.headline.weight(.black)) + Text("\(session.completedWorkingSetCount) working · \(session.completedCount) completed · \(session.steps.count - session.completedCount) skipped") + .font(.subheadline.monospacedDigit()) + .foregroundStyle(.secondary) + if let week = session.programmeWeek { + Text("Week \(week)") + .font(.caption.weight(.bold)) + .foregroundStyle(SetlinePalette.ink.opacity(0.55)) + } + } + Spacer() + Image(systemName: "chevron.right") + } + .foregroundStyle(SetlinePalette.ink) + .padding(.vertical, 8) + } + + private func historyMetric(_ label: String, _ value: String, _ color: Color) -> some View { + VStack(alignment: .leading, spacing: 8) { + Text(value) + .font(.system(size: 26, weight: .black, design: .rounded).monospacedDigit()) + .minimumScaleFactor(0.6) + .lineLimit(1) + SectionLabel(text: label) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(14) + .background(color) + .clipShape(RoundedRectangle(cornerRadius: 12)) + } +} + +struct SessionDetailView: View { + let session: WorkoutSession + + var body: some View { + List { + Section("Session receipt") { + LabeledContent("Workout", value: session.templateName) + LabeledContent("Started", value: session.startedAt.formatted(date: .abbreviated, time: .shortened)) + if let completedAt = session.completedAt { + LabeledContent("Completed", value: completedAt.formatted(date: .abbreviated, time: .shortened)) + } + if let week = session.programmeWeek { + LabeledContent("Programme week", value: "\(week)") + } + LabeledContent("Working sets", value: "\(session.completedWorkingSetCount)") + if session.tonnage > 0 { + LabeledContent("Load moved", value: "\(session.tonnage.trimmedString) kg") + } + } + Section("Execution ledger") { + ForEach(session.steps) { step in + VStack(alignment: .leading, spacing: 5) { + HStack { + Text(step.exerciseName).font(.headline) + Spacer() + Text(step.status.rawValue.uppercased()).font(.caption.weight(.black)) + } + Text("\(step.label) · \(step.stepType.title) · planned #\(step.authoredPosition + 1) · performed \(step.performedPosition.map { "#\($0 + 1)" } ?? "—")") + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + Text("Target: \(step.target.displayString)").font(.subheadline) + if !step.segments.isEmpty { + Text("Recorded: " + step.segments.map(\.recordedDescription).joined(separator: " + ")) + .font(.subheadline.weight(.semibold)) + } + if let workSeconds = step.workSeconds { + Text("Set duration: \(workSeconds.durationLabel)") + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + } + } + .padding(.vertical, 4) + } + } + } + .navigationTitle("Recorded workout") + } +} diff --git a/ios/Sources/Setline/Info.plist b/ios/Sources/Setline/Info.plist index 50b4522..1ba91ee 100644 --- a/ios/Sources/Setline/Info.plist +++ b/ios/Sources/Setline/Info.plist @@ -18,19 +18,6 @@ APPL CFBundleShortVersionString $(MARKETING_VERSION) - CFBundleURLTypes - - - CFBundleTypeRole - Editor - CFBundleURLName - com.significanthobbies.setline.auth - CFBundleURLSchemes - - setline - - - CFBundleVersion $(CURRENT_PROJECT_VERSION) ITSAppUsesNonExemptEncryption diff --git a/ios/Sources/Setline/NativeAccountClient.swift b/ios/Sources/Setline/NativeAccountClient.swift deleted file mode 100644 index 704ad96..0000000 --- a/ios/Sources/Setline/NativeAccountClient.swift +++ /dev/null @@ -1,401 +0,0 @@ -import AuthenticationServices -import CryptoKit -import Foundation -import Security -import SetlineCore -import UIKit - -struct AppleIdentityPayload: Sendable { - let identityToken: String - let nonce: String - let email: String? - let firstName: String? - let lastName: String? -} - -struct SetlineAccount: Equatable, Sendable { - let name: String - let email: String - let providers: Set - - var hasApple: Bool { providers.contains("apple") } -} - -enum NativeAccountError: LocalizedError { - case invalidCallback - case missingSession - case conflict(SetlineCloudSnapshot) - case server(String) - case http(Int, String) - - var errorDescription: String? { - switch self { - case .invalidCallback: - "Setline could not verify the sign-in handoff." - case .missingSession: - "Your Setline session expired. Sign in again." - case .conflict: - "A newer account copy needs your decision." - case let .server(message), let .http(_, message): - message - } - } -} - -actor SetlineKeychainSessionStore { - private let service: String - private let account: String - - init( - service: String = "com.significanthobbies.setline.session", - account: String = "better-auth-bearer" - ) { - self.service = service - self.account = account - } - - func load() throws -> String? { - let query: [String: Any] = [ - kSecClass as String: kSecClassGenericPassword, - kSecAttrService as String: service, - kSecAttrAccount as String: account, - kSecReturnData as String: true, - kSecMatchLimit as String: kSecMatchLimitOne, - ] - var result: CFTypeRef? - let status = SecItemCopyMatching(query as CFDictionary, &result) - if status == errSecItemNotFound { return nil } - guard status == errSecSuccess, let data = result as? Data else { - throw NativeAccountError.server("Setline could not read the secure session.") - } - return String(data: data, encoding: .utf8) - } - - func save(_ token: String) throws { - let data = Data(token.utf8) - let identity: [String: Any] = [ - kSecClass as String: kSecClassGenericPassword, - kSecAttrService as String: service, - kSecAttrAccount as String: account, - ] - let attributes: [String: Any] = [ - kSecValueData as String: data, - kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly, - ] - let updateStatus = SecItemUpdate(identity as CFDictionary, attributes as CFDictionary) - if updateStatus == errSecItemNotFound { - var insertion = identity - insertion.merge(attributes) { _, replacement in replacement } - guard SecItemAdd(insertion as CFDictionary, nil) == errSecSuccess else { - throw NativeAccountError.server("Setline could not store the secure session.") - } - } else if updateStatus != errSecSuccess { - throw NativeAccountError.server("Setline could not update the secure session.") - } - } - - func delete() throws { - let query: [String: Any] = [ - kSecClass as String: kSecClassGenericPassword, - kSecAttrService as String: service, - kSecAttrAccount as String: account, - ] - let status = SecItemDelete(query as CFDictionary) - guard status == errSecSuccess || status == errSecItemNotFound else { - throw NativeAccountError.server("Setline could not remove the secure session.") - } - } -} - -actor SetlineNativeAccountClient { - static let productionBaseURL = URL(string: "https://setline.significanthobbies.com")! - - private let baseURL: URL - private let urlSession: URLSession - private let sessionStore: SetlineKeychainSessionStore - - init( - baseURL: URL = productionBaseURL, - urlSession: URLSession = .shared, - sessionStore: SetlineKeychainSessionStore = SetlineKeychainSessionStore() - ) { - self.baseURL = baseURL - self.urlSession = urlSession - self.sessionStore = sessionStore - } - - var googleStartURL: URL { - var components = URLComponents( - url: endpoint("/api/native/auth/google/start"), - resolvingAgainstBaseURL: false - )! - components.queryItems = [URLQueryItem(name: "callback", value: "setline://auth")] - return components.url! - } - - func restoreAccount() async throws -> SetlineAccount? { - guard try await sessionStore.load() != nil else { return nil } - do { - return try await account() - } catch { - try? await sessionStore.delete() - throw error - } - } - - func exchangeHandoff(_ code: String) async throws -> SetlineAccount { - let response = try await request( - path: "/api/native/auth/exchange", - body: ["code": code], - authenticated: false - ) - let payload = try JSONDecoder().decode(TokenResponse.self, from: response.data) - try await sessionStore.save(payload.token) - return try await account() - } - - func signInWithApple(_ payload: AppleIdentityPayload) async throws -> SetlineAccount { - let response = try await appleRequest(path: "/api/auth/sign-in/social", payload: payload) - guard let token = response.response.value(forHTTPHeaderField: "set-auth-token") else { - throw NativeAccountError.missingSession - } - try await sessionStore.save(token) - return try await account() - } - - func linkApple(_ payload: AppleIdentityPayload) async throws -> SetlineAccount { - _ = try await appleRequest(path: "/api/auth/link-social", payload: payload, authenticated: true) - return try await account() - } - - func fetchState() async throws -> SetlineCloudSnapshot? { - let response = try await request(path: "/api/native/state", method: "GET") - return try decoder.decode(StateResponse.self, from: response.data).state - } - - func pushState( - _ document: SetlineCloudDocument, - baseRevision: Int? - ) async throws -> SetlineCloudSnapshot { - let body = StateWrite(document: document, baseRevision: baseRevision) - let response = try await request(path: "/api/native/state", method: "PUT", encodableBody: body) - let payload = try decoder.decode(StateResponse.self, from: response.data) - guard let state = payload.state else { - throw NativeAccountError.server("Setline did not return the saved account copy.") - } - return state - } - - func signOut() async { - _ = try? await request(path: "/api/auth/sign-out", body: [String: String]()) - try? await sessionStore.delete() - } - - func deleteAccount() async throws { - _ = try await request(path: "/api/auth/delete-user", body: [String: String]()) - try await sessionStore.delete() - } - - private func appleRequest( - path: String, - payload: AppleIdentityPayload, - authenticated: Bool = false - ) async throws -> NetworkResponse { - var idToken: [String: Any] = ["token": payload.identityToken, "nonce": payload.nonce] - if path.hasSuffix("sign-in/social") { - var user: [String: Any] = [:] - if let email = payload.email { user["email"] = email } - var name: [String: String] = [:] - if let firstName = payload.firstName { name["firstName"] = firstName } - if let lastName = payload.lastName { name["lastName"] = lastName } - if !name.isEmpty { user["name"] = name } - if !user.isEmpty { idToken["user"] = user } - } - return try await request( - path: path, - jsonBody: ["provider": "apple", "idToken": idToken], - authenticated: authenticated - ) - } - - private func account() async throws -> SetlineAccount { - let response = try await request(path: "/api/auth/get-session", method: "GET") - let session = try decoder.decode(SessionResponse.self, from: response.data) - let accountsResponse = try await request(path: "/api/auth/list-accounts", method: "GET") - let accounts = try decoder.decode([ProviderAccount].self, from: accountsResponse.data) - return SetlineAccount( - name: session.user.name, - email: session.user.email, - providers: Set(accounts.map(\.providerId)) - ) - } - - private func request( - path: String, - jsonBody: [String: Any], - authenticated: Bool - ) async throws -> NetworkResponse { - try await request( - path: path, - method: "POST", - data: try JSONSerialization.data(withJSONObject: jsonBody), - authenticated: authenticated - ) - } - - private func request( - path: String, - method: String = "POST", - body: [String: String], - authenticated: Bool = true - ) async throws -> NetworkResponse { - try await request( - path: path, - method: method, - data: try JSONEncoder().encode(body), - authenticated: authenticated - ) - } - - private func request( - path: String, - method: String, - encodableBody: T - ) async throws -> NetworkResponse { - try await request( - path: path, - method: method, - data: try encoder.encode(encodableBody), - authenticated: true - ) - } - - private func request( - path: String, - method: String, - data: Data? = nil, - authenticated: Bool = true - ) async throws -> NetworkResponse { - var request = URLRequest(url: endpoint(path)) - request.httpMethod = method - request.httpBody = data - request.setValue("application/json", forHTTPHeaderField: "Accept") - if data != nil { request.setValue("application/json", forHTTPHeaderField: "Content-Type") } - if authenticated { - guard let token = try await sessionStore.load() else { - throw NativeAccountError.missingSession - } - request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") - } - let (responseData, rawResponse) = try await urlSession.data(for: request) - guard let response = rawResponse as? HTTPURLResponse else { - throw NativeAccountError.server("Setline received an invalid server response.") - } - if response.statusCode == 409, - let conflict = try? decoder.decode(StateResponse.self, from: responseData).state { - throw NativeAccountError.conflict(conflict) - } - guard (200..<300).contains(response.statusCode) else { - let message = (try? decoder.decode(ErrorResponse.self, from: responseData).message) - ?? "Setline account service is unavailable." - if response.statusCode == 401 { throw NativeAccountError.missingSession } - throw NativeAccountError.http(response.statusCode, message) - } - return NetworkResponse(data: responseData, response: response) - } - - private func endpoint(_ path: String) -> URL { - baseURL.appending(path: path.trimmingCharacters(in: CharacterSet(charactersIn: "/"))) - } - - private var encoder: JSONEncoder { - let encoder = JSONEncoder() - encoder.dateEncodingStrategy = .iso8601 - return encoder - } - - private var decoder: JSONDecoder { - let decoder = JSONDecoder() - decoder.dateDecodingStrategy = .iso8601 - return decoder - } -} - -enum AppleNonce { - static func make() -> String { - let alphabet = Array("0123456789ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvwxyz-._") - return String((0..<32).map { _ in alphabet.randomElement()! }) - } - - static func digest(_ nonce: String) -> String { - SHA256.hash(data: Data(nonce.utf8)).map { String(format: "%02x", $0) }.joined() - } -} - -@MainActor -final class SetlineWebAuthenticator: NSObject, ASWebAuthenticationPresentationContextProviding { - private var session: ASWebAuthenticationSession? - - func authenticate(at url: URL) async throws -> String { - try await withCheckedThrowingContinuation { continuation in - let session = ASWebAuthenticationSession( - url: url, - callbackURLScheme: "setline" - ) { callbackURL, error in - if let error { - continuation.resume(throwing: error) - return - } - guard - let callbackURL, - callbackURL.scheme == "setline", - callbackURL.host == "auth", - let code = URLComponents(url: callbackURL, resolvingAgainstBaseURL: false)? - .queryItems?.first(where: { $0.name == "code" })?.value - else { - continuation.resume(throwing: NativeAccountError.invalidCallback) - return - } - continuation.resume(returning: code) - } - session.presentationContextProvider = self - session.prefersEphemeralWebBrowserSession = false - self.session = session - guard session.start() else { - continuation.resume(throwing: NativeAccountError.server("Setline could not open sign in.")) - return - } - } - } - - func presentationAnchor(for _: ASWebAuthenticationSession) -> ASPresentationAnchor { - UIApplication.shared.connectedScenes - .compactMap { $0 as? UIWindowScene } - .flatMap(\.windows) - .first(where: \.isKeyWindow) ?? ASPresentationAnchor() - } -} - -private struct TokenResponse: Decodable { let token: String } -private struct SessionResponse: Decodable { let user: SessionUser } -private struct SessionUser: Decodable { let name: String; let email: String } -private struct ProviderAccount: Decodable { let providerId: String } -private struct ErrorResponse: Decodable { let message: String } -private struct StateResponse: Decodable { let state: SetlineCloudSnapshot? } -private struct StateWrite: Encodable { - let document: SetlineCloudDocument - let baseRevision: Int? - - private enum CodingKeys: String, CodingKey { case document, baseRevision } - - func encode(to encoder: Encoder) throws { - var container = encoder.container(keyedBy: CodingKeys.self) - try container.encode(document, forKey: .document) - if let baseRevision { - try container.encode(baseRevision, forKey: .baseRevision) - } else { - try container.encodeNil(forKey: .baseRevision) - } - } -} -private struct NetworkResponse { let data: Data; let response: HTTPURLResponse } diff --git a/ios/Sources/Setline/PlanViews.swift b/ios/Sources/Setline/PlanViews.swift new file mode 100644 index 0000000..77d08be --- /dev/null +++ b/ios/Sources/Setline/PlanViews.swift @@ -0,0 +1,516 @@ +import SetlineCore +import SwiftUI + +struct PlanView: View { + @Environment(AppModel.self) private var model + @State private var editingTemplate: WorkoutTemplate? + @State private var isCreatingTemplate = false + @State private var showProgrammeSwitch = false + + var body: some View { + ScrollView { + VStack(alignment: .leading, spacing: 28) { + pageHeader("Plan", subtitle: "Templates stay authored. Sessions record deviations.") + programmeSection + templatesSection + } + .padding(20) + } + .setlineBackground() + .navigationBarHidden(true) + .sheet(isPresented: $isCreatingTemplate) { + TemplateEditorView() + } + .sheet(item: $editingTemplate) { template in + TemplateEditorView(template: template) + } + .confirmationDialog("Which programme drives Today?", isPresented: $showProgrammeSwitch) { + Button(TwelveWeekProgramme.shortName) { + Task { await model.selectProgramme(.bundled(.twelveWeekStrengthCardioMobility)) } + } + if let custom = model.document.programme.customProgramme { + Button(custom.name) { Task { await model.selectProgramme(.custom(custom)) } } + } else { + Button("Create a weekly programme") { + Task { await model.selectProgramme(.custom(CustomProgramme( + name: "My programme", + weekCount: 12, + enabled: true, + days: (1...7).map { ProgrammeDay(weekday: $0, templateID: nil) } + ))) } + } + } + Button("No programme") { Task { await model.selectProgramme(.none) } } + Button("Cancel", role: .cancel) {} + } + } + + // MARK: - Programme + + @ViewBuilder + private var programmeSection: some View { + VStack(alignment: .leading, spacing: 16) { + HStack(alignment: .top) { + VStack(alignment: .leading, spacing: 4) { + SectionLabel(text: "Active programme") + Text(programmeTitle).font(.title2.weight(.black)) + Text(programmeSubtitle) + .font(.subheadline) + .foregroundStyle(.secondary) + } + Spacer() + Button { + showProgrammeSwitch = true + } label: { + Label("Change", systemImage: "arrow.triangle.2.circlepath") + .font(.caption.weight(.bold)) + } + .frame(minHeight: 36) + } + switch model.document.programme { + case .bundled(.twelveWeekStrengthCardioMobility): + bundledProgrammeDetail + case let .custom(programme): + customProgrammeEditor(programme) + case .none: + Text("Today will offer your first template until a programme is chosen.") + .font(.subheadline) + .foregroundStyle(.secondary) + } + } + .padding(18) + .background(SetlinePalette.paper) + .clipShape(RoundedRectangle(cornerRadius: 14)) + } + + private var programmeTitle: String { + switch model.document.programme { + case let .bundled(id): id.title + case let .custom(programme): programme.name + case .none: "No programme" + } + } + + private var programmeSubtitle: String { + switch model.document.programme { + case .bundled(.twelveWeekStrengthCardioMobility): + let position = TwelveWeekProgramme.position(for: .now) + return "Week \(position.weekNumber) of 12 · authored, Monday-based" + case let .custom(programme): + return "\(programme.weekCount) weeks · \(programme.enabled ? "running" : "paused")" + case .none: + return "Choose a programme to schedule Today" + } + } + + private var bundledProgrammeDetail: some View { + let position = TwelveWeekProgramme.position(for: .now) + return VStack(alignment: .leading, spacing: 14) { + LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 6), count: 7), spacing: 6) { + ForEach(TwelveWeekProgramme.schedule) { entry in + VStack(spacing: 5) { + Text(entry.dayLabel) + .font(.caption2.weight(.bold)) + Text(entry.title) + .font(.system(size: 9, weight: .bold)) + .lineLimit(2) + .minimumScaleFactor(0.7) + .multilineTextAlignment(.center) + } + .frame(maxWidth: .infinity, minHeight: 56) + .padding(4) + .background(entry.dayIndex == position.dayIndex ? SetlinePalette.lime : SetlinePalette.blue.opacity(0.55)) + .clipShape(RoundedRectangle(cornerRadius: 8)) + .accessibilityLabel("\(entry.dayLabel): \(entry.title)") + } + } + InkRule() + SectionLabel(text: "Sessions in this block") + ForEach(ProgrammeSessionKind.allCases, id: \.self) { kind in + let template = TwelveWeekProgramme.template(for: kind, week: position.weekNumber) + NavigationLink { + SessionPreviewView(resolved: ResolvedSession( + template: template, + programmeWeek: position.weekNumber, + subtitle: "Week \(position.weekNumber)", + notes: template.notes + )) + } label: { + HStack { + VStack(alignment: .leading, spacing: 2) { + Text(template.name).font(.subheadline.weight(.bold)) + Text("\(template.exercises.count) exercises · \(template.workingSetCount) working sets") + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + } + Spacer() + Image(systemName: "chevron.right").font(.caption) + } + .foregroundStyle(SetlinePalette.ink) + .padding(.vertical, 6) + } + } + InkRule() + SectionLabel(text: "Checkpoints") + ForEach(TwelveWeekProgramme.checkpoints) { checkpoint in + HStack { + Text(checkpoint.name).font(.caption.weight(.bold)) + Spacer() + Text(TwelveWeekProgramme.checkpointDate(checkpoint) + .formatted(date: .abbreviated, time: .omitted)) + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + } + } + Text("Record \(TwelveWeekProgramme.checkpointMeasures.count) measures at each checkpoint, including knee-to-wall distance and squat support.") + .font(.caption) + .foregroundStyle(.secondary) + } + } + + private func customProgrammeEditor(_ programme: CustomProgramme) -> some View { + VStack(alignment: .leading, spacing: 14) { + Toggle("Running", isOn: Binding( + get: { programme.enabled }, + set: { _ in Task { await model.toggleProgramme() } } + )) + LazyVGrid(columns: Array(repeating: GridItem(.flexible(), spacing: 6), count: 7), spacing: 6) { + ForEach(programme.days) { day in + Menu { + Button("Rest day") { + Task { await model.assignTemplate(nil, to: day.weekday) } + } + ForEach(model.document.templates) { template in + Button(template.name) { + Task { await model.assignTemplate(template.id, to: day.weekday) } + } + } + } label: { + VStack(spacing: 7) { + Text(Calendar.current.shortWeekdaySymbols[day.weekday - 1].prefix(2)) + .font(.caption2.weight(.bold)) + Image(systemName: day.templateID == nil ? "minus" : "checkmark") + .font(.caption.weight(.black)) + } + .frame(maxWidth: .infinity, minHeight: 52) + .background(day.templateID == nil ? SetlinePalette.steel.opacity(0.55) : SetlinePalette.lime) + .clipShape(RoundedRectangle(cornerRadius: 8)) + } + .accessibilityLabel("\(Calendar.current.weekdaySymbols[day.weekday - 1]), \(templateName(for: day.templateID))") + } + } + Stepper( + "Block length: \(programme.weekCount) weeks", + value: Binding( + get: { programme.weekCount }, + set: { weeks in Task { await model.setProgrammeWeeks(weeks) } } + ), + in: 1...16 + ) + } + } + + // MARK: - Templates + + private var templatesSection: some View { + VStack(alignment: .leading, spacing: 10) { + HStack { + SectionLabel(text: "Workout templates") + Spacer() + Button { isCreatingTemplate = true } label: { + Label("New template", systemImage: "plus") + } + .font(.subheadline.weight(.bold)) + .frame(minHeight: 44) + } + if model.document.templates.isEmpty { + Text("The authored block resolves its own sessions. Add a template for anything outside it.") + .font(.subheadline) + .foregroundStyle(.secondary) + } + ForEach(model.document.templates) { template in + VStack(alignment: .leading, spacing: 12) { + HStack(alignment: .top) { + VStack(alignment: .leading, spacing: 4) { + Text(template.name).font(.title3.weight(.black)) + Text(template.detail).font(.subheadline).foregroundStyle(.secondary) + } + Spacer() + Text(template.isBundled ? "BUNDLED" : "CUSTOM") + .font(.caption2.weight(.black)) + .padding(6) + .background(template.isBundled ? SetlinePalette.blue : SetlinePalette.lime) + .clipShape(RoundedRectangle(cornerRadius: 6)) + } + HStack { + Text("\(template.exercises.count) exercises") + Text("·") + Text("\(template.workingSetCount) working") + Spacer() + Button("Duplicate") { Task { await model.duplicateTemplate(template) } } + .font(.subheadline.weight(.bold)) + if !template.isBundled { + Button("Edit") { editingTemplate = template } + .font(.subheadline.weight(.bold)) + } + } + .font(.subheadline.monospacedDigit()) + InkRule() + } + .padding(.vertical, 8) + } + } + } + + private func templateName(for id: UUID?) -> String { + guard let id else { return "rest day" } + return model.document.templates.first(where: { $0.id == id })?.name ?? "unavailable template" + } +} + +/// Authors a template with structured targets rather than free text, so +/// everything entered here can drive progression and measurement. +struct TemplateEditorView: View { + @Environment(AppModel.self) private var model + @Environment(\.dismiss) private var dismiss + @State private var draft: WorkoutTemplate + + init(template: WorkoutTemplate? = nil) { + _draft = State(initialValue: template ?? WorkoutTemplate( + name: "", + detail: "", + isBundled: false, + exercises: [Self.blankExercise()] + )) + } + + static func blankExercise() -> Exercise { + Exercise( + name: "", + cue: "", + sets: [PlannedSet( + label: "Working 1", + kind: .strength, + target: SetTarget(repsLow: 8, load: .chooseLoad), + rest: RestRange(90) + )] + ) + } + + var body: some View { + NavigationStack { + Form { + Section("Template") { + TextField("Name", text: $draft.name) + TextField("Short description", text: $draft.detail, axis: .vertical) + } + ForEach($draft.exercises) { $exercise in + Section { + exerciseFields($exercise) + ForEach($exercise.sets) { $plannedSet in + setFields($plannedSet, in: $exercise) + } + Button { + exercise.sets.append(PlannedSet( + label: "Working \(exercise.sets.count + 1)", + kind: exercise.sets.last?.kind ?? .strength, + stepType: .working, + target: exercise.sets.last?.target ?? SetTarget(repsLow: 8, load: .chooseLoad), + rest: exercise.sets.last?.rest ?? RestRange(90) + )) + } label: { + Label("Add set", systemImage: "plus") + } + Button("Remove exercise", role: .destructive) { + draft.exercises.removeAll { $0.id == exercise.id } + } + } header: { + Text(exercise.name.isEmpty ? "Exercise" : exercise.name) + } + } + Section { + Button { + draft.exercises.append(Self.blankExercise()) + } label: { + Label("Add exercise", systemImage: "plus") + } + } + } + .navigationTitle(draft.name.isEmpty ? "New template" : "Edit template") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { + Button("Cancel") { dismiss() } + } + ToolbarItem(placement: .confirmationAction) { + Button("Save") { + Task { + await model.saveTemplate(linked(draft)) + dismiss() + } + } + .disabled(!isValid) + } + } + } + } + + @ViewBuilder + private func exerciseFields(_ exercise: Binding) -> some View { + TextField("Exercise name", text: exercise.name) + .onChange(of: exercise.wrappedValue.name) { _, newValue in + // Resolving to the catalogue as you type keeps measurements unified. + guard let definition = ExerciseCatalogue.match(name: newValue) else { return } + exercise.wrappedValue.definitionSlug = definition.slug + exercise.wrappedValue.pillars = definition.pillars + if exercise.wrappedValue.cue.isEmpty { + exercise.wrappedValue.cue = definition.cue + } + } + if let definition = ExerciseCatalogue.match(name: exercise.wrappedValue.name) { + Label("Matched \(definition.name) in the library", systemImage: "checkmark.seal") + .font(.caption) + .foregroundStyle(.secondary) + } else if !exercise.wrappedValue.name.isEmpty { + Label("Not in the library — measurements still record under this name", systemImage: "info.circle") + .font(.caption) + .foregroundStyle(.secondary) + } + TextField("Coaching cue", text: exercise.cue, axis: .vertical) + } + + @ViewBuilder + private func setFields(_ plannedSet: Binding, in exercise: Binding) -> some View { + VStack(alignment: .leading, spacing: 10) { + TextField("Set label", text: plannedSet.label) + Picker("Counts as", selection: plannedSet.stepType) { + ForEach(StepType.allCases, id: \.self) { type in + Text(type.title).tag(type) + } + } + Picker("Activity", selection: plannedSet.kind) { + ForEach(ActivityKind.allCases, id: \.self) { kind in + Text(kind.rawValue.capitalized).tag(kind) + } + } + targetFields(plannedSet) + Stepper( + "Rest: \(plannedSet.wrappedValue.rest.displayString)", + value: Binding( + get: { plannedSet.wrappedValue.rest.lowSeconds }, + set: { plannedSet.wrappedValue.rest = RestRange($0) } + ), + in: 0...600, + step: 15 + ) + Toggle("Optional", isOn: plannedSet.isOptional) + Button("Remove set", role: .destructive) { + exercise.wrappedValue.sets.removeAll { $0.id == plannedSet.wrappedValue.id } + } + } + } + + @ViewBuilder + private func targetFields(_ plannedSet: Binding) -> some View { + let kind = plannedSet.wrappedValue.kind + if kind == .strength || kind == .repetitions || kind == .mobility { + HStack { + Text("Reps") + Spacer() + TextField("low", text: intBinding(plannedSet.target.repsLow)) + .frame(width: 48) + .multilineTextAlignment(.trailing) + .keyboardType(.numberPad) + Text("–") + TextField("high", text: intBinding(plannedSet.target.repsHigh)) + .frame(width: 48) + .multilineTextAlignment(.trailing) + .keyboardType(.numberPad) + } + } + if kind == .strength || kind == .timed { + HStack { + Text("Load") + Spacer() + TextField("kg, blank to choose", text: loadBinding(plannedSet.target.load)) + .frame(width: 140) + .multilineTextAlignment(.trailing) + .keyboardType(.decimalPad) + } + } + if kind == .timed { + HStack { + Text("Hold") + Spacer() + TextField("seconds", text: intBinding(plannedSet.target.holdSeconds)) + .frame(width: 80) + .multilineTextAlignment(.trailing) + .keyboardType(.numberPad) + } + } + if kind == .cardio { + HStack { + Text("Duration") + Spacer() + TextField("seconds", text: intBinding(plannedSet.target.timeSeconds)) + .frame(width: 80) + .multilineTextAlignment(.trailing) + .keyboardType(.numberPad) + } + } + HStack { + Text("Reps in reserve") + Spacer() + TextField("optional", text: intBinding(plannedSet.target.repsInReserve)) + .frame(width: 80) + .multilineTextAlignment(.trailing) + .keyboardType(.numberPad) + } + Toggle("Per side", isOn: plannedSet.target.perSide) + LabeledContent("Reads as", value: plannedSet.wrappedValue.target.displayString) + .font(.caption) + } + + private func intBinding(_ source: Binding) -> Binding { + Binding( + get: { source.wrappedValue.map(String.init) ?? "" }, + set: { source.wrappedValue = Int($0) } + ) + } + + private func loadBinding(_ source: Binding) -> Binding { + Binding( + get: { + guard case let .absolute(kilograms) = source.wrappedValue else { return "" } + return kilograms.trimmedString + }, + set: { text in + guard let value = Double(text) else { + source.wrappedValue = .chooseLoad + return + } + source.wrappedValue = .absolute(kilograms: value) + } + ) + } + + private func linked(_ template: WorkoutTemplate) -> WorkoutTemplate { + var result = template + result.exercises = result.exercises.map { exercise in + guard let definition = ExerciseCatalogue.match(name: exercise.name) else { return exercise } + var linked = exercise + linked.definitionSlug = definition.slug + linked.pillars = definition.pillars + return linked + } + return result + } + + private var isValid: Bool { + !draft.name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty + && !draft.exercises.isEmpty + && !draft.exercises.contains { exercise in + exercise.name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || exercise.sets.isEmpty + } + } +} diff --git a/ios/Sources/Setline/RestNotifier.swift b/ios/Sources/Setline/RestNotifier.swift new file mode 100644 index 0000000..b357697 --- /dev/null +++ b/ios/Sources/Setline/RestNotifier.swift @@ -0,0 +1,103 @@ +import SetlineCore +import UserNotifications + +/// Fires a local notification when an authored rest period ends. +/// +/// Without this the rest timer only exists while Setline is on screen, which is +/// precisely when it is least useful — you put the phone down between sets. The +/// notification is scheduled against the rest's wall-clock end, so it stays +/// correct whether the app is backgrounded, locked or terminated. +/// +/// Every call into `UNUserNotificationCenter` resolves `.current()` at the point +/// of use rather than holding it. Neither the centre nor its settings object is +/// marked Sendable on every SDK Setline builds against, so storing one and then +/// touching it from an async context compiles against some SDKs and fails as a +/// data-race error on others. Resolving it inside a synchronous or nonisolated +/// scope keeps a non-Sendable value from ever crossing an isolation boundary. +@MainActor +final class RestNotifier { + private static let identifier = "setline.rest.complete" + + private var hasRequestedAuthorisation = false + + /// Schedules, reschedules or clears the alert to match the session's rest. + /// + /// Called after every rest change, so an adjusted or ended rest never leaves a + /// stale alert queued. + func update(for rest: RestState?, nextStep: WorkoutStep?) async { + cancel() + guard let rest else { return } + let remaining = rest.remaining() + guard remaining > 0 else { return } + guard await ensureAuthorisation() else { return } + + let content = UNMutableNotificationContent() + content.title = "Rest complete" + if let nextStep { + content.body = "\(nextStep.exerciseName) · \(nextStep.target.displayString)" + } else { + content.body = "Return to Setline for the next set." + } + content.sound = .default + content.interruptionLevel = .timeSensitive + + let trigger = UNTimeIntervalNotificationTrigger( + timeInterval: TimeInterval(remaining), + repeats: false + ) + Self.schedule( + UNNotificationRequest( + identifier: Self.identifier, + content: content, + trigger: trigger + ) + ) + } + + func cancel() { + let centre = UNUserNotificationCenter.current() + centre.removePendingNotificationRequests(withIdentifiers: [Self.identifier]) + centre.removeDeliveredNotifications(withIdentifiers: [Self.identifier]) + } + + /// Asks once. A refusal is respected silently — resting still works on screen. + private func ensureAuthorisation() async -> Bool { + switch await Self.authorisationStatus() { + case .authorized, .provisional, .ephemeral: + return true + case .denied: + return false + case .notDetermined: + guard !hasRequestedAuthorisation else { return false } + hasRequestedAuthorisation = true + return await Self.requestAuthorisation() + @unknown default: + return false + } + } + + /// Synchronous, so handing the request over never crosses an isolation boundary. + /// A failure to queue is ignored for the same reason a refusal is: rest still + /// runs on screen, and there is nothing useful to say mid-set. + private nonisolated static func schedule(_ request: UNNotificationRequest) { + UNUserNotificationCenter.current().add(request, withCompletionHandler: nil) + } + + /// Returns only the status, never the settings object that carries it. + private nonisolated static func authorisationStatus() async -> UNAuthorizationStatus { + await withCheckedContinuation { continuation in + UNUserNotificationCenter.current().getNotificationSettings { settings in + continuation.resume(returning: settings.authorizationStatus) + } + } + } + + private nonisolated static func requestAuthorisation() async -> Bool { + await withCheckedContinuation { continuation in + UNUserNotificationCenter.current() + .requestAuthorization(options: [.alert, .sound]) { granted, _ in + continuation.resume(returning: granted) + } + } + } +} diff --git a/ios/Sources/Setline/RootView.swift b/ios/Sources/Setline/RootView.swift index 78775b6..c184bf1 100644 --- a/ios/Sources/Setline/RootView.swift +++ b/ios/Sources/Setline/RootView.swift @@ -20,6 +20,9 @@ struct RootView: View { NavigationStack { SettingsView() } .tabItem { Label("You", systemImage: "person.crop.circle") } .tag(3) + NavigationStack { ExercisesView() } + .tabItem { Label("Exercises", systemImage: "chart.line.uptrend.xyaxis") } + .tag(4) } .setlineBackground() .fullScreenCover(isPresented: $model.isWorkoutPresented) { @@ -40,13 +43,7 @@ struct TodayView: View { @Environment(AppModel.self) private var model @Environment(\.dynamicTypeSize) private var dynamicTypeSize - private var plannedTemplate: WorkoutTemplate? { - let weekday = Calendar.current.component(.weekday, from: .now) - guard let id = model.document.programme?.days.first(where: { $0.weekday == weekday })?.templateID else { - return model.document.templates.first - } - return model.document.templates.first(where: { $0.id == id }) ?? model.document.templates.first - } + private var resolved: ResolvedSession? { model.document.session() } var body: some View { ScrollView { @@ -54,8 +51,14 @@ struct TodayView: View { header if let active = model.document.activeSession { activeReceipt(active) - } else if let plannedTemplate { - workoutHero(plannedTemplate) + } else if let resolved { + workoutHero(resolved) + } else { + ContentUnavailableView( + "No programme selected", + systemImage: "calendar.badge.plus", + description: Text("Choose the authored block or build your own in Plan.") + ) } weekStrip recentEvidence @@ -103,45 +106,70 @@ struct TodayView: View { .font(.subheadline.monospacedDigit().weight(.semibold)) } - private func workoutHero(_ template: WorkoutTemplate) -> some View { + private func workoutHero(_ resolved: ResolvedSession) -> some View { VStack(alignment: .leading, spacing: 0) { HStack { - SectionLabel(text: "Today · authored plan") + SectionLabel(text: resolved.isRestDay ? "Today · scheduled rest" : "Today · authored plan") Spacer() Image(systemName: "lock.fill") .font(.caption) } .padding(.bottom, 14) - Text(template.name) + Text(resolved.template.name) .font(.system(.title, design: .rounded, weight: .black)) .tracking(-0.8) - Text(template.detail) + Text(resolved.subtitle) .font(.title3.weight(.medium)) .foregroundStyle(SetlinePalette.ink.opacity(0.66)) .padding(.top, 3) - Group { - if dynamicTypeSize.isAccessibilitySize { - VStack(alignment: .leading, spacing: 12) { - metric("EXERCISES", "\(template.exercises.count)") - metric("SETS", "\(template.exercises.flatMap(\.sets).count)") - metric("MODE", "OFFLINE") - } - } else { - HStack(spacing: 0) { - metric("EXERCISES", "\(template.exercises.count)") - metric("SETS", "\(template.exercises.flatMap(\.sets).count)") - metric("MODE", "OFFLINE") + if let notice = resolved.outOfBlockNotice { + Text(notice) + .font(.footnote.weight(.medium)) + .foregroundStyle(SetlinePalette.ink.opacity(0.7)) + .padding(10) + .frame(maxWidth: .infinity, alignment: .leading) + .background(SetlinePalette.blue.opacity(0.5)) + .clipShape(RoundedRectangle(cornerRadius: 8)) + .padding(.top, 12) + } + if !resolved.isRestDay { + Group { + if dynamicTypeSize.isAccessibilitySize { + VStack(alignment: .leading, spacing: 12) { metrics(resolved.template) } + } else { + HStack(spacing: 0) { metrics(resolved.template) } } } + .padding(.vertical, 22) + pillarChips(resolved.template.pillars) + .padding(.bottom, 18) + Button { + Task { await model.startWorkout(resolved) } + } label: { + Label("Start workout", systemImage: "arrow.right") + } + .buttonStyle(ActionSlabStyle()) + .accessibilityHint("Starts an offline workout using the authored order") + NavigationLink { + SessionPreviewView(resolved: resolved) + } label: { + Label("Review the session first", systemImage: "list.bullet") + .font(.subheadline.weight(.bold)) + .frame(maxWidth: .infinity, minHeight: 44) + } } - .padding(.vertical, 22) - Button { - Task { await model.startWorkout(template) } - } label: { - Label("Start workout", systemImage: "arrow.right") + if !resolved.notes.isEmpty { + VStack(alignment: .leading, spacing: 8) { + InkRule() + SectionLabel(text: "Authored rules") + ForEach(Array(resolved.notes.enumerated()), id: \.offset) { _, note in + Text("· \(note)") + .font(.footnote) + .foregroundStyle(SetlinePalette.ink.opacity(0.72)) + } + } + .padding(.top, 16) } - .buttonStyle(ActionSlabStyle()) - .accessibilityHint("Starts an offline workout using the authored order") } .padding(20) .background(SetlinePalette.paper) @@ -152,6 +180,27 @@ struct TodayView: View { } } + /// Scrolls rather than wraps: four pillars cannot share one phone-width row + /// without hyphenating, and a broken word reads as a rendering fault. + private func pillarChips(_ pillars: Set) -> some View { + ScrollView(.horizontal, showsIndicators: false) { + HStack(spacing: 6) { + ForEach(Pillar.allCases.filter { pillars.contains($0) }, id: \.self) { pillar in + Text(pillar.title.uppercased()) + .font(.caption2.weight(.black)) + .tracking(0.6) + .lineLimit(1) + .fixedSize() + .padding(.horizontal, 9) + .padding(.vertical, 5) + .background(SetlinePalette.blue.opacity(0.7)) + .clipShape(Capsule()) + } + } + } + .scrollBounceBehavior(.basedOnSize) + } + private func activeReceipt(_ session: WorkoutSession) -> some View { VStack(alignment: .leading, spacing: 16) { SectionLabel(text: "Workout in progress") @@ -171,6 +220,19 @@ struct TodayView: View { .clipShape(RoundedRectangle(cornerRadius: 14, style: .continuous)) } + /// Cardio and mobility days author no working sets, so counting them would + /// read as zero effort. Those sessions report their step count instead. + @ViewBuilder + private func metrics(_ template: WorkoutTemplate) -> some View { + metric("EXERCISES", "\(template.exercises.count)") + if template.workingSetCount > 0 { + metric("WORKING", "\(template.workingSetCount)") + } else { + metric("STEPS", "\(template.plannedSetCount)") + } + metric("MINUTES", template.expectedMinutes.map(String.init) ?? "—") + } + private func metric(_ label: String, _ value: String) -> some View { VStack(alignment: .leading, spacing: 5) { Text(value) @@ -183,27 +245,61 @@ struct TodayView: View { } private var weekStrip: some View { - VStack(alignment: .leading, spacing: 14) { + let week = model.document.week() + let todayIndex = todayStripIndex + return VStack(alignment: .leading, spacing: 14) { SectionLabel(text: "This week") HStack(spacing: 7) { - ForEach(1...7, id: \.self) { index in - let hasPlan = model.document.programme?.days.first(where: { $0.weekday == index })?.templateID != nil - VStack(spacing: 8) { - Text(Calendar.current.veryShortWeekdaySymbols[index - 1]) + ForEach(Array(week.enumerated()), id: \.offset) { index, day in + let hasPlan = day != nil && !(day?.isRestDay ?? true) + VStack(spacing: 6) { + Text(stripDayLabel(index)) .font(.caption2.weight(.bold)) Circle() .fill(hasPlan ? SetlinePalette.ink : SetlinePalette.steel) .frame(width: 9, height: 9) + Text(stripSessionLabel(day)) + .font(.system(size: 9, weight: .bold)) + .lineLimit(1) + .minimumScaleFactor(0.7) + .foregroundStyle(SetlinePalette.ink.opacity(0.7)) } .frame(maxWidth: .infinity) - .padding(.vertical, 12) - .background(hasPlan ? SetlinePalette.blue.opacity(0.65) : .clear) + .padding(.vertical, 10) + .background(index == todayIndex ? SetlinePalette.lime : (hasPlan ? SetlinePalette.blue.opacity(0.65) : .clear)) .clipShape(RoundedRectangle(cornerRadius: 9)) + .accessibilityLabel("\(stripDayLabel(index)): \(day.map { $0.isRestDay ? "rest day" : $0.template.name } ?? "nothing scheduled")") } } } } + /// The bundled block runs Monday-first; custom programmes follow the locale week. + private var todayStripIndex: Int { + switch model.document.programme { + case .bundled: + TwelveWeekProgramme.position(for: .now).dayIndex + case .custom, .none: + Calendar.current.component(.weekday, from: .now) - 1 + } + } + + private func stripDayLabel(_ index: Int) -> String { + let symbols = Calendar.current.veryShortWeekdaySymbols + switch model.document.programme { + case .bundled: + return symbols[(index + 1) % 7] + case .custom, .none: + return symbols[index % 7] + } + } + + private func stripSessionLabel(_ day: ResolvedSession?) -> String { + guard let day else { return "—" } + if day.isRestDay { return "Rest" } + return day.template.name + } + private var recentEvidence: some View { VStack(alignment: .leading, spacing: 14) { SectionLabel(text: "Recorded evidence") @@ -216,8 +312,13 @@ struct TodayView: View { .foregroundStyle(.secondary) } Spacer() - Text("\(latest.completedCount)") - .font(.system(size: 30, weight: .black, design: .rounded).monospacedDigit()) + VStack(alignment: .trailing, spacing: 2) { + Text("\(latest.completedWorkingSetCount)") + .font(.system(size: 30, weight: .black, design: .rounded).monospacedDigit()) + Text("WORKING SETS") + .font(.system(size: 9, weight: .bold)) + .foregroundStyle(SetlinePalette.ink.opacity(0.55)) + } } .padding(.vertical, 12) InkRule() @@ -229,3 +330,55 @@ struct TodayView: View { } } } + +/// The full authored session, readable before you start it — so the PDF is never +/// needed in the gym. +struct SessionPreviewView: View { + let resolved: ResolvedSession + + var body: some View { + List { + if !resolved.notes.isEmpty { + Section("Authored rules") { + ForEach(Array(resolved.notes.enumerated()), id: \.offset) { _, note in + Text(note).font(.footnote) + } + } + } + ForEach(resolved.template.exercises) { exercise in + Section { + ForEach(exercise.sets) { plannedSet in + VStack(alignment: .leading, spacing: 4) { + HStack { + Text(plannedSet.label) + .font(.subheadline.weight(.semibold)) + Spacer() + Text(plannedSet.stepType.title.uppercased()) + .font(.system(size: 9, weight: .black)) + .foregroundStyle(SetlinePalette.ink.opacity(0.5)) + } + Text(plannedSet.target.displayString) + .font(.headline.monospacedDigit()) + let qualifiers = plannedSet.target.qualifiers + + (plannedSet.rest.isEmpty ? [] : ["Rest \(plannedSet.rest.displayString)"]) + + (plannedSet.isOptional ? ["Optional"] : []) + if !qualifiers.isEmpty { + Text(qualifiers.joined(separator: " · ")) + .font(.caption) + .foregroundStyle(.secondary) + } + if let cue = plannedSet.cue, !cue.isEmpty { + Text(cue).font(.caption).foregroundStyle(.secondary) + } + } + .padding(.vertical, 2) + } + } header: { + Text(exercise.name) + } + } + } + .navigationTitle(resolved.template.name) + .navigationBarTitleDisplayMode(.inline) + } +} diff --git a/ios/Sources/Setline/SecondaryViews.swift b/ios/Sources/Setline/SecondaryViews.swift index cc58ada..c6a493b 100644 --- a/ios/Sources/Setline/SecondaryViews.swift +++ b/ios/Sources/Setline/SecondaryViews.swift @@ -1,449 +1,18 @@ -import AuthenticationServices import SetlineCore import SwiftUI import UniformTypeIdentifiers -struct PlanView: View { - @Environment(AppModel.self) private var model - @State private var editingTemplate: WorkoutTemplate? - @State private var isCreatingTemplate = false - - var body: some View { - ScrollView { - VStack(alignment: .leading, spacing: 28) { - pageHeader("Plan", subtitle: "Templates stay authored. Sessions record deviations.") - if let programme = model.document.programme { - VStack(alignment: .leading, spacing: 16) { - HStack { - VStack(alignment: .leading, spacing: 4) { - SectionLabel(text: "Active programme") - Text(programme.name).font(.title2.weight(.black)) - Text("\(programme.weekCount) weeks · Monday-based") - .font(.subheadline).foregroundStyle(.secondary) - } - Spacer() - Toggle("Enabled", isOn: Binding( - get: { programme.enabled }, - set: { _ in Task { await model.toggleProgramme() } } - )) - .labelsHidden() - } - LazyVGrid( - columns: Array(repeating: GridItem(.flexible(), spacing: 6), count: 7), - spacing: 6 - ) { - ForEach(programme.days) { day in - Menu { - Button("Rest day") { - Task { await model.assignTemplate(nil, to: day.weekday) } - } - ForEach(model.document.templates) { template in - Button(template.name) { - Task { await model.assignTemplate(template.id, to: day.weekday) } - } - } - } label: { - VStack(spacing: 7) { - Text(Calendar.current.shortWeekdaySymbols[day.weekday - 1].prefix(2)) - .font(.caption2.weight(.bold)) - Image(systemName: day.templateID == nil ? "minus" : "checkmark") - .font(.caption.weight(.black)) - } - .frame(maxWidth: .infinity, minHeight: 52) - .background(day.templateID == nil ? SetlinePalette.steel.opacity(0.55) : SetlinePalette.lime) - .clipShape(RoundedRectangle(cornerRadius: 8)) - } - .accessibilityLabel("\(Calendar.current.weekdaySymbols[day.weekday - 1]), \(templateName(for: day.templateID))") - } - } - Stepper( - "Block length: \(programme.weekCount) weeks", - value: Binding( - get: { programme.weekCount }, - set: { weeks in Task { await model.setProgrammeWeeks(weeks) } } - ), - in: 1...16 - ) - } - .padding(18) - .background(SetlinePalette.paper) - .clipShape(RoundedRectangle(cornerRadius: 14)) - } - VStack(alignment: .leading, spacing: 10) { - HStack { - SectionLabel(text: "Workout templates") - Spacer() - Button { isCreatingTemplate = true } label: { - Label("New template", systemImage: "plus") - } - .font(.subheadline.weight(.bold)) - .frame(minHeight: 44) - } - ForEach(model.document.templates) { template in - VStack(alignment: .leading, spacing: 12) { - HStack(alignment: .top) { - VStack(alignment: .leading, spacing: 4) { - Text(template.name).font(.title3.weight(.black)) - Text(template.detail).font(.subheadline).foregroundStyle(.secondary) - } - Spacer() - Text(template.isBundled ? "BUNDLED" : "CUSTOM") - .font(.caption2.weight(.black)) - .padding(6) - .background(template.isBundled ? SetlinePalette.blue : SetlinePalette.lime) - .clipShape(RoundedRectangle(cornerRadius: 6)) - } - HStack { - Text("\(template.exercises.count) exercises") - Text("·") - Text("\(template.exercises.flatMap(\.sets).count) sets") - Spacer() - Button("Duplicate") { Task { await model.duplicateTemplate(template) } } - .font(.subheadline.weight(.bold)) - if !template.isBundled { - Button("Edit") { editingTemplate = template } - .font(.subheadline.weight(.bold)) - } - } - .font(.subheadline.monospacedDigit()) - InkRule() - } - .padding(.vertical, 8) - } - } - } - .padding(20) - } - .setlineBackground() - .navigationBarHidden(true) - .sheet(isPresented: $isCreatingTemplate) { - TemplateEditorView() - } - .sheet(item: $editingTemplate) { template in - TemplateEditorView(template: template) - } - } - - private func templateName(for id: UUID?) -> String { - guard let id else { return "rest day" } - return model.document.templates.first(where: { $0.id == id })?.name ?? "unavailable template" - } -} - -struct HistoryView: View { - @Environment(AppModel.self) private var model - - var body: some View { - ScrollView { - VStack(alignment: .leading, spacing: 26) { - pageHeader("History", subtitle: "Recorded, calculated, and unavailable stay distinct.") - HStack(spacing: 10) { - historyMetric("SESSIONS", "\(model.document.history.count)", SetlinePalette.blue) - historyMetric("SETS", "\(model.document.history.reduce(0) { $0 + $1.completedCount })", SetlinePalette.lime) - } - progressionSection - if model.document.history.isEmpty { - ContentUnavailableView( - "No recorded workouts", - systemImage: "clock.arrow.circlepath", - description: Text("Complete a workout to create evidence. Setline will not invent a chart first.") - ) - .frame(minHeight: 320) - } else { - ForEach(model.document.history) { session in - NavigationLink { - SessionDetailView(session: session) - } label: { - HStack(alignment: .top, spacing: 14) { - VStack(spacing: 3) { - Text(session.completedAt?.formatted(.dateTime.day()) ?? "–") - .font(.title2.monospacedDigit().weight(.black)) - Text(session.completedAt?.formatted(.dateTime.month(.abbreviated)) ?? "") - .font(.caption.weight(.bold)) - } - .frame(width: 52, height: 58) - .background(SetlinePalette.blue) - .clipShape(RoundedRectangle(cornerRadius: 8)) - VStack(alignment: .leading, spacing: 5) { - Text(session.templateName).font(.headline.weight(.black)) - Text("\(session.completedCount) completed · \(session.steps.count - session.completedCount) skipped") - .font(.subheadline.monospacedDigit()) - .foregroundStyle(.secondary) - } - Spacer() - Image(systemName: "chevron.right") - } - .foregroundStyle(SetlinePalette.ink) - .padding(.vertical, 8) - } - InkRule() - } - } - } - .padding(20) - } - .setlineBackground() - .navigationBarHidden(true) - } - - private var progressionSection: some View { - let exerciseNames = Array(Set(model.document.history.flatMap(\.steps).map(\.exerciseName))).sorted() - let recommendations = exerciseNames.compactMap { - ProgressionEngine.recommendation(for: $0, history: model.document.history) - } - return VStack(alignment: .leading, spacing: 10) { - SectionLabel(text: "Next-session suggestions") - if recommendations.isEmpty { - Text("Unavailable until at least two comparable completed strength sets establish evidence.") - .font(.subheadline) - .foregroundStyle(.secondary) - } else { - ForEach(recommendations, id: \.exerciseName) { recommendation in - VStack(alignment: .leading, spacing: 5) { - Text(recommendation.exerciseName).font(.headline) - Text("\(recommendation.previousWeight.formatted()) → \(recommendation.recommendedWeight.formatted()) kg") - .font(.title3.monospacedDigit().weight(.black)) - Text(recommendation.rationale).font(.caption).foregroundStyle(.secondary) - } - .padding(14) - .background(SetlinePalette.paper) - .clipShape(RoundedRectangle(cornerRadius: 12)) - } - } - } - } - - private func historyMetric(_ label: String, _ value: String, _ color: Color) -> some View { - VStack(alignment: .leading, spacing: 8) { - Text(value).font(.system(size: 36, weight: .black, design: .rounded).monospacedDigit()) - SectionLabel(text: label) - } - .frame(maxWidth: .infinity, alignment: .leading) - .padding(16) - .background(color) - .clipShape(RoundedRectangle(cornerRadius: 12)) - } -} - -private struct TemplateEditorView: View { - @Environment(AppModel.self) private var model - @Environment(\.dismiss) private var dismiss - @State private var draft: WorkoutTemplate - - init(template: WorkoutTemplate? = nil) { - _draft = State(initialValue: template ?? WorkoutTemplate( - name: "", - detail: "", - isBundled: false, - exercises: [ - Exercise( - name: "", - cue: "", - sets: [PlannedSet(label: "Working 1", kind: .strength, target: "", restSeconds: 90)] - ), - ] - )) - } - - var body: some View { - NavigationStack { - Form { - Section("Template") { - TextField("Name", text: $draft.name) - TextField("Short description", text: $draft.detail, axis: .vertical) - } - ForEach($draft.exercises) { $exercise in - Section { - TextField("Exercise name", text: $exercise.name) - TextField("Coaching cue", text: $exercise.cue, axis: .vertical) - ForEach($exercise.sets) { $set in - VStack(alignment: .leading, spacing: 10) { - TextField("Set label", text: $set.label) - Picker("Activity", selection: $set.kind) { - ForEach(ActivityKind.allCases, id: \.self) { kind in - Text(kind.rawValue.capitalized).tag(kind) - } - } - TextField("Target", text: $set.target) - Stepper("Rest: \(set.restSeconds) seconds", value: $set.restSeconds, in: 0...600, step: 15) - Button("Remove set", role: .destructive) { - exercise.sets.removeAll { $0.id == set.id } - } - } - } - Button { - exercise.sets.append(PlannedSet( - label: "Working \(exercise.sets.count + 1)", - kind: .strength, - target: "", - restSeconds: 90 - )) - } label: { - Label("Add set", systemImage: "plus") - } - Button("Remove exercise", role: .destructive) { - draft.exercises.removeAll { $0.id == exercise.id } - } - } header: { - Text(exercise.name.isEmpty ? "Exercise" : exercise.name) - } - } - Section { - Button { - draft.exercises.append(Exercise( - name: "", - cue: "", - sets: [PlannedSet(label: "Working 1", kind: .strength, target: "", restSeconds: 90)] - )) - } label: { - Label("Add exercise", systemImage: "plus") - } - } - } - .navigationTitle(draft.name.isEmpty ? "New template" : "Edit template") - .navigationBarTitleDisplayMode(.inline) - .toolbar { - ToolbarItem(placement: .cancellationAction) { - Button("Cancel") { dismiss() } - } - ToolbarItem(placement: .confirmationAction) { - Button("Save") { - Task { - await model.saveTemplate(draft) - dismiss() - } - } - .disabled( - draft.name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || - draft.exercises.isEmpty || - draft.exercises.contains { exercise in - exercise.name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || exercise.sets.isEmpty - } - ) - } - } - } - } -} - -private struct SessionDetailView: View { - let session: WorkoutSession - - var body: some View { - List { - Section("Session receipt") { - LabeledContent("Workout", value: session.templateName) - LabeledContent("Started", value: session.startedAt.formatted(date: .abbreviated, time: .shortened)) - if let completedAt = session.completedAt { - LabeledContent("Completed", value: completedAt.formatted(date: .abbreviated, time: .shortened)) - } - } - Section("Execution ledger") { - ForEach(Array(session.steps.enumerated()), id: \.element.id) { performed, step in - VStack(alignment: .leading, spacing: 5) { - HStack { - Text(step.exerciseName).font(.headline) - Spacer() - Text(step.status.rawValue.uppercased()).font(.caption.weight(.black)) - } - Text("Planned #\(step.authoredPosition + 1) · performed \(step.performedPosition.map { "#\($0 + 1)" } ?? "—")") - .font(.caption.monospacedDigit()).foregroundStyle(.secondary) - Text("Target: \(step.target)").font(.subheadline) - if !step.segments.isEmpty { - Text("Recorded: " + step.segments.map(\.recordedDescription).joined(separator: " + ")) - .font(.subheadline.weight(.semibold)) - } - } - .padding(.vertical, 4) - } - } - } - .navigationTitle("Recorded workout") - } -} - struct SettingsView: View { @Environment(AppModel.self) private var model - @Environment(\.colorScheme) private var colorScheme @State private var isImporterPresented = false @State private var showResetConfirmation = false - @State private var showDeleteAccountConfirmation = false - @State private var appleNonce = AppleNonce.make() var body: some View { @Bindable var model = model ScrollView { VStack(alignment: .leading, spacing: 28) { pageHeader("You", subtitle: "Device-first. Nothing leaves this iPhone unless you choose it.") - settingsSection("Account & sync") { - HStack { - Image(systemName: "iphone.gen3") - .font(.title2) - .frame(width: 44, height: 44) - .background(SetlinePalette.blue) - .clipShape(RoundedRectangle(cornerRadius: 9)) - VStack(alignment: .leading, spacing: 3) { - Text(model.account?.name ?? "Device-only mode").font(.headline) - Text(model.account?.email ?? "Workout actions work offline.") - .font(.subheadline) - .foregroundStyle(.secondary) - } - Spacer() - Text(syncLabel(model.document.syncState).uppercased()) - .font(.caption2.weight(.black)) - } - if model.isAccountBusy { - HStack(spacing: 10) { - ProgressView() - Text("Contacting Setline…") - } - .frame(maxWidth: .infinity, minHeight: 48) - } else if model.account == nil { - Button { Task { await model.connectAccount() } } label: { - Label("Connect Google account", systemImage: "person.crop.circle.badge.plus") - .frame(maxWidth: .infinity, minHeight: 48) - .foregroundStyle(.white) - } - .buttonStyle(.borderedProminent) - .tint(SetlinePalette.ink) - appleAccountButton - } else { - if let lastSync = model.document.lastSyncedAt { - LabeledContent("Last synced") { - Text(lastSync, style: .relative).foregroundStyle(.secondary) - } - } - Button { Task { await model.syncNow() } } label: { - Label("Sync now", systemImage: "arrow.triangle.2.circlepath") - .frame(maxWidth: .infinity, minHeight: 48) - .foregroundStyle(.white) - } - .buttonStyle(.borderedProminent) - .tint(SetlinePalette.ink) - if model.account?.hasApple == false { - Text("Add Apple to this account so future Apple sign-ins open the same private workout copy.") - .font(.footnote) - .foregroundStyle(.secondary) - appleAccountButton - } - Button { Task { await model.signOut() } } label: { - Label("Sign out", systemImage: "rectangle.portrait.and.arrow.right") - .frame(maxWidth: .infinity, alignment: .leading) - } - .frame(minHeight: 48) - Button(role: .destructive) { showDeleteAccountConfirmation = true } label: { - Label("Delete Setline account", systemImage: "person.crop.circle.badge.minus") - .frame(maxWidth: .infinity, alignment: .leading) - } - .frame(minHeight: 48) - } - if let accountMessage = model.accountMessage { - Text(accountMessage) - .font(.footnote) - .foregroundStyle(.secondary) - .accessibilityLabel("Account status: \(accountMessage)") - } - } + storageSection settingsSection("Your data") { ShareLink( item: SetlineExportPayload(document: model.document), @@ -496,87 +65,43 @@ struct SettingsView: View { Button("Reset local data", role: .destructive) { Task { await model.resetLocalData() } } Button("Cancel", role: .cancel) {} } - .confirmationDialog( - "Delete your Setline account and private cloud copy?", - isPresented: $showDeleteAccountConfirmation - ) { - Button("Delete account", role: .destructive) { Task { await model.deleteAccount() } } - Button("Cancel", role: .cancel) {} - } message: { - Text("Workouts already saved on this iPhone remain local. This account action cannot be undone.") - } - .sheet(item: $model.cloudConflict) { conflict in - NavigationStack { - VStack(alignment: .leading, spacing: 22) { - Image(systemName: "arrow.triangle.branch") - .font(.system(size: 34, weight: .bold)) - .foregroundStyle(SetlinePalette.blue) - Text("Choose the workout copy to keep") - .font(.title2.bold()) - Text("This iPhone and your private account changed separately. Review the totals, then choose. Nothing is replaced until you decide.") + } + + /// States plainly where the training lives. There is no account to sign into + /// and no server holding a copy, so the screen says so rather than implying one. + private var storageSection: some View { + settingsSection("Storage") { + HStack { + Image(systemName: "iphone.gen3") + .font(.title2) + .frame(width: 44, height: 44) + .background(SetlinePalette.blue) + .clipShape(RoundedRectangle(cornerRadius: 9)) + VStack(alignment: .leading, spacing: 3) { + Text(storageTitle).font(.headline) + Text("Workouts run and record with no signal and no sign-in.") + .font(.subheadline) .foregroundStyle(.secondary) - LabeledContent("This iPhone") { - Text(workoutCount(model.document.history.count)) - } - LabeledContent("Account copy") { - Text(workoutCount(conflict.document.history.count)) - } - Button { Task { await model.keepDeviceCopy() } } label: { - Text("Keep this iPhone’s copy").foregroundStyle(.white) - } - .buttonStyle(.borderedProminent) - .tint(SetlinePalette.ink) - .controlSize(.large) - .frame(maxWidth: .infinity) - Button("Use the account copy") { Task { await model.useAccountCopy() } } - .buttonStyle(.bordered) - .controlSize(.large) - .frame(maxWidth: .infinity) - Button("Decide later") { model.decideConflictLater() } - .frame(maxWidth: .infinity, minHeight: 44) - Spacer() } - .padding(24) - .navigationTitle("Sync conflict") - .navigationBarTitleDisplayMode(.inline) + Spacer() } - .presentationDetents([.large]) - .interactiveDismissDisabled() + LabeledContent("Recorded workouts", value: "\(model.document.history.count)") + LabeledContent("Templates", value: "\(model.document.templates.count)") + LabeledContent("Targets", value: "\(model.document.goals.count)") + Text("Use Export to keep a copy of everything. iCloud sync across devices is being built and is not active yet.") + .font(.footnote) + .foregroundStyle(.secondary) } } - private var appleAccountButton: some View { - SignInWithAppleButton(.continue) { request in - appleNonce = AppleNonce.make() - request.requestedScopes = [.fullName, .email] - request.nonce = AppleNonce.digest(appleNonce) - } onCompletion: { result in - guard - case let .success(authorization) = result, - let credential = authorization.credential as? ASAuthorizationAppleIDCredential, - let tokenData = credential.identityToken, - let token = String(data: tokenData, encoding: .utf8) - else { - if case let .failure(error) = result, - (error as? ASAuthorizationError)?.code != .canceled { - model.accountMessage = error.localizedDescription - } - return - } - let payload = AppleIdentityPayload( - identityToken: token, - nonce: appleNonce, - email: credential.email, - firstName: credential.fullName?.givenName, - lastName: credential.fullName?.familyName - ) - Task { await model.completeAppleSignIn(payload) } + private var storageTitle: String { + switch model.document.syncState { + case .deviceOnly: "On this iPhone" + case .pending: "Saving to iCloud" + case .synced: "Synced with iCloud" + case .conflict: "Decision needed" + case .failed: "iCloud retry needed" } - .signInWithAppleButtonStyle(colorScheme == .dark ? .white : .black) - .frame(maxWidth: .infinity, minHeight: 48) - .clipShape(RoundedRectangle(cornerRadius: 10)) - .accessibilityIdentifier("apple-account-button") - .disabled(model.isAccountBusy) } private func settingsSection(_ title: String, @ViewBuilder content: () -> Content) -> some View { @@ -588,23 +113,9 @@ struct SettingsView: View { .clipShape(RoundedRectangle(cornerRadius: 14)) } } - - private func syncLabel(_ state: SyncState) -> String { - switch state { - case .deviceOnly: "On device" - case .pending: "Syncing" - case .synced: "Synced" - case .conflict: "Decision needed" - case .failed: "Retry needed" - } - } - - private func workoutCount(_ count: Int) -> String { - "\(count) workout\(count == 1 ? "" : "s")" - } } -private func pageHeader(_ title: String, subtitle: String) -> some View { +func pageHeader(_ title: String, subtitle: String) -> some View { VStack(alignment: .leading, spacing: 8) { Text("SETLINE").font(.caption.weight(.black)).tracking(2.2) InkRule() @@ -627,12 +138,27 @@ private struct SetlineExportPayload: Transferable { } } -private extension SetSegment { +extension SetSegment { + /// How one segment reads in a receipt. Every recorded dimension is shown, so a + /// two-segment set is never flattened into a single pair of numbers. var recordedDescription: String { - if let weight, let repetitions { return "\(weight.formatted()) kg × \(repetitions)" } - if let repetitions { return "\(repetitions) reps" } - if let durationSeconds { return "\(durationSeconds)s" } - if let distanceKilometres { return "\(distanceKilometres.formatted()) km" } - return "Recorded" + var parts: [String] = [] + if let side, side != .both { parts.append(side.title) } + if let repetitions, let weight { + parts.append("\(repetitions) × \(weight.trimmedString) kg") + } else if let repetitions { + parts.append("\(repetitions) reps") + } else if let weight { + parts.append("\(weight.trimmedString) kg") + } + if let assistanceKilograms { parts.append("assisted −\(assistanceKilograms.trimmedString) kg") } + if let durationSeconds { parts.append(durationSeconds.durationLabel) } + if let distanceKilometres { parts.append("\(distanceKilometres.trimmedString) km") } + if let rangeOfMotionValue { parts.append("\(rangeOfMotionValue.trimmedString) range") } + if let rpe { parts.append("RPE \(rpe.trimmedString)") } + if let repsInReserve { parts.append("\(repsInReserve) RIR") } + if reachedFailure { parts.append("to failure") } + if hadPain { parts.append("pain flagged") } + return parts.isEmpty ? "Recorded" : parts.joined(separator: " · ") } } diff --git a/ios/Sources/Setline/Setline.entitlements b/ios/Sources/Setline/Setline.entitlements index a812db5..2086589 100644 --- a/ios/Sources/Setline/Setline.entitlements +++ b/ios/Sources/Setline/Setline.entitlements @@ -2,9 +2,11 @@ - com.apple.developer.applesignin - - Default - + diff --git a/ios/Sources/Setline/WorkoutPlayerView.swift b/ios/Sources/Setline/WorkoutPlayerView.swift index d49ea19..fd24d13 100644 --- a/ios/Sources/Setline/WorkoutPlayerView.swift +++ b/ios/Sources/Setline/WorkoutPlayerView.swift @@ -79,8 +79,13 @@ struct WorkoutPlayerView: View { .foregroundStyle(SetlinePalette.lime) Text("The plan is recorded.") .font(.system(.largeTitle, design: .rounded, weight: .black)) - Text("\(session.completedCount) completed · \(session.steps.count - session.completedCount) skipped") + Text("\(session.completedWorkingSetCount) working sets · \(session.completedCount) steps completed · \(session.steps.count - session.completedCount) skipped") .font(.headline.monospacedDigit()) + if session.tonnage > 0 { + Text("\(session.tonnage.trimmedString) kg total load moved") + .font(.subheadline.monospacedDigit()) + .foregroundStyle(SetlinePalette.ink.opacity(0.7)) + } Button("Save workout") { Task { await model.finishWorkout() } } .buttonStyle(ActionSlabStyle()) } @@ -89,59 +94,70 @@ struct WorkoutPlayerView: View { } } +/// Identifies one numeric field so focus can move between them unambiguously. +private enum EntryField: Hashable { + case reps(UUID) + case weight(UUID) + case duration(UUID) + case distance(UUID) +} + +/// One editable piece of the set being recorded. +private struct SegmentDraft: Identifiable, Equatable { + let id = UUID() + var weight = "" + var repetitions = "" + var duration = "" + var distance = "" + var rpe = "" + var side: BodySide? + + var isBlank: Bool { + weight.isEmpty && repetitions.isEmpty && duration.isEmpty && distance.isEmpty + } + + func segment(kind: ActivityKind) -> SetSegment? { + let seconds = Int(duration).map { kind == .cardio ? $0 * 60 : $0 } + let segment = SetSegment( + weight: Double(weight), + repetitions: Int(repetitions), + durationSeconds: seconds, + distanceKilometres: Double(distance), + rpe: Double(rpe), + side: side + ) + return segment.isEmpty ? nil : segment + } +} + private struct AttemptBoard: View { @Environment(AppModel.self) private var model let step: WorkoutStep - @State private var weight = "" - @State private var repetitions = "" - @State private var duration = "" - @State private var distance = "" - @State private var hasDropSegment = false - @State private var dropWeight = "" - @State private var dropRepetitions = "" + + @State private var drafts: [SegmentDraft] = [] + @State private var quickEntry = "" + @State private var isQuickEntryShown = false + @State private var workStartedAt: Date? + @State private var accumulatedWorkSeconds = 0 + /// The decimal keypad has no return key, so entry needs an explicit way out. + /// Focus is tracked per field rather than as one flag, so moving between Reps + /// and Weight actually transfers focus instead of leaving it ambiguous. + @FocusState private var focusedField: EntryField? var body: some View { ScrollView { VStack(alignment: .leading, spacing: 20) { - HStack(alignment: .top) { - VStack(alignment: .leading, spacing: 5) { - SectionLabel(text: step.isExtra ? "Session-only extra" : "\(step.label) · planned") - Text(step.exerciseName) - .font(.system(size: 32, weight: .black, design: .rounded)) - .tracking(-0.7) - } - Spacer() - Text("#\(step.authoredPosition + 1)") - .font(.headline.monospacedDigit().weight(.black)) - .padding(.horizontal, 10) - .padding(.vertical, 7) - .background(SetlinePalette.blue) - .clipShape(RoundedRectangle(cornerRadius: 7)) - } - VStack(alignment: .leading, spacing: 5) { - Text("TARGET") - .font(.caption.weight(.bold)) - .tracking(1.1) - Text(step.target) - .font(.system(size: 42, weight: .black, design: .rounded).monospacedDigit()) - .minimumScaleFactor(0.7) - .lineLimit(1) - Text(step.cue) - .font(.body.weight(.medium)) - .foregroundStyle(SetlinePalette.ink.opacity(0.65)) - } - .padding(.vertical, 4) + heading + targetBlock + InkRule() + workTimer InkRule() actualInputs - if step.kind == .strength { - Button(hasDropSegment ? "Remove drop segment" : "Add drop segment") { - hasDropSegment.toggle() - } - .font(.subheadline.weight(.bold)) - .frame(minHeight: 44) - } + quickEntryBlock Button { - Task { await model.completeCurrent(segments: segments) } + Task { + await model.completeCurrent(segments: segments, workSeconds: recordedWorkSeconds) + } } label: { Label("Record set · start rest", systemImage: "checkmark") } @@ -162,44 +178,337 @@ private struct AttemptBoard: View { .padding(20) } .background(SetlinePalette.paper) + .scrollDismissesKeyboard(.interactively) + .toolbar { + ToolbarItemGroup(placement: .keyboard) { + Spacer() + Button("Done") { focusedField = nil } + .font(.subheadline.weight(.bold)) + } + } + .onAppear(perform: seedDrafts) } + private var heading: some View { + HStack(alignment: .top) { + VStack(alignment: .leading, spacing: 5) { + SectionLabel(text: headingLabel) + Text(step.exerciseName) + .font(.system(size: 32, weight: .black, design: .rounded)) + .tracking(-0.7) + } + Spacer() + VStack(spacing: 4) { + Text("#\(step.authoredPosition + 1)") + .font(.headline.monospacedDigit().weight(.black)) + .padding(.horizontal, 10) + .padding(.vertical, 7) + .background(step.stepType.countsAsWorkingSet ? SetlinePalette.lime : SetlinePalette.blue) + .clipShape(RoundedRectangle(cornerRadius: 7)) + if step.isOptional { + Text("OPTIONAL") + .font(.system(size: 9, weight: .black)) + .foregroundStyle(SetlinePalette.ink.opacity(0.55)) + } + } + } + } + + /// The set label already names its own kind on most authored sets ("Warm-up", + /// "Working set 2 of 3"), so the step type is only appended when it adds something. + private var headingLabel: String { + if step.isExtra { return "Session-only extra" } + let type = step.stepType.title + guard !step.label.localizedCaseInsensitiveContains(type) else { return step.label } + return "\(step.label) · \(type.lowercased())" + } + + private var targetBlock: some View { + VStack(alignment: .leading, spacing: 5) { + Text("TARGET") + .font(.caption.weight(.bold)) + .tracking(1.1) + Text(step.target.displayString) + .font(.system(size: 42, weight: .black, design: .rounded).monospacedDigit()) + .minimumScaleFactor(0.6) + .lineLimit(2) + if !step.target.qualifiers.isEmpty { + Text(step.target.qualifiers.joined(separator: " · ")) + .font(.subheadline.weight(.bold)) + .foregroundStyle(SetlinePalette.ink.opacity(0.7)) + } + if !step.rest.isEmpty { + Text("Authored rest \(step.rest.displayString)") + .font(.caption.monospacedDigit()) + .foregroundStyle(SetlinePalette.ink.opacity(0.55)) + } + if !step.cue.isEmpty { + Text(step.cue) + .font(.body.weight(.medium)) + .foregroundStyle(SetlinePalette.ink.opacity(0.65)) + .padding(.top, 4) + } + } + .padding(.vertical, 4) + } + + // MARK: - Work timer + + private var workTimer: some View { + VStack(alignment: .leading, spacing: 10) { + SectionLabel(text: "Set timer") + HStack(spacing: 14) { + TimelineView(.periodic(from: .now, by: 0.5)) { context in + Text(TimeInterval(liveWorkSeconds(at: context.date)).durationClock) + .font(.system(size: 34, weight: .black, design: .rounded).monospacedDigit()) + .accessibilityLabel("Set duration \(liveWorkSeconds(at: context.date)) seconds") + } + Spacer() + Button(workStartedAt == nil ? "Start set" : "Stop") { + toggleWorkTimer() + } + .font(.subheadline.weight(.bold)) + .frame(minWidth: 96, minHeight: 44) + .background(workStartedAt == nil ? SetlinePalette.blue : SetlinePalette.coral.opacity(0.85)) + .clipShape(RoundedRectangle(cornerRadius: 9)) + if accumulatedWorkSeconds > 0 || workStartedAt != nil { + Button("Reset") { resetWorkTimer() } + .font(.subheadline.weight(.bold)) + .frame(minHeight: 44) + } + } + Text("Timed independently of rest, so time under load is recorded rather than estimated.") + .font(.caption) + .foregroundStyle(SetlinePalette.ink.opacity(0.55)) + } + } + + private func liveWorkSeconds(at date: Date) -> Int { + guard let workStartedAt else { return accumulatedWorkSeconds } + return accumulatedWorkSeconds + max(0, Int(date.timeIntervalSince(workStartedAt))) + } + + private func toggleWorkTimer() { + if let workStartedAt { + accumulatedWorkSeconds += max(0, Int(Date.now.timeIntervalSince(workStartedAt))) + self.workStartedAt = nil + } else { + workStartedAt = .now + } + } + + private func resetWorkTimer() { + workStartedAt = nil + accumulatedWorkSeconds = 0 + } + + private var recordedWorkSeconds: Int? { + let total = liveWorkSeconds(at: .now) + return total > 0 ? total : nil + } + + // MARK: - Segment entry + @ViewBuilder private var actualInputs: some View { VStack(alignment: .leading, spacing: 14) { - SectionLabel(text: "Recorded actuals") + HStack { + SectionLabel(text: "Recorded actuals") + Spacer() + Button { + isQuickEntryShown.toggle() + } label: { + Label("Type it", systemImage: "text.cursor") + .font(.caption.weight(.bold)) + } + .frame(minHeight: 32) + } + ForEach($drafts) { $draft in + segmentRow($draft, index: drafts.firstIndex(where: { $0.id == draft.id }) ?? 0) + } + HStack(spacing: 12) { + Button { + drafts.append(SegmentDraft(side: step.target.perSide ? .right : nil)) + } label: { + Label("Add segment", systemImage: "plus") + .font(.subheadline.weight(.bold)) + } + .frame(minHeight: 44) + if drafts.count > 1 { + Button(role: .destructive) { + _ = drafts.popLast() + } label: { + Label("Remove last", systemImage: "minus") + .font(.subheadline.weight(.bold)) + } + .frame(minHeight: 44) + } + } + if drafts.count > 1 { + Text("All \(drafts.count) segments record as one set.") + .font(.caption.weight(.semibold)) + .foregroundStyle(SetlinePalette.ink.opacity(0.6)) + } + } + } + + @ViewBuilder + private func segmentRow(_ draft: Binding, index: Int) -> some View { + VStack(alignment: .leading, spacing: 8) { + if drafts.count > 1 || step.target.perSide { + HStack { + Text("SEGMENT \(index + 1)") + .font(.system(size: 10, weight: .black)) + .foregroundStyle(SetlinePalette.ink.opacity(0.5)) + Spacer() + if step.target.perSide { + Picker("Side", selection: draft.side) { + Text("Left").tag(BodySide?.some(.left)) + Text("Right").tag(BodySide?.some(.right)) + Text("Both").tag(BodySide?.some(.both)) + } + .pickerStyle(.segmented) + .frame(maxWidth: 200) + } + } + } + let id = draft.wrappedValue.id switch step.kind { case .strength: HStack(spacing: 12) { - numericField("Weight", value: $weight, unit: "kg") - numericField("Reps", value: $repetitions, unit: "reps") - } - if hasDropSegment { - HStack(spacing: 12) { - numericField("Drop weight", value: $dropWeight, unit: "kg") - numericField("Drop reps", value: $dropRepetitions, unit: "reps") - } - .transition(.opacity.combined(with: .move(edge: .top))) + numericField("Reps", value: draft.repetitions, unit: "reps", field: .reps(id)) + numericField("Weight", value: draft.weight, unit: "kg", field: .weight(id)) } case .repetitions, .mobility: - numericField("Repetitions", value: $repetitions, unit: "reps") + numericField("Repetitions", value: draft.repetitions, unit: "reps", field: .reps(id)) case .timed: - numericField("Duration", value: $duration, unit: "seconds") + HStack(spacing: 12) { + numericField("Duration", value: draft.duration, unit: "seconds", field: .duration(id)) + numericField("Weight", value: draft.weight, unit: "kg", field: .weight(id)) + } case .cardio: HStack(spacing: 12) { - numericField("Duration", value: $duration, unit: "minutes") - numericField("Distance", value: $distance, unit: "km") + numericField("Duration", value: draft.duration, unit: "minutes", field: .duration(id)) + numericField("Distance", value: draft.distance, unit: "km", field: .distance(id)) } } } + .padding(.bottom, 4) } - private func numericField(_ title: String, value: Binding, unit: String) -> some View { + // MARK: - Quick entry + + @ViewBuilder + private var quickEntryBlock: some View { + if isQuickEntryShown { + VStack(alignment: .leading, spacing: 8) { + SectionLabel(text: "Quick entry") + TextField("5x40, 2x30", text: $quickEntry) + .textFieldStyle(.roundedBorder) + .autocorrectionDisabled() + .textInputAutocapitalization(.never) + .font(.body.monospaced()) + .accessibilityLabel("Shorthand set entry") + let parsed = SetEntryParser.parse(quickEntry) + if !quickEntry.isEmpty { + // The interpretation is always shown before it is applied, so + // shorthand never silently records the wrong thing. + Text(parsed.segments.isEmpty + ? "Not understood yet." + : "Reads as: " + parsed.segments.map(describe).joined(separator: " + ")) + .font(.caption.weight(.semibold)) + .foregroundStyle(parsed.segments.isEmpty + ? SetlinePalette.coral + : SetlinePalette.ink.opacity(0.75)) + if !parsed.unrecognised.isEmpty { + Text("Ignored: \(parsed.unrecognised.joined(separator: ", "))") + .font(.caption) + .foregroundStyle(SetlinePalette.coral) + } + } + Button("Apply to segments") { + applyQuickEntry(parsed) + } + .font(.subheadline.weight(.bold)) + .frame(minHeight: 44) + .disabled(parsed.segments.isEmpty) + } + .padding(14) + .background(SetlinePalette.chalk) + .clipShape(RoundedRectangle(cornerRadius: 10)) + } + } + + private func applyQuickEntry(_ parsed: SetEntryParser.Result) { + guard !parsed.segments.isEmpty else { return } + drafts = parsed.segments.map { segment in + SegmentDraft( + weight: segment.weight.map(\.trimmedString) ?? "", + repetitions: segment.repetitions.map(String.init) ?? "", + duration: segment.durationSeconds.map { step.kind == .cardio ? String($0 / 60) : String($0) } ?? "", + distance: segment.distanceKilometres.map(\.trimmedString) ?? "", + rpe: segment.rpe.map(\.trimmedString) ?? "", + side: segment.side + ) + } + quickEntry = "" + isQuickEntryShown = false + } + + private func describe(_ segment: SetSegment) -> String { + var parts: [String] = [] + if let side = segment.side, side != .both { parts.append(side.title) } + if let reps = segment.repetitions, let weight = segment.weight { + parts.append("\(reps) × \(weight.trimmedString) kg") + } else if let reps = segment.repetitions { + parts.append("\(reps) reps") + } else if let weight = segment.weight { + parts.append("\(weight.trimmedString) kg") + } + if let seconds = segment.durationSeconds { parts.append(seconds.durationLabel) } + if let kilometres = segment.distanceKilometres { parts.append("\(kilometres.trimmedString) km") } + if let rpe = segment.rpe { parts.append("RPE \(rpe.trimmedString)") } + return parts.joined(separator: " · ") + } + + // MARK: - State + + /// Per-side work starts with a left and a right segment; everything else with one. + private func seedDrafts() { + guard drafts.isEmpty else { return } + if step.target.perSide { + drafts = [SegmentDraft(side: .left), SegmentDraft(side: .right)] + } else { + drafts = [SegmentDraft()] + } + } + + private var segments: [SetSegment] { + drafts.compactMap { $0.segment(kind: step.kind) } + } + + private var canComplete: Bool { + guard let first = segments.first else { return false } + switch step.kind { + case .strength: return first.repetitions != nil + case .repetitions, .mobility: return first.repetitions != nil + case .timed: return first.durationSeconds != nil + case .cardio: return first.durationSeconds != nil || first.distanceKilometres != nil + } + } + + private func numericField( + _ title: String, + value: Binding, + unit: String, + field: EntryField + ) -> some View { VStack(alignment: .leading, spacing: 6) { Text(title).font(.caption.weight(.bold)) HStack(alignment: .firstTextBaseline, spacing: 5) { TextField("0", text: value) .keyboardType(.decimalPad) + .focused($focusedField, equals: field) .font(.system(size: 30, weight: .black, design: .rounded).monospacedDigit()) .accessibilityLabel(title) Text(unit) @@ -213,33 +522,6 @@ private struct AttemptBoard: View { } .frame(maxWidth: .infinity) } - - private var canComplete: Bool { - switch step.kind { - case .strength: Double(weight) != nil && Int(repetitions) != nil - case .repetitions, .mobility: Int(repetitions) != nil - case .timed: Int(duration) != nil - case .cardio: Int(duration) != nil || Double(distance) != nil - } - } - - private var segments: [SetSegment] { - var result = [SetSegment( - weight: Double(weight), - repetitions: Int(repetitions), - durationSeconds: durationSeconds, - distanceKilometres: Double(distance) - )] - if hasDropSegment, let dropWeight = Double(dropWeight), let dropRepetitions = Int(dropRepetitions) { - result.append(SetSegment(weight: dropWeight, repetitions: dropRepetitions)) - } - return result - } - - private var durationSeconds: Int? { - guard let value = Int(duration) else { return nil } - return step.kind == .cardio ? value * 60 : value - } } private struct RestBoard: View { @@ -271,7 +553,7 @@ private struct RestBoard: View { SectionLabel(text: "Next in authored order") Text(next.exerciseName) .font(.system(.title, design: .rounded, weight: .black)) - Text("\(next.label) · \(next.target)") + Text("\(next.label) · \(next.target.displayString)") .font(.title3.weight(.semibold).monospacedDigit()) Button(remaining > 0 ? "Start next early" : "Start next set") { Task { await model.endRest() } @@ -336,7 +618,7 @@ private struct SetRail: View { } } -private extension TimeInterval { +extension TimeInterval { var durationClock: String { let total = max(0, Int(self)) return String(format: "%02d:%02d", total / 60, total % 60) diff --git a/ios/Sources/SetlineCore/CloudSync.swift b/ios/Sources/SetlineCore/CloudSync.swift deleted file mode 100644 index 0bdcea5..0000000 --- a/ios/Sources/SetlineCore/CloudSync.swift +++ /dev/null @@ -1,47 +0,0 @@ -import Foundation - -/// The versioned document exchanged by native Setline clients. -/// Device-only synchronization metadata is deliberately excluded so a successful -/// sync never creates another document change by itself. -public struct SetlineCloudDocument: Codable, Equatable, Sendable { - public var schemaVersion: Int - public var templates: [WorkoutTemplate] - public var programme: CustomProgramme? - public var activeSession: WorkoutSession? - public var history: [WorkoutSession] - - public init(document: SetlineDocument) { - schemaVersion = document.schemaVersion - templates = document.templates - programme = document.programme - activeSession = document.activeSession - history = document.history - } - - public func localDocument( - syncState: SyncState = .synced, - lastSyncedAt: Date = .now - ) -> SetlineDocument { - SetlineDocument( - schemaVersion: schemaVersion, - templates: templates, - programme: programme, - activeSession: activeSession, - history: history, - syncState: syncState, - lastSyncedAt: lastSyncedAt - ) - } -} - -public struct SetlineCloudSnapshot: Codable, Equatable, Identifiable, Sendable { - public var document: SetlineCloudDocument - public var revision: Int - - public init(document: SetlineCloudDocument, revision: Int) { - self.document = document - self.revision = revision - } - - public var id: Int { revision } -} diff --git a/ios/Sources/SetlineCore/Domain.swift b/ios/Sources/SetlineCore/Domain.swift index 3de6c18..ce7d584 100644 --- a/ios/Sources/SetlineCore/Domain.swift +++ b/ios/Sources/SetlineCore/Domain.swift @@ -25,25 +25,138 @@ public enum StepStatus: String, Codable, Sendable { case deferred } +public enum BodySide: String, Codable, CaseIterable, Sendable { + case left + case right + case both + + public var title: String { + switch self { + case .left: "Left" + case .right: "Right" + case .both: "Both" + } + } +} + +/// One contiguous piece of work inside a single set. +/// +/// A set is not always one number pair. `5 reps × 40 kg` immediately followed by +/// `2 reps × 30 kg` is one set with two segments, and both halves have to survive +/// into the record for the set to mean anything later. public struct SetSegment: Codable, Equatable, Identifiable, Sendable { public var id: UUID public var weight: Double? public var repetitions: Int? public var durationSeconds: Int? public var distanceKilometres: Double? + public var rpe: Double? + public var repsInReserve: Int? + public var reachedFailure: Bool + public var assistanceKilograms: Double? + public var rangeOfMotionValue: Double? + public var averageHeartRate: Int? + public var side: BodySide? + /// Measured time under load for this segment, from the work timer. + public var workSeconds: Int? + public var hadPain: Bool + public var note: String? public init( id: UUID = UUID(), weight: Double? = nil, repetitions: Int? = nil, durationSeconds: Int? = nil, - distanceKilometres: Double? = nil + distanceKilometres: Double? = nil, + rpe: Double? = nil, + repsInReserve: Int? = nil, + reachedFailure: Bool = false, + assistanceKilograms: Double? = nil, + rangeOfMotionValue: Double? = nil, + averageHeartRate: Int? = nil, + side: BodySide? = nil, + workSeconds: Int? = nil, + hadPain: Bool = false, + note: String? = nil ) { self.id = id self.weight = weight self.repetitions = repetitions self.durationSeconds = durationSeconds self.distanceKilometres = distanceKilometres + self.rpe = rpe + self.repsInReserve = repsInReserve + self.reachedFailure = reachedFailure + self.assistanceKilograms = assistanceKilograms + self.rangeOfMotionValue = rangeOfMotionValue + self.averageHeartRate = averageHeartRate + self.side = side + self.workSeconds = workSeconds + self.hadPain = hadPain + self.note = note + } + + /// Decodes documents written before the richer segment fields existed. + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID() + weight = try container.decodeIfPresent(Double.self, forKey: .weight) + repetitions = try container.decodeIfPresent(Int.self, forKey: .repetitions) + durationSeconds = try container.decodeIfPresent(Int.self, forKey: .durationSeconds) + distanceKilometres = try container.decodeIfPresent(Double.self, forKey: .distanceKilometres) + rpe = try container.decodeIfPresent(Double.self, forKey: .rpe) + repsInReserve = try container.decodeIfPresent(Int.self, forKey: .repsInReserve) + reachedFailure = try container.decodeIfPresent(Bool.self, forKey: .reachedFailure) ?? false + assistanceKilograms = try container.decodeIfPresent(Double.self, forKey: .assistanceKilograms) + rangeOfMotionValue = try container.decodeIfPresent(Double.self, forKey: .rangeOfMotionValue) + averageHeartRate = try container.decodeIfPresent(Int.self, forKey: .averageHeartRate) + side = try container.decodeIfPresent(BodySide.self, forKey: .side) + workSeconds = try container.decodeIfPresent(Int.self, forKey: .workSeconds) + hadPain = try container.decodeIfPresent(Bool.self, forKey: .hadPain) ?? false + note = try container.decodeIfPresent(String.self, forKey: .note) + } + + /// The effective load, accounting for assistance on bodyweight movements. + public var effectiveKilograms: Double? { + guard let weight else { + guard let assistanceKilograms else { return nil } + return -assistanceKilograms + } + return weight - (assistanceKilograms ?? 0) + } + + public var isEmpty: Bool { + weight == nil && repetitions == nil && durationSeconds == nil + && distanceKilometres == nil && rangeOfMotionValue == nil + } +} + +/// Version 1 wrote `target` as free text and `rest` as a scalar `restSeconds`. +/// Both planned sets and recorded steps carried those fields, so the fallbacks +/// live in one place rather than being repeated in each decoder. +enum LegacyDecoding { + private struct Key: CodingKey { + var stringValue: String + var intValue: Int? { nil } + init(_ stringValue: String) { self.stringValue = stringValue } + init?(stringValue: String) { self.stringValue = stringValue } + init?(intValue: Int) { nil } + } + + static func target(from decoder: any Decoder) throws -> SetTarget { + let container = try decoder.container(keyedBy: Key.self) + if let structured = try? container.decodeIfPresent(SetTarget.self, forKey: Key("target")) { + return structured + } + return SetTarget(legacy: try container.decodeIfPresent(String.self, forKey: Key("target")) ?? "") + } + + static func rest(from decoder: any Decoder) throws -> RestRange { + let container = try decoder.container(keyedBy: Key.self) + if let range = try? container.decodeIfPresent(RestRange.self, forKey: Key("rest")) { + return range + } + return RestRange(try container.decodeIfPresent(Int.self, forKey: Key("restSeconds")) ?? 0) } } @@ -51,21 +164,46 @@ public struct PlannedSet: Codable, Equatable, Identifiable, Sendable { public var id: UUID public var label: String public var kind: ActivityKind - public var target: String - public var restSeconds: Int + public var stepType: StepType + public var target: SetTarget + public var rest: RestRange + /// Conditional work the programme offers but never inserts silently. + public var isOptional: Bool + /// Overrides the parent exercise cue when this specific set needs different + /// instruction, as warm-up ramps and conditional sets routinely do. + public var cue: String? public init( id: UUID = UUID(), label: String, kind: ActivityKind, - target: String, - restSeconds: Int + stepType: StepType = .working, + target: SetTarget, + rest: RestRange, + isOptional: Bool = false, + cue: String? = nil ) { self.id = id self.label = label self.kind = kind + self.stepType = stepType self.target = target - self.restSeconds = restSeconds + self.rest = rest + self.isOptional = isOptional + self.cue = cue + } + + /// Decodes documents whose targets were free text and whose rest was scalar. + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID() + label = try container.decodeIfPresent(String.self, forKey: .label) ?? "" + kind = try container.decodeIfPresent(ActivityKind.self, forKey: .kind) ?? .strength + stepType = try container.decodeIfPresent(StepType.self, forKey: .stepType) ?? .working + target = try LegacyDecoding.target(from: decoder) + rest = try LegacyDecoding.rest(from: decoder) + isOptional = try container.decodeIfPresent(Bool.self, forKey: .isOptional) ?? false + cue = try container.decodeIfPresent(String.self, forKey: .cue) } } @@ -74,12 +212,39 @@ public struct Exercise: Codable, Equatable, Identifiable, Sendable { public var name: String public var cue: String public var sets: [PlannedSet] + /// Links this exercise to a catalogue definition so measurements accumulate + /// across every template and session that trains the same movement. + public var definitionSlug: String? + public var pillars: Set - public init(id: UUID = UUID(), name: String, cue: String, sets: [PlannedSet]) { + public init( + id: UUID = UUID(), + name: String, + cue: String, + sets: [PlannedSet], + definitionSlug: String? = nil, + pillars: Set = [.strength] + ) { self.id = id self.name = name self.cue = cue self.sets = sets + self.definitionSlug = definitionSlug + self.pillars = pillars + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID() + name = try container.decodeIfPresent(String.self, forKey: .name) ?? "" + cue = try container.decodeIfPresent(String.self, forKey: .cue) ?? "" + sets = try container.decodeIfPresent([PlannedSet].self, forKey: .sets) ?? [] + definitionSlug = try container.decodeIfPresent(String.self, forKey: .definitionSlug) + pillars = try container.decodeIfPresent(Set.self, forKey: .pillars) ?? [.strength] + } + + public var workingSets: [PlannedSet] { + sets.filter { $0.stepType.countsAsWorkingSet } } } @@ -89,68 +254,147 @@ public struct WorkoutTemplate: Codable, Equatable, Identifiable, Sendable { public var detail: String public var isBundled: Bool public var exercises: [Exercise] + /// Authored notes the programme attaches to the session as a whole. + public var notes: [String] + public var expectedMinutes: Int? public init( id: UUID = UUID(), name: String, detail: String, isBundled: Bool, - exercises: [Exercise] + exercises: [Exercise], + notes: [String] = [], + expectedMinutes: Int? = nil ) { self.id = id self.name = name self.detail = detail self.isBundled = isBundled self.exercises = exercises + self.notes = notes + self.expectedMinutes = expectedMinutes + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID() + name = try container.decodeIfPresent(String.self, forKey: .name) ?? "" + detail = try container.decodeIfPresent(String.self, forKey: .detail) ?? "" + isBundled = try container.decodeIfPresent(Bool.self, forKey: .isBundled) ?? false + exercises = try container.decodeIfPresent([Exercise].self, forKey: .exercises) ?? [] + notes = try container.decodeIfPresent([String].self, forKey: .notes) ?? [] + expectedMinutes = try container.decodeIfPresent(Int.self, forKey: .expectedMinutes) } + + public var plannedSetCount: Int { exercises.flatMap(\.sets).count } + public var workingSetCount: Int { exercises.flatMap(\.workingSets).count } + public var pillars: Set { exercises.reduce(into: []) { $0.formUnion($1.pillars) } } } public struct WorkoutStep: Codable, Equatable, Identifiable, Sendable { public var id: UUID public var plannedSetID: UUID? public var exerciseName: String + public var exerciseSlug: String? public var cue: String public var label: String public var kind: ActivityKind - public var target: String + public var stepType: StepType + public var target: SetTarget + public var pillars: Set public var authoredPosition: Int - public var restSeconds: Int + public var rest: RestRange + public var isOptional: Bool public var status: StepStatus public var segments: [SetSegment] public var isExtra: Bool public var performedPosition: Int? public var completedAt: Date? + /// Measured duration of the set itself, distinct from the rest that follows. + public var workSeconds: Int? public init( id: UUID = UUID(), plannedSetID: UUID?, exerciseName: String, + exerciseSlug: String? = nil, cue: String, label: String, kind: ActivityKind, - target: String, + stepType: StepType = .working, + target: SetTarget, + pillars: Set = [.strength], authoredPosition: Int, - restSeconds: Int, + rest: RestRange, + isOptional: Bool = false, status: StepStatus = .planned, segments: [SetSegment] = [], isExtra: Bool = false, performedPosition: Int? = nil, - completedAt: Date? = nil + completedAt: Date? = nil, + workSeconds: Int? = nil ) { self.id = id self.plannedSetID = plannedSetID self.exerciseName = exerciseName + self.exerciseSlug = exerciseSlug self.cue = cue self.label = label self.kind = kind + self.stepType = stepType self.target = target + self.pillars = pillars self.authoredPosition = authoredPosition - self.restSeconds = restSeconds + self.rest = rest + self.isOptional = isOptional self.status = status self.segments = segments self.isExtra = isExtra self.performedPosition = performedPosition self.completedAt = completedAt + self.workSeconds = workSeconds + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID() + plannedSetID = try container.decodeIfPresent(UUID.self, forKey: .plannedSetID) + exerciseName = try container.decodeIfPresent(String.self, forKey: .exerciseName) ?? "" + exerciseSlug = try container.decodeIfPresent(String.self, forKey: .exerciseSlug) + cue = try container.decodeIfPresent(String.self, forKey: .cue) ?? "" + label = try container.decodeIfPresent(String.self, forKey: .label) ?? "" + kind = try container.decodeIfPresent(ActivityKind.self, forKey: .kind) ?? .strength + stepType = try container.decodeIfPresent(StepType.self, forKey: .stepType) ?? .working + target = try LegacyDecoding.target(from: decoder) + pillars = try container.decodeIfPresent(Set.self, forKey: .pillars) ?? [.strength] + authoredPosition = try container.decodeIfPresent(Int.self, forKey: .authoredPosition) ?? 0 + rest = try LegacyDecoding.rest(from: decoder) + isOptional = try container.decodeIfPresent(Bool.self, forKey: .isOptional) ?? false + status = try container.decodeIfPresent(StepStatus.self, forKey: .status) ?? .planned + segments = try container.decodeIfPresent([SetSegment].self, forKey: .segments) ?? [] + isExtra = try container.decodeIfPresent(Bool.self, forKey: .isExtra) ?? false + performedPosition = try container.decodeIfPresent(Int.self, forKey: .performedPosition) + completedAt = try container.decodeIfPresent(Date.self, forKey: .completedAt) + workSeconds = try container.decodeIfPresent(Int.self, forKey: .workSeconds) + } + + /// The cue shown to the lifter: the set's own instruction when it has one. + public var effectiveCue: String { cue } + + public var countsTowardVolume: Bool { + stepType.countsAsWorkingSet && status == .complete + } + + /// Total load moved by this step, for tonnage. Warm-ups deliberately excluded. + public var tonnage: Double { + guard countsTowardVolume else { return 0 } + return segments.reduce(0) { total, segment in + guard let kilograms = segment.effectiveKilograms, let reps = segment.repetitions else { + return total + } + return total + kilograms * Double(reps) + } } } @@ -185,6 +429,10 @@ public struct WorkoutSession: Codable, Equatable, Identifiable, Sendable { public var steps: [WorkoutStep] public var activeIndex: Int public var rest: RestState? + /// Where this session sat in the programme, so history stays interpretable + /// after the block ends. + public var programmeWeek: Int? + public var programmeDayIndex: Int? public init( id: UUID = UUID(), @@ -194,7 +442,9 @@ public struct WorkoutSession: Codable, Equatable, Identifiable, Sendable { completedAt: Date? = nil, steps: [WorkoutStep], activeIndex: Int = 0, - rest: RestState? = nil + rest: RestState? = nil, + programmeWeek: Int? = nil, + programmeDayIndex: Int? = nil ) { self.id = id self.templateID = templateID @@ -204,6 +454,8 @@ public struct WorkoutSession: Codable, Equatable, Identifiable, Sendable { self.steps = steps self.activeIndex = activeIndex self.rest = rest + self.programmeWeek = programmeWeek + self.programmeDayIndex = programmeDayIndex } public var currentStep: WorkoutStep? { @@ -214,6 +466,18 @@ public struct WorkoutSession: Codable, Equatable, Identifiable, Sendable { public var completedCount: Int { steps.count { $0.status == .complete } } + + public var completedWorkingSetCount: Int { + steps.count(where: \.countsTowardVolume) + } + + public var tonnage: Double { + steps.reduce(0) { $0 + $1.tonnage } + } + + public var pillars: Set { + steps.filter { $0.status == .complete }.reduce(into: []) { $0.formUnion($1.pillars) } + } } public struct ProgrammeDay: Codable, Equatable, Identifiable, Sendable { @@ -250,6 +514,32 @@ public struct CustomProgramme: Codable, Equatable, Identifiable, Sendable { } } +/// Which programme drives Today. Bundled blocks are dated and week-aware, so +/// they resolve sessions rather than storing a fixed weekday-to-template map. +public enum ProgrammeSelection: Codable, Equatable, Sendable { + case none + case bundled(BundledProgrammeID) + case custom(CustomProgramme) + + public var customProgramme: CustomProgramme? { + guard case let .custom(programme) = self else { return nil } + return programme + } + + public var bundledID: BundledProgrammeID? { + guard case let .bundled(id) = self else { return nil } + return id + } + + public var isEnabled: Bool { + switch self { + case .none: false + case .bundled: true + case let .custom(programme): programme.enabled + } + } +} + public enum SyncState: String, Codable, Sendable { case deviceOnly case pending @@ -261,18 +551,22 @@ public enum SyncState: String, Codable, Sendable { public struct SetlineDocument: Codable, Equatable, Sendable { public var schemaVersion: Int public var templates: [WorkoutTemplate] - public var programme: CustomProgramme? + public var programme: ProgrammeSelection public var activeSession: WorkoutSession? public var history: [WorkoutSession] + public var goals: [ExerciseGoal] public var syncState: SyncState public var lastSyncedAt: Date? + public static let currentSchemaVersion = 2 + public init( - schemaVersion: Int = 1, + schemaVersion: Int = SetlineDocument.currentSchemaVersion, templates: [WorkoutTemplate] = [], - programme: CustomProgramme? = nil, + programme: ProgrammeSelection = .none, activeSession: WorkoutSession? = nil, history: [WorkoutSession] = [], + goals: [ExerciseGoal] = [], syncState: SyncState = .deviceOnly, lastSyncedAt: Date? = nil ) { @@ -281,12 +575,151 @@ public struct SetlineDocument: Codable, Equatable, Sendable { self.programme = programme self.activeSession = activeSession self.history = history + self.goals = goals self.syncState = syncState self.lastSyncedAt = lastSyncedAt } + + /// Reads both the version 1 envelope, whose `programme` was a bare custom + /// programme, and the current selection-based envelope. + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + schemaVersion = try container.decodeIfPresent(Int.self, forKey: .schemaVersion) ?? 1 + templates = try container.decodeIfPresent([WorkoutTemplate].self, forKey: .templates) ?? [] + if let selection = try? container.decodeIfPresent(ProgrammeSelection.self, forKey: .programme) { + programme = selection + } else if let legacy = try? container.decodeIfPresent(CustomProgramme.self, forKey: .programme) { + programme = .custom(legacy) + } else { + programme = .none + } + activeSession = try container.decodeIfPresent(WorkoutSession.self, forKey: .activeSession) + history = try container.decodeIfPresent([WorkoutSession].self, forKey: .history) ?? [] + goals = try container.decodeIfPresent([ExerciseGoal].self, forKey: .goals) ?? [] + syncState = try container.decodeIfPresent(SyncState.self, forKey: .syncState) ?? .deviceOnly + lastSyncedAt = try container.decodeIfPresent(Date.self, forKey: .lastSyncedAt) + } } public extension SetlineDocument { + /// True when two documents hold the same training, ignoring sync bookkeeping. + /// + /// Recording that a save succeeded must never itself look like a change, or + /// syncing would trigger another sync forever. + func hasSameContent(as other: SetlineDocument) -> Bool { + var left = self + var right = other + left.syncState = .deviceOnly + left.lastSyncedAt = nil + right.syncState = .deviceOnly + right.lastSyncedAt = nil + return left == right + } + + /// What a fresh install opens on: the authored twelve-week block, enabled. + static var initial: SetlineDocument { + SetlineDocument(programme: .bundled(.twelveWeekStrengthCardioMobility)) + } + + /// A document carrying four weeks of recorded bench and pulldown work plus + /// authored targets, so the measurement surfaces can be exercised and captured + /// without waiting a month for real evidence to accumulate. + static var demoWithEvidence: SetlineDocument { + let week: TimeInterval = 604_800 + let benchProgression: [(load: Double, reps: [Int])] = [ + (65, [8, 8, 8]), + (67.5, [7, 7, 6]), + (70, [6, 6, 6]), + (72.5, [8, 7, 7]), + ] + let pulldownProgression: [(load: Double, reps: [Int])] = [ + (50, [10, 10, 9]), + (52.5, [9, 9, 8]), + (55, [8, 8, 8]), + (55, [10, 10, 10]), + ] + + func session(weeksAgo: Int, index: Int) -> WorkoutSession { + let date = Date.now.addingTimeInterval(-Double(weeksAgo) * week) + var position = 0 + func steps( + name: String, + slug: String, + repsHigh: Int, + progression: [(load: Double, reps: [Int])] + ) -> [WorkoutStep] { + let entry = progression[index] + return entry.reps.map { reps in + defer { position += 1 } + return WorkoutStep( + plannedSetID: UUID(), + exerciseName: name, + exerciseSlug: slug, + cue: "", + label: "Working set \(position % 3 + 1) of 3", + kind: .strength, + stepType: .working, + target: SetTarget( + repsLow: repsHigh - 3, + repsHigh: repsHigh, + load: .absolute(kilograms: entry.load), + repsInReserve: 1 + ), + authoredPosition: position, + rest: RestRange(lowSeconds: 150, highSeconds: 180), + status: .complete, + segments: [SetSegment(weight: entry.load, repetitions: reps)], + completedAt: date + ) + } + } + return WorkoutSession( + templateID: ProgrammeSessionKind.upper.templateID, + templateName: "Upper", + startedAt: date, + completedAt: date.addingTimeInterval(3_900), + steps: steps( + name: "Bench press", + slug: "bench-press", + repsHigh: 8, + progression: benchProgression + ) + steps( + name: "Lat pulldown", + slug: "lat-pulldown", + repsHigh: 10, + progression: pulldownProgression + ), + programmeWeek: index + 1, + programmeDayIndex: 0 + ) + } + + // Newest first, matching how completed sessions are stored. + let history = (0..<4).map { offset in + session(weeksAgo: offset, index: 3 - offset) + } + return SetlineDocument( + programme: .bundled(.twelveWeekStrengthCardioMobility), + history: history, + goals: [ + ExerciseGoal( + exerciseName: "Bench press", + metric: .topSetLoad, + targetValue: 90, + referenceRepetitions: 5, + createdAt: Date.now.addingTimeInterval(-4 * week), + note: "Bodyweight-relative strength target for the block after this one." + ), + ExerciseGoal( + exerciseName: "Lat pulldown", + metric: .estimatedOneRepMax, + targetValue: 80, + createdAt: Date.now.addingTimeInterval(-4 * week) + ), + ] + ) + } + static var sample: SetlineDocument { let lower = WorkoutTemplate( name: "Lower strength", @@ -294,20 +727,66 @@ public extension SetlineDocument { isBundled: true, exercises: [ Exercise(name: "Front squat", cue: "Brace before the descent. Keep elbows tall.", sets: [ - PlannedSet(label: "Warm-up", kind: .strength, target: "40 kg × 8", restSeconds: 60), - PlannedSet(label: "Working 1", kind: .strength, target: "60 kg × 5", restSeconds: 150), - PlannedSet(label: "Working 2", kind: .strength, target: "60 kg × 5", restSeconds: 150), - PlannedSet(label: "Working 3", kind: .strength, target: "60 kg × 5", restSeconds: 150), - ]), + PlannedSet( + label: "Warm-up", + kind: .strength, + stepType: .warmUp, + target: SetTarget(repsLow: 8, load: .absolute(kilograms: 40)), + rest: RestRange(60) + ), + PlannedSet( + label: "Working 1", + kind: .strength, + target: SetTarget(repsLow: 5, load: .absolute(kilograms: 60)), + rest: RestRange(150) + ), + PlannedSet( + label: "Working 2", + kind: .strength, + target: SetTarget(repsLow: 5, load: .absolute(kilograms: 60)), + rest: RestRange(150) + ), + PlannedSet( + label: "Working 3", + kind: .strength, + target: SetTarget(repsLow: 5, load: .absolute(kilograms: 60)), + rest: RestRange(150) + ), + ], pillars: [.strength]), Exercise(name: "Romanian deadlift", cue: "Hips back. Keep the bar close.", sets: [ - PlannedSet(label: "Working 1", kind: .strength, target: "70 kg × 8", restSeconds: 120), - PlannedSet(label: "Working 2", kind: .strength, target: "70 kg × 8", restSeconds: 120), - PlannedSet(label: "Working 3", kind: .strength, target: "70 kg × 8", restSeconds: 120), - ]), + PlannedSet( + label: "Working 1", + kind: .strength, + target: SetTarget(repsLow: 8, load: .absolute(kilograms: 70)), + rest: RestRange(120) + ), + PlannedSet( + label: "Working 2", + kind: .strength, + target: SetTarget(repsLow: 8, load: .absolute(kilograms: 70)), + rest: RestRange(120) + ), + PlannedSet( + label: "Working 3", + kind: .strength, + target: SetTarget(repsLow: 8, load: .absolute(kilograms: 70)), + rest: RestRange(120) + ), + ], pillars: [.strength]), Exercise(name: "Suitcase carry", cue: "Walk tall without leaning.", sets: [ - PlannedSet(label: "Left", kind: .timed, target: "45 seconds", restSeconds: 45), - PlannedSet(label: "Right", kind: .timed, target: "45 seconds", restSeconds: 45), - ]), + PlannedSet( + label: "Left", + kind: .timed, + target: SetTarget(holdSeconds: 45, perSide: true), + rest: RestRange(45) + ), + PlannedSet( + label: "Right", + kind: .timed, + target: SetTarget(holdSeconds: 45, perSide: true), + rest: RestRange(45) + ), + ], pillars: [.strength, .stamina]), ] ) let conditioning = WorkoutTemplate( @@ -315,34 +794,58 @@ public extension SetlineDocument { detail: "Intervals · hips · shoulders", isBundled: true, exercises: [ - Exercise(name: "Bike intervals", cue: "Strong, repeatable effort. Do not sprint the first round.", sets: [ - PlannedSet(label: "Round 1", kind: .cardio, target: "4 minutes", restSeconds: 90), - PlannedSet(label: "Round 2", kind: .cardio, target: "4 minutes", restSeconds: 90), - PlannedSet(label: "Round 3", kind: .cardio, target: "4 minutes", restSeconds: 90), - ]), - Exercise(name: "90/90 hip switches", cue: "Move slowly through the available range.", sets: [ - PlannedSet(label: "Mobility", kind: .mobility, target: "8 each side", restSeconds: 30), - ]), + Exercise( + name: "Bike intervals", + cue: "Strong, repeatable effort. Do not sprint the first round.", + sets: (1...3).map { round in + PlannedSet( + label: "Round \(round)", + kind: .cardio, + stepType: .cardio, + target: SetTarget(timeSeconds: 240), + rest: RestRange(90) + ) + }, + pillars: [.stamina] + ), + Exercise( + name: "90/90 hip switches", + cue: "Move slowly through the available range.", + sets: [ + PlannedSet( + label: "Mobility", + kind: .mobility, + stepType: .mobility, + target: SetTarget(repsLow: 8, perSide: true), + rest: RestRange(30) + ), + ], + pillars: [.mobility] + ), ] ) return SetlineDocument( templates: [lower, conditioning], - programme: CustomProgramme( + programme: .custom(CustomProgramme( name: "Current block", weekCount: 12, enabled: true, days: (1...7).map { day in ProgrammeDay(weekday: day, templateID: day == 2 || day == 5 ? lower.id : (day == 4 ? conditioning.id : nil)) } - ) + )) ) } - mutating func startWorkout(templateID: UUID, at date: Date = .now) throws { + /// Starts a session from an already-resolved template. Programme sessions are + /// generated per week and day, so they are not present in `templates`. + mutating func startWorkout( + template: WorkoutTemplate, + at date: Date = .now, + programmeWeek: Int? = nil, + programmeDayIndex: Int? = nil + ) throws { guard activeSession == nil else { throw SetlineError.sessionAlreadyActive } - guard let template = templates.first(where: { $0.id == templateID }) else { - throw SetlineError.templateNotFound - } var position = 0 let steps = template.exercises.flatMap { exercise in exercise.sets.map { planned in @@ -350,12 +853,16 @@ public extension SetlineDocument { return WorkoutStep( plannedSetID: planned.id, exerciseName: exercise.name, - cue: exercise.cue, + exerciseSlug: exercise.definitionSlug, + cue: planned.cue ?? exercise.cue, label: planned.label, kind: planned.kind, + stepType: planned.stepType, target: planned.target, + pillars: exercise.pillars, authoredPosition: position, - restSeconds: planned.restSeconds + rest: planned.rest, + isOptional: planned.isOptional ) } } @@ -363,26 +870,41 @@ public extension SetlineDocument { templateID: template.id, templateName: template.name, startedAt: date, - steps: steps + steps: steps, + programmeWeek: programmeWeek, + programmeDayIndex: programmeDayIndex ) } - mutating func completeCurrent(with segments: [SetSegment], at date: Date = .now) throws { + mutating func startWorkout(templateID: UUID, at date: Date = .now) throws { + guard let template = templates.first(where: { $0.id == templateID }) else { + throw SetlineError.templateNotFound + } + try startWorkout(template: template, at: date) + } + + mutating func completeCurrent( + with segments: [SetSegment], + workSeconds: Int? = nil, + at date: Date = .now + ) throws { guard var session = activeSession, session.steps.indices.contains(session.activeIndex) else { throw SetlineError.noActiveStep } session.steps[session.activeIndex].segments = segments session.steps[session.activeIndex].status = .complete session.steps[session.activeIndex].completedAt = date + session.steps[session.activeIndex].workSeconds = workSeconds session.steps[session.activeIndex].performedPosition = session.completedCount - let authoredRest = session.steps[session.activeIndex].restSeconds + let authoredRest = session.steps[session.activeIndex].rest session.activeIndex = nextPendingIndex(in: session.steps, after: session.activeIndex) ?? session.steps.count - if session.activeIndex < session.steps.count && authoredRest > 0 { + if session.activeIndex < session.steps.count && !authoredRest.isEmpty { + let seconds = authoredRest.timerSeconds session.rest = RestState( - authoredSeconds: authoredRest, - adjustedSeconds: authoredRest, + authoredSeconds: seconds, + adjustedSeconds: seconds, startedAt: date, - endsAt: date.addingTimeInterval(TimeInterval(authoredRest)) + endsAt: date.addingTimeInterval(TimeInterval(seconds)) ) } else { session.rest = nil @@ -419,12 +941,15 @@ public extension SetlineDocument { let extra = WorkoutStep( plannedSetID: nil, exerciseName: current.exerciseName, + exerciseSlug: current.exerciseSlug, cue: current.cue, label: "Extra set", kind: current.kind, + stepType: current.stepType, target: current.target, + pillars: current.pillars, authoredPosition: current.authoredPosition, - restSeconds: current.restSeconds, + rest: current.rest, isExtra: true ) session.steps.insert(extra, at: min(session.activeIndex + 1, session.steps.count)) diff --git a/ios/Sources/SetlineCore/ExerciseCatalogue.swift b/ios/Sources/SetlineCore/ExerciseCatalogue.swift new file mode 100644 index 0000000..6f32cb0 --- /dev/null +++ b/ios/Sources/SetlineCore/ExerciseCatalogue.swift @@ -0,0 +1,984 @@ +import Foundation + +public enum MuscleGroup: String, Codable, CaseIterable, Sendable { + case chest + case upperBack + case lats + case shoulders + case biceps + case triceps + case forearms + case trunk + case lowerBack + case glutes + case quadriceps + case hamstrings + case adductors + case calves + case hipFlexors + case thoracicSpine + case ankles + case fullBody + + public var title: String { + switch self { + case .chest: "Chest" + case .upperBack: "Upper back" + case .lats: "Lats" + case .shoulders: "Shoulders" + case .biceps: "Biceps" + case .triceps: "Triceps" + case .forearms: "Forearms & grip" + case .trunk: "Trunk" + case .lowerBack: "Lower back" + case .glutes: "Glutes" + case .quadriceps: "Quadriceps" + case .hamstrings: "Hamstrings" + case .adductors: "Adductors" + case .calves: "Calves" + case .hipFlexors: "Hip flexors" + case .thoracicSpine: "Thoracic spine" + case .ankles: "Ankles" + case .fullBody: "Full body" + } + } +} + +public enum Equipment: String, Codable, CaseIterable, Sendable { + case none + case barbell + case dumbbell + case kettlebell + case machine + case cable + case smithMachine + case pullUpBar + case rings + case bench + case box + case bands + case medicineBall + case sled + case rope + case treadmill + case bike + case rower + case elliptical + case skiErg + case wall + case foamRoller + + public var title: String { + switch self { + case .none: "Bodyweight" + case .barbell: "Barbell" + case .dumbbell: "Dumbbell" + case .kettlebell: "Kettlebell" + case .machine: "Machine" + case .cable: "Cable" + case .smithMachine: "Smith machine" + case .pullUpBar: "Pull-up bar" + case .rings: "Rings" + case .bench: "Bench" + case .box: "Box" + case .bands: "Bands" + case .medicineBall: "Medicine ball" + case .sled: "Sled" + case .rope: "Rope" + case .treadmill: "Treadmill" + case .bike: "Bike" + case .rower: "Rower" + case .elliptical: "Elliptical" + case .skiErg: "Ski erg" + case .wall: "Wall" + case .foamRoller: "Foam roller" + } + } +} + +/// A movement's stable identity. Templates and recorded steps point at a slug so +/// every measurement of the same movement accumulates in one place, no matter +/// which template or programme produced it. +public struct ExerciseDefinition: Codable, Equatable, Identifiable, Sendable { + public var slug: String + public var name: String + public var aliases: [String] + public var pillars: Set + public var kind: ActivityKind + public var primaryMuscles: [MuscleGroup] + public var secondaryMuscles: [MuscleGroup] + public var equipment: [Equipment] + public var isUnilateral: Bool + public var defaultRest: RestRange + public var cue: String + /// The metrics worth setting a goal against for this movement. + public var goalMetrics: [MetricKind] + + public var id: String { slug } + + public init( + slug: String, + name: String, + aliases: [String] = [], + pillars: Set, + kind: ActivityKind, + primaryMuscles: [MuscleGroup] = [], + secondaryMuscles: [MuscleGroup] = [], + equipment: [Equipment] = [.none], + isUnilateral: Bool = false, + defaultRest: RestRange = RestRange(90), + cue: String = "", + goalMetrics: [MetricKind] = [.estimatedOneRepMax, .topSetLoad] + ) { + self.slug = slug + self.name = name + self.aliases = aliases + self.pillars = pillars + self.kind = kind + self.primaryMuscles = primaryMuscles + self.secondaryMuscles = secondaryMuscles + self.equipment = equipment + self.isUnilateral = isUnilateral + self.defaultRest = defaultRest + self.cue = cue + self.goalMetrics = goalMetrics + } +} + +/// The bundled movement library. +/// +/// Held in Swift rather than a JSON resource so slugs are compile-time checked +/// and the catalogue is reachable from the framework without resource plumbing. +public enum ExerciseCatalogue { + public static let all: [ExerciseDefinition] = strength + mobilityAndFlexibility + stamina + crossFit + + private static let byNormalisedName: [String: ExerciseDefinition] = { + var index: [String: ExerciseDefinition] = [:] + for definition in all { + index[ExerciseMetrics.normalise(definition.name)] = definition + for alias in definition.aliases { + index[ExerciseMetrics.normalise(alias)] = definition + } + } + return index + }() + + private static let bySlug: [String: ExerciseDefinition] = { + Dictionary(all.map { ($0.slug, $0) }, uniquingKeysWith: { first, _ in first }) + }() + + public static func definition(slug: String) -> ExerciseDefinition? { bySlug[slug] } + + /// Resolves a free-text exercise name to a catalogue definition. + public static func match(name: String) -> ExerciseDefinition? { + byNormalisedName[ExerciseMetrics.normalise(name)] + } + + public static func definitions(for pillar: Pillar) -> [ExerciseDefinition] { + all.filter { $0.pillars.contains(pillar) }.sorted { $0.name < $1.name } + } + + public static func search(_ query: String) -> [ExerciseDefinition] { + let needle = ExerciseMetrics.normalise(query) + guard !needle.isEmpty else { return all.sorted { $0.name < $1.name } } + return all + .filter { definition in + ExerciseMetrics.normalise(definition.name).contains(needle) + || definition.aliases.contains { ExerciseMetrics.normalise($0).contains(needle) } + } + .sorted { $0.name < $1.name } + } + + // MARK: - Strength + + static let strength: [ExerciseDefinition] = [ + ExerciseDefinition( + slug: "bench-press", + name: "Bench press", + aliases: ["barbell bench press", "flat bench"], + pillars: [.strength], + kind: .strength, + primaryMuscles: [.chest], + secondaryMuscles: [.triceps, .shoulders], + equipment: [.barbell, .bench], + defaultRest: RestRange(lowSeconds: 150, highSeconds: 180), + cue: "Set the shoulder blades and repeat the same touch point." + ), + ExerciseDefinition( + slug: "incline-bench-press", + name: "Incline bench press", + pillars: [.strength], + kind: .strength, + primaryMuscles: [.chest, .shoulders], + secondaryMuscles: [.triceps], + equipment: [.barbell, .bench], + defaultRest: RestRange(lowSeconds: 120, highSeconds: 180) + ), + ExerciseDefinition( + slug: "dumbbell-bench-press", + name: "Dumbbell bench press", + pillars: [.strength], + kind: .strength, + primaryMuscles: [.chest], + secondaryMuscles: [.triceps, .shoulders], + equipment: [.dumbbell, .bench], + defaultRest: RestRange(lowSeconds: 120, highSeconds: 150) + ), + ExerciseDefinition( + slug: "push-up", + name: "Push-up", + pillars: [.strength], + kind: .repetitions, + primaryMuscles: [.chest], + secondaryMuscles: [.triceps, .trunk], + defaultRest: RestRange(60), + goalMetrics: [.maxRepetitions] + ), + ExerciseDefinition( + slug: "overhead-press", + name: "Overhead press", + aliases: ["barbell overhead press", "strict press"], + pillars: [.strength], + kind: .strength, + primaryMuscles: [.shoulders], + secondaryMuscles: [.triceps, .trunk], + equipment: [.barbell], + defaultRest: RestRange(lowSeconds: 120, highSeconds: 180) + ), + ExerciseDefinition( + slug: "machine-or-db-shoulder-press", + name: "Machine or DB shoulder press", + aliases: ["shoulder press", "machine shoulder press", "dumbbell shoulder press"], + pillars: [.strength], + kind: .strength, + primaryMuscles: [.shoulders], + secondaryMuscles: [.triceps], + equipment: [.machine, .dumbbell], + defaultRest: RestRange(lowSeconds: 90, highSeconds: 150), + cue: "Choose a machine or neutral-grip dumbbells; do not force a barbell position." + ), + ExerciseDefinition( + slug: "lateral-raise", + name: "Lateral raise", + pillars: [.strength], + kind: .strength, + primaryMuscles: [.shoulders], + equipment: [.dumbbell], + defaultRest: RestRange(60) + ), + ExerciseDefinition( + slug: "lat-pulldown", + name: "Lat pulldown", + aliases: ["pulldown", "cable pulldown"], + pillars: [.strength], + kind: .strength, + primaryMuscles: [.lats], + secondaryMuscles: [.upperBack, .biceps], + equipment: [.machine, .cable], + defaultRest: RestRange(lowSeconds: 90, highSeconds: 150), + cue: "Lead with the elbows; do not shorten the range." + ), + ExerciseDefinition( + slug: "pull-up", + name: "Strict pull-up", + aliases: ["pull-up", "pullup", "strict pullup"], + pillars: [.strength], + kind: .repetitions, + primaryMuscles: [.lats], + secondaryMuscles: [.upperBack, .biceps, .forearms], + equipment: [.pullUpBar], + defaultRest: RestRange(lowSeconds: 120, highSeconds: 180), + cue: "Full hang to chin over the bar without kipping.", + goalMetrics: [.maxRepetitions, .topSetLoad] + ), + ExerciseDefinition( + slug: "chin-up", + name: "Chin-up", + pillars: [.strength], + kind: .repetitions, + primaryMuscles: [.lats, .biceps], + equipment: [.pullUpBar], + defaultRest: RestRange(lowSeconds: 120, highSeconds: 180), + goalMetrics: [.maxRepetitions, .topSetLoad] + ), + ExerciseDefinition( + slug: "chest-supported-or-cable-row", + name: "Chest-supported or cable row", + aliases: ["chest-supported row", "cable row", "seated cable row", "seated row"], + pillars: [.strength], + kind: .strength, + primaryMuscles: [.upperBack], + secondaryMuscles: [.lats, .biceps], + equipment: [.machine, .cable], + defaultRest: RestRange(lowSeconds: 90, highSeconds: 150), + cue: "Row without using lower-back momentum." + ), + ExerciseDefinition( + slug: "barbell-row", + name: "Barbell row", + pillars: [.strength], + kind: .strength, + primaryMuscles: [.upperBack, .lats], + secondaryMuscles: [.lowerBack, .biceps], + equipment: [.barbell], + defaultRest: RestRange(lowSeconds: 120, highSeconds: 180) + ), + ExerciseDefinition( + slug: "face-pull", + name: "Face pull", + pillars: [.strength, .mobility], + kind: .strength, + primaryMuscles: [.upperBack, .shoulders], + equipment: [.cable, .bands], + defaultRest: RestRange(60) + ), + ExerciseDefinition( + slug: "biceps-curl", + name: "Biceps curl", + aliases: ["dumbbell curl", "barbell curl"], + pillars: [.strength], + kind: .strength, + primaryMuscles: [.biceps], + equipment: [.dumbbell, .barbell], + defaultRest: RestRange(60) + ), + ExerciseDefinition( + slug: "triceps-extension", + name: "Triceps extension", + pillars: [.strength], + kind: .strength, + primaryMuscles: [.triceps], + equipment: [.cable, .dumbbell], + defaultRest: RestRange(60) + ), + ExerciseDefinition( + slug: "back-squat", + name: "Back squat", + pillars: [.strength], + kind: .strength, + primaryMuscles: [.quadriceps, .glutes], + secondaryMuscles: [.trunk, .lowerBack], + equipment: [.barbell], + defaultRest: RestRange(lowSeconds: 150, highSeconds: 210) + ), + ExerciseDefinition( + slug: "front-squat", + name: "Front squat", + pillars: [.strength], + kind: .strength, + primaryMuscles: [.quadriceps], + secondaryMuscles: [.trunk, .upperBack], + equipment: [.barbell], + defaultRest: RestRange(lowSeconds: 150, highSeconds: 180), + cue: "Brace before the descent. Keep elbows tall." + ), + ExerciseDefinition( + slug: "hack-squat-or-leg-press", + name: "Hack squat or leg press", + aliases: ["hack squat", "leg press"], + pillars: [.strength], + kind: .strength, + primaryMuscles: [.quadriceps, .glutes], + equipment: [.machine], + defaultRest: RestRange(lowSeconds: 150, highSeconds: 180), + cue: "Keep the same chosen machine and a repeatable depth for the full block." + ), + ExerciseDefinition( + slug: "goblet-squat", + name: "Goblet squat", + aliases: ["light goblet squat"], + pillars: [.strength, .mobility], + kind: .strength, + primaryMuscles: [.quadriceps, .glutes], + equipment: [.kettlebell, .dumbbell], + defaultRest: RestRange(60), + cue: "Use a slow descent and control the available range." + ), + ExerciseDefinition( + slug: "deadlift", + name: "Deadlift", + pillars: [.strength], + kind: .strength, + primaryMuscles: [.glutes, .hamstrings, .lowerBack], + secondaryMuscles: [.upperBack, .forearms], + equipment: [.barbell], + defaultRest: RestRange(lowSeconds: 180, highSeconds: 240) + ), + ExerciseDefinition( + slug: "romanian-deadlift", + name: "Romanian deadlift", + aliases: ["rdl"], + pillars: [.strength], + kind: .strength, + primaryMuscles: [.hamstrings, .glutes], + secondaryMuscles: [.lowerBack, .forearms], + equipment: [.barbell], + defaultRest: RestRange(lowSeconds: 150, highSeconds: 180), + cue: "Push the hips back, keep the bar close, and never train this to failure." + ), + ExerciseDefinition( + slug: "supported-bulgarian-split-squat", + name: "Supported Bulgarian split squat", + aliases: ["bulgarian split squat", "bulgarians"], + pillars: [.strength], + kind: .strength, + primaryMuscles: [.quadriceps, .glutes], + secondaryMuscles: [.adductors], + equipment: [.dumbbell, .bench], + isUnilateral: true, + defaultRest: RestRange(lowSeconds: 90, highSeconds: 150), + cue: "Use support so balance does not limit the legs." + ), + ExerciseDefinition( + slug: "lying-leg-curl", + name: "Lying leg curl", + aliases: ["leg curl"], + pillars: [.strength], + kind: .strength, + primaryMuscles: [.hamstrings], + equipment: [.machine], + defaultRest: RestRange(lowSeconds: 60, highSeconds: 90), + cue: "Control the return; do not shorten range." + ), + ExerciseDefinition( + slug: "standing-calf-raise", + name: "Standing calf raise", + aliases: ["calf raise"], + pillars: [.strength], + kind: .strength, + primaryMuscles: [.calves], + equipment: [.smithMachine, .machine, .dumbbell], + defaultRest: RestRange(lowSeconds: 60, highSeconds: 90), + cue: "Control the descent, pause in the stretch, rise fully, and do not bounce." + ), + ExerciseDefinition( + slug: "hip-thrust", + name: "Hip thrust", + pillars: [.strength], + kind: .strength, + primaryMuscles: [.glutes], + secondaryMuscles: [.hamstrings], + equipment: [.barbell, .bench], + defaultRest: RestRange(lowSeconds: 90, highSeconds: 150) + ), + ExerciseDefinition( + slug: "ab-wheel", + name: "Ab wheel from knees", + aliases: ["ab wheel", "ab rollout"], + pillars: [.strength], + kind: .repetitions, + primaryMuscles: [.trunk], + secondaryMuscles: [.lats], + defaultRest: RestRange(lowSeconds: 60, highSeconds: 90), + cue: "Stop before the lower back sags or arches.", + goalMetrics: [.maxRepetitions] + ), + ExerciseDefinition( + slug: "plank", + name: "Plank", + pillars: [.strength], + kind: .timed, + primaryMuscles: [.trunk], + defaultRest: RestRange(60), + goalMetrics: [.bestHoldSeconds] + ), + ExerciseDefinition( + slug: "hanging-leg-raise", + name: "Hanging leg raise", + pillars: [.strength], + kind: .repetitions, + primaryMuscles: [.trunk, .hipFlexors], + equipment: [.pullUpBar], + defaultRest: RestRange(lowSeconds: 60, highSeconds: 90), + goalMetrics: [.maxRepetitions] + ), + ExerciseDefinition( + slug: "farmer-carry", + name: "Farmer carry", + aliases: ["farmers carry", "farmer's carry"], + pillars: [.strength, .stamina], + kind: .timed, + primaryMuscles: [.forearms, .trunk], + secondaryMuscles: [.upperBack, .glutes], + equipment: [.dumbbell, .kettlebell], + defaultRest: RestRange(lowSeconds: 90, highSeconds: 120), + cue: "Stay tall; avoid leaning or excessive shrugging.", + goalMetrics: [.bestHoldSeconds, .topSetLoad] + ), + ExerciseDefinition( + slug: "suitcase-carry", + name: "Suitcase carry", + pillars: [.strength, .stamina], + kind: .timed, + primaryMuscles: [.trunk, .forearms], + equipment: [.dumbbell, .kettlebell], + isUnilateral: true, + defaultRest: RestRange(45), + cue: "Walk tall without leaning.", + goalMetrics: [.bestHoldSeconds, .topSetLoad] + ), + ExerciseDefinition( + slug: "scapular-pulldown", + name: "Very light scapular pulldown", + aliases: ["scapular pulldown"], + pillars: [.mobility, .strength], + kind: .strength, + primaryMuscles: [.upperBack, .lats], + equipment: [.cable, .machine], + defaultRest: RestRange(30), + cue: "Move the shoulder blades without turning this into a working set.", + goalMetrics: [.maxRepetitions] + ), + ] + + // MARK: - Mobility and flexibility + + static let mobilityAndFlexibility: [ExerciseDefinition] = [ + ExerciseDefinition( + slug: "knee-to-wall-ankle-rocks", + name: "Knee-to-wall ankle rocks", + aliases: ["ankle rocks"], + pillars: [.mobility], + kind: .mobility, + primaryMuscles: [.ankles, .calves], + equipment: [.wall], + isUnilateral: true, + defaultRest: RestRange(30), + cue: "Keep the heel down and the movement controlled.", + goalMetrics: [.rangeOfMotion, .maxRepetitions] + ), + ExerciseDefinition( + slug: "supported-squat-hold", + name: "Supported squat hold", + pillars: [.mobility, .flexibility], + kind: .timed, + primaryMuscles: [.ankles, .glutes, .adductors], + equipment: [.none], + defaultRest: RestRange(30), + cue: "Hold a rack or post. Elevate the heels when needed; do not force depth.", + goalMetrics: [.bestHoldSeconds, .rangeOfMotion] + ), + ExerciseDefinition( + slug: "supported-squat-repetitions", + name: "Supported squat repetitions", + pillars: [.mobility], + kind: .mobility, + primaryMuscles: [.quadriceps, .ankles], + defaultRest: RestRange(30), + cue: "Use a short pause and heel elevation when needed.", + goalMetrics: [.maxRepetitions] + ), + ExerciseDefinition( + slug: "ninety-ninety-hip-switches", + name: "90/90 hip switches", + aliases: ["90/90 switches", "hip switches"], + pillars: [.mobility], + kind: .mobility, + primaryMuscles: [.glutes, .hipFlexors], + isUnilateral: true, + defaultRest: RestRange(30), + cue: "Move through hip rotation without forcing the knees.", + goalMetrics: [.maxRepetitions, .rangeOfMotion] + ), + ExerciseDefinition( + slug: "half-kneeling-hip-flexor-stretch", + name: "Half-kneeling hip-flexor stretch", + aliases: ["hip flexor stretch"], + pillars: [.flexibility], + kind: .timed, + primaryMuscles: [.hipFlexors], + isUnilateral: true, + defaultRest: RestRange(15), + cue: "Extend the hip without arching the lower back.", + goalMetrics: [.bestHoldSeconds] + ), + ExerciseDefinition( + slug: "wall-slides", + name: "Wall slides", + pillars: [.mobility], + kind: .mobility, + primaryMuscles: [.shoulders, .thoracicSpine], + equipment: [.wall], + defaultRest: RestRange(30), + cue: "Move smoothly through a comfortable shoulder range.", + goalMetrics: [.maxRepetitions, .rangeOfMotion] + ), + ExerciseDefinition( + slug: "bench-lat-stretch", + name: "Bench lat stretch", + pillars: [.flexibility], + kind: .timed, + primaryMuscles: [.lats, .shoulders], + equipment: [.bench], + defaultRest: RestRange(15), + cue: "Keep the ribs controlled while reaching overhead.", + goalMetrics: [.bestHoldSeconds] + ), + ExerciseDefinition( + slug: "doorway-pec-stretch", + name: "Doorway pec stretch", + aliases: ["pec stretch"], + pillars: [.flexibility], + kind: .timed, + primaryMuscles: [.chest, .shoulders], + isUnilateral: true, + defaultRest: RestRange(15), + cue: "Stop for sharp or radiating pain.", + goalMetrics: [.bestHoldSeconds] + ), + ExerciseDefinition( + slug: "open-book-rotation", + name: "Open-book rotation", + pillars: [.mobility], + kind: .mobility, + primaryMuscles: [.thoracicSpine], + isUnilateral: true, + defaultRest: RestRange(15), + cue: "Use only if it feels useful; do not force range.", + goalMetrics: [.maxRepetitions, .rangeOfMotion] + ), + ExerciseDefinition( + slug: "straight-knee-calf-stretch", + name: "Straight-knee calf stretch", + pillars: [.flexibility], + kind: .timed, + primaryMuscles: [.calves], + equipment: [.wall], + isUnilateral: true, + defaultRest: RestRange(15), + goalMetrics: [.bestHoldSeconds] + ), + ExerciseDefinition( + slug: "bent-knee-calf-stretch", + name: "Bent-knee calf stretch", + pillars: [.flexibility], + kind: .timed, + primaryMuscles: [.calves, .ankles], + equipment: [.wall], + isUnilateral: true, + defaultRest: RestRange(15), + goalMetrics: [.bestHoldSeconds] + ), + ExerciseDefinition( + slug: "unloaded-hip-hinge", + name: "Unloaded hip hinges", + pillars: [.mobility], + kind: .mobility, + primaryMuscles: [.hamstrings, .glutes], + defaultRest: RestRange(30), + cue: "Push the hips back while keeping a small knee bend.", + goalMetrics: [.maxRepetitions] + ), + ExerciseDefinition( + slug: "arm-circles", + name: "Arm circles", + pillars: [.mobility], + kind: .mobility, + primaryMuscles: [.shoulders], + defaultRest: RestRange(0), + cue: "Complete equal repetitions forward and backward.", + goalMetrics: [.maxRepetitions] + ), + ExerciseDefinition( + slug: "thoracic-extension-over-roller", + name: "Thoracic extension over roller", + pillars: [.mobility, .flexibility], + kind: .timed, + primaryMuscles: [.thoracicSpine], + equipment: [.foamRoller], + defaultRest: RestRange(15), + goalMetrics: [.bestHoldSeconds] + ), + ExerciseDefinition( + slug: "hamstring-stretch", + name: "Seated hamstring stretch", + pillars: [.flexibility], + kind: .timed, + primaryMuscles: [.hamstrings], + isUnilateral: true, + defaultRest: RestRange(15), + goalMetrics: [.bestHoldSeconds, .rangeOfMotion] + ), + ExerciseDefinition( + slug: "pigeon-stretch", + name: "Pigeon stretch", + pillars: [.flexibility], + kind: .timed, + primaryMuscles: [.glutes, .hipFlexors], + isUnilateral: true, + defaultRest: RestRange(15), + goalMetrics: [.bestHoldSeconds] + ), + ExerciseDefinition( + slug: "couch-stretch", + name: "Couch stretch", + pillars: [.flexibility], + kind: .timed, + primaryMuscles: [.hipFlexors, .quadriceps], + isUnilateral: true, + defaultRest: RestRange(15), + goalMetrics: [.bestHoldSeconds] + ), + ExerciseDefinition( + slug: "deep-squat-hold", + name: "Deep squat hold", + pillars: [.mobility, .flexibility], + kind: .timed, + primaryMuscles: [.ankles, .adductors, .glutes], + defaultRest: RestRange(30), + goalMetrics: [.bestHoldSeconds, .rangeOfMotion] + ), + ExerciseDefinition( + slug: "shoulder-dislocates", + name: "Shoulder dislocates", + pillars: [.mobility], + kind: .mobility, + primaryMuscles: [.shoulders, .thoracicSpine], + equipment: [.bands], + defaultRest: RestRange(15), + goalMetrics: [.maxRepetitions, .rangeOfMotion] + ), + ] + + // MARK: - Stamina + + /// Cardio machines differ only by identity and equipment, so they share one + /// builder rather than repeating the same eight fields each time. + static func cardioMachine( + slug: String, + name: String, + equipment: [Equipment], + aliases: [String] = [], + pillars: Set = [.stamina], + cue: String = "" + ) -> ExerciseDefinition { + ExerciseDefinition( + slug: slug, + name: name, + aliases: aliases, + pillars: pillars, + kind: .cardio, + primaryMuscles: [.fullBody], + equipment: equipment, + defaultRest: RestRange(0), + cue: cue, + goalMetrics: [.longestDistanceMetres, .bestPaceSecondsPerKilometre] + ) + } + + static let stamina: [ExerciseDefinition] = [ + cardioMachine( + slug: "easy-cardio", + name: "Easy cardio", + equipment: [.treadmill, .bike, .elliptical, .rower], + aliases: ["conversational cardio", "easy cardio cooldown"], + cue: "Stay around 3\u{2013}4/10; full sentences should remain possible." + ), + cardioMachine( + slug: "easy-treadmill-bike-or-rower", + name: "Easy treadmill, bike or rower", + equipment: [.treadmill, .bike, .rower], + aliases: ["easy bike or treadmill"], + cue: "Use an easy pace as general preparation." + ), + ExerciseDefinition( + slug: "controlled-hard-interval", + name: "Controlled hard interval", + pillars: [.stamina], + kind: .cardio, + primaryMuscles: [.fullBody], + equipment: [.bike, .elliptical, .rower, .treadmill], + defaultRest: RestRange(180), + cue: "Use 8/10 effort: demanding and controlled, never all-out.", + goalMetrics: [.longestDistanceMetres, .bestPaceSecondsPerKilometre] + ), + cardioMachine( + slug: "easy-interval-recovery", + name: "Easy interval recovery", + equipment: [.bike, .elliptical, .rower, .treadmill], + cue: "Recover at an easy pace." + ), + cardioMachine( + slug: "bike-or-elliptical", + name: "Bike or elliptical", + equipment: [.bike, .elliptical], + aliases: ["bike or elliptical cooldown", "bike intervals"] + ), + cardioMachine(slug: "run", name: "Run", equipment: [.treadmill, .none]), + cardioMachine( + slug: "row", + name: "Row", + equipment: [.rower], + pillars: [.stamina, .strength] + ), + cardioMachine(slug: "ski-erg", name: "Ski erg", equipment: [.skiErg]), + cardioMachine( + slug: "incline-walk", + name: "Incline walk", + equipment: [.treadmill, .none], + aliases: ["recovery walk", "walk"] + ), + cardioMachine(slug: "assault-bike", name: "Assault bike", equipment: [.bike]), + ExerciseDefinition( + slug: "jump-rope", + name: "Jump rope", + aliases: ["single unders"], + pillars: [.stamina], + kind: .repetitions, + primaryMuscles: [.calves, .fullBody], + equipment: [.rope], + defaultRest: RestRange(30), + goalMetrics: [.maxRepetitions, .bestHoldSeconds] + ), + ] + + // MARK: - CrossFit movement vocabulary + + static let crossFit: [ExerciseDefinition] = [ + ExerciseDefinition( + slug: "clean-and-jerk", + name: "Clean and jerk", + pillars: [.strength, .stamina], + kind: .strength, + primaryMuscles: [.fullBody], + equipment: [.barbell], + defaultRest: RestRange(lowSeconds: 120, highSeconds: 180) + ), + ExerciseDefinition( + slug: "power-clean", + name: "Power clean", + pillars: [.strength], + kind: .strength, + primaryMuscles: [.fullBody, .glutes], + equipment: [.barbell], + defaultRest: RestRange(lowSeconds: 120, highSeconds: 180) + ), + ExerciseDefinition( + slug: "snatch", + name: "Snatch", + pillars: [.strength], + kind: .strength, + primaryMuscles: [.fullBody, .shoulders], + equipment: [.barbell], + defaultRest: RestRange(lowSeconds: 120, highSeconds: 180) + ), + ExerciseDefinition( + slug: "thruster", + name: "Thruster", + pillars: [.strength, .stamina], + kind: .strength, + primaryMuscles: [.quadriceps, .shoulders], + equipment: [.barbell, .dumbbell], + defaultRest: RestRange(lowSeconds: 90, highSeconds: 150) + ), + ExerciseDefinition( + slug: "wall-ball", + name: "Wall ball", + pillars: [.strength, .stamina], + kind: .repetitions, + primaryMuscles: [.quadriceps, .shoulders], + equipment: [.medicineBall, .wall], + defaultRest: RestRange(60), + goalMetrics: [.maxRepetitions] + ), + ExerciseDefinition( + slug: "kettlebell-swing", + name: "Kettlebell swing", + pillars: [.strength, .stamina], + kind: .strength, + primaryMuscles: [.glutes, .hamstrings], + secondaryMuscles: [.trunk, .forearms], + equipment: [.kettlebell], + defaultRest: RestRange(60) + ), + ExerciseDefinition( + slug: "box-jump", + name: "Box jump", + pillars: [.strength, .stamina], + kind: .repetitions, + primaryMuscles: [.quadriceps, .calves], + equipment: [.box], + defaultRest: RestRange(60), + goalMetrics: [.maxRepetitions] + ), + ExerciseDefinition( + slug: "burpee", + name: "Burpee", + pillars: [.stamina, .strength], + kind: .repetitions, + primaryMuscles: [.fullBody], + defaultRest: RestRange(60), + goalMetrics: [.maxRepetitions] + ), + ExerciseDefinition( + slug: "toes-to-bar", + name: "Toes-to-bar", + pillars: [.strength, .mobility], + kind: .repetitions, + primaryMuscles: [.trunk, .lats], + equipment: [.pullUpBar], + defaultRest: RestRange(lowSeconds: 60, highSeconds: 90), + goalMetrics: [.maxRepetitions] + ), + ExerciseDefinition( + slug: "double-under", + name: "Double-under", + pillars: [.stamina], + kind: .repetitions, + primaryMuscles: [.calves], + equipment: [.rope], + defaultRest: RestRange(60), + goalMetrics: [.maxRepetitions] + ), + ExerciseDefinition( + slug: "handstand-push-up", + name: "Handstand push-up", + pillars: [.strength], + kind: .repetitions, + primaryMuscles: [.shoulders, .triceps], + equipment: [.wall], + defaultRest: RestRange(lowSeconds: 90, highSeconds: 150), + goalMetrics: [.maxRepetitions] + ), + ExerciseDefinition( + slug: "ring-dip", + name: "Ring dip", + pillars: [.strength], + kind: .repetitions, + primaryMuscles: [.chest, .triceps], + equipment: [.rings], + defaultRest: RestRange(lowSeconds: 90, highSeconds: 120), + goalMetrics: [.maxRepetitions, .topSetLoad] + ), + ExerciseDefinition( + slug: "muscle-up", + name: "Muscle-up", + pillars: [.strength], + kind: .repetitions, + primaryMuscles: [.lats, .chest, .triceps], + equipment: [.rings, .pullUpBar], + defaultRest: RestRange(lowSeconds: 120, highSeconds: 180), + goalMetrics: [.maxRepetitions] + ), + ExerciseDefinition( + slug: "sled-push", + name: "Sled push", + pillars: [.strength, .stamina], + kind: .timed, + primaryMuscles: [.quadriceps, .glutes], + equipment: [.sled], + defaultRest: RestRange(lowSeconds: 90, highSeconds: 150), + goalMetrics: [.longestDistanceMetres, .topSetLoad] + ), + ExerciseDefinition( + slug: "rope-climb", + name: "Rope climb", + pillars: [.strength], + kind: .repetitions, + primaryMuscles: [.lats, .forearms], + equipment: [.rope], + defaultRest: RestRange(lowSeconds: 90, highSeconds: 150), + goalMetrics: [.maxRepetitions] + ), + ] +} diff --git a/ios/Sources/SetlineCore/Goals.swift b/ios/Sources/SetlineCore/Goals.swift new file mode 100644 index 0000000..ea4a47d --- /dev/null +++ b/ios/Sources/SetlineCore/Goals.swift @@ -0,0 +1,434 @@ +import Foundation + +/// A measurable quality of one exercise. Every "current" value Setline shows and +/// every "ideal" value you author is expressed as one of these, so the two are +/// always comparable. +public enum MetricKind: String, Codable, CaseIterable, Sendable { + /// Estimated one-repetition maximum, in kilograms. + case estimatedOneRepMax + /// Heaviest load completed for at least a reference repetition count. + case topSetLoad + /// Most repetitions completed in a single set. + case maxRepetitions + /// Longest hold or carry, in seconds. + case bestHoldSeconds + /// Furthest single effort, in metres. + case longestDistanceMetres + /// Quickest pace, in seconds per kilometre. Lower is better. + case bestPaceSecondsPerKilometre + /// Measured range, in the unit the movement is assessed in. + case rangeOfMotion + + public var title: String { + switch self { + case .estimatedOneRepMax: "Estimated 1RM" + case .topSetLoad: "Top set load" + case .maxRepetitions: "Max repetitions" + case .bestHoldSeconds: "Best hold" + case .longestDistanceMetres: "Longest distance" + case .bestPaceSecondsPerKilometre: "Best pace" + case .rangeOfMotion: "Range of motion" + } + } + + public var unit: String { + switch self { + case .estimatedOneRepMax, .topSetLoad: "kg" + case .maxRepetitions: "reps" + case .bestHoldSeconds: "sec" + case .longestDistanceMetres: "m" + case .bestPaceSecondsPerKilometre: "/km" + case .rangeOfMotion: "cm" + } + } + + /// Pace improves as it falls; every other metric improves as it rises. + public var lowerIsBetter: Bool { self == .bestPaceSecondsPerKilometre } + + /// Metrics that only mean something when the movement is loaded. + public var requiresLoad: Bool { + self == .estimatedOneRepMax || self == .topSetLoad + } + + public func format(_ value: Double) -> String { + switch self { + case .estimatedOneRepMax, .topSetLoad: "\(value.kilogramString) kg" + case .maxRepetitions: "\(Int(value)) reps" + case .bestHoldSeconds: Int(value).durationLabel + case .longestDistanceMetres: value.distanceLabel + case .bestPaceSecondsPerKilometre: "\(Int(value).paceLabel)/km" + case .rangeOfMotion: "\(value.trimmedString) cm" + } + } +} + +/// The ideal you are training toward for one exercise. +public struct ExerciseGoal: Codable, Equatable, Identifiable, Sendable { + public var id: UUID + /// Matched against recorded step names, case- and whitespace-insensitively. + public var exerciseName: String + public var metric: MetricKind + public var targetValue: Double + /// For `topSetLoad`, the repetition count the load must be held for. + public var referenceRepetitions: Int? + public var targetDate: Date? + public var createdAt: Date + public var note: String? + + public init( + id: UUID = UUID(), + exerciseName: String, + metric: MetricKind, + targetValue: Double, + referenceRepetitions: Int? = nil, + targetDate: Date? = nil, + createdAt: Date = .now, + note: String? = nil + ) { + self.id = id + self.exerciseName = exerciseName + self.metric = metric + self.targetValue = targetValue + self.referenceRepetitions = referenceRepetitions + self.targetDate = targetDate + self.createdAt = createdAt + self.note = note + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID() + exerciseName = try container.decodeIfPresent(String.self, forKey: .exerciseName) ?? "" + metric = try container.decodeIfPresent(MetricKind.self, forKey: .metric) ?? .estimatedOneRepMax + targetValue = try container.decodeIfPresent(Double.self, forKey: .targetValue) ?? 0 + referenceRepetitions = try container.decodeIfPresent(Int.self, forKey: .referenceRepetitions) + targetDate = try container.decodeIfPresent(Date.self, forKey: .targetDate) + createdAt = try container.decodeIfPresent(Date.self, forKey: .createdAt) ?? .now + note = try container.decodeIfPresent(String.self, forKey: .note) + } +} + +/// One measured point, always carrying the session that produced it. Setline +/// never shows a number it cannot attribute to a recorded set. +public struct MeasuredValue: Equatable, Identifiable, Sendable { + public var id: UUID { sessionID } + public var metric: MetricKind + public var value: Double + public var repetitions: Int? + public var achievedAt: Date + public var sessionID: UUID + public var sessionName: String + + public init( + metric: MetricKind, + value: Double, + repetitions: Int? = nil, + achievedAt: Date, + sessionID: UUID, + sessionName: String + ) { + self.metric = metric + self.value = value + self.repetitions = repetitions + self.achievedAt = achievedAt + self.sessionID = sessionID + self.sessionName = sessionName + } + + public var provenance: String { + "\(sessionName) · \(achievedAt.formatted(date: .abbreviated, time: .omitted))" + } +} + +/// How far a goal has come and, when the evidence supports it, where it is headed. +public struct GoalProgress: Equatable, Sendable { + public var goal: ExerciseGoal + /// The best recorded value, or nil when nothing comparable has been recorded. + public var current: MeasuredValue? + /// Where the metric stood when the goal was created, used as the origin. + public var baseline: MeasuredValue? + /// 0 to 1 from baseline to target. Nil when there is no evidence to measure. + public var fraction: Double? + public var remaining: Double? + /// Change per week across the recorded series. Nil below two data points. + public var ratePerWeek: Double? + public var projectedDate: Date? + public var evidenceCount: Int + + public var isAchieved: Bool { + guard let current else { return false } + return goal.metric.lowerIsBetter + ? current.value <= goal.targetValue + : current.value >= goal.targetValue + } +} + +/// Derives current values, records and goal progress from recorded history. +/// +/// Everything here reads only completed **working** sets. Warm-up ramps, +/// preparation and cooldown work are deliberately invisible to measurement, in +/// line with the authored rule that warm-ups are not working sets. +public enum ExerciseMetrics { + /// Epley. Deliberately capped: past about 12 repetitions the estimate stops + /// being a strength measurement, so Setline declines to report one. + static let maximumRepetitionsForEstimate = 12 + + public static func normalise(_ name: String) -> String { + name.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() + } + + public static func estimatedOneRepMax(kilograms: Double, repetitions: Int) -> Double? { + guard kilograms > 0, repetitions > 0, repetitions <= maximumRepetitionsForEstimate else { + return nil + } + if repetitions == 1 { return kilograms } + return kilograms * (1 + Double(repetitions) / 30) + } + + /// Every completed working step for one exercise, newest first. + public static func workingSteps( + for exerciseName: String, + history: [WorkoutSession] + ) -> [(session: WorkoutSession, step: WorkoutStep)] { + let key = normalise(exerciseName) + return history.flatMap { session in + session.steps + .filter { normalise($0.exerciseName) == key && $0.countsTowardVolume } + .map { (session, $0) } + } + } + + /// The measured series for a metric, oldest first, one best point per session. + public static func series( + for exerciseName: String, + metric: MetricKind, + referenceRepetitions: Int? = nil, + history: [WorkoutSession] + ) -> [MeasuredValue] { + var bestBySession: [UUID: MeasuredValue] = [:] + for (session, step) in workingSteps(for: exerciseName, history: history) { + guard let candidate = value( + for: metric, + step: step, + session: session, + referenceRepetitions: referenceRepetitions + ) else { continue } + if let existing = bestBySession[session.id], !improves(candidate.value, on: existing.value, metric: metric) { + continue + } + bestBySession[session.id] = candidate + } + return bestBySession.values.sorted { $0.achievedAt < $1.achievedAt } + } + + /// The single best recorded value for a metric. + public static func current( + for exerciseName: String, + metric: MetricKind, + referenceRepetitions: Int? = nil, + history: [WorkoutSession] + ) -> MeasuredValue? { + series( + for: exerciseName, + metric: metric, + referenceRepetitions: referenceRepetitions, + history: history + ).max { improves($1.value, on: $0.value, metric: metric) } + } + + /// Which metrics this exercise has actually produced evidence for. + public static func availableMetrics( + for exerciseName: String, + history: [WorkoutSession] + ) -> [MetricKind] { + MetricKind.allCases.filter { metric in + !series(for: exerciseName, metric: metric, history: history).isEmpty + } + } + + public static func progress(for goal: ExerciseGoal, history: [WorkoutSession]) -> GoalProgress { + let points = series( + for: goal.exerciseName, + metric: goal.metric, + referenceRepetitions: goal.referenceRepetitions, + history: history + ) + let current = points.max { improves($1.value, on: $0.value, metric: goal.metric) } + // The origin is the last measurement at or before the goal was authored; + // without one, the earliest point available. + let baseline = points.last { $0.achievedAt <= goal.createdAt } ?? points.first + var fraction: Double? + var remaining: Double? + if let current { + remaining = goal.metric.lowerIsBetter + ? max(0, current.value - goal.targetValue) + : max(0, goal.targetValue - current.value) + if let baseline { + let span = goal.metric.lowerIsBetter + ? baseline.value - goal.targetValue + : goal.targetValue - baseline.value + let travelled = goal.metric.lowerIsBetter + ? baseline.value - current.value + : current.value - baseline.value + if span > 0 { fraction = min(1, max(0, travelled / span)) } + } + } + let rate = ratePerWeek(points, metric: goal.metric) + return GoalProgress( + goal: goal, + current: current, + baseline: baseline, + fraction: fraction, + remaining: remaining, + ratePerWeek: rate, + projectedDate: projectedDate( + current: current, + remaining: remaining, + ratePerWeek: rate, + metric: goal.metric + ), + evidenceCount: points.count + ) + } + + // MARK: - Internals + + static func improves(_ candidate: Double, on existing: Double, metric: MetricKind) -> Bool { + metric.lowerIsBetter ? candidate < existing : candidate > existing + } + + /// One measurement of a step, or nil when the step cannot express that metric. + /// + /// Each metric reads the recorded segments in its own way, so the dispatch and + /// the per-metric arithmetic are kept apart. + static func value( + for metric: MetricKind, + step: WorkoutStep, + session: WorkoutSession, + referenceRepetitions: Int? + ) -> MeasuredValue? { + guard let reading = reading(for: metric, step: step, referenceRepetitions: referenceRepetitions) else { + return nil + } + return MeasuredValue( + metric: metric, + value: reading.value, + repetitions: reading.repetitions, + achievedAt: step.completedAt ?? session.completedAt ?? session.startedAt, + sessionID: session.id, + sessionName: session.templateName + ) + } + + static func reading( + for metric: MetricKind, + step: WorkoutStep, + referenceRepetitions: Int? + ) -> (value: Double, repetitions: Int?)? { + switch metric { + case .estimatedOneRepMax: bestEstimatedOneRepMax(in: step.segments) + case .topSetLoad: heaviestLoad(in: step.segments, atLeast: referenceRepetitions ?? 1) + case .maxRepetitions: totalRepetitions(in: step.segments) + case .bestHoldSeconds: longestHold(in: step.segments) + case .longestDistanceMetres: furthestDistance(in: step.segments) + case .bestPaceSecondsPerKilometre: quickestPace(in: step.segments) + case .rangeOfMotion: deepestRange(in: step.segments) + } + } + + static func bestEstimatedOneRepMax(in segments: [SetSegment]) -> (Double, Int?)? { + let estimates = segments.compactMap { segment -> (Double, Int)? in + guard let kilograms = segment.effectiveKilograms, + let reps = segment.repetitions, + let estimate = estimatedOneRepMax(kilograms: kilograms, repetitions: reps) + else { return nil } + return (estimate, reps) + } + guard let best = estimates.max(by: { $0.0 < $1.0 }) else { return nil } + return (best.0, best.1) + } + + static func heaviestLoad(in segments: [SetSegment], atLeast minimumReps: Int) -> (Double, Int?)? { + let loads = segments.compactMap { segment -> (Double, Int)? in + guard let kilograms = segment.effectiveKilograms, + let reps = segment.repetitions, + reps >= minimumReps + else { return nil } + return (kilograms, reps) + } + guard let best = loads.max(by: { $0.0 < $1.0 }) else { return nil } + return (best.0, best.1) + } + + /// Summed across segments: `5×40 + 2×30` is seven repetitions of work. + static func totalRepetitions(in segments: [SetSegment]) -> (Double, Int?)? { + let reps = segments.compactMap(\.repetitions).reduce(0, +) + guard reps > 0 else { return nil } + return (Double(reps), reps) + } + + static func longestHold(in segments: [SetSegment]) -> (Double, Int?)? { + let seconds = segments.compactMap { $0.durationSeconds ?? $0.workSeconds } + guard let best = seconds.max(), best > 0 else { return nil } + return (Double(best), nil) + } + + static func furthestDistance(in segments: [SetSegment]) -> (Double, Int?)? { + let metres = segments.compactMap(\.distanceKilometres).map { $0 * 1_000 } + guard let best = metres.max(), best > 0 else { return nil } + return (best, nil) + } + + static func quickestPace(in segments: [SetSegment]) -> (Double, Int?)? { + let paces = segments.compactMap { segment -> Double? in + guard let kilometres = segment.distanceKilometres, kilometres > 0, + let seconds = segment.durationSeconds ?? segment.workSeconds, seconds > 0 + else { return nil } + return Double(seconds) / kilometres + } + guard let best = paces.min() else { return nil } + return (best, nil) + } + + static func deepestRange(in segments: [SetSegment]) -> (Double, Int?)? { + let values = segments.compactMap(\.rangeOfMotionValue) + guard let best = values.max(), best > 0 else { return nil } + return (best, nil) + } + + /// Least-squares slope over time, expressed per week. Nil below two points or + /// when every point shares a timestamp. + static func ratePerWeek(_ points: [MeasuredValue], metric: MetricKind) -> Double? { + guard points.count >= 2 else { return nil } + let origin = points[0].achievedAt.timeIntervalSince1970 + let weeks = points.map { ($0.achievedAt.timeIntervalSince1970 - origin) / 604_800 } + let values = points.map(\.value) + let meanWeek = weeks.reduce(0, +) / Double(weeks.count) + let meanValue = values.reduce(0, +) / Double(values.count) + var covariance = 0.0 + var variance = 0.0 + for index in weeks.indices { + let deltaWeek = weeks[index] - meanWeek + covariance += deltaWeek * (values[index] - meanValue) + variance += deltaWeek * deltaWeek + } + guard variance > 0 else { return nil } + return covariance / variance + } + + static func projectedDate( + current: MeasuredValue?, + remaining: Double?, + ratePerWeek: Double?, + metric: MetricKind + ) -> Date? { + guard let current, let remaining, remaining > 0, let ratePerWeek else { return nil } + // A trend moving away from the goal cannot produce an arrival date. For + // pace, improvement is a falling value; for everything else, a rising one. + let progressPerWeek = metric.lowerIsBetter ? -ratePerWeek : ratePerWeek + guard progressPerWeek > 0 else { return nil } + let weeks = remaining / progressPerWeek + guard weeks.isFinite, weeks > 0, weeks < 520 else { return nil } + return current.achievedAt.addingTimeInterval(weeks * 604_800) + } +} diff --git a/ios/Sources/SetlineCore/Persistence.swift b/ios/Sources/SetlineCore/Persistence.swift index 46022aa..2904e49 100644 --- a/ios/Sources/SetlineCore/Persistence.swift +++ b/ios/Sources/SetlineCore/Persistence.swift @@ -15,14 +15,58 @@ public actor SetlineStore { public func load() throws -> SetlineDocument { guard FileManager.default.fileExists(atPath: fileURL.path) else { - return .sample + return .initial } let data = try Data(contentsOf: fileURL) - let document = try Self.decoder.decode(SetlineDocument.self, from: data) - guard document.schemaVersion == 1 else { + return try Self.migrate(Self.decoder.decode(SetlineDocument.self, from: data)) + } + + /// Brings a decoded document up to the current schema. + /// + /// Version 1 stored free-text targets, scalar rest and a bare custom + /// programme; the decoders in `Domain` absorb those shapes, so migration only + /// has to stamp the version and backfill catalogue links. + static func migrate(_ document: SetlineDocument) throws -> SetlineDocument { + guard document.schemaVersion <= SetlineDocument.currentSchemaVersion else { throw SetlineError.unsupportedSchema(document.schemaVersion) } - return document + guard document.schemaVersion < SetlineDocument.currentSchemaVersion else { return document } + var migrated = document + migrated.schemaVersion = SetlineDocument.currentSchemaVersion + migrated.templates = migrated.templates.map(linkCatalogue(in:)) + migrated.history = migrated.history.map(linkCatalogue(in:)) + if let active = migrated.activeSession { migrated.activeSession = linkCatalogue(in: active) } + return migrated + } + + /// Resolves recorded exercise names to catalogue slugs so historic sessions + /// contribute to the same measurements as new ones. + static func linkCatalogue(in template: WorkoutTemplate) -> WorkoutTemplate { + var result = template + result.exercises = result.exercises.map { exercise in + guard exercise.definitionSlug == nil, + let definition = ExerciseCatalogue.match(name: exercise.name) + else { return exercise } + var linked = exercise + linked.definitionSlug = definition.slug + linked.pillars = definition.pillars + return linked + } + return result + } + + static func linkCatalogue(in session: WorkoutSession) -> WorkoutSession { + var result = session + result.steps = result.steps.map { step in + guard step.exerciseSlug == nil, + let definition = ExerciseCatalogue.match(name: step.exerciseName) + else { return step } + var linked = step + linked.exerciseSlug = definition.slug + linked.pillars = definition.pillars + return linked + } + return result } public func save(_ document: SetlineDocument) throws { @@ -37,11 +81,7 @@ public actor SetlineStore { } public func previewImport(_ data: Data) throws -> SetlineDocument { - let document = try Self.decoder.decode(SetlineDocument.self, from: data) - guard document.schemaVersion == 1 else { - throw SetlineError.unsupportedSchema(document.schemaVersion) - } - return document + try Self.migrate(Self.decoder.decode(SetlineDocument.self, from: data)) } public func replace(with document: SetlineDocument) throws { diff --git a/ios/Sources/SetlineCore/Progression.swift b/ios/Sources/SetlineCore/Progression.swift index bf40c51..97e453c 100644 --- a/ios/Sources/SetlineCore/Progression.swift +++ b/ios/Sources/SetlineCore/Progression.swift @@ -1,33 +1,178 @@ import Foundation +/// What to do with the load next time this movement comes up. +public enum ProgressionAction: String, Equatable, Sendable { + /// Every working set reached the top of the rep range cleanly. + case addLoad + /// Hold the load and add repetitions inside the range. + case addRepetitions + /// The last session fell below the bottom of the range; reduce the load. + case reduceLoad + /// Not enough comparable evidence to say anything. + case insufficientEvidence +} + public struct ProgressionRecommendation: Equatable, Sendable { public var exerciseName: String - public var previousWeight: Double - public var recommendedWeight: Double + public var exerciseSlug: String? + public var action: ProgressionAction + public var currentLoad: Double? + public var recommendedLoad: Double? + /// The repetitions achieved on each working set of the most recent session, + /// in authored order, so the suggestion can always be audited. + public var lastSessionRepetitions: [Int] + public var lastSessionDate: Date? public var rationale: String - public init(exerciseName: String, previousWeight: Double, recommendedWeight: Double, rationale: String) { + public init( + exerciseName: String, + exerciseSlug: String? = nil, + action: ProgressionAction, + currentLoad: Double? = nil, + recommendedLoad: Double? = nil, + lastSessionRepetitions: [Int] = [], + lastSessionDate: Date? = nil, + rationale: String + ) { self.exerciseName = exerciseName - self.previousWeight = previousWeight - self.recommendedWeight = recommendedWeight + self.exerciseSlug = exerciseSlug + self.action = action + self.currentLoad = currentLoad + self.recommendedLoad = recommendedLoad + self.lastSessionRepetitions = lastSessionRepetitions + self.lastSessionDate = lastSessionDate self.rationale = rationale } + + /// A short audit line such as "8, 8, 8 at 65 kg". + public var evidenceSummary: String? { + guard !lastSessionRepetitions.isEmpty else { return nil } + let reps = lastSessionRepetitions.map(String.init).joined(separator: ", ") + guard let currentLoad else { return reps } + return "\(reps) at \(currentLoad.trimmedString) kg" + } } +/// Double progression: add repetitions inside the prescribed range first, then +/// add load once every working set sits at the top of it. +/// +/// The rule and its increment come from the authored programme rather than a flat +/// default, so bench moves in 2.5 kg only after `3 × 8` is clean while a machine +/// moves by one increment. public enum ProgressionEngine { - public static func recommendation(for exercise: String, history: [WorkoutSession]) -> ProgressionRecommendation? { - let completed = history - .flatMap(\.steps) - .filter { $0.exerciseName == exercise && $0.status == .complete && $0.kind == .strength } - guard completed.count >= 2 else { return nil } - let recent = completed.prefix(3) - let weights = recent.compactMap { $0.segments.first?.weight } - guard weights.count == recent.count, let latest = weights.first, Set(weights).count == 1 else { return nil } - return ProgressionRecommendation( - exerciseName: exercise, - previousWeight: latest, - recommendedWeight: latest + 2.5, - rationale: "The last \(weights.count) comparable working sets were completed at \(latest.formatted()) kg. This suggestion applies to this session only." + /// What the most recent session that trained this movement actually produced. + struct LatestEvidence: Equatable, Sendable { + var repetitions: [Int] + /// Nil when the movement was unloaded or the working sets used different + /// loads, in which case no single load can be recommended. + var currentLoad: Double? + var date: Date? + } + + static func latestEvidence(for exerciseName: String, history: [WorkoutSession]) -> LatestEvidence? { + // Only completed working sets from the most recent session that trained + // this movement. Warm-ups and preparation never inform progression. + let steps = ExerciseMetrics.workingSteps(for: exerciseName, history: history) + guard let latestSessionID = steps.first?.session.id else { return nil } + let sorted = steps + .filter { $0.session.id == latestSessionID } + .sorted { $0.step.authoredPosition < $1.step.authoredPosition } + guard !sorted.isEmpty else { return nil } + + let repetitions = sorted + .map { $0.step.segments.compactMap(\.repetitions).reduce(0, +) } + .filter { $0 > 0 } + guard !repetitions.isEmpty else { return nil } + + let loads = sorted.compactMap { $0.step.segments.first?.effectiveKilograms } + let distinctLoads = Set(loads.map { ($0 * 100).rounded() }) + return LatestEvidence( + repetitions: repetitions, + currentLoad: distinctLoads.count == 1 ? loads.first : nil, + date: sorted.compactMap(\.step.completedAt).max() ?? sorted.first?.session.completedAt + ) + } + + /// Recommends the next load for an exercise using its authored rule. + public static func recommendation( + for exerciseName: String, + slug: String? = nil, + rule: ProgressionRule?, + history: [WorkoutSession] + ) -> ProgressionRecommendation? { + let resolvedSlug = slug ?? ExerciseCatalogue.match(name: exerciseName)?.slug + let resolvedRule = rule ?? resolvedSlug.flatMap { TwelveWeekProgramme.rule(forSlug: $0) } + guard let evidence = latestEvidence(for: exerciseName, history: history) else { return nil } + + func recommend( + _ action: ProgressionAction, + recommendedLoad: Double? = nil, + rationale: String + ) -> ProgressionRecommendation { + ProgressionRecommendation( + exerciseName: exerciseName, + exerciseSlug: resolvedSlug, + action: action, + currentLoad: evidence.currentLoad, + recommendedLoad: recommendedLoad, + lastSessionRepetitions: evidence.repetitions, + lastSessionDate: evidence.date, + rationale: rationale + ) + } + + guard let resolvedRule, resolvedRule.repsHigh > 0 else { + return recommend( + .insufficientEvidence, + rationale: "No authored rep range for this movement, so Setline will not suggest a load." + ) + } + + let range = "\(resolvedRule.repsLow)–\(resolvedRule.repsHigh) reps" + if evidence.repetitions.contains(where: { $0 < resolvedRule.repsLow }) { + let increment = resolvedRule.incrementKilograms ?? 2.5 + return recommend( + .reduceLoad, + recommendedLoad: evidence.currentLoad.map { max(0, $0 - increment) }, + rationale: "At least one working set fell below \(resolvedRule.repsLow) reps. Reduce the load and rebuild inside \(range)." + ) + } + + if evidence.repetitions.allSatisfy({ $0 >= resolvedRule.repsHigh }) { + guard let currentLoad = evidence.currentLoad, let increment = resolvedRule.incrementKilograms else { + return recommend( + .addLoad, + rationale: "Every working set reached \(resolvedRule.repsHigh) reps. \(resolvedRule.specialRule)" + ) + } + return recommend( + .addLoad, + recommendedLoad: currentLoad + increment, + rationale: "Every working set reached \(resolvedRule.repsHigh) reps at \(currentLoad.trimmedString) kg. \(resolvedRule.specialRule)" + ) + } + + return recommend( + .addRepetitions, + recommendedLoad: evidence.currentLoad, + rationale: "Keep the load and add repetitions until every set reaches \(resolvedRule.repsHigh), then increase." ) } + + /// Recommendations for every movement with recorded working sets, ordered by + /// how recently it was trained. + public static func recommendations(history: [WorkoutSession]) -> [ProgressionRecommendation] { + var seen = Set() + var names: [String] = [] + for session in history { + for step in session.steps where step.countsTowardVolume { + let key = ExerciseMetrics.normalise(step.exerciseName) + if seen.insert(key).inserted { names.append(step.exerciseName) } + } + } + return names.compactMap { name in + recommendation(for: name, rule: nil, history: history) + } + .filter { $0.action != .insufficientEvidence } + } } diff --git a/ios/Sources/SetlineCore/SetEntryParser.swift b/ios/Sources/SetlineCore/SetEntryParser.swift new file mode 100644 index 0000000..e699c75 --- /dev/null +++ b/ios/Sources/SetlineCore/SetEntryParser.swift @@ -0,0 +1,283 @@ +import Foundation + +/// Turns shorthand typed at the rack into structured segments. +/// +/// Deliberately rule-based rather than model-driven: entering what you just +/// lifted must never be probabilistic. When the text cannot be understood the +/// parser says so instead of guessing, and the caller shows the interpretation +/// back before anything is recorded. +/// +/// Understood forms, comma- or semicolon-separated for multiple segments: +/// +/// 5x40 five repetitions at 40 kg +/// 40kg x 5 same set, weight-first because the unit disambiguates +/// 5 reps 40 kg explicit units in either order +/// bw x 8 bodyweight +/// bw+10 x 8 bodyweight plus 10 kg +/// assist 15 x 6 15 kg of assistance +/// 45s a 45-second hold or carry +/// 2min a two-minute effort +/// 5km 25min distance with its duration +/// 5x40 @rpe8 rir1 effort qualifiers +/// left 8, right 8 per-side work +/// 5x40, 2x30 one set with two segments +public enum SetEntryParser { + public struct Result: Equatable, Sendable { + public var segments: [SetSegment] + /// Fragments the parser could not interpret, surfaced rather than dropped. + public var unrecognised: [String] + + public var isEmpty: Bool { segments.isEmpty } + public var isFullyUnderstood: Bool { unrecognised.isEmpty && !segments.isEmpty } + } + + public static func parse(_ text: String) -> Result { + var segments: [SetSegment] = [] + var unrecognised: [String] = [] + for fragment in split(text) { + if let segment = parseSegment(fragment) { + segments.append(segment) + } else { + unrecognised.append(fragment) + } + } + return Result(segments: segments, unrecognised: unrecognised) + } + + /// Renders segments back into the shorthand that would reproduce them, so the + /// field can be round-tripped when editing a recorded set. + public static func shorthand(for segments: [SetSegment]) -> String { + segments.map(shorthand(for:)).joined(separator: ", ") + } + + static func shorthand(for segment: SetSegment) -> String { + var parts: [String] = [] + if let side = segment.side, side != .both { parts.append(side.rawValue) } + switch (segment.repetitions, segment.weight) { + case let (reps?, weight?): + parts.append("\(reps)x\(weight.trimmedString)") + case let (reps?, nil): + if let assistance = segment.assistanceKilograms { + parts.append("assist \(assistance.trimmedString) x \(reps)") + } else { + parts.append("\(reps) reps") + } + case let (nil, weight?): + parts.append("\(weight.trimmedString) kg") + case (nil, nil): + break + } + if let seconds = segment.durationSeconds { + parts.append(seconds % 60 == 0 && seconds >= 60 ? "\(seconds / 60)min" : "\(seconds)s") + } + if let kilometres = segment.distanceKilometres { parts.append("\(kilometres.trimmedString)km") } + if let rpe = segment.rpe { parts.append("@rpe\(rpe.trimmedString)") } + if let rir = segment.repsInReserve { parts.append("rir\(rir)") } + if segment.reachedFailure { parts.append("fail") } + return parts.joined(separator: " ") + } + + // MARK: - Fragmentation + + static func split(_ text: String) -> [String] { + text + .replacingOccurrences(of: " then ", with: ",") + .replacingOccurrences(of: " & ", with: ",") + .split(whereSeparator: { $0 == "," || $0 == ";" || $0 == "\n" }) + .map { $0.trimmingCharacters(in: .whitespaces) } + .filter { !$0.isEmpty } + } + + // MARK: - Segment parsing + + static func parseSegment(_ fragment: String) -> SetSegment? { + var working = fragment.lowercased() + var segment = SetSegment() + var understoodAnything = false + + // Qualifiers and units are consumed first so that whatever remains can be + // read as a bare "reps x weight" pair without ambiguity. + if let side = takeSide(&working) { + segment.side = side + understoodAnything = true + } + if takeFailure(&working) { + segment.reachedFailure = true + understoodAnything = true + } + if let rpe = takeNumber(&working, pattern: #"@?\s*rpe\s*([0-9]{1,2}(?:\.[05])?)"#) + ?? takeNumber(&working, pattern: #"@\s*([0-9]{1,2}(?:\.[05])?)"#) { + segment.rpe = rpe + understoodAnything = true + } + if let rir = takeNumber(&working, pattern: #"rir\s*([0-9]{1,2})"#) { + segment.repsInReserve = Int(rir) + understoodAnything = true + } + if let assistance = takeNumber( + &working, + pattern: #"(?:assist(?:ed)?|assistance)\s*([0-9]+(?:\.[0-9]+)?)\s*(?:kgs?|kilos?|kilograms?)?"# + ) { + segment.assistanceKilograms = assistance + understoodAnything = true + } + if let bodyweight = takeBodyweight(&working) { + if bodyweight > 0 { segment.weight = bodyweight } + understoodAnything = true + } + if let minutes = takeNumber(&working, pattern: #"([0-9]+(?:\.[0-9]+)?)\s*(?:min(?:s|ute|utes)?)"#) { + segment.durationSeconds = Int((minutes * 60).rounded()) + understoodAnything = true + } + if let seconds = takeNumber(&working, pattern: #"([0-9]+(?:\.[0-9]+)?)\s*(?:s|sec|secs|second|seconds)\b"#) { + segment.durationSeconds = (segment.durationSeconds ?? 0) + Int(seconds.rounded()) + understoodAnything = true + } + if let kilometres = takeNumber(&working, pattern: #"([0-9]+(?:\.[0-9]+)?)\s*(?:km|kms|kilometres?|kilometers?)\b"#) { + segment.distanceKilometres = kilometres + understoodAnything = true + } + if let metres = takeNumber(&working, pattern: #"([0-9]+(?:\.[0-9]+)?)\s*(?:m|metres?|meters?)\b"#) { + segment.distanceKilometres = (segment.distanceKilometres ?? 0) + metres / 1_000 + understoodAnything = true + } + if let weight = takeNumber(&working, pattern: #"([0-9]+(?:\.[0-9]+)?)\s*(?:kgs?|kilos?|kilograms?)\b"#) { + segment.weight = weight + understoodAnything = true + } + if let reps = takeNumber(&working, pattern: #"([0-9]+)\s*(?:r|rep|reps|repetitions?)\b"#) { + segment.repetitions = Int(reps) + understoodAnything = true + } + if let degrees = takeNumber(&working, pattern: #"([0-9]+(?:\.[0-9]+)?)\s*(?:deg|degrees?|°)"#) { + segment.rangeOfMotionValue = degrees + understoodAnything = true + } + + // A remaining "A x B" pair. Reps come first when no unit settled it, + // matching how the plan is written; an already-known value pins the other. + if let pair = takePair(&working) { + if segment.repetitions != nil, segment.weight == nil { + segment.weight = pair.second + } else if segment.weight != nil, segment.repetitions == nil { + segment.repetitions = Int(pair.first) + } else if segment.repetitions == nil, segment.weight == nil { + segment.repetitions = Int(pair.first) + segment.weight = pair.second + } + understoodAnything = true + } + + // Whatever units were consumed can leave a dangling separator and number, + // as "40kg x 5" or "bw+10 x 8" do. Those numbers still carry meaning. + for character in ["×", "x", "*"] { + working = working.replacingOccurrences(of: character, with: " ") + } + for value in takeRemainingNumbers(&working) { + if segment.repetitions == nil { + segment.repetitions = Int(value) + } else if segment.weight == nil { + segment.weight = value + } else { + continue + } + understoodAnything = true + } + + let leftover = working.trimmingCharacters(in: CharacterSet.alphanumerics.inverted) + .trimmingCharacters(in: .whitespaces) + guard understoodAnything, leftover.isEmpty || leftover.allSatisfy({ !$0.isNumber }) else { + return nil + } + guard !segment.isEmpty || segment.reachedFailure else { return nil } + return segment + } + + // MARK: - Token extraction + + /// Matches `pattern`, removes the match from `text`, and returns capture 1. + static func takeNumber(_ text: inout String, pattern: String) -> Double? { + guard let (range, capture) = firstMatch(in: text, pattern: pattern) else { return nil } + guard let value = Double(capture) else { return nil } + text.replaceSubrange(range, with: " ") + return value + } + + /// Every bare number left after units and separators were consumed, in order. + static func takeRemainingNumbers(_ text: inout String) -> [Double] { + var values: [Double] = [] + while let value = takeNumber(&text, pattern: #"([0-9]+(?:\.[0-9]+)?)"#) { + values.append(value) + if values.count >= 4 { break } + } + return values + } + + static func takeSide(_ text: inout String) -> BodySide? { + if let (range, _) = firstMatch(in: text, pattern: #"\b(left|lt)\b"#) { + text.replaceSubrange(range, with: " ") + return .left + } + if let (range, _) = firstMatch(in: text, pattern: #"\b(right|rt)\b"#) { + text.replaceSubrange(range, with: " ") + return .right + } + if let (range, _) = firstMatch(in: text, pattern: #"\b(each side|per side|both)\b"#) { + text.replaceSubrange(range, with: " ") + return .both + } + return nil + } + + static func takeFailure(_ text: inout String) -> Bool { + guard let (range, _) = firstMatch(in: text, pattern: #"\b(fail|failed|failure|amrap|to failure)\b"#) else { + return false + } + text.replaceSubrange(range, with: " ") + return true + } + + /// `bw`, `bodyweight`, or `bw+10`. Returns the added load, zero when bare. + static func takeBodyweight(_ text: inout String) -> Double? { + let pattern = #"\b(?:bw|bodyweight)\b(?:\s*\+\s*([0-9]+(?:\.[0-9]+)?)\s*(?:kgs?|kilos?)?)?"# + guard let regex = try? NSRegularExpression(pattern: pattern) else { return nil } + let nsRange = NSRange(text.startIndex.. 1, + let captureRange = Range(match.range(at: 1), in: text), + let value = Double(text[captureRange]) { + added = value + } + text.replaceSubrange(range, with: " ") + return added + } + + static func takePair(_ text: inout String) -> (first: Double, second: Double)? { + let pattern = #"([0-9]+(?:\.[0-9]+)?)\s*[x×*]\s*([0-9]+(?:\.[0-9]+)?)"# + guard let regex = try? NSRegularExpression(pattern: pattern) else { return nil } + let nsRange = NSRange(text.startIndex.. (Range, String)? { + guard let regex = try? NSRegularExpression(pattern: pattern) else { return nil } + let nsRange = NSRange(text.startIndex.. 1 ? 1 : 0 + guard let captureRange = Range(match.range(at: captureIndex), in: text) else { return nil } + return (range, String(text[captureRange])) + } +} diff --git a/ios/Sources/SetlineCore/Targets.swift b/ios/Sources/SetlineCore/Targets.swift new file mode 100644 index 0000000..c9466a2 --- /dev/null +++ b/ios/Sources/SetlineCore/Targets.swift @@ -0,0 +1,277 @@ +import Foundation + +/// The four trainable qualities Setline measures. A movement can serve several +/// at once, so callers hold a set rather than a single value. +public enum Pillar: String, Codable, CaseIterable, Sendable { + case strength + case stamina + case mobility + case flexibility + + public var title: String { + switch self { + case .strength: "Strength" + case .stamina: "Stamina" + case .mobility: "Mobility" + case .flexibility: "Flexibility" + } + } +} + +/// Why a set exists inside a session. Only `working` sets count toward volume, +/// personal records and progression decisions — the authored programme is +/// explicit that warm-ups are not working sets. +public enum StepType: String, Codable, CaseIterable, Sendable { + case preparation + case warmUp + case working + case cardio + case mobility + case cooldown + case check + + public var countsAsWorkingSet: Bool { self == .working } + + public var title: String { + switch self { + case .preparation: "Preparation" + case .warmUp: "Warm-up" + case .working: "Working" + case .cardio: "Cardio" + case .mobility: "Mobility" + case .cooldown: "Cooldown" + case .check: "Check" + } + } +} + +/// How a set's load is prescribed. Authored programmes routinely express load +/// relatively ("about 70%", "bodyweight + 10 kg") or leave it to the lifter, and +/// collapsing those into a single number loses the instruction. +public enum LoadTarget: Codable, Equatable, Sendable { + case absolute(kilograms: Double) + case percentOfOneRepMax(Double) + case bodyweight(plusKilograms: Double) + case assisted(kilograms: Double) + case chooseLoad + + public var displayString: String { + switch self { + case let .absolute(kilograms): + "\(kilograms.trimmedString) kg" + case let .percentOfOneRepMax(percent): + "\(percent.trimmedString)% 1RM" + case let .bodyweight(plus): + plus == 0 ? "Bodyweight" : "Bodyweight + \(plus.trimmedString) kg" + case let .assisted(kilograms): + "Assisted −\(kilograms.trimmedString) kg" + case .chooseLoad: + "Choose load" + } + } +} + +/// Prescribed movement speed, in seconds per phase. +public struct Tempo: Codable, Equatable, Sendable { + public var eccentricSeconds: Int + public var pauseBottomSeconds: Int + public var concentricSeconds: Int + public var pauseTopSeconds: Int + + public init( + eccentricSeconds: Int, + pauseBottomSeconds: Int = 0, + concentricSeconds: Int, + pauseTopSeconds: Int = 0 + ) { + self.eccentricSeconds = eccentricSeconds + self.pauseBottomSeconds = pauseBottomSeconds + self.concentricSeconds = concentricSeconds + self.pauseTopSeconds = pauseTopSeconds + } + + public var displayString: String { + "\(eccentricSeconds)-\(pauseBottomSeconds)-\(concentricSeconds)-\(pauseTopSeconds)" + } +} + +/// An inclusive range of rest seconds. The authored programme prescribes rest as +/// a band ("2.5-3 min"), so storing a scalar would silently pick one end. +public struct RestRange: Codable, Equatable, Sendable { + public var lowSeconds: Int + public var highSeconds: Int + + public init(lowSeconds: Int, highSeconds: Int) { + self.lowSeconds = max(0, min(lowSeconds, highSeconds)) + self.highSeconds = max(0, max(lowSeconds, highSeconds)) + } + + public init(_ seconds: Int) { + self.init(lowSeconds: seconds, highSeconds: seconds) + } + + public static let none = RestRange(0) + + /// The value the rest timer counts down from. + public var timerSeconds: Int { lowSeconds } + + public var isEmpty: Bool { highSeconds == 0 } + + public var displayString: String { + if isEmpty { return "No rest" } + if lowSeconds == highSeconds { return lowSeconds.restLabel } + return "\(lowSeconds.restValue)–\(highSeconds.restLabel)" + } +} + +/// The complete structured prescription for one set. +/// +/// This replaces the free-text target string the programme used to carry. Rep +/// ranges, reps in reserve, tempo, per-side work and relative load all have to +/// be machine-readable for progression, volume and personal records to mean +/// anything. +public struct SetTarget: Codable, Equatable, Sendable { + public var repsLow: Int? + public var repsHigh: Int? + public var load: LoadTarget? + public var repsInReserve: Int? + public var rpe: Double? + public var tempo: Tempo? + public var timeSeconds: Int? + public var holdSeconds: Int? + public var distanceMetres: Double? + public var paceSecondsPerKilometre: Int? + public var heartRateZone: Int? + public var perSide: Bool + /// Preserves a target string that predates structured targets so historic + /// sessions keep displaying exactly what they were performed against. + public var legacyDisplay: String? + + public init( + repsLow: Int? = nil, + repsHigh: Int? = nil, + load: LoadTarget? = nil, + repsInReserve: Int? = nil, + rpe: Double? = nil, + tempo: Tempo? = nil, + timeSeconds: Int? = nil, + holdSeconds: Int? = nil, + distanceMetres: Double? = nil, + paceSecondsPerKilometre: Int? = nil, + heartRateZone: Int? = nil, + perSide: Bool = false, + legacyDisplay: String? = nil + ) { + self.repsLow = repsLow + self.repsHigh = repsHigh + self.load = load + self.repsInReserve = repsInReserve + self.rpe = rpe + self.tempo = tempo + self.timeSeconds = timeSeconds + self.holdSeconds = holdSeconds + self.distanceMetres = distanceMetres + self.paceSecondsPerKilometre = paceSecondsPerKilometre + self.heartRateZone = heartRateZone + self.perSide = perSide + self.legacyDisplay = legacyDisplay + } + + /// Wraps an un-parseable historic target so nothing recorded is ever lost. + public init(legacy display: String) { + self.init(legacyDisplay: display) + } + + public var repetitionsDisplay: String? { + guard let repsLow else { return nil } + guard let repsHigh, repsHigh != repsLow else { return "\(repsLow) reps" } + return "\(repsLow)–\(repsHigh) reps" + } + + public var durationDisplay: String? { + guard let seconds = timeSeconds ?? holdSeconds else { return nil } + return seconds.durationLabel + } + + /// The single line the player shows as TARGET. + public var displayString: String { + if let legacyDisplay, !legacyDisplay.isEmpty { return legacyDisplay } + var parts: [String] = [] + if let load { parts.append(load.displayString) } + if let repetitionsDisplay { parts.append(repetitionsDisplay) } + if let durationDisplay { parts.append(durationDisplay) } + if let distanceMetres { parts.append(distanceMetres.distanceLabel) } + if let paceSecondsPerKilometre { parts.append("\(paceSecondsPerKilometre.paceLabel)/km") } + if let heartRateZone { parts.append("Zone \(heartRateZone)") } + if parts.isEmpty { return "Complete" } + var line = parts.joined(separator: " · ") + if perSide { line += " per side" } + return line + } + + /// Secondary qualifiers shown beneath the target, never folded into it. + public var qualifiers: [String] { + var result: [String] = [] + if let repsInReserve { result.append("\(repsInReserve) RIR") } + if let rpe { result.append("RPE \(rpe.trimmedString)") } + if let tempo { result.append("Tempo \(tempo.displayString)") } + return result + } + + public var isEmpty: Bool { + self == SetTarget() + } +} + +// MARK: - Formatting helpers + +public extension Double { + /// Formats without a trailing ".0" so "65 kg" never renders as "65.0 kg", and + /// without leaking binary floating-point precision — an estimated 1RM must + /// read "91.83 kg", never "91.83333333333333 kg". + var trimmedString: String { + guard isFinite else { return "—" } + let bounded = (self * 100).rounded() / 100 + if bounded == bounded.rounded() { return String(Int(bounded)) } + var text = String(format: "%.2f", bounded) + while text.hasSuffix("0") { text.removeLast() } + if text.hasSuffix(".") { text.removeLast() } + return text + } + + /// Rounded to a single decimal, for kilogram values where two decimals claim + /// more precision than a barbell can express. + var kilogramString: String { + ((self * 10).rounded() / 10).trimmedString + } + + var distanceLabel: String { + self >= 1_000 ? "\((self / 1_000).trimmedString) km" : "\(trimmedString) m" + } +} + +public extension Int { + /// "45 sec", "2 min", "2 min 30 sec" — never a bare second count for long work. + var durationLabel: String { + if self < 60 { return "\(self) sec" } + let minutes = self / 60 + let seconds = self % 60 + if seconds == 0 { return "\(minutes) min" } + return "\(minutes) min \(seconds) sec" + } + + /// The numeric part of a rest bound, used to build "2.5–3 min". + var restValue: String { + if self < 60 { return "\(self)" } + let minutes = Double(self) / 60 + return minutes.trimmedString + } + + var restLabel: String { + self < 60 ? "\(self) sec" : "\(restValue) min" + } + + var paceLabel: String { + String(format: "%d:%02d", self / 60, self % 60) + } +} diff --git a/ios/Sources/SetlineCore/TodayResolution.swift b/ios/Sources/SetlineCore/TodayResolution.swift new file mode 100644 index 0000000..39b20ef --- /dev/null +++ b/ios/Sources/SetlineCore/TodayResolution.swift @@ -0,0 +1,154 @@ +import Foundation + +/// What the programme prescribes for one calendar day. +public struct ResolvedSession: Equatable, Sendable { + public var template: WorkoutTemplate + public var programmeWeek: Int? + public var programmeDayIndex: Int? + /// "Week 3 · Tuesday · Lower", or the template name for ad-hoc work. + public var subtitle: String + public var notes: [String] + /// True when the programme is running but this day has no session. + public var isRestDay: Bool + /// Set when the calendar sits outside a dated block, so Today can say so + /// rather than silently showing week 1. + public var outOfBlockNotice: String? + + public init( + template: WorkoutTemplate, + programmeWeek: Int? = nil, + programmeDayIndex: Int? = nil, + subtitle: String, + notes: [String] = [], + isRestDay: Bool = false, + outOfBlockNotice: String? = nil + ) { + self.template = template + self.programmeWeek = programmeWeek + self.programmeDayIndex = programmeDayIndex + self.subtitle = subtitle + self.notes = notes + self.isRestDay = isRestDay + self.outOfBlockNotice = outOfBlockNotice + } +} + +public extension SetlineDocument { + /// Resolves the session for a date from whichever programme is active. + /// + /// Returns nil only when there is nothing at all to offer: no programme and + /// no templates. A rest day returns a session marked `isRestDay` so the + /// caller can show the plan honestly instead of inventing a workout. + func session(on date: Date = .now, calendar: Calendar = .current) -> ResolvedSession? { + switch programme { + case let .bundled(id): + return bundledSession(id: id, on: date, calendar: calendar) + case let .custom(programme): + return customSession(programme: programme, on: date, calendar: calendar) + case .none: + guard let first = templates.first else { return nil } + return ResolvedSession( + template: first, + subtitle: first.detail.isEmpty ? "Unscheduled" : first.detail, + notes: first.notes + ) + } + } + + private func bundledSession( + id: BundledProgrammeID, + on date: Date, + calendar: Calendar + ) -> ResolvedSession { + switch id { + case .twelveWeekStrengthCardioMobility: + let position = TwelveWeekProgramme.position(for: date, calendar: calendar) + var notice: String? + if position.beforeBlock { + let start = TwelveWeekProgramme.startDate(calendar: calendar) + notice = "The block starts \(start.formatted(date: .abbreviated, time: .omitted)). This is week 1, day 1 as a preview." + } else if position.afterBlock { + notice = "The block finished on 18 October 2026. This shows the final week; review it before starting another." + } + return ResolvedSession( + template: position.template, + programmeWeek: position.weekNumber, + programmeDayIndex: position.dayIndex, + subtitle: "Week \(position.weekNumber) of \(TwelveWeekProgramme.weekCount) · \(weekdayName(position.dayIndex, calendar: calendar)) · \(position.schedule.title)", + notes: position.template.notes, + outOfBlockNotice: notice + ) + } + } + + private func customSession( + programme: CustomProgramme, + on date: Date, + calendar: Calendar + ) -> ResolvedSession? { + let weekday = calendar.component(.weekday, from: date) + let assigned = programme.days.first { $0.weekday == weekday }?.templateID + guard programme.enabled else { + guard let first = templates.first else { return nil } + return ResolvedSession( + template: first, + subtitle: "\(programme.name) is paused", + notes: first.notes + ) + } + guard let assigned else { + return ResolvedSession( + template: WorkoutTemplate(name: "Rest day", detail: "No session scheduled", isBundled: false, exercises: []), + subtitle: "\(programme.name) · rest day", + isRestDay: true + ) + } + guard let template = templates.first(where: { $0.id == assigned }) else { + guard let first = templates.first else { return nil } + return ResolvedSession( + template: first, + subtitle: "\(programme.name) · assigned workout unavailable", + notes: first.notes + ) + } + return ResolvedSession( + template: template, + subtitle: "\(programme.name) · \(template.name)", + notes: template.notes + ) + } + + /// The seven days of the current programme week, for the Today strip. + func week(containing date: Date = .now, calendar: Calendar = .current) -> [ResolvedSession?] { + switch programme { + case let .bundled(id): + switch id { + case .twelveWeekStrengthCardioMobility: + let position = TwelveWeekProgramme.position(for: date, calendar: calendar) + let mondayOffset = (position.weekNumber - 1) * 7 + let start = calendar.startOfDay(for: TwelveWeekProgramme.startDate(calendar: calendar)) + return (0..<7).map { index in + guard let day = calendar.date(byAdding: .day, value: mondayOffset + index, to: start) else { + return nil + } + return bundledSession(id: id, on: day, calendar: calendar) + } + } + case .custom, .none: + guard let sunday = calendar.dateInterval(of: .weekOfYear, for: date)?.start else { + return Array(repeating: nil, count: 7) + } + return (0..<7).map { index in + guard let day = calendar.date(byAdding: .day, value: index, to: sunday) else { return nil } + return session(on: day, calendar: calendar) + } + } + } + + private func weekdayName(_ dayIndex: Int, calendar: Calendar) -> String { + // dayIndex is Monday-based; weekdaySymbols is Sunday-first. + let symbols = calendar.weekdaySymbols + guard symbols.count == 7 else { return "" } + return symbols[(dayIndex + 1) % 7] + } +} diff --git a/ios/Sources/SetlineCore/TwelveWeekProgramme.swift b/ios/Sources/SetlineCore/TwelveWeekProgramme.swift new file mode 100644 index 0000000..a314804 --- /dev/null +++ b/ios/Sources/SetlineCore/TwelveWeekProgramme.swift @@ -0,0 +1,996 @@ +import Foundation + +public enum BundledProgrammeID: String, Codable, CaseIterable, Sendable { + case twelveWeekStrengthCardioMobility + + public var title: String { + switch self { + case .twelveWeekStrengthCardioMobility: + "12-Week Strength, Cardio & Mobility Plan" + } + } +} + +/// The five session shapes the twelve-week block schedules. +public enum ProgrammeSessionKind: String, Codable, CaseIterable, Sendable { + case upper + case lower + case easyCardioMobility + case upperPlusHardCardio + case fullMobility + + /// A stable identity so history written in one week still resolves later. + public var templateID: UUID { + switch self { + case .upper: UUID(uuidString: "5E71C0DE-0000-4000-A000-000000000001")! + case .lower: UUID(uuidString: "5E71C0DE-0000-4000-A000-000000000002")! + case .easyCardioMobility: UUID(uuidString: "5E71C0DE-0000-4000-A000-000000000003")! + case .upperPlusHardCardio: UUID(uuidString: "5E71C0DE-0000-4000-A000-000000000004")! + case .fullMobility: UUID(uuidString: "5E71C0DE-0000-4000-A000-000000000005")! + } + } +} + +public struct ProgrammeScheduleEntry: Equatable, Sendable, Identifiable { + /// 0 = Monday, matching the block's Monday-based weeks. + public var dayIndex: Int + public var dayLabel: String + public var title: String + public var kind: ProgrammeSessionKind + /// Whether the day counts toward the weekly completion standard. + public var isRequired: Bool + + public var id: Int { dayIndex } +} + +public struct ProgrammeCheckpoint: Equatable, Sendable, Identifiable { + public var name: String + public var dayOffset: Int + public var id: Int { dayOffset } +} + +/// A load increase rule for one movement, as the block writes it. +public struct ProgressionRule: Equatable, Sendable { + public var exerciseSlug: String + public var repsLow: Int + public var repsHigh: Int + /// Total added load once every working set reaches the top of the range. + public var incrementKilograms: Double? + public var specialRule: String + + public init( + exerciseSlug: String, + repsLow: Int, + repsHigh: Int, + incrementKilograms: Double?, + specialRule: String + ) { + self.exerciseSlug = exerciseSlug + self.repsLow = repsLow + self.repsHigh = repsHigh + self.incrementKilograms = incrementKilograms + self.specialRule = specialRule + } +} + +public struct ProgrammePosition: Equatable, Sendable { + public var weekNumber: Int + public var dayIndex: Int + public var inBlock: Bool + public var beforeBlock: Bool + public var afterBlock: Bool + public var schedule: ProgrammeScheduleEntry + public var template: WorkoutTemplate +} + +/// Sarthak's authored twelve-week block, Monday 27 July to Sunday 18 October 2026. +/// +/// The block is week-aware rather than a fixed set of templates: the third RDL +/// set, the hard-cardio round count, the pull-up checkpoints and the optional +/// lateral raise all depend on which week you are in. Sessions are therefore +/// resolved on demand instead of stored. +public enum TwelveWeekProgramme { + public static let id = BundledProgrammeID.twelveWeekStrengthCardioMobility + public static let name = "Sarthak's 12-Week Strength, Cardio & Mobility Plan" + public static let shortName = "12-Week Strength · Cardio · Mobility" + public static let weekCount = 12 + public static let dayCount = weekCount * 7 + + public static let startDateComponents = DateComponents(year: 2026, month: 7, day: 27) + + public static let schedule: [ProgrammeScheduleEntry] = [ + ProgrammeScheduleEntry(dayIndex: 0, dayLabel: "MON", title: "Upper", kind: .upper, isRequired: true), + ProgrammeScheduleEntry(dayIndex: 1, dayLabel: "TUE", title: "Lower", kind: .lower, isRequired: true), + ProgrammeScheduleEntry( + dayIndex: 2, + dayLabel: "WED", + title: "Easy + mobility", + kind: .easyCardioMobility, + isRequired: true + ), + ProgrammeScheduleEntry( + dayIndex: 3, + dayLabel: "THU", + title: "Upper + hard", + kind: .upperPlusHardCardio, + isRequired: true + ), + ProgrammeScheduleEntry(dayIndex: 4, dayLabel: "FRI", title: "Mobility", kind: .fullMobility, isRequired: true), + ProgrammeScheduleEntry(dayIndex: 5, dayLabel: "SAT", title: "Lower", kind: .lower, isRequired: true), + ProgrammeScheduleEntry( + dayIndex: 6, + dayLabel: "SUN", + title: "Easy + mobility", + kind: .easyCardioMobility, + isRequired: true + ), + ] + + /// Baseline, week 5, week 9 and end-of-block reassessments. + public static let checkpoints: [ProgrammeCheckpoint] = [ + ProgrammeCheckpoint(name: "Baseline", dayOffset: 0), + ProgrammeCheckpoint(name: "Week 5", dayOffset: 28), + ProgrammeCheckpoint(name: "Week 9", dayOffset: 56), + ProgrammeCheckpoint(name: "End of block", dayOffset: 83), + ] + + /// The nine measures the block asks you to record at each checkpoint. + public static let checkpointMeasures: [String] = [ + "Body weight", + "Waist", + "Bench: best clean working set", + "Strict pull-ups", + "Hack squat / leg press working load", + "RDL working load and reps", + "45-min easy-cardio pace", + "Knee-to-wall distance", + "Squat support / heel elevation", + ] + + public static let progressionRules: [ProgressionRule] = [ + ProgressionRule( + exerciseSlug: "bench-press", + repsLow: 5, + repsHigh: 8, + incrementKilograms: 2.5, + specialRule: "Only after 3 × 8 is clean." + ), + ProgressionRule( + exerciseSlug: "machine-or-db-shoulder-press", + repsLow: 6, + repsHigh: 10, + incrementKilograms: nil, + specialRule: "Smallest available increment. Protect technique and shoulder comfort." + ), + ProgressionRule( + exerciseSlug: "lat-pulldown", + repsLow: 6, + repsHigh: 10, + incrementKilograms: nil, + specialRule: "One machine increment. Do not shorten range." + ), + ProgressionRule( + exerciseSlug: "chest-supported-or-cable-row", + repsLow: 8, + repsHigh: 12, + incrementKilograms: nil, + specialRule: "One machine increment. Do not shorten range." + ), + ProgressionRule( + exerciseSlug: "hack-squat-or-leg-press", + repsLow: 6, + repsHigh: 10, + incrementKilograms: nil, + specialRule: "Smallest reasonable increment. Keep the same machine and depth." + ), + ProgressionRule( + exerciseSlug: "romanian-deadlift", + repsLow: 6, + repsHigh: 10, + incrementKilograms: 2.5, + specialRule: "2.5–5 kg total. Never sacrifice hinge position." + ), + ProgressionRule( + exerciseSlug: "supported-bulgarian-split-squat", + repsLow: 8, + repsHigh: 12, + incrementKilograms: 2, + specialRule: "1–2 kg per dumbbell, only after both legs reach the top range." + ), + ProgressionRule( + exerciseSlug: "lying-leg-curl", + repsLow: 10, + repsHigh: 15, + incrementKilograms: nil, + specialRule: "One machine increment. Controlled eccentric." + ), + ProgressionRule( + exerciseSlug: "standing-calf-raise", + repsLow: 10, + repsHigh: 20, + incrementKilograms: nil, + specialRule: "Reach 20 controlled reps on all sets, then add load." + ), + ProgressionRule( + exerciseSlug: "ab-wheel", + repsLow: 6, + repsHigh: 12, + incrementKilograms: nil, + specialRule: "Reps, then range, then a slower eccentric." + ), + ProgressionRule( + exerciseSlug: "farmer-carry", + repsLow: 0, + repsHigh: 0, + incrementKilograms: nil, + specialRule: "Reach 2 × 45 sec, then add weight and return to 30 sec." + ), + ] + + public static func rule(forSlug slug: String) -> ProgressionRule? { + progressionRules.first { $0.exerciseSlug == slug } + } + + // MARK: - Calendar + + public static func startDate(calendar: Calendar = .current) -> Date { + calendar.date(from: startDateComponents) ?? Date(timeIntervalSince1970: 1_784_505_600) + } + + /// Day offset from the block start, clamped into the block for resolution but + /// reported honestly through `beforeBlock` / `afterBlock`. + public static func position(for date: Date, calendar: Calendar = .current) -> ProgrammePosition { + let start = calendar.startOfDay(for: startDate(calendar: calendar)) + let today = calendar.startOfDay(for: date) + let offset = calendar.dateComponents([.day], from: start, to: today).day ?? 0 + let beforeBlock = offset < 0 + let afterBlock = offset >= dayCount + let bounded = min(dayCount - 1, max(0, offset)) + let weekNumber = bounded / 7 + 1 + let dayIndex = bounded % 7 + let entry = schedule[dayIndex] + return ProgrammePosition( + weekNumber: weekNumber, + dayIndex: dayIndex, + inBlock: !beforeBlock && !afterBlock, + beforeBlock: beforeBlock, + afterBlock: afterBlock, + schedule: entry, + template: template(for: entry.kind, week: weekNumber, dayIndex: dayIndex) + ) + } + + public static func checkpointDate(_ checkpoint: ProgrammeCheckpoint, calendar: Calendar = .current) -> Date { + calendar.date( + byAdding: .day, + value: checkpoint.dayOffset, + to: calendar.startOfDay(for: startDate(calendar: calendar)) + ) ?? startDate(calendar: calendar) + } + + // MARK: - Session resolution + + public static func template( + for kind: ProgrammeSessionKind, + week: Int, + dayIndex: Int = 0 + ) -> WorkoutTemplate { + let boundedWeek = min(weekCount, max(1, week)) + switch kind { + case .upper, .upperPlusHardCardio: + return upperTemplate(week: boundedWeek, dayIndex: dayIndex, includeHardCardio: kind == .upperPlusHardCardio) + case .lower: + return lowerTemplate(week: boundedWeek) + case .easyCardioMobility: + return WorkoutTemplate( + id: kind.templateID, + name: "Easy cardio + full mobility", + detail: "45 min conversational · full mobility routine", + isBundled: true, + exercises: easyCardioExercises + fullMobilityExercises, + notes: [ + "Start around the existing 5 km/h baseline when walking.", + "Increase speed or incline only after two comfortable weeks.", + ], + expectedMinutes: 60 + ) + case .fullMobility: + return WorkoutTemplate( + id: kind.templateID, + name: "Full mobility", + detail: "12–15 min routine · Friday recovery", + isBundled: true, + exercises: fullMobilityExercises, + notes: [ + "An optional 20–40 minute walk is allowed only when recovery is good.", + "Sharp pain, radiating symptoms, or worsening back pain are stop signals.", + ], + expectedMinutes: 15 + ) + } + } + + /// Whether a strict pull-up is tested on this session. The block tests at the + /// start of weeks 5 and 9, and at the end of week 12 — never more often. + static func testsPullUp(week: Int, dayIndex: Int) -> Bool { + (dayIndex == 0 && (week == 5 || week == 9)) || (dayIndex == 3 && week == 12) + } + + /// Reps in reserve on compounds: 2–3 while learning, then 1–2. + static func repsInReserve(week: Int) -> Int { week <= 2 ? 2 : 1 } + + // MARK: - Upper + + static func upperTemplate(week: Int, dayIndex: Int, includeHardCardio: Bool) -> WorkoutTemplate { + let kind: ProgrammeSessionKind = includeHardCardio ? .upperPlusHardCardio : .upper + var exercises = upperPreparationExercises + exercises.append(benchExercise(week: week)) + if testsPullUp(week: week, dayIndex: dayIndex) { + exercises.append(pullUpCheckpointExercise) + } + exercises.append(latPulldownExercise(week: week)) + exercises.append(shoulderPressExercise(week: week)) + exercises.append(rowExercise(week: week)) + // Optional accessory the block permits only after four consistent weeks. + if week >= 5 { exercises.append(lateralRaiseExercise) } + exercises.append(abWheelExercise) + exercises.append(farmerCarryExercise) + exercises.append(contentsOf: upperCooldownExercises) + if includeHardCardio { + exercises.append(contentsOf: hardCardioExercises(week: week)) + } + var notes = [ + "Bench begins at 65 kg for 3 × 5–8. Add 2.5 kg only after 3 × 8 is clean.", + week <= 2 + ? "Weeks 1–2: finish with 2–3 reps in reserve." + : "Keep 1–2 reps in reserve on compounds.", + ] + if includeHardCardio { + notes.append("Complete the full Upper session first. Hard cardio comes afterward.") + } + if week >= 5 { + notes.append("Optional lateral raises are compliant to skip; they do not fix a missing pattern.") + } + return WorkoutTemplate( + id: kind.templateID, + name: includeHardCardio ? "Upper + hard cardio" : "Upper", + detail: includeHardCardio + ? "Bench · pull · press · row · then intervals" + : "Bench · vertical pull · press · row · trunk · carry", + isBundled: true, + exercises: exercises, + notes: notes, + expectedMinutes: includeHardCardio ? 105 : 65 + ) + } + + static let upperPreparationExercises: [Exercise] = [ + exercise("easy-treadmill-bike-or-rower", sets: [ + set( + "General preparation · 1 of 4", + .cardio, + .preparation, + SetTarget(timeSeconds: 180), + cue: "Use an easy pace for 2–3 minutes." + ), + ]), + exercise("arm-circles", sets: [ + set( + "General preparation · 2 of 4", + .mobility, + .preparation, + SetTarget(repsLow: 20), + cue: "Complete 10 forward and 10 backward." + ), + ]), + exercise("wall-slides", sets: [ + set("General preparation · 3 of 4", .mobility, .preparation, SetTarget(repsLow: 8)), + ]), + exercise("scapular-pulldown", sets: [ + set( + "General preparation · 4 of 4", + .strength, + .preparation, + SetTarget(repsLow: 10, load: .chooseLoad) + ), + ]), + ] + + static func benchExercise(week: Int) -> Exercise { + // The authored ramp: 20 kg × 10, 40 × 5, 55 × 2–3, then 65 kg working sets. + var sets = [ + set( + "20 kg bar · ramp 1 of 3", + .strength, + .warmUp, + SetTarget(repsLow: 10, load: .absolute(kilograms: 20)), + rest: RestRange(60), + cue: "Set the shoulder blades and repeat the same touch point." + ), + set( + "40 kg · ramp 2 of 3", + .strength, + .warmUp, + SetTarget(repsLow: 5, load: .absolute(kilograms: 40)), + rest: RestRange(60), + cue: "Keep the setup identical to the working sets." + ), + set( + "55 kg · ramp 3 of 3", + .strength, + .warmUp, + SetTarget(repsLow: 2, repsHigh: 3, load: .absolute(kilograms: 55)), + rest: RestRange(90), + cue: "Warm up without accumulating fatigue." + ), + ] + sets += (1...3).map { number in + set( + "Working set \(number) of 3", + .strength, + .working, + SetTarget( + repsLow: 5, + repsHigh: 8, + load: .absolute(kilograms: 65), + repsInReserve: repsInReserve(week: week) + ), + rest: RestRange(lowSeconds: 150, highSeconds: 180), + cue: "Do not train bench to failure." + ) + } + return exercise("bench-press", sets: sets) + } + + static let pullUpCheckpointExercise = exercise( + "pull-up", + sets: [ + set( + "One test before pulldowns", + .repetitions, + .check, + SetTarget(repsLow: 1, load: .bodyweight(plusKilograms: 0)), + optional: true, + cue: "Attempt one clean strict pull-up only. Do not repeat-test." + ), + ] + ) + + static func latPulldownExercise(week: Int) -> Exercise { + exercise("lat-pulldown", sets: [ + warmUpSet( + "1 light set", + SetTarget(repsLow: 8, load: .chooseLoad), + cue: "Use a comfortable neutral or shoulder-width grip." + ), + ] + workingSets( + count: 3, + repsLow: 6, + repsHigh: 10, + week: week, + rest: RestRange(lowSeconds: 90, highSeconds: 150) + )) + } + + static func shoulderPressExercise(week: Int) -> Exercise { + exercise("machine-or-db-shoulder-press", sets: [ + warmUpSet("1 light set", SetTarget(repsLow: 6, repsHigh: 8, load: .chooseLoad)), + ] + workingSets( + count: 2, + repsLow: 6, + repsHigh: 10, + week: week, + rest: RestRange(lowSeconds: 90, highSeconds: 150) + )) + } + + static func rowExercise(week: Int) -> Exercise { + exercise("chest-supported-or-cable-row", sets: [ + warmUpSet( + "Optional light set", + SetTarget(repsLow: 8, load: .chooseLoad), + optional: true, + cue: "Use this familiarisation set only if needed." + ), + ] + workingSets( + count: 3, + repsLow: 8, + repsHigh: 12, + week: week, + rest: RestRange(lowSeconds: 90, highSeconds: 150) + )) + } + + static let lateralRaiseExercise = exercise( + "lateral-raise", + sets: (1...2).map { number in + set( + "Optional set \(number) of 2", + .strength, + .working, + SetTarget(repsLow: 12, repsHigh: 20, load: .chooseLoad), + rest: RestRange(60), + optional: true, + cue: "Add only if shoulders feel good and recovery is comfortable." + ) + } + ) + + static let abWheelExercise = exercise( + "ab-wheel", + sets: (1...2).map { number in + set( + "Working set \(number) of 2", + .repetitions, + .working, + SetTarget(repsLow: 6, repsHigh: 12), + rest: RestRange(lowSeconds: 60, highSeconds: 90) + ) + } + ) + + static let farmerCarryExercise = exercise( + "farmer-carry", + sets: [ + set( + "Optional light carry", + .timed, + .warmUp, + SetTarget(load: .chooseLoad, holdSeconds: 15), + rest: RestRange(60), + optional: true + ), + ] + (1...2).map { number in + set( + "Carry \(number) of 2", + .timed, + .working, + SetTarget(load: .chooseLoad, holdSeconds: 30), + rest: RestRange(lowSeconds: 90, highSeconds: 120), + cue: "Build toward 45 seconds, then add weight and return to 30." + ) + } + ) + + static let upperCooldownExercises: [Exercise] = [ + exercise("doorway-pec-stretch", sets: [ + set( + "1 hold per side", + .timed, + .cooldown, + SetTarget(holdSeconds: 45, perSide: true), + cue: "Use 30–45 seconds per side." + ), + ]), + exercise("bench-lat-stretch", sets: [ + set("1 hold", .timed, .cooldown, SetTarget(holdSeconds: 45)), + ]), + exercise("open-book-rotation", sets: [ + set( + "Optional · each side", + .mobility, + .cooldown, + SetTarget(repsLow: 5, perSide: true), + optional: true + ), + ]), + ] + + // MARK: - Lower + + static func lowerTemplate(week: Int) -> WorkoutTemplate { + let rdlSets = week <= 2 ? 2 : 3 + let exercises = lowerPreparationExercises + [ + hackSquatExercise(week: week), + romanianDeadliftExercise(week: week, workingSets: rdlSets), + bulgarianExercise(week: week), + legCurlExercise(week: week), + calfRaiseExercise(week: week), + ] + lowerCooldownExercises + return WorkoutTemplate( + id: ProgrammeSessionKind.lower.templateID, + name: "Lower", + detail: "Squat · hinge · split squat · curl · calf", + isBundled: true, + exercises: exercises, + notes: [ + "Choose hack squat or leg press once and keep it for all 12 weeks.", + week <= 2 + ? "Weeks 1–2 use exactly two RDL working sets." + : "The third RDL set is conditional on stable technique and reasonable lower-back fatigue.", + "Do not add leg extensions or back extensions during the core block.", + ], + expectedMinutes: 70 + ) + } + + static let lowerPreparationExercises: [Exercise] = [ + exercise("easy-treadmill-bike-or-rower", sets: [ + set( + "General preparation · 1 of 5", + .cardio, + .preparation, + SetTarget(timeSeconds: 180), + cue: "Use an easy pace for 3 minutes." + ), + ]), + exercise("knee-to-wall-ankle-rocks", sets: [ + set( + "General preparation · 2 of 5", + .mobility, + .preparation, + SetTarget(repsLow: 10, perSide: true) + ), + ]), + exercise("supported-squat-repetitions", sets: [ + set("General preparation · 3 of 5", .mobility, .preparation, SetTarget(repsLow: 5)), + ]), + exercise("goblet-squat", sets: [ + set( + "General preparation · 4 of 5", + .strength, + .preparation, + SetTarget(repsLow: 6, repsHigh: 8, load: .chooseLoad), + cue: "Elevate the heels when needed." + ), + ]), + exercise("unloaded-hip-hinge", sets: [ + set("General preparation · 5 of 5", .mobility, .preparation, SetTarget(repsLow: 8)), + ]), + ] + + static func hackSquatExercise(week: Int) -> Exercise { + exercise("hack-squat-or-leg-press", sets: [ + warmUpSet("Light × 10 · ramp 1 of 3", SetTarget(repsLow: 10, load: .chooseLoad)), + warmUpSet( + "About 50% × 5 · ramp 2 of 3", + SetTarget(repsLow: 5, load: .percentOfOneRepMax(50)) + ), + warmUpSet( + "About 70% × 3 · ramp 3 of 3", + SetTarget(repsLow: 3, load: .percentOfOneRepMax(70)), + rest: RestRange(90), + cue: "Repeat the working-set stance and depth." + ), + ] + workingSets( + count: 3, + repsLow: 6, + repsHigh: 10, + week: week, + rest: RestRange(lowSeconds: 150, highSeconds: 180), + cue: "Do not train to failure; keep depth repeatable." + )) + } + + static func romanianDeadliftExercise(week: Int, workingSets: Int) -> Exercise { + var sets = [ + set( + "Bar × 8 · ramp 1 of 2", + .strength, + .warmUp, + SetTarget(repsLow: 8, load: .absolute(kilograms: 20)), + rest: RestRange(60) + ), + set( + "50–60% × 5 · ramp 2 of 2", + .strength, + .warmUp, + SetTarget(repsLow: 5, load: .percentOfOneRepMax(55)), + rest: RestRange(90), + cue: "Stop when further descent would require spinal movement." + ), + ] + sets += (1...workingSets).map { number in + let isConditional = number == 3 + return set( + isConditional ? "Conditional working set 3 of 3" : "Working set \(number) of \(workingSets)", + .strength, + .working, + SetTarget( + repsLow: 6, + repsHigh: 10, + load: .chooseLoad, + repsInReserve: repsInReserve(week: week) + ), + rest: RestRange(lowSeconds: 150, highSeconds: 180), + optional: isConditional, + cue: isConditional + ? "Complete only when technique is stable and lower-back fatigue is reasonable." + : "Keep the hinge in hamstrings and glutes; never train this to failure." + ) + } + return exercise("romanian-deadlift", sets: sets) + } + + static func bulgarianExercise(week: Int) -> Exercise { + exercise("supported-bulgarian-split-squat", sets: [ + warmUpSet( + "Bodyweight or light × 5 per leg", + SetTarget(repsLow: 5, load: .chooseLoad, perSide: true) + ), + ] + workingSets( + count: 2, + repsLow: 8, + repsHigh: 12, + week: week, + rest: RestRange(lowSeconds: 90, highSeconds: 150), + perSide: true, + cue: "Let the legs, not balance, limit the set." + )) + } + + static func legCurlExercise(week: Int) -> Exercise { + exercise("lying-leg-curl", sets: [ + warmUpSet("1 light set", SetTarget(repsLow: 8, repsHigh: 10, load: .chooseLoad)), + ] + workingSets( + count: 2, + repsLow: 10, + repsHigh: 15, + week: week, + rest: RestRange(lowSeconds: 60, highSeconds: 90) + )) + } + + static func calfRaiseExercise(week: Int) -> Exercise { + exercise("standing-calf-raise", sets: [ + set( + "Bodyweight × 10", + .repetitions, + .warmUp, + SetTarget(repsLow: 10, load: .bodyweight(plusKilograms: 0)), + rest: RestRange(60), + cue: "Use a Smith machine, single-leg dumbbell raise, or straight-knee leg-press calf press." + ), + ] + workingSets( + count: 3, + repsLow: 10, + repsHigh: 20, + week: week, + rest: RestRange(lowSeconds: 60, highSeconds: 90) + )) + } + + static let lowerCooldownExercises: [Exercise] = [ + exercise("straight-knee-calf-stretch", sets: [ + set( + "1 hold per side", + .timed, + .cooldown, + SetTarget(holdSeconds: 45, perSide: true), + cue: "Use 30–45 seconds per side." + ), + ]), + exercise("bent-knee-calf-stretch", sets: [ + set( + "1 hold per side", + .timed, + .cooldown, + SetTarget(holdSeconds: 45, perSide: true), + cue: "Use 30–45 seconds per side." + ), + ]), + exercise("half-kneeling-hip-flexor-stretch", sets: [ + set( + "1 hold per side", + .timed, + .cooldown, + SetTarget(holdSeconds: 45, perSide: true), + cue: "Avoid arching the lower back." + ), + ]), + ] + + // MARK: - Cardio + + /// 7–8 min easy, then 4 rounds in weeks 1–2 and 5 thereafter, then 5 min easy. + static func hardCardioExercises(week: Int) -> [Exercise] { + let rounds = week <= 2 ? 4 : 5 + var exercises = [ + exercise("bike-or-elliptical", sets: [ + set( + "Easy warm-up", + .cardio, + .cardio, + SetTarget(timeSeconds: 480), + cue: "Use 7–8 easy minutes after the full Upper session." + ), + ]), + ] + exercises.append(exercise("controlled-hard-interval", sets: (1...rounds).map { round in + set( + "Hard round \(round) of \(rounds)", + .cardio, + .cardio, + SetTarget(timeSeconds: 120), + rest: RestRange(180), + cue: "Use 8/10 effort: demanding and controlled, never all-out." + ) + })) + exercises.append(exercise("bike-or-elliptical", sets: [ + set( + "Easy cooldown", + .cardio, + .cooldown, + SetTarget(timeSeconds: 300), + cue: "Finish with 5 easy minutes." + ), + ])) + return exercises + } + + static let easyCardioExercises: [Exercise] = [ + exercise("easy-cardio", sets: [ + set( + "Very easy start · 1 of 3", + .cardio, + .cardio, + SetTarget(timeSeconds: 300), + cue: "Use treadmill walking, incline walking, bike, or elliptical." + ), + set( + "Aerobic work · 2 of 3", + .cardio, + .cardio, + SetTarget(timeSeconds: 2_100), + cue: "Stay around 3–4/10; full sentences should remain possible." + ), + set( + "Easy finish · 3 of 3", + .cardio, + .cooldown, + SetTarget(timeSeconds: 300), + cue: "Finish fresh; do not turn the session into a race." + ), + ]), + ] + + // MARK: - Mobility + + /// The eight-movement, 12–15 minute routine, in authored order. + static let fullMobilityExercises: [Exercise] = [ + exercise("knee-to-wall-ankle-rocks", sets: (1...2).map { number in + set( + "Set \(number) of 2 · each side", + .mobility, + .mobility, + SetTarget(repsLow: 10, perSide: true), + rest: RestRange(30) + ) + }), + exercise("supported-squat-hold", sets: (1...2).map { number in + set( + "Hold \(number) of 2", + .timed, + .mobility, + SetTarget(holdSeconds: 45), + rest: RestRange(30), + cue: "Hold a rack or post. Elevate the heels when needed; do not force depth." + ) + }), + exercise("goblet-squat", sets: (1...2).map { number in + set( + "Set \(number) of 2 · slow descent", + .strength, + .mobility, + SetTarget(repsLow: 6, load: .chooseLoad), + rest: RestRange(30), + cue: "Use a slow descent and control the available range." + ) + }), + exercise("ninety-ninety-hip-switches", sets: (1...2).map { number in + set( + "Set \(number) of 2 · each side", + .mobility, + .mobility, + SetTarget(repsLow: 6, perSide: true), + rest: RestRange(30) + ) + }), + exercise("half-kneeling-hip-flexor-stretch", sets: [ + set( + "1 hold per side", + .timed, + .mobility, + SetTarget(holdSeconds: 45, perSide: true), + rest: RestRange(15) + ), + ]), + exercise("wall-slides", sets: (1...2).map { number in + set("Set \(number) of 2", .mobility, .mobility, SetTarget(repsLow: 8), rest: RestRange(30)) + }), + exercise("bench-lat-stretch", sets: [ + set("1 hold", .timed, .mobility, SetTarget(holdSeconds: 45), rest: RestRange(15)), + ]), + exercise("doorway-pec-stretch", sets: [ + set( + "1 hold per side", + .timed, + .mobility, + SetTarget(holdSeconds: 45, perSide: true), + rest: RestRange(15), + cue: "Use 30–45 seconds per side; stop for sharp or radiating pain." + ), + ]), + ] + + // MARK: - Builders + + /// Builds an exercise from the catalogue so every authored movement is a + /// known definition and inherits its pillars, cue and default rest. + static func exercise(_ slug: String, cue: String? = nil, sets: [PlannedSet]) -> Exercise { + guard let definition = ExerciseCatalogue.definition(slug: slug) else { + // A missing slug is an authoring error, surfaced rather than hidden. + return Exercise(name: slug, cue: cue ?? "", sets: sets, definitionSlug: slug) + } + return Exercise( + name: definition.name, + cue: cue ?? definition.cue, + sets: sets, + definitionSlug: slug, + pillars: definition.pillars + ) + } + + /// A single light preparation set before the working sets, as most of the + /// block's accessories prescribe. + static func warmUpSet( + _ label: String, + _ target: SetTarget, + rest: RestRange = RestRange(60), + optional: Bool = false, + cue: String? = nil + ) -> PlannedSet { + set(label, .strength, .warmUp, target, rest: rest, optional: optional, cue: cue) + } + + /// The block's working sets for one movement: the same range, rest and + /// reps-in-reserve repeated, labelled "Working set n of N". + static func workingSets( + count: Int, + repsLow: Int, + repsHigh: Int, + week: Int, + rest: RestRange, + perSide: Bool = false, + cue: String? = nil + ) -> [PlannedSet] { + (1...count).map { number in + set( + perSide + ? "Working set \(number) of \(count) · per leg" + : "Working set \(number) of \(count)", + .strength, + .working, + SetTarget( + repsLow: repsLow, + repsHigh: repsHigh, + load: .chooseLoad, + repsInReserve: repsInReserve(week: week), + perSide: perSide + ), + rest: rest, + cue: cue + ) + } + } + + static func set( + _ label: String, + _ kind: ActivityKind, + _ stepType: StepType, + _ target: SetTarget, + rest: RestRange = .none, + optional: Bool = false, + cue: String? = nil + ) -> PlannedSet { + PlannedSet( + label: label, + kind: kind, + stepType: stepType, + target: target, + rest: rest, + isOptional: optional, + cue: cue + ) + } +} diff --git a/ios/Tests/SetlineCoreTests/SetlineCoreTests.swift b/ios/Tests/SetlineCoreTests/SetlineCoreTests.swift index 4acebe5..2aede84 100644 --- a/ios/Tests/SetlineCoreTests/SetlineCoreTests.swift +++ b/ios/Tests/SetlineCoreTests/SetlineCoreTests.swift @@ -2,7 +2,11 @@ import XCTest @testable import SetlineCore final class SetlineCoreTests: XCTestCase { - func testCloudDocumentExcludesDeviceSyncMetadata() { + // MARK: - Session mechanics + + /// Sync bookkeeping must not read as a training change, or a successful save + /// would look like new work and trigger the next save indefinitely. + func testSyncMetadataIsNotATrainingChange() { var first = SetlineDocument.sample first.syncState = .pending first.lastSyncedAt = Date(timeIntervalSince1970: 100) @@ -10,16 +14,17 @@ final class SetlineCoreTests: XCTestCase { second.syncState = .failed second.lastSyncedAt = Date(timeIntervalSince1970: 200) - XCTAssertEqual(SetlineCloudDocument(document: first), SetlineCloudDocument(document: second)) + XCTAssertTrue(first.hasSameContent(as: second)) + XCTAssertNotEqual(first, second) } - func testCloudDocumentRestoresAsSyncedLocalDocument() { - let cloud = SetlineCloudDocument(document: .sample) - let restored = cloud.localDocument(lastSyncedAt: Date(timeIntervalSince1970: 300)) + func testRecordedWorkIsATrainingChange() throws { + let first = SetlineDocument.sample + var second = first + let templateID = try XCTUnwrap(second.templates.first?.id) + try second.startWorkout(templateID: templateID) - XCTAssertEqual(restored.syncState, .synced) - XCTAssertEqual(restored.lastSyncedAt, Date(timeIntervalSince1970: 300)) - XCTAssertEqual(SetlineCloudDocument(document: restored), cloud) + XCTAssertFalse(first.hasSameContent(as: second)) } func testSessionSnapshotKeepsAuthoredOrderWhenTemplateChanges() throws { @@ -35,19 +40,37 @@ final class SetlineCoreTests: XCTestCase { XCTAssertEqual(document.activeSession?.steps.map(\.exerciseName), authoredNames) } - func testDropSegmentsRemainOrderedInsideOnePlannedSet() throws { + /// The headline requirement: `5 reps × 40 kg` then `2 reps × 30 kg` is one set. + func testMultipleSegmentsRecordAsOneSet() throws { var document = SetlineDocument.sample let templateID = try XCTUnwrap(document.templates.first?.id) try document.startWorkout(templateID: templateID) let segments = [ - SetSegment(weight: 60, repetitions: 5), - SetSegment(weight: 50, repetitions: 3), + SetSegment(weight: 40, repetitions: 5), + SetSegment(weight: 30, repetitions: 2), ] try document.completeCurrent(with: segments, at: Date(timeIntervalSince1970: 500)) - XCTAssertEqual(document.activeSession?.steps.first?.segments, segments) - XCTAssertEqual(document.activeSession?.steps.first?.status, .complete) + let step = try XCTUnwrap(document.activeSession?.steps.first) + XCTAssertEqual(step.segments, segments) + XCTAssertEqual(step.status, .complete) + XCTAssertEqual(step.segments.count, 2, "Both segments belong to the same recorded set") + } + + func testWorkSecondsAreRecordedSeparatelyFromRest() throws { + var document = SetlineDocument.sample + let templateID = try XCTUnwrap(document.templates.first?.id) + try document.startWorkout(templateID: templateID) + + try document.completeCurrent( + with: [SetSegment(weight: 40, repetitions: 8)], + workSeconds: 37, + at: Date(timeIntervalSince1970: 0) + ) + + XCTAssertEqual(document.activeSession?.steps.first?.workSeconds, 37) + XCTAssertEqual(document.activeSession?.rest?.authoredSeconds, 60) } func testDeferringChangesQueueButRetainsAuthoredPosition() throws { @@ -66,13 +89,13 @@ final class SetlineCoreTests: XCTestCase { func testExtraSetDoesNotModifyTemplate() throws { var document = SetlineDocument.sample let template = try XCTUnwrap(document.templates.first) - let originalSetCount = template.exercises.flatMap(\.sets).count + let originalSetCount = template.plannedSetCount try document.startWorkout(templateID: template.id) try document.addExtraSet() XCTAssertEqual(document.activeSession?.steps.count, originalSetCount + 1) - XCTAssertEqual(document.templates.first?.exercises.flatMap(\.sets).count, originalSetCount) + XCTAssertEqual(document.templates.first?.plannedSetCount, originalSetCount) XCTAssertTrue(document.activeSession?.steps[1].isExtra == true) } @@ -81,10 +104,7 @@ final class SetlineCoreTests: XCTestCase { let templateID = try XCTUnwrap(document.templates.first?.id) let start = Date(timeIntervalSince1970: 1_000) try document.startWorkout(templateID: templateID, at: start) - try document.completeCurrent( - with: [SetSegment(weight: 40, repetitions: 8)], - at: start - ) + try document.completeCurrent(with: [SetSegment(weight: 40, repetitions: 8)], at: start) let rest = try XCTUnwrap(document.activeSession?.rest) XCTAssertEqual(rest.remaining(at: start.addingTimeInterval(17)), rest.adjustedSeconds - 17) @@ -108,6 +128,17 @@ final class SetlineCoreTests: XCTestCase { XCTAssertNotNil(restored.activeSession?.rest) } + func testFreshInstallOpensOnTheAuthoredBlock() async throws { + let url = FileManager.default.temporaryDirectory + .appending(path: UUID().uuidString) + .appending(path: "setline.json") + let store = SetlineStore(fileURL: url) + + let document = try await store.load() + + XCTAssertEqual(document.programme, .bundled(.twelveWeekStrengthCardioMobility)) + } + func testDuplicateTemplateIsIndependent() throws { var document = SetlineDocument.sample let original = try XCTUnwrap(document.templates.first) @@ -119,28 +150,794 @@ final class SetlineCoreTests: XCTestCase { XCTAssertFalse(copy.isBundled) } - func testProgressionRequiresComparableEvidence() { - let step = WorkoutStep( + // MARK: - Version 1 migration + + /// Version 1 wrote free-text targets, scalar rest and a bare custom programme. + /// None of that may be lost when the document is read by the current schema. + func testVersionOneDocumentMigratesWithoutLosingRecordedWork() throws { + let legacy = """ + { + "schemaVersion": 1, + "syncState": "deviceOnly", + "templates": [ + { + "id": "11111111-1111-4111-8111-111111111111", + "name": "Legacy upper", + "detail": "Sample", + "isBundled": true, + "exercises": [ + { + "id": "22222222-2222-4222-8222-222222222222", + "name": "Bench press", + "cue": "Old cue", + "sets": [ + { + "id": "33333333-3333-4333-8333-333333333333", + "label": "Working 1", + "kind": "strength", + "target": "70 kg × 5", + "restSeconds": 180 + } + ] + } + ] + } + ], + "programme": { + "id": "44444444-4444-4444-8444-444444444444", + "name": "Old block", + "weekCount": 8, + "enabled": true, + "days": [] + }, + "history": [ + { + "id": "55555555-5555-4555-8555-555555555555", + "templateID": "11111111-1111-4111-8111-111111111111", + "templateName": "Legacy upper", + "startedAt": "2026-07-01T10:00:00Z", + "completedAt": "2026-07-01T11:00:00Z", + "activeIndex": 1, + "steps": [ + { + "id": "66666666-6666-4666-8666-666666666666", + "exerciseName": "Bench press", + "cue": "Old cue", + "label": "Working 1", + "kind": "strength", + "target": "70 kg × 5", + "authoredPosition": 0, + "restSeconds": 180, + "status": "complete", + "isExtra": false, + "segments": [{ "id": "77777777-7777-4777-8777-777777777777", "weight": 70, "repetitions": 5 }] + } + ] + } + ] + } + """ + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .iso8601 + let decoded = try decoder.decode(SetlineDocument.self, from: Data(legacy.utf8)) + let migrated = try SetlineStore.migrate(decoded) + + XCTAssertEqual(migrated.schemaVersion, SetlineDocument.currentSchemaVersion) + // The free-text target survives verbatim rather than being reinterpreted. + let plannedTarget = try XCTUnwrap(migrated.templates.first?.exercises.first?.sets.first?.target) + XCTAssertEqual(plannedTarget.displayString, "70 kg × 5") + XCTAssertEqual(migrated.templates.first?.exercises.first?.sets.first?.rest, RestRange(180)) + XCTAssertEqual(migrated.programme.customProgramme?.name, "Old block") + // The recorded set is intact and now linked to the catalogue. + let step = try XCTUnwrap(migrated.history.first?.steps.first) + XCTAssertEqual(step.segments.first?.weight, 70) + XCTAssertEqual(step.segments.first?.repetitions, 5) + XCTAssertEqual(step.exerciseSlug, "bench-press") + XCTAssertTrue(step.pillars.contains(.strength)) + } + + func testUnknownFutureSchemaIsRejected() { + var document = SetlineDocument.sample + document.schemaVersion = 99 + + XCTAssertThrowsError(try SetlineStore.migrate(document)) { error in + XCTAssertEqual(error as? SetlineError, .unsupportedSchema(99)) + } + } +} + +// MARK: - The authored twelve-week block + +final class TwelveWeekProgrammeTests: XCTestCase { + private var calendar: Calendar = { + var calendar = Calendar(identifier: .gregorian) + calendar.timeZone = TimeZone(identifier: "Europe/London") ?? .gmt + return calendar + }() + + private func date(_ year: Int, _ month: Int, _ day: Int) -> Date { + calendar.date(from: DateComponents(year: year, month: month, day: day))! + } + + func testBlockStartsOnMondayTwentySeventhJuly() { + let position = TwelveWeekProgramme.position(for: date(2026, 7, 27), calendar: calendar) + + XCTAssertEqual(position.weekNumber, 1) + XCTAssertEqual(position.dayIndex, 0) + XCTAssertTrue(position.inBlock) + XCTAssertEqual(position.schedule.kind, .upper) + } + + func testBlockEndsOnSundayEighteenthOctober() { + let position = TwelveWeekProgramme.position(for: date(2026, 10, 18), calendar: calendar) + + XCTAssertEqual(position.weekNumber, 12) + XCTAssertEqual(position.dayIndex, 6) + XCTAssertTrue(position.inBlock) + XCTAssertEqual(position.schedule.kind, .easyCardioMobility) + } + + func testDatesOutsideTheBlockAreReportedRatherThanClampedSilently() { + let before = TwelveWeekProgramme.position(for: date(2026, 7, 26), calendar: calendar) + let after = TwelveWeekProgramme.position(for: date(2026, 10, 19), calendar: calendar) + + XCTAssertTrue(before.beforeBlock) + XCTAssertFalse(before.inBlock) + XCTAssertTrue(after.afterBlock) + XCTAssertFalse(after.inBlock) + } + + /// Every one of the 84 dated days resolves to the authored weekday session. + func testEveryDayOfTheBlockResolvesToItsAuthoredSession() throws { + let start = date(2026, 7, 27) + for offset in 0..= 3 { + // The third set is offered, never silently inserted. + XCTAssertEqual(rdl?.workingSets.last?.isOptional, true, "week \(week)") + } + } + } + + func testHardCardioUsesFourRoundsInWeeksOneAndTwoThenFive() { + for week in 1...TwelveWeekProgramme.weekCount { + let template = TwelveWeekProgramme.template(for: .upperPlusHardCardio, week: week, dayIndex: 3) + let intervals = template.exercises.first { $0.definitionSlug == "controlled-hard-interval" } + + XCTAssertEqual(intervals?.sets.count, week <= 2 ? 4 : 5, "week \(week)") + XCTAssertEqual(intervals?.sets.first?.target.timeSeconds, 120, "week \(week)") + XCTAssertEqual(intervals?.sets.first?.rest, RestRange(180), "week \(week)") + } + } + + func testPullUpIsTestedOnlyAtWeeksFiveNineAndTheEndOfWeekTwelve() { + for week in 1...TwelveWeekProgramme.weekCount { + for dayIndex in [0, 3] { + let kind: ProgrammeSessionKind = dayIndex == 0 ? .upper : .upperPlusHardCardio + let template = TwelveWeekProgramme.template(for: kind, week: week, dayIndex: dayIndex) + let testsPullUp = template.exercises.contains { + $0.sets.contains { $0.stepType == .check } + } + let expected = (dayIndex == 0 && (week == 5 || week == 9)) || (dayIndex == 3 && week == 12) + + XCTAssertEqual(testsPullUp, expected, "week \(week) day \(dayIndex)") + } + } + } + + func testOptionalLateralRaiseAppearsOnlyFromWeekFive() { + for week in 1...TwelveWeekProgramme.weekCount { + let template = TwelveWeekProgramme.template(for: .upper, week: week) + let hasLateralRaise = template.exercises.contains { $0.definitionSlug == "lateral-raise" } + + XCTAssertEqual(hasLateralRaise, week >= 5, "week \(week)") + if hasLateralRaise { + let raise = template.exercises.first { $0.definitionSlug == "lateral-raise" } + XCTAssertTrue(raise?.sets.allSatisfy(\.isOptional) == true) + } + } + } + + func testBenchRampAndWorkingSetsMatchTheAuthoredPlan() throws { + let template = TwelveWeekProgramme.template(for: .upper, week: 1) + let bench = try XCTUnwrap(template.exercises.first { $0.definitionSlug == "bench-press" }) + let warmUps = bench.sets.filter { $0.stepType == .warmUp } + + XCTAssertEqual(warmUps.count, 3) + XCTAssertEqual(warmUps[0].target.load, .absolute(kilograms: 20)) + XCTAssertEqual(warmUps[0].target.repsLow, 10) + XCTAssertEqual(warmUps[1].target.load, .absolute(kilograms: 40)) + XCTAssertEqual(warmUps[1].target.repsLow, 5) + XCTAssertEqual(warmUps[2].target.load, .absolute(kilograms: 55)) + XCTAssertEqual(warmUps[2].target.repsLow, 2) + XCTAssertEqual(warmUps[2].target.repsHigh, 3) + + let working = bench.workingSets + XCTAssertEqual(working.count, 3) + XCTAssertEqual(working[0].target.load, .absolute(kilograms: 65)) + XCTAssertEqual(working[0].target.repsLow, 5) + XCTAssertEqual(working[0].target.repsHigh, 8) + XCTAssertEqual(working[0].rest, RestRange(lowSeconds: 150, highSeconds: 180)) + } + + func testRepsInReserveTightensAfterTheLearningWeeks() { + let earlyBench = TwelveWeekProgramme.template(for: .upper, week: 1) + .exercises.first { $0.definitionSlug == "bench-press" }?.workingSets.first + let laterBench = TwelveWeekProgramme.template(for: .upper, week: 6) + .exercises.first { $0.definitionSlug == "bench-press" }?.workingSets.first + + XCTAssertEqual(earlyBench?.target.repsInReserve, 2) + XCTAssertEqual(laterBench?.target.repsInReserve, 1) + } + + func testFullMobilityRoutineCarriesAllEightAuthoredMovements() { + let template = TwelveWeekProgramme.template(for: .fullMobility, week: 1) + + XCTAssertEqual(template.exercises.count, 8) + XCTAssertEqual(template.exercises.map(\.definitionSlug), [ + "knee-to-wall-ankle-rocks", + "supported-squat-hold", + "goblet-squat", + "ninety-ninety-hip-switches", + "half-kneeling-hip-flexor-stretch", + "wall-slides", + "bench-lat-stretch", + "doorway-pec-stretch", + ]) + } + + func testEasyCardioSessionTotalsFortyFiveMinutes() throws { + let template = TwelveWeekProgramme.template(for: .easyCardioMobility, week: 1) + let cardio = try XCTUnwrap(template.exercises.first { $0.definitionSlug == "easy-cardio" }) + let seconds = cardio.sets.compactMap(\.target.timeSeconds).reduce(0, +) + + XCTAssertEqual(seconds, 45 * 60) + } + + /// A movement authored into the block but missing from the catalogue would lose + /// its pillars and measurements, so the two must never drift apart. + func testEveryAuthoredMovementExistsInTheCatalogue() { + for kind in ProgrammeSessionKind.allCases { + for week in [1, 3, 5, 9, 12] { + for dayIndex in [0, 3] { + let template = TwelveWeekProgramme.template(for: kind, week: week, dayIndex: dayIndex) + for exercise in template.exercises { + let slug = exercise.definitionSlug + XCTAssertNotNil(slug, "\(kind) week \(week): \(exercise.name) has no slug") + XCTAssertNotNil( + slug.flatMap { ExerciseCatalogue.definition(slug: $0) }, + "\(kind) week \(week): \(slug ?? "nil") missing from the catalogue" + ) + } + } + } + } + } + + func testCheckpointsFallOnTheAuthoredDates() { + let expected = [ + ("Baseline", date(2026, 7, 27)), + ("Week 5", date(2026, 8, 24)), + ("Week 9", date(2026, 9, 21)), + ("End of block", date(2026, 10, 18)), + ] + for (index, checkpoint) in TwelveWeekProgramme.checkpoints.enumerated() { + XCTAssertEqual(checkpoint.name, expected[index].0) + XCTAssertEqual( + TwelveWeekProgramme.checkpointDate(checkpoint, calendar: calendar), + expected[index].1 + ) + } + } + + func testTodayResolutionUsesTheBundledBlock() throws { + let document = SetlineDocument.initial + let resolved = try XCTUnwrap(document.session(on: date(2026, 8, 4), calendar: calendar)) + + // 4 August 2026 is the Tuesday of week 2. + XCTAssertEqual(resolved.programmeWeek, 2) + XCTAssertEqual(resolved.programmeDayIndex, 1) + XCTAssertEqual(resolved.template.name, "Lower") + XCTAssertNil(resolved.outOfBlockNotice) + } + + func testWeekStripReturnsSevenBundledDays() { + let week = SetlineDocument.initial.week(containing: date(2026, 8, 4), calendar: calendar) + + XCTAssertEqual(week.count, 7) + XCTAssertEqual(week.compactMap { $0?.template.name }, [ + "Upper", + "Lower", + "Easy cardio + full mobility", + "Upper + hard cardio", + "Full mobility", + "Lower", + "Easy cardio + full mobility", + ]) + } +} + +// MARK: - Shorthand set entry + +final class SetEntryParserTests: XCTestCase { + func testRepsFirstPairMatchesTheAuthoredConvention() { + let result = SetEntryParser.parse("5x40") + + XCTAssertEqual(result.segments.count, 1) + XCTAssertEqual(result.segments.first?.repetitions, 5) + XCTAssertEqual(result.segments.first?.weight, 40) + XCTAssertTrue(result.isFullyUnderstood) + } + + /// The exact requirement: two segments, one set. + func testTwoSegmentsParseAsOneSet() { + let result = SetEntryParser.parse("5x40, 2x30") + + XCTAssertEqual(result.segments.count, 2) + XCTAssertEqual(result.segments[0].repetitions, 5) + XCTAssertEqual(result.segments[0].weight, 40) + XCTAssertEqual(result.segments[1].repetitions, 2) + XCTAssertEqual(result.segments[1].weight, 30) + } + + func testExplicitUnitsDisambiguateOrder() { + let weightFirst = SetEntryParser.parse("40kg x 5") + + XCTAssertEqual(weightFirst.segments.first?.weight, 40) + XCTAssertEqual(weightFirst.segments.first?.repetitions, 5) + } + + func testExplicitRepsAndWeightInEitherOrder() { + let a = SetEntryParser.parse("5 reps 40 kg") + let b = SetEntryParser.parse("40 kg 5 reps") + + XCTAssertEqual(a.segments.first?.repetitions, 5) + XCTAssertEqual(a.segments.first?.weight, 40) + XCTAssertEqual(b.segments.first?.repetitions, 5) + XCTAssertEqual(b.segments.first?.weight, 40) + } + + func testBodyweightWithAddedLoad() { + let bare = SetEntryParser.parse("bw x 8") + let loaded = SetEntryParser.parse("bw+10 x 8") + + XCTAssertEqual(bare.segments.first?.repetitions, 8) + XCTAssertNil(bare.segments.first?.weight) + XCTAssertEqual(loaded.segments.first?.repetitions, 8) + XCTAssertEqual(loaded.segments.first?.weight, 10) + } + + func testAssistedRepetitions() { + let result = SetEntryParser.parse("assist 15kg x 6") + + XCTAssertEqual(result.segments.first?.assistanceKilograms, 15) + XCTAssertEqual(result.segments.first?.repetitions, 6) + } + + func testDurationsAndDistances() { + XCTAssertEqual(SetEntryParser.parse("45s").segments.first?.durationSeconds, 45) + XCTAssertEqual(SetEntryParser.parse("2min").segments.first?.durationSeconds, 120) + XCTAssertEqual(SetEntryParser.parse("5km 25min").segments.first?.distanceKilometres, 5) + XCTAssertEqual(SetEntryParser.parse("5km 25min").segments.first?.durationSeconds, 1_500) + } + + func testEffortQualifiers() { + let result = SetEntryParser.parse("5x40 @rpe8 rir1") + + XCTAssertEqual(result.segments.first?.rpe, 8) + XCTAssertEqual(result.segments.first?.repsInReserve, 1) + XCTAssertEqual(result.segments.first?.repetitions, 5) + XCTAssertEqual(result.segments.first?.weight, 40) + } + + func testPerSideEntry() { + let result = SetEntryParser.parse("left 8x20, right 8x20") + + XCTAssertEqual(result.segments.count, 2) + XCTAssertEqual(result.segments[0].side, .left) + XCTAssertEqual(result.segments[1].side, .right) + XCTAssertEqual(result.segments[0].repetitions, 8) + } + + func testFailureIsFlagged() { + XCTAssertEqual(SetEntryParser.parse("8x60 fail").segments.first?.reachedFailure, true) + } + + /// Nonsense is reported, never silently turned into a recorded number. + func testUnparseableTextIsReportedRatherThanGuessed() { + let result = SetEntryParser.parse("something odd") + + XCTAssertTrue(result.segments.isEmpty) + XCTAssertEqual(result.unrecognised, ["something odd"]) + XCTAssertFalse(result.isFullyUnderstood) + } + + func testShorthandRoundTrips() { + let original = SetEntryParser.parse("5x40, 2x30").segments + let round = SetEntryParser.parse(SetEntryParser.shorthand(for: original)).segments + + XCTAssertEqual(round.map(\.repetitions), original.map(\.repetitions)) + XCTAssertEqual(round.map(\.weight), original.map(\.weight)) + } +} + +// MARK: - Measurement, goals and progression + +final class ExerciseMetricsTests: XCTestCase { + private let sessionDate = Date(timeIntervalSince1970: 1_700_000_000) + + private func step( + _ name: String, + reps: Int, + kilograms: Double?, + type: StepType = .working, + position: Int = 0, + completedAt: Date + ) -> WorkoutStep { + WorkoutStep( plannedSetID: UUID(), - exerciseName: "Front squat", + exerciseName: name, + exerciseSlug: ExerciseCatalogue.match(name: name)?.slug, cue: "", label: "Working", kind: .strength, - target: "60 kg × 5", - authoredPosition: 0, - restSeconds: 120, + stepType: type, + target: SetTarget(repsLow: reps, load: kilograms.map { .absolute(kilograms: $0) }), + authoredPosition: position, + rest: RestRange(120), status: .complete, - segments: [SetSegment(weight: 60, repetitions: 5)] + segments: [SetSegment(weight: kilograms, repetitions: reps)], + completedAt: completedAt + ) + } + + private func session(_ steps: [WorkoutStep], at date: Date) -> WorkoutSession { + WorkoutSession( + templateID: UUID(), + templateName: "Upper", + startedAt: date, + completedAt: date, + steps: steps ) + } + + func testEpleyEstimateAndItsRepetitionCeiling() { + XCTAssertEqual(ExerciseMetrics.estimatedOneRepMax(kilograms: 100, repetitions: 1), 100) + XCTAssertEqual(ExerciseMetrics.estimatedOneRepMax(kilograms: 60, repetitions: 5)!, 70, accuracy: 0.001) + // Past twelve repetitions the estimate stops measuring strength. + XCTAssertNil(ExerciseMetrics.estimatedOneRepMax(kilograms: 40, repetitions: 20)) + XCTAssertNil(ExerciseMetrics.estimatedOneRepMax(kilograms: 0, repetitions: 5)) + } + + /// Warm-up ramps must not create records, volume or progression evidence. + func testWarmUpSetsAreInvisibleToMeasurement() { + let history = [session([ + step("Bench press", reps: 10, kilograms: 200, type: .warmUp, completedAt: sessionDate), + step("Bench press", reps: 5, kilograms: 65, type: .working, position: 1, completedAt: sessionDate), + ], at: sessionDate)] + + let top = ExerciseMetrics.current(for: "Bench press", metric: .topSetLoad, history: history) + + XCTAssertEqual(top?.value, 65, "The 200 kg warm-up must never become a record") + XCTAssertEqual(history[0].tonnage, 65 * 5) + XCTAssertEqual(history[0].completedWorkingSetCount, 1) + } + + func testMeasuredValuesCarryTheirProvenance() throws { + let history = [session([ + step("Bench press", reps: 5, kilograms: 70, completedAt: sessionDate), + ], at: sessionDate)] + + let value = try XCTUnwrap( + ExerciseMetrics.current(for: "bench PRESS", metric: .topSetLoad, history: history) + ) + + XCTAssertEqual(value.value, 70) + XCTAssertEqual(value.sessionName, "Upper") + XCTAssertTrue(value.provenance.contains("Upper")) + } + + func testMaxRepetitionsSumsSegmentsWithinOneSet() { + var step = step("Ab wheel from knees", reps: 5, kilograms: nil, completedAt: sessionDate) + step.segments = [SetSegment(repetitions: 5), SetSegment(repetitions: 2)] + let history = [session([step], at: sessionDate)] + + let value = ExerciseMetrics.current(for: "Ab wheel from knees", metric: .maxRepetitions, history: history) + + XCTAssertEqual(value?.value, 7) + } + + func testGoalProgressMeasuresFromBaselineAndProjectsForward() throws { + let week0 = sessionDate + let week1 = sessionDate.addingTimeInterval(604_800) + let week2 = sessionDate.addingTimeInterval(2 * 604_800) let history = [ - WorkoutSession(templateID: UUID(), templateName: "A", startedAt: .now, completedAt: .now, steps: [step]), - WorkoutSession(templateID: UUID(), templateName: "A", startedAt: .now, completedAt: .now, steps: [step]), + session([step("Bench press", reps: 5, kilograms: 70, completedAt: week2)], at: week2), + session([step("Bench press", reps: 5, kilograms: 67.5, completedAt: week1)], at: week1), + session([step("Bench press", reps: 5, kilograms: 65, completedAt: week0)], at: week0), ] + let goal = ExerciseGoal( + exerciseName: "Bench press", + metric: .topSetLoad, + targetValue: 80, + referenceRepetitions: 5, + createdAt: week0 + ) + + let progress = ExerciseMetrics.progress(for: goal, history: history) - let recommendation = ProgressionEngine.recommendation(for: "Front squat", history: history) + XCTAssertEqual(progress.current?.value, 70) + XCTAssertEqual(progress.baseline?.value, 65) + XCTAssertEqual(try XCTUnwrap(progress.fraction), (70 - 65) / (80 - 65), accuracy: 0.001) + XCTAssertEqual(progress.remaining, 10) + XCTAssertEqual(try XCTUnwrap(progress.ratePerWeek), 2.5, accuracy: 0.001) + XCTAssertNotNil(progress.projectedDate) + XCTAssertFalse(progress.isAchieved) + XCTAssertEqual(progress.evidenceCount, 3) + } + + func testGoalWithoutEvidenceReportsNothingRatherThanZero() { + let goal = ExerciseGoal(exerciseName: "Snatch", metric: .estimatedOneRepMax, targetValue: 60) + + let progress = ExerciseMetrics.progress(for: goal, history: []) + + XCTAssertNil(progress.current) + XCTAssertNil(progress.fraction) + XCTAssertNil(progress.ratePerWeek) + XCTAssertNil(progress.projectedDate) + XCTAssertEqual(progress.evidenceCount, 0) + XCTAssertFalse(progress.isAchieved) + } + + func testAchievedGoalIsRecognisedInBothDirections() { + let history = [session([step("Bench press", reps: 5, kilograms: 85, completedAt: sessionDate)], at: sessionDate)] + let rising = ExerciseGoal(exerciseName: "Bench press", metric: .topSetLoad, targetValue: 80) + + XCTAssertTrue(ExerciseMetrics.progress(for: rising, history: history).isAchieved) + + var paceStep = step("Run", reps: 1, kilograms: nil, completedAt: sessionDate) + paceStep.segments = [SetSegment(durationSeconds: 1_500, distanceKilometres: 5)] + let paceHistory = [session([paceStep], at: sessionDate)] + // 300 s/km recorded against a 330 s/km target: lower is better. + let falling = ExerciseGoal( + exerciseName: "Run", + metric: .bestPaceSecondsPerKilometre, + targetValue: 330 + ) + + XCTAssertTrue(ExerciseMetrics.progress(for: falling, history: paceHistory).isAchieved) + } + + func testTrendMovingAwayFromTheGoalProducesNoArrivalDate() { + let week0 = sessionDate + let week1 = sessionDate.addingTimeInterval(604_800) + let history = [ + session([step("Bench press", reps: 5, kilograms: 60, completedAt: week1)], at: week1), + session([step("Bench press", reps: 5, kilograms: 70, completedAt: week0)], at: week0), + ] + let goal = ExerciseGoal( + exerciseName: "Bench press", + metric: .topSetLoad, + targetValue: 90, + createdAt: week0 + ) + + let progress = ExerciseMetrics.progress(for: goal, history: history) + + XCTAssertNil(progress.projectedDate, "A declining trend cannot arrive at a higher target") + } +} + +final class ProgressionEngineTests: XCTestCase { + private let sessionDate = Date(timeIntervalSince1970: 1_700_000_000) + + private func benchSession(reps: [Int], kilograms: Double) -> WorkoutSession { + WorkoutSession( + templateID: UUID(), + templateName: "Upper", + startedAt: sessionDate, + completedAt: sessionDate, + steps: reps.enumerated().map { index, count in + WorkoutStep( + plannedSetID: UUID(), + exerciseName: "Bench press", + exerciseSlug: "bench-press", + cue: "", + label: "Working set \(index + 1) of 3", + kind: .strength, + stepType: .working, + target: SetTarget(repsLow: 5, repsHigh: 8, load: .absolute(kilograms: kilograms)), + authoredPosition: index, + rest: RestRange(180), + status: .complete, + segments: [SetSegment(weight: kilograms, repetitions: count)], + completedAt: sessionDate + ) + } + ) + } + + /// 8, 8, 8 clean at 65 kg is the authored trigger for 67.5 kg. + func testAllSetsAtTopOfRangeAddsTheAuthoredIncrement() throws { + let recommendation = try XCTUnwrap(ProgressionEngine.recommendation( + for: "Bench press", + rule: nil, + history: [benchSession(reps: [8, 8, 8], kilograms: 65)] + )) + + XCTAssertEqual(recommendation.action, .addLoad) + XCTAssertEqual(recommendation.currentLoad, 65) + XCTAssertEqual(recommendation.recommendedLoad, 67.5) + XCTAssertEqual(recommendation.lastSessionRepetitions, [8, 8, 8]) + XCTAssertTrue(recommendation.rationale.contains("3 × 8")) + } + + /// 8, 7, 6 stays at 65 kg and adds repetitions instead. + func testMidRangeHoldsTheLoadAndAddsRepetitions() throws { + let recommendation = try XCTUnwrap(ProgressionEngine.recommendation( + for: "Bench press", + rule: nil, + history: [benchSession(reps: [8, 7, 6], kilograms: 65)] + )) + + XCTAssertEqual(recommendation.action, .addRepetitions) + XCTAssertEqual(recommendation.recommendedLoad, 65) + XCTAssertEqual(recommendation.evidenceSummary, "8, 7, 6 at 65 kg") + } + + /// 5, 4, 3 falls below the range floor, so the load comes down. + func testFallingBelowTheRangeReducesTheLoad() throws { + let recommendation = try XCTUnwrap(ProgressionEngine.recommendation( + for: "Bench press", + rule: nil, + history: [benchSession(reps: [5, 4, 3], kilograms: 65)] + )) + + XCTAssertEqual(recommendation.action, .reduceLoad) + XCTAssertEqual(recommendation.recommendedLoad, 62.5) + } + + func testNoEvidenceProducesNoRecommendation() { + XCTAssertNil(ProgressionEngine.recommendation(for: "Bench press", rule: nil, history: [])) + } + + func testOnlyTheMostRecentSessionInformsTheSuggestion() throws { + let older = benchSession(reps: [8, 8, 8], kilograms: 65) + var recent = benchSession(reps: [6, 6, 6], kilograms: 67.5) + recent.startedAt = sessionDate.addingTimeInterval(604_800) + recent.completedAt = recent.startedAt + recent.steps = recent.steps.map { step in + var next = step + next.completedAt = recent.startedAt + return next + } + + let recommendation = try XCTUnwrap(ProgressionEngine.recommendation( + for: "Bench press", + rule: nil, + history: [recent, older] + )) + + XCTAssertEqual(recommendation.action, .addRepetitions) + XCTAssertEqual(recommendation.currentLoad, 67.5) + } +} + +// MARK: - Catalogue + +final class FormattingTests: XCTestCase { + /// An estimated 1RM of 72.5 x (1 + 8/30) is 91.8333... — binary floating-point + /// precision must never reach the interface. + func testTrimmedStringNeverLeaksFloatingPointPrecision() { + XCTAssertEqual((72.5 * (1 + 8.0 / 30)).trimmedString, "91.83") + XCTAssertEqual(2.5000000000000007.trimmedString, "2.5") + XCTAssertEqual(65.0.trimmedString, "65") + XCTAssertEqual(72.5.trimmedString, "72.5") + XCTAssertEqual(0.trimmedString, "0") + XCTAssertEqual(Double.infinity.trimmedString, "—") + } + + func testKilogramValuesRoundToOneDecimal() { + XCTAssertEqual((72.5 * (1 + 8.0 / 30)).kilogramString, "91.8") + XCTAssertEqual(72.5.kilogramString, "72.5") + XCTAssertEqual(65.0.kilogramString, "65") + XCTAssertEqual(MetricKind.estimatedOneRepMax.format(72.5 * (1 + 8.0 / 30)), "91.8 kg") + XCTAssertEqual(MetricKind.topSetLoad.format(72.5), "72.5 kg") + } + + func testDurationAndRestLabels() { + XCTAssertEqual(45.durationLabel, "45 sec") + XCTAssertEqual(120.durationLabel, "2 min") + XCTAssertEqual(150.durationLabel, "2 min 30 sec") + XCTAssertEqual(RestRange(lowSeconds: 150, highSeconds: 180).displayString, "2.5–3 min") + XCTAssertEqual(RestRange(90).displayString, "1.5 min") + XCTAssertEqual(RestRange.none.displayString, "No rest") + } + + func testTargetDisplayCombinesLoadAndRepetitionRange() { + let target = SetTarget( + repsLow: 5, + repsHigh: 8, + load: .absolute(kilograms: 65), + repsInReserve: 2 + ) + + XCTAssertEqual(target.displayString, "65 kg · 5–8 reps") + XCTAssertEqual(target.qualifiers, ["2 RIR"]) + } + + func testPerSideAndRelativeLoadTargetsReadCorrectly() { + XCTAssertEqual( + SetTarget(repsLow: 8, repsHigh: 12, load: .chooseLoad, perSide: true).displayString, + "Choose load · 8–12 reps per side" + ) + XCTAssertEqual( + SetTarget(repsLow: 3, load: .percentOfOneRepMax(70)).displayString, + "70% 1RM · 3 reps" + ) + XCTAssertEqual( + SetTarget(repsLow: 8, load: .bodyweight(plusKilograms: 10)).displayString, + "Bodyweight + 10 kg · 8 reps" + ) + XCTAssertEqual(SetTarget().displayString, "Complete") + } +} + +final class ExerciseCatalogueTests: XCTestCase { + func testEverySlugIsUnique() { + let slugs = ExerciseCatalogue.all.map(\.slug) + + XCTAssertEqual(Set(slugs).count, slugs.count) + } + + func testEveryDefinitionDeclaresAtLeastOnePillar() { + for definition in ExerciseCatalogue.all { + XCTAssertFalse(definition.pillars.isEmpty, definition.slug) + } + } + + func testAllFourPillarsAreCovered() { + for pillar in Pillar.allCases { + XCTAssertFalse( + ExerciseCatalogue.definitions(for: pillar).isEmpty, + "No movements train \(pillar.title)" + ) + } + } + + func testNameAndAliasLookupIsCaseInsensitive() { + XCTAssertEqual(ExerciseCatalogue.match(name: " BENCH PRESS ")?.slug, "bench-press") + XCTAssertEqual(ExerciseCatalogue.match(name: "rdl")?.slug, "romanian-deadlift") + XCTAssertEqual(ExerciseCatalogue.match(name: "leg press")?.slug, "hack-squat-or-leg-press") + XCTAssertNil(ExerciseCatalogue.match(name: "not a movement")) + } - XCTAssertEqual(recommendation?.previousWeight, 60) - XCTAssertEqual(recommendation?.recommendedWeight, 62.5) - XCTAssertTrue(recommendation?.rationale.contains("session only") == true) + func testSearchMatchesNamesAndAliases() { + XCTAssertTrue(ExerciseCatalogue.search("squat").contains { $0.slug == "front-squat" }) + XCTAssertTrue(ExerciseCatalogue.search("rdl").contains { $0.slug == "romanian-deadlift" }) } } diff --git a/ios/Tests/SetlineUITests/SetlineUITests.swift b/ios/Tests/SetlineUITests/SetlineUITests.swift index 740d3b4..282d88e 100644 --- a/ios/Tests/SetlineUITests/SetlineUITests.swift +++ b/ios/Tests/SetlineUITests/SetlineUITests.swift @@ -6,42 +6,209 @@ final class SetlineUITests: XCTestCase { continueAfterFailure = false } - func testStartsWorkoutAndShowsTimestampRest() { + /// `--ui-demo` pins a fixed fixture so these tests never depend on which day of + /// the authored twelve-week block today happens to be. + private func launch(_ arguments: [String] = ["--ui-demo"]) -> XCUIApplication { let app = XCUIApplication() - app.launchArguments = ["--fresh-demo"] + app.launchArguments = arguments app.launch() + return app + } + + /// The decimal keypad has no return key, so the player supplies a Done button + /// above it. Entry is unusable without one, which is why this taps the real + /// control rather than working around its absence. + private func dismissKeyboard(_ app: XCUIApplication) { + guard app.keyboards.count > 0 else { return } + let done = app.buttons["Done"] + if done.waitForExistence(timeout: 2) { + done.tap() + } + } + + /// Records the current set and waits for the authored rest to start. + /// + /// The record button sits below a set timer and a variable number of segment + /// rows, so it may need scrolling into reach. Retrying around the observable + /// outcome — the rest board appearing — keeps this from depending on where the + /// button happens to land. + private func recordSetAndWaitForRest(_ app: XCUIApplication) { + let rest = app.staticTexts["REST · WALL CLOCK"] + for _ in 0..<3 { + dismissKeyboard(app) + let record = app.buttons["Record set · start rest"] + guard record.waitForExistence(timeout: 3), record.isHittable else { + app.swipeUp() + continue + } + record.tap() + if rest.waitForExistence(timeout: 5) { return } + } + XCTFail("Recording the set did not start the authored rest period") + } + + private func text(_ app: XCUIApplication, containing fragment: String) -> XCUIElement { + app.staticTexts.containing( + NSPredicate(format: "label CONTAINS[c] %@", fragment) + ).firstMatch + } + + func testStartsWorkoutAndShowsTimestampRest() { + let app = launch() XCTAssertTrue(app.staticTexts["Follow the plan.\nRecord the truth."].waitForExistence(timeout: 3)) app.buttons["Start workout"].tap() XCTAssertTrue(app.staticTexts["Front squat"].waitForExistence(timeout: 3)) - let weight = app.textFields["Weight"] - weight.tap() - weight.typeText("40") let reps = app.textFields["Reps"] reps.tap() reps.typeText("8") - app.buttons["Record set · start rest"].tap() + let weight = app.textFields["Weight"] + weight.tap() + weight.typeText("40") + recordSetAndWaitForRest(app) - XCTAssertTrue(app.staticTexts["REST · WALL CLOCK"].waitForExistence(timeout: 3)) XCTAssertTrue(app.buttons["Start next early"].exists) } + func testSetTimerRunsIndependentlyOfRest() { + let app = launch() + + app.buttons["Start workout"].tap() + XCTAssertTrue(app.staticTexts["SET TIMER"].waitForExistence(timeout: 3)) + let start = app.buttons["Start set"] + XCTAssertTrue(start.exists) + start.tap() + XCTAssertTrue(app.buttons["Stop"].waitForExistence(timeout: 2)) + app.buttons["Stop"].tap() + XCTAssertTrue(app.buttons["Start set"].waitForExistence(timeout: 2)) + XCTAssertTrue(app.buttons["Reset"].exists) + } + + /// The headline requirement: `5 reps × 40 kg` then `2 reps × 30 kg`, recorded as + /// one set, surviving all the way into the session receipt. + func testRecordsTwoSegmentsAsOneSetAndKeepsBothInTheReceipt() { + let app = launch() + + app.buttons["Start workout"].tap() + XCTAssertTrue(app.staticTexts["Front squat"].waitForExistence(timeout: 3)) + + app.buttons["Type it"].tap() + let shorthand = app.textFields["Shorthand set entry"] + XCTAssertTrue(shorthand.waitForExistence(timeout: 2)) + shorthand.tap() + shorthand.typeText("5x40, 2x30") + + // The interpretation is shown before anything is recorded. + let reading = app.staticTexts.containing( + NSPredicate(format: "label CONTAINS %@", "Reads as:") + ).firstMatch + XCTAssertTrue(reading.waitForExistence(timeout: 2)) + + app.buttons["Apply to segments"].tap() + XCTAssertTrue(app.staticTexts["SEGMENT 2"].waitForExistence(timeout: 2)) + XCTAssertTrue(app.staticTexts["All 2 segments record as one set."].exists) + + recordSetAndWaitForRest(app) + + app.buttons["Finish"].tap() + app.buttons["Finish and save"].tap() + + let historyTab = app.tabBars.buttons["History"] + XCTAssertTrue(historyTab.waitForExistence(timeout: 5)) + historyTab.tap() + + let session = text(app, containing: "Lower strength") + XCTAssertTrue(session.waitForExistence(timeout: 5)) + session.tap() + + let recorded = text(app, containing: "5 × 40 kg + 2 × 30 kg") + XCTAssertTrue( + recorded.waitForExistence(timeout: 5), + "Both segments must survive into the receipt as one set" + ) + } + func testCoreTabsAreReachable() { - let app = XCUIApplication() - app.launchArguments = ["--fresh-demo"] - app.launch() + let app = launch() - for tab in ["Plan", "History", "You"] { + for tab in ["Plan", "History", "You", "Exercises"] { app.tabBars.buttons[tab].tap() XCTAssertTrue(app.staticTexts[tab].waitForExistence(timeout: 2)) } } + func testAuthoredBlockDrivesTodayOnAFreshInstall() { + let app = launch(["--fresh-demo"]) + + app.tabBars.buttons["Plan"].tap() + XCTAssertTrue( + app.staticTexts["12-Week Strength, Cardio & Mobility Plan"].waitForExistence(timeout: 3) + ) + // Checkpoints are part of the authored block, not an afterthought. + XCTAssertTrue(app.staticTexts["Baseline"].exists) + XCTAssertTrue(app.staticTexts["End of block"].exists) + } + + func testTodaySessionCanBeReviewedBeforeStarting() { + let app = launch(["--fresh-demo"]) + + let review = app.buttons["Review the session first"] + XCTAssertTrue(review.waitForExistence(timeout: 3)) + review.tap() + XCTAssertTrue(text(app, containing: "Authored rules").waitForExistence(timeout: 5)) + } + + func testExercisesTabExplainsItselfBeforeAnyEvidenceExists() { + let app = launch() + + app.tabBars.buttons["Exercises"].tap() + XCTAssertTrue(app.staticTexts["No recorded working sets"].waitForExistence(timeout: 3)) + let setTarget = app.buttons["Set a target from the catalogue"] + XCTAssertTrue(setTarget.exists) + setTarget.tap() + XCTAssertTrue(app.navigationBars["Movement library"].waitForExistence(timeout: 3)) + } + + /// With four weeks of recorded evidence, an exercise shows its measured + /// current value, the authored target, and a trend that is actually drawn. + func testExerciseDetailShowsCurrentTargetAndTrend() { + let app = launch(["--evidence-demo", "--exercises-demo"]) + + let bench = text(app, containing: "Bench press") + XCTAssertTrue(bench.waitForExistence(timeout: 5)) + bench.tap() + + XCTAssertTrue(text(app, containing: "Current · measured").waitForExistence(timeout: 5)) + // 72.5 kg is the heaviest recorded top set in the seeded evidence. + XCTAssertTrue(text(app, containing: "72.5 kg").exists) + XCTAssertTrue(text(app, containing: "Ideal · authored").exists) + XCTAssertTrue(text(app, containing: "90 kg").exists) + + // Every measured value must name the session that produced it. + XCTAssertTrue(text(app, containing: "Upper ·").exists) + + // The trend is only drawn from two comparable sessions upward. + let chart = app.descendants(matching: .any).matching( + NSPredicate(format: "label CONTAINS[c] %@", "trend across") + ).firstMatch + XCTAssertTrue(chart.waitForExistence(timeout: 5), "The trend chart should render from four sessions") + } + + func testProgressionSuggestionCitesItsEvidence() { + let app = launch(["--evidence-demo", "--history-demo"]) + + XCTAssertTrue(text(app, containing: "Next-session suggestions").waitForExistence(timeout: 5)) + // The most recent bench session was 8, 7, 7 at 72.5 kg — mid-range, so the + // load holds and repetitions go up. + XCTAssertTrue(text(app, containing: "8, 7, 7 at 72.5 kg").exists) + XCTAssertTrue(text(app, containing: "ADD REPS").exists) + // The pulldown hit 10, 10, 10 at the top of its range, so load advances. + XCTAssertTrue(text(app, containing: "ADD LOAD").exists) + } + func testPlanOffersNativeTemplateAuthoring() { - let app = XCUIApplication() - app.launchArguments = ["--fresh-demo"] - app.launch() + let app = launch() app.tabBars.buttons["Plan"].tap() let newTemplate = app.buttons["New template"] @@ -49,16 +216,20 @@ final class SetlineUITests: XCTestCase { newTemplate.tap() XCTAssertTrue(app.navigationBars["New template"].waitForExistence(timeout: 3)) XCTAssertTrue(app.textFields["Name"].exists) - XCTAssertTrue(app.buttons["Add exercise"].exists) + let addExercise = app.buttons["Add exercise"] + if !addExercise.exists { app.swipeUp() } + XCTAssertTrue(addExercise.waitForExistence(timeout: 3)) } - func testAccountScreenOffersAppleAlongsideGoogle() { - let app = XCUIApplication() - app.launchArguments = ["--fresh-demo"] - app.launch() + func testStorageScreenStatesWhereTrainingLivesWithoutOfferingAnAccount() { + let app = launch() app.tabBars.buttons["You"].tap() - XCTAssertTrue(app.buttons["Connect Google account"].waitForExistence(timeout: 3)) - XCTAssertTrue(app.buttons["apple-account-button"].exists) + XCTAssertTrue(app.staticTexts["On this iPhone"].waitForExistence(timeout: 3)) + XCTAssertTrue(app.staticTexts["STORAGE"].exists) + XCTAssertTrue(app.buttons["Export complete Setline data"].exists) + // There is no account, so nothing may invite the user to sign in. + XCTAssertFalse(app.buttons["Connect Google account"].exists) + XCTAssertFalse(app.buttons["apple-account-button"].exists) } } diff --git a/ios/artifacts/simulator/accessibility-xl.png b/ios/artifacts/simulator/accessibility-xl.png index 7b63f90..70b5e0e 100644 Binary files a/ios/artifacts/simulator/accessibility-xl.png and b/ios/artifacts/simulator/accessibility-xl.png differ diff --git a/ios/artifacts/simulator/account-sync.png b/ios/artifacts/simulator/account-sync.png deleted file mode 100644 index fe9aad9..0000000 Binary files a/ios/artifacts/simulator/account-sync.png and /dev/null differ diff --git a/ios/artifacts/simulator/exercise-detail.png b/ios/artifacts/simulator/exercise-detail.png new file mode 100644 index 0000000..6e7aca6 Binary files /dev/null and b/ios/artifacts/simulator/exercise-detail.png differ diff --git a/ios/artifacts/simulator/exercises.png b/ios/artifacts/simulator/exercises.png new file mode 100644 index 0000000..7d97ba6 Binary files /dev/null and b/ios/artifacts/simulator/exercises.png differ diff --git a/ios/artifacts/simulator/history.png b/ios/artifacts/simulator/history.png index 6c0ffc5..4c37f63 100644 Binary files a/ios/artifacts/simulator/history.png and b/ios/artifacts/simulator/history.png differ diff --git a/ios/artifacts/simulator/plan.png b/ios/artifacts/simulator/plan.png index 7f2a8ba..2898fb6 100644 Binary files a/ios/artifacts/simulator/plan.png and b/ios/artifacts/simulator/plan.png differ diff --git a/ios/artifacts/simulator/rest-timer.png b/ios/artifacts/simulator/rest-timer.png index 24c1371..7e33242 100644 Binary files a/ios/artifacts/simulator/rest-timer.png and b/ios/artifacts/simulator/rest-timer.png differ diff --git a/ios/artifacts/simulator/sync-conflict.png b/ios/artifacts/simulator/sync-conflict.png deleted file mode 100644 index 1b9114a..0000000 Binary files a/ios/artifacts/simulator/sync-conflict.png and /dev/null differ diff --git a/ios/artifacts/simulator/today.png b/ios/artifacts/simulator/today.png index 347cf68..377d855 100644 Binary files a/ios/artifacts/simulator/today.png and b/ios/artifacts/simulator/today.png differ diff --git a/ios/artifacts/simulator/workout-player.png b/ios/artifacts/simulator/workout-player.png index c081a6b..b681d1c 100644 Binary files a/ios/artifacts/simulator/workout-player.png and b/ios/artifacts/simulator/workout-player.png differ diff --git a/ios/project.yml b/ios/project.yml index 1d89940..b3ff213 100644 --- a/ios/project.yml +++ b/ios/project.yml @@ -42,11 +42,6 @@ targets: CFBundleDisplayName: Setline CFBundleShortVersionString: "$(MARKETING_VERSION)" CFBundleVersion: "$(CURRENT_PROJECT_VERSION)" - CFBundleURLTypes: - - CFBundleTypeRole: Editor - CFBundleURLName: com.significanthobbies.setline.auth - CFBundleURLSchemes: - - setline ITSAppUsesNonExemptEncryption: false LSApplicationCategoryType: public.app-category.healthcare-fitness UIApplicationSupportsIndirectInputEvents: true diff --git a/knip.json b/knip.json index 6b8635b..3dbb146 100644 --- a/knip.json +++ b/knip.json @@ -1,20 +1,6 @@ { "$schema": "https://unpkg.com/knip@6/schema.json", - "entry": [ - "tests/*.test.mjs", - "src/lib/workout-data-transfer.ts", - "src/lib/progression.ts", - "src/lib/custom-programme.ts", - "src/lib/custom-workouts.ts", - "src/lib/history-analytics.ts", - "worker/native-handoff.ts", - "worker/native-state.ts" - ], - "project": [ - "src/**/*.{ts,tsx}", - "worker/**/*.{ts,mjs,mts}", - "tests/**/*.mjs" - ], - "ignore": ["worker/agent-edge.mjs"], + "entry": ["tests/*.test.mjs", "scripts/*.mjs"], + "project": ["tests/**/*.mjs", "scripts/**/*.mjs"], "ignoreDependencies": ["jscpd"] } diff --git a/migrations/0001_auth_and_state.sql b/migrations/0001_auth_and_state.sql deleted file mode 100644 index 52b90a4..0000000 --- a/migrations/0001_auth_and_state.sql +++ /dev/null @@ -1,60 +0,0 @@ -PRAGMA foreign_keys = ON; - -CREATE TABLE user ( - id TEXT PRIMARY KEY NOT NULL, - name TEXT NOT NULL, - email TEXT NOT NULL UNIQUE, - emailVerified INTEGER NOT NULL DEFAULT 0, - image TEXT, - createdAt INTEGER NOT NULL, - updatedAt INTEGER NOT NULL -); - -CREATE TABLE session ( - id TEXT PRIMARY KEY NOT NULL, - expiresAt INTEGER NOT NULL, - token TEXT NOT NULL UNIQUE, - createdAt INTEGER NOT NULL, - updatedAt INTEGER NOT NULL, - ipAddress TEXT, - userAgent TEXT, - userId TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE -); - -CREATE INDEX session_user_idx ON session(userId); - -CREATE TABLE account ( - id TEXT PRIMARY KEY NOT NULL, - accountId TEXT NOT NULL, - providerId TEXT NOT NULL, - userId TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE, - accessToken TEXT, - refreshToken TEXT, - idToken TEXT, - accessTokenExpiresAt INTEGER, - refreshTokenExpiresAt INTEGER, - scope TEXT, - password TEXT, - createdAt INTEGER NOT NULL, - updatedAt INTEGER NOT NULL -); - -CREATE INDEX account_user_idx ON account(userId); - -CREATE TABLE verification ( - id TEXT PRIMARY KEY NOT NULL, - identifier TEXT NOT NULL, - value TEXT NOT NULL, - expiresAt INTEGER NOT NULL, - createdAt INTEGER NOT NULL, - updatedAt INTEGER NOT NULL -); - -CREATE INDEX verification_identifier_idx ON verification(identifier); - -CREATE TABLE workout_state ( - user_id TEXT PRIMARY KEY NOT NULL REFERENCES user(id) ON DELETE CASCADE, - payload TEXT NOT NULL CHECK (length(payload) <= 524288), - updated_at INTEGER NOT NULL, - created_at INTEGER NOT NULL -); diff --git a/migrations/0002_mcp_read_tokens.sql b/migrations/0002_mcp_read_tokens.sql deleted file mode 100644 index d22f82d..0000000 --- a/migrations/0002_mcp_read_tokens.sql +++ /dev/null @@ -1,12 +0,0 @@ -CREATE TABLE mcp_read_tokens ( - id TEXT PRIMARY KEY NOT NULL, - user_id TEXT NOT NULL REFERENCES user(id) ON DELETE CASCADE, - name TEXT NOT NULL, - token_hash TEXT NOT NULL UNIQUE, - token_hint TEXT NOT NULL, - created_at INTEGER NOT NULL, - revoked_at INTEGER -); - -CREATE INDEX mcp_read_tokens_user_idx - ON mcp_read_tokens(user_id, revoked_at, created_at DESC); diff --git a/migrations/0003_native_account_sync.sql b/migrations/0003_native_account_sync.sql deleted file mode 100644 index bbcaba2..0000000 --- a/migrations/0003_native_account_sync.sql +++ /dev/null @@ -1,17 +0,0 @@ -CREATE TABLE native_auth_handoffs ( - code_hash TEXT PRIMARY KEY NOT NULL, - session_token TEXT NOT NULL, - expires_at INTEGER NOT NULL, - created_at INTEGER NOT NULL -); - -CREATE INDEX native_auth_handoffs_expiry_idx - ON native_auth_handoffs(expires_at); - -CREATE TABLE native_workout_state ( - user_id TEXT PRIMARY KEY NOT NULL REFERENCES user(id) ON DELETE CASCADE, - payload TEXT NOT NULL, - revision INTEGER NOT NULL, - created_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL -); diff --git a/openspec/changes/add-setline-google-auth/.openspec.yaml b/openspec/changes/archive/2026-08-16-withdrawn-add-setline-google-auth/.openspec.yaml similarity index 100% rename from openspec/changes/add-setline-google-auth/.openspec.yaml rename to openspec/changes/archive/2026-08-16-withdrawn-add-setline-google-auth/.openspec.yaml diff --git a/openspec/changes/archive/2026-08-16-withdrawn-add-setline-google-auth/WITHDRAWN.md b/openspec/changes/archive/2026-08-16-withdrawn-add-setline-google-auth/WITHDRAWN.md new file mode 100644 index 0000000..d33d556 --- /dev/null +++ b/openspec/changes/archive/2026-08-16-withdrawn-add-setline-google-auth/WITHDRAWN.md @@ -0,0 +1,24 @@ +# Withdrawn 2026-08-16 + +This change was never completed and has been withdrawn rather than archived as +delivered. Its premise no longer holds. + +It proposed a Cloudflare Worker at `setline.significanthobbies.com`, optional +Google sign-in through Better Auth, and private per-user D1 state. All three +were built and then removed: + +- The Worker and the `setline` D1 database were deleted on 2026-08-16. Every + table held zero rows — no one ever signed in, so the cross-device continuity + this change existed to provide was never once used. +- Better Auth, Google sign-in, Sign in with Apple, the private state API and the + whole-document sync/conflict flow were removed with the backend. +- Setline is now Apple-only and device-first. `AGENTS.md` records the standing + constraint: no backend, no Cloudflare, no database, no hosting account. + +Cross-device continuity is still wanted. It is being pursued through iCloud +instead, which needs no server and no account of Setline's own. That is separate +work with its own proposal; nothing here should be revived to deliver it. + +The proposal, design, tasks and specs are kept verbatim for the reasoning +record — particularly the offline-queue and deterministic-reconciliation design, +which stays relevant to any sync approach. diff --git a/openspec/changes/add-setline-google-auth/design.md b/openspec/changes/archive/2026-08-16-withdrawn-add-setline-google-auth/design.md similarity index 100% rename from openspec/changes/add-setline-google-auth/design.md rename to openspec/changes/archive/2026-08-16-withdrawn-add-setline-google-auth/design.md diff --git a/openspec/changes/add-setline-google-auth/proposal.md b/openspec/changes/archive/2026-08-16-withdrawn-add-setline-google-auth/proposal.md similarity index 100% rename from openspec/changes/add-setline-google-auth/proposal.md rename to openspec/changes/archive/2026-08-16-withdrawn-add-setline-google-auth/proposal.md diff --git a/openspec/changes/add-setline-google-auth/specs/setline-private-account/spec.md b/openspec/changes/archive/2026-08-16-withdrawn-add-setline-google-auth/specs/setline-private-account/spec.md similarity index 100% rename from openspec/changes/add-setline-google-auth/specs/setline-private-account/spec.md rename to openspec/changes/archive/2026-08-16-withdrawn-add-setline-google-auth/specs/setline-private-account/spec.md diff --git a/openspec/changes/add-setline-google-auth/specs/setline-workout-player/spec.md b/openspec/changes/archive/2026-08-16-withdrawn-add-setline-google-auth/specs/setline-workout-player/spec.md similarity index 100% rename from openspec/changes/add-setline-google-auth/specs/setline-workout-player/spec.md rename to openspec/changes/archive/2026-08-16-withdrawn-add-setline-google-auth/specs/setline-workout-player/spec.md diff --git a/openspec/changes/add-setline-google-auth/tasks.md b/openspec/changes/archive/2026-08-16-withdrawn-add-setline-google-auth/tasks.md similarity index 100% rename from openspec/changes/add-setline-google-auth/tasks.md rename to openspec/changes/archive/2026-08-16-withdrawn-add-setline-google-auth/tasks.md diff --git a/openspec/specs/archive/README.md b/openspec/specs/archive/README.md new file mode 100644 index 0000000..6c2074b --- /dev/null +++ b/openspec/specs/archive/README.md @@ -0,0 +1,14 @@ +# Archived specs + +Specifications for capabilities that were built and then removed. They are kept +because the reasoning is worth having, not because they describe the product. +Nothing here is a current requirement. + +- `account-data-deletion` — archived 2026-08-16. Specified authenticated + self-service deletion of a Setline account and its private cloud copy, via + Better Auth and D1 foreign-key cascades. Every part of the surface it governed + was deleted with the Cloudflare Worker on 2026-08-16: there is no account, no + session, no `workout_state` row and no server to delete anything from. Deleting + the app, or Reset local data, now removes the only copy that exists. The + requirement that the privacy notice describe self-service account deletion was + retired at the same time; the notice now states that nothing is collected. diff --git a/openspec/specs/account-data-deletion/spec.md b/openspec/specs/archive/account-data-deletion/spec.md similarity index 100% rename from openspec/specs/account-data-deletion/spec.md rename to openspec/specs/archive/account-data-deletion/spec.md diff --git a/package.json b/package.json index bf93b36..9f97003 100644 --- a/package.json +++ b/package.json @@ -3,16 +3,14 @@ "version": "0.1.0", "private": true, "packageManager": "pnpm@10.33.2", - "description": "Mobile-first workout execution tracker", + "description": "Device-first iPhone workout execution tracker with a static public site", "engines": { "node": ">=22.13.0" }, "scripts": { - "dev": "wrangler dev", - "build": "tsc --noEmit", - "typecheck": "tsc --noEmit", - "format:check": "prettier --check \"src/**/*.{ts,tsx,css}\" \"worker/**/*.{ts,mjs,mts}\" \"tests/**/*.mjs\" \"*.{json,mjs,ts}\" \".github/workflows/*.{yml,yaml}\"", - "test:coverage": "c8 --all --include='src/**/*.{ts,tsx}' --include='worker/**/*.{ts,mjs}' --include='public/sw.js' --exclude='**/*.d.*' --lines=33 --branches=75 --functions=66 --reporter=text --reporter=json-summary node --test --test-concurrency=1 tests/*.test.mjs", + "format:check": "prettier --check \"tests/**/*.mjs\" \"scripts/**/*.mjs\" \"public/sw.js\" \"public/*.css\" \"*.{json,mjs}\" \".github/workflows/*.{yml,yaml}\"", + "lint": "eslint . --ignore-pattern dist", + "test": "node --test --test-concurrency=1 tests/*.test.mjs", "knip": "knip --no-exit-code --reporter symbols", "knip:strict": "knip --reporter symbols", "quality:unused": "node scripts/check-code-health.mjs unused", @@ -23,37 +21,19 @@ "quality:suppressions": "node scripts/check-code-health.mjs suppressions", "quality:hygiene": "node scripts/check-code-health.mjs hygiene", "quality:native": "node scripts/check-native-code-health.mjs", - "quality": "pnpm format:check && pnpm lint && pnpm typecheck && pnpm test:coverage && pnpm quality:unused && pnpm quality:complexity && pnpm quality:duplication && pnpm quality:cycles && pnpm quality:dependencies && pnpm quality:suppressions && pnpm quality:hygiene", - "check": "pnpm quality", - "types:worker": "wrangler types --config wrangler.jsonc --env-interface CloudflareBindings", - "db:migrate:local": "wrangler d1 migrations apply setline --local", - "db:migrate:remote": "wrangler d1 migrations apply setline --remote", - "deploy": "pnpm run check && wrangler deploy --tag \"$(git rev-parse HEAD)\"", - "test": "node --test --test-concurrency=1 tests/*.test.mjs", - "lint": "eslint . --ignore-pattern dist" - }, - "dependencies": { - "better-auth": "1.6.25", - "drizzle-orm": "0.45.2" + "quality": "pnpm format:check && pnpm lint && pnpm test && pnpm quality:unused && pnpm quality:complexity && pnpm quality:duplication && pnpm quality:cycles && pnpm quality:dependencies && pnpm quality:suppressions && pnpm quality:hygiene", + "check": "pnpm quality" }, "devDependencies": { - "@types/node": "22.19.19", - "c8": "12.0.0", "eslint": "9.39.4", "jscpd": "5.0.14", "knip": "6.32.2", - "prettier": "3.9.6", - "typescript": "5.9.3", - "vite": "8.2.1", - "wrangler": "4.121.0" + "prettier": "3.9.6" }, "type": "module", "pnpm": { "onlyBuiltDependencies": [ - "esbuild", - "sharp", - "unrs-resolver", - "workerd" + "esbuild" ] } } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index bbed4fc..a7ac3bc 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7,20 +7,7 @@ settings: importers: .: - dependencies: - better-auth: - specifier: 1.6.25 - version: 1.6.25(drizzle-orm@0.45.2(kysely@0.29.4))(next@16.2.12(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(react-dom@19.2.6(react@19.2.6))(react@19.2.6) - drizzle-orm: - specifier: 0.45.2 - version: 0.45.2(kysely@0.29.4) devDependencies: - '@types/node': - specifier: 22.19.19 - version: 22.19.19 - c8: - specifier: 12.0.0 - version: 12.0.0 eslint: specifier: 9.39.4 version: 9.39.4(jiti@2.7.0) @@ -33,148 +20,9 @@ importers: prettier: specifier: 3.9.6 version: 3.9.6 - typescript: - specifier: 5.9.3 - version: 5.9.3 - vite: - specifier: 8.2.1 - version: 8.2.1(@types/node@22.19.19)(esbuild@0.28.1)(jiti@2.7.0)(terser@5.47.1)(yaml@2.9.0) - wrangler: - specifier: 4.121.0 - version: 4.121.0 packages: - '@bcoe/v8-coverage@1.0.2': - resolution: {integrity: sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==} - engines: {node: '>=18'} - - '@better-auth/core@1.6.25': - resolution: {integrity: sha512-lMTlhtwyK4NpY9kPF+2rQCRKYpg136d3gM2xl8esxT1PjJx5Nh5YwZvxcYCIjDuO759sx6TCloJTuwcZGG6ZBw==} - peerDependencies: - '@better-auth/utils': 0.4.2 - '@better-fetch/fetch': 1.3.1 - '@cloudflare/workers-types': '>=4' - '@opentelemetry/api': ^1.9.0 - better-call: 1.3.7 - jose: ^6.1.0 - kysely: ^0.28.5 || ^0.29.0 - nanostores: ^1.0.1 - peerDependenciesMeta: - '@cloudflare/workers-types': - optional: true - '@opentelemetry/api': - optional: true - - '@better-auth/drizzle-adapter@1.6.25': - resolution: {integrity: sha512-ru/DeKjFPQUVeKkxF/ScazmPqIY7lwfkAV5Yt4j24wmn1Y8vFwoiPRnHgXUeZqBs10+nubaRwEqLF39CP6EhRw==} - peerDependencies: - '@better-auth/core': ^1.6.25 - '@better-auth/utils': 0.4.2 - drizzle-orm: ^0.45.2 - peerDependenciesMeta: - drizzle-orm: - optional: true - - '@better-auth/kysely-adapter@1.6.25': - resolution: {integrity: sha512-zxiePhtN1YClS1irKYPVwWfN6kYp+QoYlz1hdQUOj8hXyo2aE/ny4RNAb6v332b0+U6Vu88EhYITRPdmvCo6uA==} - peerDependencies: - '@better-auth/core': ^1.6.25 - '@better-auth/utils': 0.4.2 - kysely: ^0.28.17 || ^0.29.0 - peerDependenciesMeta: - kysely: - optional: true - - '@better-auth/memory-adapter@1.6.25': - resolution: {integrity: sha512-GhEzTumc8yfTz+OZ6pMg06BA49xob49x1bX+1mEl/FStDJoSF+6mTfI5M2ytFxaiN89336/aUjkW8u+qRyLexw==} - peerDependencies: - '@better-auth/core': ^1.6.25 - '@better-auth/utils': 0.4.2 - - '@better-auth/mongo-adapter@1.6.25': - resolution: {integrity: sha512-ZtMmjcOdXR2Ziqx5y8ptTOaNpe0snNfALbBUPXJsgeyeRkDJDYzyLZ8MpuvNBTNllNeIFDbiXWAK5k+pEBZrUQ==} - peerDependencies: - '@better-auth/core': ^1.6.25 - '@better-auth/utils': 0.4.2 - mongodb: ^6.0.0 || ^7.0.0 - peerDependenciesMeta: - mongodb: - optional: true - - '@better-auth/prisma-adapter@1.6.25': - resolution: {integrity: sha512-ym7B6Iqcry+/4aQnYpFwqP/GBIiXvjrm/5B6+0qmx8mkTY/apHFTpHuGzUYYNf4vPTtzF3eYY2+s2GOsomKaRg==} - peerDependencies: - '@better-auth/core': ^1.6.25 - '@better-auth/utils': 0.4.2 - '@prisma/client': ^5.0.0 || ^6.0.0 || ^7.0.0 - prisma: ^5.0.0 || ^6.0.0 || ^7.0.0 - peerDependenciesMeta: - '@prisma/client': - optional: true - prisma: - optional: true - - '@better-auth/telemetry@1.6.25': - resolution: {integrity: sha512-2ZfC9lp7tU6Jw/q2Lz/bKfQqGMdMwc/IQDTYdBhvtGi24qInYVnhp2ZCW57hHM9j+fq1ULOtxgg6M3T1LEaihw==} - peerDependencies: - '@better-auth/core': ^1.6.25 - '@better-auth/utils': 0.4.2 - '@better-fetch/fetch': 1.3.1 - - '@better-auth/utils@0.4.2': - resolution: {integrity: sha512-AUxrvu+HaaODsUyzDxFgwd/8RZ1yZaYo42LXKSrU2oGgR38pS1ij8nqQKNgtTWoYGpNevNXtCfgTy6loHveW9A==} - - '@better-fetch/fetch@1.3.1': - resolution: {integrity: sha512-ABkD1WhyfPZprKRQI3bhATjeiFuNWC9PXhfGWqL+sg/gKrM977oFrYkdb4msM3hgUGonr7KlOsOFT5TU2rht9g==} - - '@cloudflare/kv-asset-handler@0.5.0': - resolution: {integrity: sha512-jxQYkj8dSIzc0cD6cMMNdOc1UVjqSqu8BZdor5s8cGjW2I8BjODt/kWPVdY+u9zj3ms75Q5qaZgnxUad83+eAg==} - engines: {node: '>=22.0.0'} - - '@cloudflare/unenv-preset@2.16.1': - resolution: {integrity: sha512-ECxObrMfyTl5bhQf/lZCXwo5G6xX9IAUo+nDMKK4SZ8m4Jvvxp52vilxyySSWh2YTZz8+HQ07qGH/2rEom1vDw==} - peerDependencies: - unenv: 2.0.0-rc.24 - workerd: '>1.20260305.0 <2.0.0-0' - peerDependenciesMeta: - workerd: - optional: true - - '@cloudflare/workerd-darwin-64@1.20260804.1': - resolution: {integrity: sha512-191/PPEFicRK2wK69eXzSjnLgHL79k7zR2VUpyIr8rhFgGns1b5bTHgnBuUrgU2LPbEtwbE5eL2hJ0uhLAFEow==} - engines: {node: '>=16'} - cpu: [x64] - os: [darwin] - - '@cloudflare/workerd-darwin-arm64@1.20260804.1': - resolution: {integrity: sha512-aI2cAFLsrNkSz3kLSQrgrO9ICTfY7jb2h0jgaWDE9mQLQQDfpXeYrKWt07tTgMmeNP79o9w3NZe3aqtt8mTGHQ==} - engines: {node: '>=16'} - cpu: [arm64] - os: [darwin] - - '@cloudflare/workerd-linux-64@1.20260804.1': - resolution: {integrity: sha512-KBCjxBIlN2jucfQGaTK4EgmPsWzQgYR/zYhPfi3mkWwdoTyG1dgrt2aizKps/SYse85ci/SOxojKk0/K7vstPw==} - engines: {node: '>=16'} - cpu: [x64] - os: [linux] - - '@cloudflare/workerd-linux-arm64@1.20260804.1': - resolution: {integrity: sha512-7lswfarBZ7xkHpTFrNb74ExwOltIalVaASc+GOYfCNtnwFxK/JZSVByfm/hnZEBtrHU7fMY2z7dYT64rwS0pHg==} - engines: {node: '>=16'} - cpu: [arm64] - os: [linux] - - '@cloudflare/workerd-windows-64@1.20260804.1': - resolution: {integrity: sha512-GOgRWYtxISN5rAWfx3K7zubt3xEn0/ZPFrbcLL+GwT4ouCKyNoHqfT1cPNB6Nx7t8BHEjnuTG7gkHO4Wd5ORdg==} - engines: {node: '>=16'} - cpu: [x64] - os: [win32] - - '@cspotcode/source-map-support@0.8.1': - resolution: {integrity: sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==} - engines: {node: '>=12'} - '@emnapi/core@1.11.2': resolution: {integrity: sha512-TC8MkTuZUtcTSiFeuC0ksCh9QIJ5+F21MvZ4Wn4ORfYaFJ/0dsiudv5tVkejgwZlwQ39jL9WWDe2lz8x0WglOA==} @@ -184,162 +32,6 @@ packages: '@emnapi/wasi-threads@1.2.2': resolution: {integrity: sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA==} - '@esbuild/aix-ppc64@0.28.1': - resolution: {integrity: sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==} - engines: {node: '>=18'} - cpu: [ppc64] - os: [aix] - - '@esbuild/android-arm64@0.28.1': - resolution: {integrity: sha512-34EGEbCIAgosYz6goLcopX6Mo7NyGv9tfwEM2/7Ce2VcVRk568iSvniGWcUXIy7wEDR1wzolcxcriFVrWYcwBg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [android] - - '@esbuild/android-arm@0.28.1': - resolution: {integrity: sha512-0k2F129Xdio1TdJfzJ8sy1Q47vUD2NnwdhiAf7drUN1EBTfPf4hsFCtmMgu/6m8JSzsBrlmVjudMBQqOfG8usQ==} - engines: {node: '>=18'} - cpu: [arm] - os: [android] - - '@esbuild/android-x64@0.28.1': - resolution: {integrity: sha512-dbwY7ltSMDWsRatcRpCnES4F+im88OCUgGZjy52shC7GqHRE/cYlxNbB4Z4UpJswpcc4Qxd2oE/ufM0p61IKng==} - engines: {node: '>=18'} - cpu: [x64] - os: [android] - - '@esbuild/darwin-arm64@0.28.1': - resolution: {integrity: sha512-TZbWkQY7kvTAXbXUT7uVACR5cMHsDiSz9z7ZKAX/RTq/WJEk3QyRr0wZpNhBDX+/0CtdqUIJlOiodQcta6tY3Q==} - engines: {node: '>=18'} - cpu: [arm64] - os: [darwin] - - '@esbuild/darwin-x64@0.28.1': - resolution: {integrity: sha512-zfdzgK9ACBNZLI/CyHTOx81SyNbM6YXn7rxSgX97VjyiPl9W1i4Ka4fgKECEoFCKGpvBj5qArWIGgQjOwkgskQ==} - engines: {node: '>=18'} - cpu: [x64] - os: [darwin] - - '@esbuild/freebsd-arm64@0.28.1': - resolution: {integrity: sha512-wG2EA8ENdEI0qhkSZMjfqrdY+ziCYCPMmtZjjIwOmXFjmyzEHn+UUxk5of+SYsjtfs3VpnlC7QLzSI5hY/rOAw==} - engines: {node: '>=18'} - cpu: [arm64] - os: [freebsd] - - '@esbuild/freebsd-x64@0.28.1': - resolution: {integrity: sha512-i7dZ9vQgnvSCzi/rYCXNgtF/U+eKZNJBzu3eTQbRgHnM7tNSizLOkRFAl3qzVc/Op/u5YkHHa4pf/3DOYHthLQ==} - engines: {node: '>=18'} - cpu: [x64] - os: [freebsd] - - '@esbuild/linux-arm64@0.28.1': - resolution: {integrity: sha512-yHs+0uc8+nvEAfAfxrWQKK5peSNzBc4PegcMO0EJ2hT71uA7vB8Ihg2e77R2P7SG5uYjPbHlLLmve4LLLRCf0g==} - engines: {node: '>=18'} - cpu: [arm64] - os: [linux] - - '@esbuild/linux-arm@0.28.1': - resolution: {integrity: sha512-qVXBOHQS+d5Y722GwJzJUtOLlX7km3CraOaGormF1pDtPd2C/l1SHRPgjLunLGe51Sh5YYWKMFDyV4SxgMQYTQ==} - engines: {node: '>=18'} - cpu: [arm] - os: [linux] - - '@esbuild/linux-ia32@0.28.1': - resolution: {integrity: sha512-d1z4ZuP0ajrfz/FhGT4vv278rX8KnPPJx8i5+AtK7TYbx9Le9F1hyzurZpkEyjkGa9dUGhQow4C1NmeGvqxN2w==} - engines: {node: '>=18'} - cpu: [ia32] - os: [linux] - - '@esbuild/linux-loong64@0.28.1': - resolution: {integrity: sha512-M5sRjUVZrkm1OAPR3dlOYzNmN+loZKGVi1VUQGrwuqLcbR6qeAz+famMhjASeH3YVKvZz+zT1jlh/keC3Rj/lg==} - engines: {node: '>=18'} - cpu: [loong64] - os: [linux] - - '@esbuild/linux-mips64el@0.28.1': - resolution: {integrity: sha512-mRObBZeHh2OxcBFPWE/FjylkRgZdYuiTR3vaTozquCGOH14iP9oN4x4Ge81CoIDYQrXmIxpFumJBu5MtZpnQJQ==} - engines: {node: '>=18'} - cpu: [mips64el] - os: [linux] - - '@esbuild/linux-ppc64@0.28.1': - resolution: {integrity: sha512-slScBsMAb3GFDcdrCgLwZtPYRoH2H/youv10QiZyRjmsP48fznoveWytSgCI/R0ZcUgpc0ZhIUEx6LHts8yrfQ==} - engines: {node: '>=18'} - cpu: [ppc64] - os: [linux] - - '@esbuild/linux-riscv64@0.28.1': - resolution: {integrity: sha512-kw0owk1o0GFETUJyW0jc0G4Yzs0BHZn0JDZ8JRT088vjJYX777BAs1fDGxAC+q831qOs2DTC96mNsG2opdfyyQ==} - engines: {node: '>=18'} - cpu: [riscv64] - os: [linux] - - '@esbuild/linux-s390x@0.28.1': - resolution: {integrity: sha512-/lAIjX8aYFRByhh6L5rYtPEDRqa9de/4V/juOXcta5frjvzXO4/sqEtyytse0g3zZFuWu5cDN0MkLz2qRDD2Ag==} - engines: {node: '>=18'} - cpu: [s390x] - os: [linux] - - '@esbuild/linux-x64@0.28.1': - resolution: {integrity: sha512-u/anNYF2mmVOEDwLtnQ1wOr3EZ9sTNGLWrsYGYwHWzGA3Si84IOkHXlbWTD1NB+9/1lcnweYKO54uhxZydNzfA==} - engines: {node: '>=18'} - cpu: [x64] - os: [linux] - - '@esbuild/netbsd-arm64@0.28.1': - resolution: {integrity: sha512-oks0DYbLwWMmaakTsCb+zL4E+aHRVLom9IJZOAthMQEPiQmydXHkziYEsGYRx0uNV/IjEKGAV941JzH02pflqw==} - engines: {node: '>=18'} - cpu: [arm64] - os: [netbsd] - - '@esbuild/netbsd-x64@0.28.1': - resolution: {integrity: sha512-aeL6lAnN89Hz43Mlh1G8ARasbuoYvSITDEx0tHh5b7jJnHcssqgjy9Yx430GDpmCa6OyrKoS0aNRjKundRizGg==} - engines: {node: '>=18'} - cpu: [x64] - os: [netbsd] - - '@esbuild/openbsd-arm64@0.28.1': - resolution: {integrity: sha512-MEFJe5C3R8pwXdZ5Y21oo6m7ePiS0d9pWucn99O/wvyJZChoIQKrQDxKrGeW8F5+T0okTHesAmDeiHDTIq0V/Q==} - engines: {node: '>=18'} - cpu: [arm64] - os: [openbsd] - - '@esbuild/openbsd-x64@0.28.1': - resolution: {integrity: sha512-i/ZLIOafE0Z8cI/XANJAixoJL/uRAoS2xOA3rb0xN+KK0K177cMAsQYkzHtBrtMXAKuAc7HGgcWiZ/sRC1Nxgw==} - engines: {node: '>=18'} - cpu: [x64] - os: [openbsd] - - '@esbuild/openharmony-arm64@0.28.1': - resolution: {integrity: sha512-ge+Z7EXFNt2BO1oAMsVpiQ8EwndV9i1xXerAeTIK7AtPs3bKFXQM7nlRxDSIUIMeueR1CNXxqztLzdNeReKBJg==} - engines: {node: '>=18'} - cpu: [arm64] - os: [openharmony] - - '@esbuild/sunos-x64@0.28.1': - resolution: {integrity: sha512-BEjgtECkL3vY+SaSQ6nzVfiALUeFxpawyp8Jmf5PtYhf1Ug40N1h/hxlhts+f1FvSvarEigdxS3BlSMI2PJLcQ==} - engines: {node: '>=18'} - cpu: [x64] - os: [sunos] - - '@esbuild/win32-arm64@0.28.1': - resolution: {integrity: sha512-lCv9eK/H6ZJWbE7bh2nw54CZ9M2nupBxJcTsdk/QQnWkdSjKGuxmmH8/GWrlT1eMmZfn4dGcCjRte397WqfQXA==} - engines: {node: '>=18'} - cpu: [arm64] - os: [win32] - - '@esbuild/win32-ia32@0.28.1': - resolution: {integrity: sha512-zvb/mB2bSCoJOpoCBgYKKpX6YM6mJBlBUVUtVj41DlZJVEB6/0CKlRYxP5wWl1C1ILiCoAU5wZZ4q1P3qeS6Eg==} - engines: {node: '>=18'} - cpu: [ia32] - os: [win32] - - '@esbuild/win32-x64@0.28.1': - resolution: {integrity: sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A==} - engines: {node: '>=18'} - cpu: [x64] - os: [win32] - '@eslint-community/eslint-utils@4.9.1': resolution: {integrity: sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} @@ -398,517 +90,116 @@ packages: resolution: {integrity: sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==} engines: {node: '>=18.18'} - '@img/colour@1.1.0': - resolution: {integrity: sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ==} - engines: {node: '>=18'} - - '@img/sharp-darwin-arm64@0.34.5': - resolution: {integrity: sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [arm64] - os: [darwin] - - '@img/sharp-darwin-arm64@0.35.2': - resolution: {integrity: sha512-eEieHsMksAW4IiO5NzauESRl2D2qz3J/kwUxUrSfV06A93eEaRfMpHXyUb1mAqrR7i8U9A0GRqE9pjn6u1Jjpg==} - engines: {node: '>=20.9.0'} - cpu: [arm64] - os: [darwin] - - '@img/sharp-darwin-x64@0.34.5': - resolution: {integrity: sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [x64] - os: [darwin] - - '@img/sharp-darwin-x64@0.35.2': - resolution: {integrity: sha512-BaktuGPCeHJMARpodR8jK4uKiZrPAy9WrfQW0sdI37clracq8Bp01AYS3SZgi5FS/y5twa9t4+LIuuxQjqRrWw==} - engines: {node: '>=20.9.0'} - cpu: [x64] - os: [darwin] + '@napi-rs/wasm-runtime@1.2.3': + resolution: {integrity: sha512-UMduMbqO5s5zF2NkNacMT/yK5Y5QiKvWr2+50bzIIxFDwVJ2h49b+oyjaCGPhJxd2/gC2x39EHv/gHVuu36x2Q==} + engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} + peerDependencies: + '@emnapi/core': ^1.7.1 || ^2.0.0-alpha.4 + '@emnapi/runtime': ^1.7.1 || ^2.0.0-alpha.4 - '@img/sharp-freebsd-wasm32@0.35.2': - resolution: {integrity: sha512-YoAxdnd8hPUkvLHd3bWY+YA8nw3xM/RyRopYucNsWHVSan8NLVM3X2volsfoRDcXdUJPg6tXahSd7HXPK7lRnw==} - engines: {node: '>=20.9.0'} - os: [freebsd] + '@oxc-parser/binding-android-arm-eabi@0.143.0': + resolution: {integrity: sha512-n9uozULWflPqBtdmI8lAabLqGKNgLVNN0ZH8HfgCwpKGNtzRzauB76jTiW/3YLkcA7N1zskpi9GdVnZuu1SAvg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] - '@img/sharp-libvips-darwin-arm64@1.2.4': - resolution: {integrity: sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==} + '@oxc-parser/binding-android-arm64@0.143.0': + resolution: {integrity: sha512-9BbdjHETk6O3zH/DDid9IgBtF0GlpLabNKN231uraXpRDSfY+iiZxTP5bk1Z63GBownVdhdINFIeddmMz4MzpQ==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] - os: [darwin] + os: [android] - '@img/sharp-libvips-darwin-arm64@1.3.1': - resolution: {integrity: sha512-4V/M3roRMTYjiwZY9IOVQOE8OyeCxFAkYmyZDrZl51uOKjibm3oeEJ4WAmLxutAfzFbC9jqUiPs2gbnGflH+7g==} + '@oxc-parser/binding-darwin-arm64@0.143.0': + resolution: {integrity: sha512-gh+6ecoHUy4/sUcolBl/1qPXKBbYNxFY0Pk0ujgQvINTMSftJY7o4yb8gOkDJPeZeB8+a+u7xTe6umoP8N5HFA==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] os: [darwin] - '@img/sharp-libvips-darwin-x64@1.2.4': - resolution: {integrity: sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==} + '@oxc-parser/binding-darwin-x64@0.143.0': + resolution: {integrity: sha512-qd1hl2d+lXgHv/VQ/M9qm8TrMC5T4RqDBwtOnl+1D0QMjwcz+8AaB4JSg8STgeag0GP6a6L74XEGAsrTSJWNzQ==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [darwin] - '@img/sharp-libvips-darwin-x64@1.3.1': - resolution: {integrity: sha512-c0/DxItpJv2+dGhgycJBBgotdqruGYDvA79drdh0MD1dFpy7JzJ/PlXwi1H4rFf0eTy8tgbI91aHDnZIceY3jQ==} + '@oxc-parser/binding-freebsd-x64@0.143.0': + resolution: {integrity: sha512-M5XXcNa7aOqLPKTR41msfghKu2yQ4xWvCm11/gwU0JzOzHNk5sgW//rVEjJ+LO48+VDAMzXTSzurUVxIDKwozw==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] - os: [darwin] - - '@img/sharp-libvips-linux-arm64@1.2.4': - resolution: {integrity: sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==} - cpu: [arm64] - os: [linux] - libc: [glibc] + os: [freebsd] - '@img/sharp-libvips-linux-arm64@1.3.1': - resolution: {integrity: sha512-JznefmcK9j1JKPz8AkQDh89kjojubyfOasWBPKfzMIhPwsgDy9evpE/naJTXXXmghS1iFwR8u/kTwh/I2/+GCw==} - cpu: [arm64] + '@oxc-parser/binding-linux-arm-gnueabihf@0.143.0': + resolution: {integrity: sha512-T/GXusuOkPNQhCQCSBbcU/N8j0rAypuDBl1IyFK+lyYT594XsVz80clPC/OtbSSpBGyJxj8uYEfctxVuxVYoww==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] os: [linux] - libc: [glibc] - '@img/sharp-libvips-linux-arm@1.2.4': - resolution: {integrity: sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==} + '@oxc-parser/binding-linux-arm-musleabihf@0.143.0': + resolution: {integrity: sha512-oKu4RcBlXSqo3OC62dp6YTnQaZIurNDpCX3BnAM3+bJxt7s8J2TJKMnC0UYer1qhlRaDCg6wkTaTw+2IlsZ12w==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm] os: [linux] - libc: [glibc] - '@img/sharp-libvips-linux-arm@1.3.1': - resolution: {integrity: sha512-aGGy9aWzXgHBG7HNyQPWorZthlp7+x6fDRoPAQbGO3ThcttuTyKIx3NuSHb6zb4gBNq6/yNn9f1cy9nFKS/Vmg==} - cpu: [arm] + '@oxc-parser/binding-linux-arm64-gnu@0.143.0': + resolution: {integrity: sha512-WJBbD186AZmMGaSIhlktC+rPl8L3peCTXAh88Ih9uEvK0en2mPojGyCGYiL6mHtV1RPV3JyfJW5t6n5hh0lXhA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-ppc64@1.2.4': - resolution: {integrity: sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==} - cpu: [ppc64] + '@oxc-parser/binding-linux-arm64-musl@0.143.0': + resolution: {integrity: sha512-t1AcYOwEzgceadT4v5e+vaCCb0AncCA3v5AyzfBAz/tMq11qzVccXKzNHtkWdjBsgvTKwRkaUF3QvT4kot8vcQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] os: [linux] - libc: [glibc] + libc: [musl] - '@img/sharp-libvips-linux-ppc64@1.3.1': - resolution: {integrity: sha512-1EkwGNCZk6iWNCMWqrvdJ+r1j0PT1zIz60CNPhYnJlK/zyeWqlsPZIe+ocBVqPF8k/Ssee/NCk+tE9Ryrko6ng==} + '@oxc-parser/binding-linux-ppc64-gnu@0.143.0': + resolution: {integrity: sha512-RsnO/NoD8376LMJq8JS8TwI0ieNaFRTuNe2GVJntQg6gwZNMENZsEbknHdVwjpOmxdGLGodcwaGSbAeRr5Bgjw==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [ppc64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-riscv64@1.2.4': - resolution: {integrity: sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==} + '@oxc-parser/binding-linux-riscv64-gnu@0.143.0': + resolution: {integrity: sha512-48fSVfR9TZi5CASZFyv0VC6z6BCoeihFsX031mAD/oSH7d9PYsPgIqza7d9mjP7Z2KTEpTFyH6SIu0Ui6R1vdg==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [riscv64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-riscv64@1.3.1': - resolution: {integrity: sha512-Ilays+w2bXdnxzxtQdmXR62u8o8GYa3eL4+Gr+1KiE4xperMZUslRaVPJwwPkzlHEjGfXAfRVAa/7CYCtSqsBw==} + '@oxc-parser/binding-linux-riscv64-musl@0.143.0': + resolution: {integrity: sha512-T8CpdD+SfE01DnIOD4HpVxu0ZJOfMJ/VhCvikKfaXAxkZ+9veyLM/D2hpi7Y2hFUyPmVQO3FNZHmYzV/WlVR4g==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [riscv64] os: [linux] - libc: [glibc] - - '@img/sharp-libvips-linux-s390x@1.2.4': - resolution: {integrity: sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==} - cpu: [s390x] - os: [linux] - libc: [glibc] + libc: [musl] - '@img/sharp-libvips-linux-s390x@1.3.1': - resolution: {integrity: sha512-VfBwVHQTbRoj4XlpA/KLZ7ltgMpz+4WSejFzQ+GnoImjo1PtEJ59QB2qR1xQEeRPYIkNrPIm2L4cICMvz4C2ew==} + '@oxc-parser/binding-linux-s390x-gnu@0.143.0': + resolution: {integrity: sha512-QLdeMsCcacenPEFsfxnBUDF1y6opyz5+fmOz9bfD5Y7fiGCMupUCuB3KTPQhNwshIG1P9fPqar9MHxuBDd4bwQ==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [s390x] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-x64@1.2.4': - resolution: {integrity: sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==} + '@oxc-parser/binding-linux-x64-gnu@0.143.0': + resolution: {integrity: sha512-659ujfqLy6k7cuH3sbzhd8b+ztSq+i6E2E9pG78Q0BmHjAExfGIdgc8cGgMdwAozDXeZFHkJ+LXYJdWsaGdgyw==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] libc: [glibc] - '@img/sharp-libvips-linux-x64@1.3.1': - resolution: {integrity: sha512-+c8ukgwU62DS54nCAjw7keOfHUkmr0B5QHEdcOqRnodF/MNXJbVI8Eopoj4B/0H8Asr65I+A4Amrn7a85/md6A==} + '@oxc-parser/binding-linux-x64-musl@0.143.0': + resolution: {integrity: sha512-/Mw/9j4TfZcnKphPrzOE6t4MMknXadcAAuVUlDRTF/ETWB5xOgQvOJV2Mh9We/bWxZdoxaGAdc+hy4GuYwQ2yQ==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [x64] os: [linux] - libc: [glibc] - - '@img/sharp-libvips-linuxmusl-arm64@1.2.4': - resolution: {integrity: sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==} - cpu: [arm64] - os: [linux] libc: [musl] - '@img/sharp-libvips-linuxmusl-arm64@1.3.1': - resolution: {integrity: sha512-qlKb/pwbkAi1WMsJrYHk7CuDrd12s27U2QnRhFYUoJNrRCmkosMTttuRFat/DDB3IlDm5qE1TJgZ4JDnHX8Ldw==} + '@oxc-parser/binding-openharmony-arm64@0.143.0': + resolution: {integrity: sha512-8rIKWR2BFuifbIK/1XB9wTaSdtuJ25dlE7ZQYDnEwj/2xH2vHsxnvIjHT3ZjSVuLLwGGlSslIG/fbOJ8TV8rTw==} + engines: {node: ^20.19.0 || >=22.12.0} cpu: [arm64] - os: [linux] - libc: [musl] - - '@img/sharp-libvips-linuxmusl-x64@1.2.4': - resolution: {integrity: sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==} - cpu: [x64] - os: [linux] - libc: [musl] - - '@img/sharp-libvips-linuxmusl-x64@1.3.1': - resolution: {integrity: sha512-yO21HwoUVLN8Qa+/SBjQLMYwBWAVJjeGPNe+hc0OUeMeifEtJqu5a1c4HayE1nNpDih9y3/KkoltfkDodmKAlg==} - cpu: [x64] - os: [linux] - libc: [musl] - - '@img/sharp-linux-arm64@0.34.5': - resolution: {integrity: sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [arm64] - os: [linux] - libc: [glibc] - - '@img/sharp-linux-arm64@0.35.2': - resolution: {integrity: sha512-af12Pnd0ZGu2HfP8NayB0kk6eC/lrfbQE6HlR4jD+34wdJ1Vw9TF6TMn6ZvffT+WgqVsl0hRbmNvz2u/23VmwA==} - engines: {node: '>=20.9.0'} - cpu: [arm64] - os: [linux] - libc: [glibc] - - '@img/sharp-linux-arm@0.34.5': - resolution: {integrity: sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [arm] - os: [linux] - libc: [glibc] - - '@img/sharp-linux-arm@0.35.2': - resolution: {integrity: sha512-SE4kzF2mepn6z+6E7L6lsV8FzuLL6IPQdyX8ZiwROAG/G8td+hP/m7FsFPwidtrF19gvajuC9l6TxAVcsA4S7A==} - engines: {node: '>=20.9.0'} - cpu: [arm] - os: [linux] - libc: [glibc] - - '@img/sharp-linux-ppc64@0.34.5': - resolution: {integrity: sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [ppc64] - os: [linux] - libc: [glibc] - - '@img/sharp-linux-ppc64@0.35.2': - resolution: {integrity: sha512-hYSBm7zcNtDCozCxQHYZJiu63b/bXsgRZuOxCIBZsStMM9Vap47iFHdbX4kCvQsblPB/k+clhELpdQJHQLSHvg==} - engines: {node: '>=20.9.0'} - cpu: [ppc64] - os: [linux] - libc: [glibc] - - '@img/sharp-linux-riscv64@0.34.5': - resolution: {integrity: sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [riscv64] - os: [linux] - libc: [glibc] - - '@img/sharp-linux-riscv64@0.35.2': - resolution: {integrity: sha512-qQt0Kc13+Hoan/Awq/qMSQw3L+RI1NCRPgD5cUJ/1WSSmIoysLOc72jlRM3E0OHN9Yr313jgeQ2T+zW+F03QFA==} - engines: {node: '>=20.9.0'} - cpu: [riscv64] - os: [linux] - libc: [glibc] - - '@img/sharp-linux-s390x@0.34.5': - resolution: {integrity: sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [s390x] - os: [linux] - libc: [glibc] - - '@img/sharp-linux-s390x@0.35.2': - resolution: {integrity: sha512-E4fLLfRPzDLlEeDaTzI98OFLcv++WL5ChLLMwPoVd0CIoZQqupBSNbOisPL5am9XsbQ9T84+iiMpUvbFtkunbA==} - engines: {node: '>=20.9.0'} - cpu: [s390x] - os: [linux] - libc: [glibc] - - '@img/sharp-linux-x64@0.34.5': - resolution: {integrity: sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [x64] - os: [linux] - libc: [glibc] - - '@img/sharp-linux-x64@0.35.2': - resolution: {integrity: sha512-gi0zFJJRLswfCZmHtJdikXPOc5u7qamSOS3NHedLqLd4W8Q0NqjdBr6TTRIgsfFjqfTsHFgdfvJ9LwqSgcHiAA==} - engines: {node: '>=20.9.0'} - cpu: [x64] - os: [linux] - libc: [glibc] - - '@img/sharp-linuxmusl-arm64@0.34.5': - resolution: {integrity: sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [arm64] - os: [linux] - libc: [musl] - - '@img/sharp-linuxmusl-arm64@0.35.2': - resolution: {integrity: sha512-siWbOW1u6HFnFLrp0waKyW7VEf7jYvcDWdrXEFa8AkdAQgEvuu5Fz8/Y70w9EeqAdwDtfU012BhEHHaDqvQNzg==} - engines: {node: '>=20.9.0'} - cpu: [arm64] - os: [linux] - libc: [musl] - - '@img/sharp-linuxmusl-x64@0.34.5': - resolution: {integrity: sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [x64] - os: [linux] - libc: [musl] - - '@img/sharp-linuxmusl-x64@0.35.2': - resolution: {integrity: sha512-YBqMMcjDi4QGYiSn4vNOYBhmlC4z5AXqkOUUqI2e0AFA4urNv4ESgOgwNl3K+4etQhha0twXlzeF20bbULm9Yg==} - engines: {node: '>=20.9.0'} - cpu: [x64] - os: [linux] - libc: [musl] - - '@img/sharp-wasm32@0.34.5': - resolution: {integrity: sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [wasm32] - - '@img/sharp-wasm32@0.35.2': - resolution: {integrity: sha512-Mrv4JQNYVQ94xH+jzZ9r+gowleN8mv2FTgKT+PI6bx5C0G8TdNYndu161pg2i7uoBwxy2ImPMHrJOM2LZef7Bw==} - engines: {node: '>=20.9.0'} - - '@img/sharp-webcontainers-wasm32@0.35.2': - resolution: {integrity: sha512-QNV27pxs9wpApEiCfvHM1RDoP1w1+2KrUWWDPEhEwg+latvOrfuhWrHWZKwdSFwU6jh3myjw/yOCRsUIuOft3g==} - engines: {node: '>=20.9.0'} - cpu: [wasm32] - - '@img/sharp-win32-arm64@0.34.5': - resolution: {integrity: sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [arm64] - os: [win32] - - '@img/sharp-win32-arm64@0.35.2': - resolution: {integrity: sha512-BiVRYc/t6/Vl3e1hBx0hugG4oN9Pydf4fgMSpxTQJmwGUg/YoXTWHiFeRymHfCZzifxu4F4rpk/I67D0LQ20wQ==} - engines: {node: '>=20.9.0'} - cpu: [arm64] - os: [win32] - - '@img/sharp-win32-ia32@0.34.5': - resolution: {integrity: sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [ia32] - os: [win32] - - '@img/sharp-win32-ia32@0.35.2': - resolution: {integrity: sha512-YYEhx9PImCC7T0tI8JDMi4DB9LwLCXCU5OWNYEXAxh5Q1ShKkyC6byxzoBJ3gEFDnH2lQckWuDe70G7mB2XJog==} - engines: {node: ^20.9.0} - cpu: [ia32] - os: [win32] - - '@img/sharp-win32-x64@0.34.5': - resolution: {integrity: sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - cpu: [x64] - os: [win32] - - '@img/sharp-win32-x64@0.35.2': - resolution: {integrity: sha512-imoOyBcoM/iiUr4J6VPpCNjPnjvP/Gks95898yB8YqoGGYmHYbOyCuNv9FMhFgtaiHFGbHW8bxKqRV6VjtXThQ==} - engines: {node: '>=20.9.0'} - cpu: [x64] - os: [win32] - - '@istanbuljs/schema@0.1.6': - resolution: {integrity: sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw==} - engines: {node: '>=8'} - - '@jridgewell/gen-mapping@0.3.13': - resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==} - - '@jridgewell/resolve-uri@3.1.2': - resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} - engines: {node: '>=6.0.0'} - - '@jridgewell/source-map@0.3.11': - resolution: {integrity: sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==} - - '@jridgewell/sourcemap-codec@1.5.5': - resolution: {integrity: sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==} - - '@jridgewell/trace-mapping@0.3.31': - resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} - - '@jridgewell/trace-mapping@0.3.9': - resolution: {integrity: sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==} - - '@napi-rs/wasm-runtime@1.2.3': - resolution: {integrity: sha512-UMduMbqO5s5zF2NkNacMT/yK5Y5QiKvWr2+50bzIIxFDwVJ2h49b+oyjaCGPhJxd2/gC2x39EHv/gHVuu36x2Q==} - engines: {node: ^20.19.0 || ^22.13.0 || >=23.5.0} - peerDependencies: - '@emnapi/core': ^1.7.1 || ^2.0.0-alpha.4 - '@emnapi/runtime': ^1.7.1 || ^2.0.0-alpha.4 - - '@next/env@16.2.12': - resolution: {integrity: sha512-d0Z5Bc13Fa4nR8pFAKx2jay2yhJM16vlfHbTzYnUQAxlNb6B6lmn4hjt69lYNt4kRtyYP6gEM49lPRHNbIyneg==} - - '@next/swc-darwin-arm64@16.2.12': - resolution: {integrity: sha512-0W1R0teHWJrqKX0FH20IzzIWAOuGtBxPGuObrxy1lE8hQvCFj49KE8a3WUg0D7sq6rn6zkM4c7YGUnhudBS6oA==} - engines: {node: '>= 10'} - cpu: [arm64] - os: [darwin] - - '@next/swc-darwin-x64@16.2.12': - resolution: {integrity: sha512-Hy5Ls099+aFUmOLmIgPfLqNi6iCwhL3uQCssz5rWk+5Nkc6TUKCE83DY5BbNylfm3+mfwcSFnLRfrZDJhVxdtw==} - engines: {node: '>= 10'} - cpu: [x64] - os: [darwin] - - '@next/swc-linux-arm64-gnu@16.2.12': - resolution: {integrity: sha512-+YqU2h1cQkHsGfvjAsrSmst8UIFBibBGm5x3Xgel8NLMiDQtNOM4sM2GOEMvG5YiOBNeN/Ykk8cQC2S0Xrqljg==} - engines: {node: '>= 10'} - cpu: [arm64] - os: [linux] - libc: [glibc] - - '@next/swc-linux-arm64-musl@16.2.12': - resolution: {integrity: sha512-0qjhiYBaKAqF63LA1ZWAAnKTzFUguAaZiRa5etMLGGPj/B6uEVjtIZldIzFEp3wHlB0koK6aTzqPtSdplTCjoA==} - engines: {node: '>= 10'} - cpu: [arm64] - os: [linux] - libc: [musl] - - '@next/swc-linux-x64-gnu@16.2.12': - resolution: {integrity: sha512-7A3q26W+h7gnA15uqBToNuDqBEFZZcqh0mW2mn4AJh/G5pdg2RVE3n4slzLEliASZFG3NmsbEzng/x2Sh09mBg==} - engines: {node: '>= 10'} - cpu: [x64] - os: [linux] - libc: [glibc] - - '@next/swc-linux-x64-musl@16.2.12': - resolution: {integrity: sha512-qSjL/uppm+cbh21s72Ss8gkiOhQ4dExWHNGOWy6eZV7STj5WsKehgxT61beSsOj+YYQuTplL376lOCdMQU5T8w==} - engines: {node: '>= 10'} - cpu: [x64] - os: [linux] - libc: [musl] - - '@next/swc-win32-arm64-msvc@16.2.12': - resolution: {integrity: sha512-X6hzsOUJac/e7AWSbn9gQ9nzHld1xWP5iyjHpYWvud8pufB679O1xg4JDyKr8Xd69Jvd+kM2Der6uftiZCmjYA==} - engines: {node: '>= 10'} - cpu: [arm64] - os: [win32] - - '@next/swc-win32-x64-msvc@16.2.12': - resolution: {integrity: sha512-F6fakeHuFTLOPt0bslQJdf+xtT+WIP9DVn/m4y1w1mRnVPyh3D/cNvzlRkxM444xfm+IvvYNSOrKiA2CDJ0Uxw==} - engines: {node: '>= 10'} - cpu: [x64] - os: [win32] - - '@noble/ciphers@2.2.0': - resolution: {integrity: sha512-Z6pjIZ/8IJcCGzb2S/0Px5J81yij85xASuk1teLNeg75bfT07MV3a/O2Mtn1I2se43k3lkVEcFaR10N4cgQcZA==} - engines: {node: '>= 20.19.0'} - - '@noble/hashes@2.2.0': - resolution: {integrity: sha512-IYqDGiTXab6FniAgnSdZwgWbomxpy9FtYvLKs7wCUs2a8RkITG+DFGO1DM9cr+E3/RgADRpFjrKVaJ1z6sjtEg==} - engines: {node: '>= 20.19.0'} - - '@opentelemetry/semantic-conventions@1.43.0': - resolution: {integrity: sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg==} - engines: {node: '>=14'} - - '@oxc-parser/binding-android-arm-eabi@0.143.0': - resolution: {integrity: sha512-n9uozULWflPqBtdmI8lAabLqGKNgLVNN0ZH8HfgCwpKGNtzRzauB76jTiW/3YLkcA7N1zskpi9GdVnZuu1SAvg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm] - os: [android] - - '@oxc-parser/binding-android-arm64@0.143.0': - resolution: {integrity: sha512-9BbdjHETk6O3zH/DDid9IgBtF0GlpLabNKN231uraXpRDSfY+iiZxTP5bk1Z63GBownVdhdINFIeddmMz4MzpQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [android] - - '@oxc-parser/binding-darwin-arm64@0.143.0': - resolution: {integrity: sha512-gh+6ecoHUy4/sUcolBl/1qPXKBbYNxFY0Pk0ujgQvINTMSftJY7o4yb8gOkDJPeZeB8+a+u7xTe6umoP8N5HFA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [darwin] - - '@oxc-parser/binding-darwin-x64@0.143.0': - resolution: {integrity: sha512-qd1hl2d+lXgHv/VQ/M9qm8TrMC5T4RqDBwtOnl+1D0QMjwcz+8AaB4JSg8STgeag0GP6a6L74XEGAsrTSJWNzQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [darwin] - - '@oxc-parser/binding-freebsd-x64@0.143.0': - resolution: {integrity: sha512-M5XXcNa7aOqLPKTR41msfghKu2yQ4xWvCm11/gwU0JzOzHNk5sgW//rVEjJ+LO48+VDAMzXTSzurUVxIDKwozw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [freebsd] - - '@oxc-parser/binding-linux-arm-gnueabihf@0.143.0': - resolution: {integrity: sha512-T/GXusuOkPNQhCQCSBbcU/N8j0rAypuDBl1IyFK+lyYT594XsVz80clPC/OtbSSpBGyJxj8uYEfctxVuxVYoww==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm] - os: [linux] - - '@oxc-parser/binding-linux-arm-musleabihf@0.143.0': - resolution: {integrity: sha512-oKu4RcBlXSqo3OC62dp6YTnQaZIurNDpCX3BnAM3+bJxt7s8J2TJKMnC0UYer1qhlRaDCg6wkTaTw+2IlsZ12w==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm] - os: [linux] - - '@oxc-parser/binding-linux-arm64-gnu@0.143.0': - resolution: {integrity: sha512-WJBbD186AZmMGaSIhlktC+rPl8L3peCTXAh88Ih9uEvK0en2mPojGyCGYiL6mHtV1RPV3JyfJW5t6n5hh0lXhA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [linux] - libc: [glibc] - - '@oxc-parser/binding-linux-arm64-musl@0.143.0': - resolution: {integrity: sha512-t1AcYOwEzgceadT4v5e+vaCCb0AncCA3v5AyzfBAz/tMq11qzVccXKzNHtkWdjBsgvTKwRkaUF3QvT4kot8vcQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [linux] - libc: [musl] - - '@oxc-parser/binding-linux-ppc64-gnu@0.143.0': - resolution: {integrity: sha512-RsnO/NoD8376LMJq8JS8TwI0ieNaFRTuNe2GVJntQg6gwZNMENZsEbknHdVwjpOmxdGLGodcwaGSbAeRr5Bgjw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [ppc64] - os: [linux] - libc: [glibc] - - '@oxc-parser/binding-linux-riscv64-gnu@0.143.0': - resolution: {integrity: sha512-48fSVfR9TZi5CASZFyv0VC6z6BCoeihFsX031mAD/oSH7d9PYsPgIqza7d9mjP7Z2KTEpTFyH6SIu0Ui6R1vdg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [riscv64] - os: [linux] - libc: [glibc] - - '@oxc-parser/binding-linux-riscv64-musl@0.143.0': - resolution: {integrity: sha512-T8CpdD+SfE01DnIOD4HpVxu0ZJOfMJ/VhCvikKfaXAxkZ+9veyLM/D2hpi7Y2hFUyPmVQO3FNZHmYzV/WlVR4g==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [riscv64] - os: [linux] - libc: [musl] - - '@oxc-parser/binding-linux-s390x-gnu@0.143.0': - resolution: {integrity: sha512-QLdeMsCcacenPEFsfxnBUDF1y6opyz5+fmOz9bfD5Y7fiGCMupUCuB3KTPQhNwshIG1P9fPqar9MHxuBDd4bwQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [s390x] - os: [linux] - libc: [glibc] - - '@oxc-parser/binding-linux-x64-gnu@0.143.0': - resolution: {integrity: sha512-659ujfqLy6k7cuH3sbzhd8b+ztSq+i6E2E9pG78Q0BmHjAExfGIdgc8cGgMdwAozDXeZFHkJ+LXYJdWsaGdgyw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [linux] - libc: [glibc] - - '@oxc-parser/binding-linux-x64-musl@0.143.0': - resolution: {integrity: sha512-/Mw/9j4TfZcnKphPrzOE6t4MMknXadcAAuVUlDRTF/ETWB5xOgQvOJV2Mh9We/bWxZdoxaGAdc+hy4GuYwQ2yQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [linux] - libc: [musl] - - '@oxc-parser/binding-openharmony-arm64@0.143.0': - resolution: {integrity: sha512-8rIKWR2BFuifbIK/1XB9wTaSdtuJ25dlE7ZQYDnEwj/2xH2vHsxnvIjHT3ZjSVuLLwGGlSslIG/fbOJ8TV8rTw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [openharmony] + os: [openharmony] '@oxc-parser/binding-win32-arm64-msvc@0.143.0': resolution: {integrity: sha512-5U9kQYMfRRI6Zq7KDxgbIP0RMnKrfn3gLepRMgJuRkPSUALTiRCk9d/uyhb4lGDjUdzwK7mBkKqhLgzBPCmLpQ==} @@ -1034,135 +325,14 @@ packages: cpu: [x64] os: [win32] - '@poppinss/colors@4.1.6': - resolution: {integrity: sha512-H9xkIdFswbS8n1d6vmRd8+c10t2Qe+rZITbbDHHkQixH5+2x1FDGmi/0K+WgWiqQFKPSlIYB7jlH6Kpfn6Fleg==} - - '@poppinss/dumper@0.6.5': - resolution: {integrity: sha512-NBdYIb90J7LfOI32dOewKI1r7wnkiH6m920puQ3qHUeZkxNkQiFnXVWoE6YtFSv6QOiPPf7ys6i+HWWecDz7sw==} + '@tybys/wasm-util@0.10.3': + resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==} - '@poppinss/exception@1.2.3': - resolution: {integrity: sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw==} + '@types/estree@1.0.9': + resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} - '@rolldown/binding-android-arm64@1.2.3': - resolution: {integrity: sha512-zrJtHDcaZJ1Fp7xf4hNl+7seH9Cn/N5TwLYkhgXREtBwAd/jaqW3uqeHxpDugJLVICWg4eW44kOQEGJ1r6jCGw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [android] - - '@rolldown/binding-darwin-arm64@1.2.3': - resolution: {integrity: sha512-ieIiibVCp0tX7TLu2cafoNPv8wJyYi01ekXpbf8q2j7F4rGAhhXb/eQh7ge9DRBY78GwmRQtvjZDux7EDbA8kA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [darwin] - - '@rolldown/binding-darwin-x64@1.2.3': - resolution: {integrity: sha512-Zh9tCon19eDXJoihx0rqKhMUlMYqzwj3aPsSuHmI4RWZh62dWUL+DJN4C5YQya5TcQBJU/Fe8+rY0jhXTQITqA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [darwin] - - '@rolldown/binding-freebsd-x64@1.2.3': - resolution: {integrity: sha512-nGbJWewA1wrXXZiQhjAT5rhibGfns5ZNkDVqxsO6zJ3f3YvpoDNNmGMSbbhLuXKjNScaBJVOAboztAWVespQMg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [freebsd] - - '@rolldown/binding-linux-arm-gnueabihf@1.2.3': - resolution: {integrity: sha512-QNniJr5Kml0kDEB98jiDOJjXNroxIIi0IXIbdYzY26Xt1pVbeP62+KnoIZLwirOymX/0jDk/2gI/bNUv7A7OIw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm] - os: [linux] - - '@rolldown/binding-linux-arm64-gnu@1.2.3': - resolution: {integrity: sha512-TkqEAcmmvH3I/q4114NB4RVt6241Dao48pF45uLcFGrwAaIn0iITgTAKP/dLjbN0R4buJjGb91+UHSoFmpgIWw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-arm64-musl@1.2.3': - resolution: {integrity: sha512-NHqjnxpsndf4MPymxteFAWHHfkTL8HjWh1KB7z23ofZ6QO2euONuxDXjat69dKZRALnGypg8k8SsK8vZJoXv1Q==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [linux] - libc: [musl] - - '@rolldown/binding-linux-ppc64-gnu@1.2.3': - resolution: {integrity: sha512-6tbrbwfz5GB9DQ4Jwo6hy9v+vR31xZlvzZ6n5Xut6Hhx5PvrA9q/HsK8KMaYQp063iqZGXwNvZtYNLD7EM/x0w==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [ppc64] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-s390x-gnu@1.2.3': - resolution: {integrity: sha512-oyuXxXmoZHjXC917IAPFAAv4wWAa0cM9afk8nx1+9/jNNOX1uPf8yDA6p7G0RypOfw/X0PQt5IfoquY1um+zSg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [s390x] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-x64-gnu@1.2.3': - resolution: {integrity: sha512-TytMwF2KVGqP2tgd0I1OY0PAv78dZRAYcF5ssDzjM34SUXCED3uXvSd5+lHoC0bTD6eEdFz7LdQNCO1y0oVk9w==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-x64-musl@1.2.3': - resolution: {integrity: sha512-/E9m3qstrJFVPoULV25mVQblSNExY2+kBsYe4sy0Tn0yOOgJ8wZbZt3KnRbF/XeU2Gl1STKUQnDNTqhIE5MD4A==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [linux] - libc: [musl] - - '@rolldown/binding-openharmony-arm64@1.2.3': - resolution: {integrity: sha512-Kr0OcsoQI816i6HOl3vFHpd1K0eZyh76zgfj4c1nTyaTsd5r2Mj1lwM4R90y/qaCfmTn9eHy0SKwi98eitRxug==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [openharmony] - - '@rolldown/binding-win32-arm64-msvc@1.2.3': - resolution: {integrity: sha512-hOtMwTqnME+/gJcH/PCZ0wn0zPUjiWOgkHpxbSJpfGKMezHltx1S7/k1SitzVa7Ww2cqrDDaFbZEhcJZO8o+Jw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [win32] - - '@rolldown/binding-win32-x64-msvc@1.2.3': - resolution: {integrity: sha512-ekcqMMkI2PlhYnfzQnB/cEdYUVVJViWvoUyLrbzgDoi3Snfc1mVBwdnc306ufA5ejy8JSPjT2RlW1nQSjW7efg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [win32] - - '@rolldown/pluginutils@1.0.1': - resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} - - '@sindresorhus/is@7.2.0': - resolution: {integrity: sha512-P1Cz1dWaFfR4IR+U13mqqiGsLFf1KbayybWwdd2vfctdV6hDpUkgCY0nKOLLTMSoRd/jJNjtbqzf13K8DCCXQw==} - engines: {node: '>=18'} - - '@speed-highlight/core@1.2.15': - resolution: {integrity: sha512-BMq1K3DsElxDWawkX6eLg9+CKJrTVGCBAWVuHXVUV2u0s2711qiChLSId6ikYPfxhdYocLNt3wWwSvDiTvFabw==} - - '@standard-schema/spec@1.1.0': - resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} - - '@swc/helpers@0.5.15': - resolution: {integrity: sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==} - - '@tybys/wasm-util@0.10.3': - resolution: {integrity: sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg==} - - '@types/estree@1.0.9': - resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} - - '@types/istanbul-lib-coverage@2.0.6': - resolution: {integrity: sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w==} - - '@types/json-schema@7.0.15': - resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} - - '@types/node@22.19.19': - resolution: {integrity: sha512-dyh/xO2Fh5bYrfWaaqGrRQQGkNdmYw6AmaAUvYeUMNTWQtvb796ikLdmTchRmOlOiIJ1TDXfWgVx1QkUlQ6Hew==} + '@types/json-schema@7.0.15': + resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} acorn-jsx@5.3.2: resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} @@ -1177,144 +347,27 @@ packages: ajv@6.15.0: resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==} - ansi-regex@6.2.2: - resolution: {integrity: sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==} - engines: {node: '>=12'} - ansi-styles@4.3.0: resolution: {integrity: sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==} engines: {node: '>=8'} - ansi-styles@6.2.3: - resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==} - engines: {node: '>=12'} - argparse@2.0.1: resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} balanced-match@1.0.2: resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} - balanced-match@4.0.4: - resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} - engines: {node: 18 || 20 || >=22} - - baseline-browser-mapping@2.10.30: - resolution: {integrity: sha512-xjOFN16Ha1+Rz4nFYKqHU/LSB+gx/Vi3yQLX7r7sAW+Wa+8hhF2h4pvqTrTMc8+WcDBEunnUurr46Jvv0jk3Vg==} - engines: {node: '>=6.0.0'} - hasBin: true - - better-auth@1.6.25: - resolution: {integrity: sha512-fvoq+oCO+FF5fpP3XfU7znRyGFpHB77UG2EyxsKNy+Cak7Q5pELu+auvvDveQbWQxcoKugZ7jYQQPFQLpUTGOw==} - peerDependencies: - '@lynx-js/react': '*' - '@prisma/client': ^5.0.0 || ^6.0.0 || ^7.0.0 - '@sveltejs/kit': ^2.0.0 - '@tanstack/react-start': ^1.0.0 - '@tanstack/solid-start': ^1.0.0 - better-sqlite3: ^12.0.0 - drizzle-kit: '>=0.31.4' - drizzle-orm: ^0.45.2 - mongodb: ^6.0.0 || ^7.0.0 - mysql2: ^3.0.0 - next: ^14.0.0 || ^15.0.0 || ^16.0.0 - pg: ^8.0.0 - prisma: ^5.0.0 || ^6.0.0 || ^7.0.0 - react: ^18.0.0 || ^19.0.0 - react-dom: ^18.0.0 || ^19.0.0 - solid-js: ^1.0.0 - svelte: ^4.0.0 || ^5.0.0 - vitest: ^2.0.0 || ^3.0.0 || ^4.0.0 - vue: ^3.0.0 - peerDependenciesMeta: - '@lynx-js/react': - optional: true - '@prisma/client': - optional: true - '@sveltejs/kit': - optional: true - '@tanstack/react-start': - optional: true - '@tanstack/solid-start': - optional: true - better-sqlite3: - optional: true - drizzle-kit: - optional: true - drizzle-orm: - optional: true - mongodb: - optional: true - mysql2: - optional: true - next: - optional: true - pg: - optional: true - prisma: - optional: true - react: - optional: true - react-dom: - optional: true - solid-js: - optional: true - svelte: - optional: true - vitest: - optional: true - vue: - optional: true - - better-call@1.3.7: - resolution: {integrity: sha512-Al51/hjp2SSp6CRTa3F2ptcx4yQVS1xWKoY6jcVXqNYOap6mHFP2jUBn5EwIL4iIed1/Sq4hlQ+Umm6EflZG+w==} - peerDependencies: - zod: ^4.0.0 - peerDependenciesMeta: - zod: - optional: true - - blake3-wasm@2.1.5: - resolution: {integrity: sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==} - brace-expansion@1.1.14: resolution: {integrity: sha512-MWPGfDxnyzKU7rNOW9SP/c50vi3xrmrua/+6hfPbCS2ABNWfx24vPidzvC7krjU/RTo235sV776ymlsMtGKj8g==} - brace-expansion@5.0.6: - resolution: {integrity: sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==} - engines: {node: 18 || 20 || >=22} - - buffer-from@1.1.2: - resolution: {integrity: sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==} - - c8@12.0.0: - resolution: {integrity: sha512-4zpJvrd1nKWutnnKC2pXkFmb6iM1l+ffN//o1CzlTNwW7GSOs9a1xrLqkC48nU8oEkjmPZLPiwMsIaOvoF4Pqg==} - engines: {node: ^20.19.0 || ^22.12.0 || >=23} - hasBin: true - peerDependencies: - monocart-coverage-reports: ^2 - peerDependenciesMeta: - monocart-coverage-reports: - optional: true - callsites@3.1.0: resolution: {integrity: sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==} engines: {node: '>=6'} - caniuse-lite@1.0.30001793: - resolution: {integrity: sha512-iwSsYWaCOoh26cV8NwNRViHlrfUvYsHDfRVcbtmw0Kg6PJIZZXwMkj1442FYLBGkeUf1juAsU3DTfxW579mrPA==} - chalk@4.1.2: resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==} engines: {node: '>=10'} - client-only@0.0.1: - resolution: {integrity: sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==} - - cliui@9.0.1: - resolution: {integrity: sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==} - engines: {node: '>=20'} - color-convert@2.0.1: resolution: {integrity: sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==} engines: {node: '>=7.0.0'} @@ -1322,19 +375,9 @@ packages: color-name@1.1.4: resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} - commander@2.20.3: - resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==} - concat-map@0.0.1: resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} - convert-source-map@2.0.0: - resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} - - cookie@1.1.1: - resolution: {integrity: sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==} - engines: {node: '>=18'} - cross-spawn@7.0.6: resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==} engines: {node: '>= 8'} @@ -1351,120 +394,6 @@ packages: deep-is@0.1.4: resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} - defu@6.1.7: - resolution: {integrity: sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ==} - - detect-libc@2.1.2: - resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} - engines: {node: '>=8'} - - drizzle-orm@0.45.2: - resolution: {integrity: sha512-kY0BSaTNYWnoDMVoyY8uxmyHjpJW1geOmBMdSSicKo9CIIWkSxMIj2rkeSR51b8KAPB7m+qysjuHme5nKP+E5Q==} - peerDependencies: - '@aws-sdk/client-rds-data': '>=3' - '@cloudflare/workers-types': '>=4' - '@electric-sql/pglite': '>=0.2.0' - '@libsql/client': '>=0.10.0' - '@libsql/client-wasm': '>=0.10.0' - '@neondatabase/serverless': '>=0.10.0' - '@op-engineering/op-sqlite': '>=2' - '@opentelemetry/api': ^1.4.1 - '@planetscale/database': '>=1.13' - '@prisma/client': '*' - '@tidbcloud/serverless': '*' - '@types/better-sqlite3': '*' - '@types/pg': '*' - '@types/sql.js': '*' - '@upstash/redis': '>=1.34.7' - '@vercel/postgres': '>=0.8.0' - '@xata.io/client': '*' - better-sqlite3: '>=7' - bun-types: '*' - expo-sqlite: '>=14.0.0' - gel: '>=2' - knex: '*' - kysely: '*' - mysql2: '>=2' - pg: '>=8' - postgres: '>=3' - prisma: '*' - sql.js: '>=1' - sqlite3: '>=5' - peerDependenciesMeta: - '@aws-sdk/client-rds-data': - optional: true - '@cloudflare/workers-types': - optional: true - '@electric-sql/pglite': - optional: true - '@libsql/client': - optional: true - '@libsql/client-wasm': - optional: true - '@neondatabase/serverless': - optional: true - '@op-engineering/op-sqlite': - optional: true - '@opentelemetry/api': - optional: true - '@planetscale/database': - optional: true - '@prisma/client': - optional: true - '@tidbcloud/serverless': - optional: true - '@types/better-sqlite3': - optional: true - '@types/pg': - optional: true - '@types/sql.js': - optional: true - '@upstash/redis': - optional: true - '@vercel/postgres': - optional: true - '@xata.io/client': - optional: true - better-sqlite3: - optional: true - bun-types: - optional: true - expo-sqlite: - optional: true - gel: - optional: true - knex: - optional: true - kysely: - optional: true - mysql2: - optional: true - pg: - optional: true - postgres: - optional: true - prisma: - optional: true - sql.js: - optional: true - sqlite3: - optional: true - - emoji-regex@10.6.0: - resolution: {integrity: sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==} - - error-stack-parser-es@1.0.5: - resolution: {integrity: sha512-5qucVt2XcuGMcEGgWI7i+yZpmpByQ8J1lHhcL7PwqCwu9FPP3VUXzT4ltHe5i2z9dePwEHcDVOAfSnHsOlCXRA==} - - esbuild@0.28.1: - resolution: {integrity: sha512-HrJrvZv5ayxBzPfwphOoNzkzOIIlifzk0KJrGK2c8R4+LKpMtpYLQeUdjnwjWv/LZlkH2laZk+4w78pi99D4Vw==} - engines: {node: '>=18'} - hasBin: true - - escalade@3.2.0: - resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} - engines: {node: '>=6'} - escape-string-regexp@4.0.0: resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==} engines: {node: '>=10'} @@ -1547,28 +476,11 @@ packages: flatted@3.4.2: resolution: {integrity: sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==} - foreground-child@3.3.1: - resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==} - engines: {node: '>=14'} - formatly@0.3.0: resolution: {integrity: sha512-9XNj/o4wrRFyhSMJOvsuyMwy8aUfBaZ1VrqHVfohyXf0Sw0e+yfKG+xZaY3arGCOMdwFsqObtzVOc1gU9KiT9w==} engines: {node: '>=18.3.0'} hasBin: true - fsevents@2.3.3: - resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} - engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} - os: [darwin] - - get-caller-file@2.0.5: - resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} - engines: {node: 6.* || 8.* || >= 10.*} - - get-east-asian-width@1.6.0: - resolution: {integrity: sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==} - engines: {node: '>=18'} - get-tsconfig@4.14.1: resolution: {integrity: sha512-Dz/6HxkrxgNehhxLVeyv8sad9UzF2xBVeaKBQNDfJ5XiSXmp2gTR0eO0RWiT2NCKS5aGP9jjkOMggTN90qU50A==} @@ -1576,10 +488,6 @@ packages: resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} engines: {node: '>=10.13.0'} - glob@13.0.6: - resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==} - engines: {node: 18 || 20 || >=22} - globals@14.0.0: resolution: {integrity: sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==} engines: {node: '>=18'} @@ -1588,9 +496,6 @@ packages: resolution: {integrity: sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==} engines: {node: '>=8'} - html-escaper@2.0.2: - resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==} - ignore@5.3.2: resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} engines: {node: '>= 4'} @@ -1614,25 +519,10 @@ packages: isexe@2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} - istanbul-lib-coverage@3.2.2: - resolution: {integrity: sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==} - engines: {node: '>=8'} - - istanbul-lib-report@3.0.1: - resolution: {integrity: sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==} - engines: {node: '>=10'} - - istanbul-reports@3.2.0: - resolution: {integrity: sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==} - engines: {node: '>=8'} - jiti@2.7.0: resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==} hasBin: true - jose@6.2.4: - resolution: {integrity: sha512-N8acGzVsQy6M/fjFcxtysNc4Q379TcM5dM/qKkNtsHFji88yANnXTr7BLeP75iPnFwBfQzM/jg2BZ9+HZrHCZA==} - js-yaml@4.1.1: resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==} hasBin: true @@ -1687,97 +577,15 @@ packages: keyv@4.5.4: resolution: {integrity: sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==} - kleur@4.1.5: - resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==} - engines: {node: '>=6'} - knip@6.32.2: resolution: {integrity: sha512-WXTXbmocrw7gqm1A1TQvFN0OgJ7hUSU6E1g6SPRIzzHFogUBhXByc7cYeOFVtJ2uODg7DP4VbESYBYnfbtBYsg==} engines: {node: ^20.19.0 || >=22.12.0} hasBin: true - kysely@0.29.4: - resolution: {integrity: sha512-y5mVgQNkMbs1eK9Xyc0pmNdabN2wHhRYY/5r4W5HrUT1rYCEPeVNSj1RUJeSDKT3U0p+mXCvLgkrFuIafYI6BA==} - engines: {node: '>=22.0.0'} - levn@0.4.1: resolution: {integrity: sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==} engines: {node: '>= 0.8.0'} - lightningcss-android-arm64@1.33.0: - resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [android] - - lightningcss-darwin-arm64@1.33.0: - resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [darwin] - - lightningcss-darwin-x64@1.33.0: - resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [darwin] - - lightningcss-freebsd-x64@1.33.0: - resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [freebsd] - - lightningcss-linux-arm-gnueabihf@1.33.0: - resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} - engines: {node: '>= 12.0.0'} - cpu: [arm] - os: [linux] - - lightningcss-linux-arm64-gnu@1.33.0: - resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [linux] - libc: [glibc] - - lightningcss-linux-arm64-musl@1.33.0: - resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [linux] - libc: [musl] - - lightningcss-linux-x64-gnu@1.33.0: - resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [linux] - libc: [glibc] - - lightningcss-linux-x64-musl@1.33.0: - resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [linux] - libc: [musl] - - lightningcss-win32-arm64-msvc@1.33.0: - resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [win32] - - lightningcss-win32-x64-msvc@1.33.0: - resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [win32] - - lightningcss@1.33.0: - resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} - engines: {node: '>= 12.0.0'} - locate-path@6.0.0: resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} engines: {node: '>=10'} @@ -1785,65 +593,15 @@ packages: lodash.merge@4.6.2: resolution: {integrity: sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==} - lru-cache@11.5.2: - resolution: {integrity: sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g==} - engines: {node: 20 || >=22} - - make-dir@4.0.0: - resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==} - engines: {node: '>=10'} - - miniflare@5.20260804.1-alpha: - resolution: {integrity: sha512-J0QBHEj+d75TyFE9VhH+2dXgvdYt/pfyDlm+9IiYUFocQvqYy9iuW1DIqNawh1N7Kr6iMrDzVkgDSdt6pA75uA==} - engines: {node: '>=22.0.0'} - - minimatch@10.2.5: - resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==} - engines: {node: 18 || 20 || >=22} - minimatch@3.1.5: resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==} - minipass@7.1.3: - resolution: {integrity: sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==} - engines: {node: '>=16 || 14 >=14.17'} - ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} - nanoid@3.3.18: - resolution: {integrity: sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==} - engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} - hasBin: true - - nanostores@1.4.1: - resolution: {integrity: sha512-PGd3uPojJB9Z07d5NX3Db/SOSBbyy3wLMUGq0GpnEEJfVzY9mq7daPMAZ3jObV5D3Jn+YKND636eI5ULg7F80Q==} - engines: {node: ^20.0.0 || >=22.0.0} - natural-compare@1.4.0: resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} - next@16.2.12: - resolution: {integrity: sha512-iD59eYQWmbFcEbX7v/acG5DRym9iw1DdaPoD0WTA920naWsE25wShzJW4+UvAs8MK9EC2kBfIH6vtto1H1PHGw==} - engines: {node: '>=20.9.0'} - hasBin: true - peerDependencies: - '@opentelemetry/api': ^1.1.0 - '@playwright/test': ^1.51.1 - babel-plugin-react-compiler: '*' - react: ^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0 - react-dom: ^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0 - sass: ^1.3.0 - peerDependenciesMeta: - '@opentelemetry/api': - optional: true - '@playwright/test': - optional: true - babel-plugin-react-compiler: - optional: true - sass: - optional: true - optionator@0.9.4: resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} engines: {node: '>= 0.8.0'} @@ -1875,31 +633,10 @@ packages: resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} engines: {node: '>=8'} - path-scurry@2.0.2: - resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==} - engines: {node: 18 || 20 || >=22} - - path-to-regexp@6.3.0: - resolution: {integrity: sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ==} - - pathe@2.0.3: - resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} - - picocolors@1.1.1: - resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} - picomatch@4.0.5: resolution: {integrity: sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==} engines: {node: '>=12'} - postcss@8.4.31: - resolution: {integrity: sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==} - engines: {node: ^10 || ^12 || >=14} - - postcss@8.5.26: - resolution: {integrity: sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==} - engines: {node: ^10 || ^12 || >=14} - prelude-ls@1.2.1: resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} engines: {node: '>= 0.8.0'} @@ -1913,15 +650,6 @@ packages: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} - react-dom@19.2.6: - resolution: {integrity: sha512-0prMI+hvBbPjsWnxDLxlCGyM8PN6UuWjEUCYmZhO67xIV9Xasa/r/vDnq+Xyq4Lo27g8QSbO5YzARu0D1Sps3g==} - peerDependencies: - react: ^19.2.6 - - react@19.2.6: - resolution: {integrity: sha512-sfWGGfavi0xr8Pg0sVsyHMAOziVYKgPLNrS7ig+ivMNb3wbCBw3KxtflsGBAwD3gYQlE/AEZsTLgToRrSCjb0Q==} - engines: {node: '>=0.10.0'} - resolve-from@4.0.0: resolution: {integrity: sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==} engines: {node: '>=4'} @@ -1929,77 +657,18 @@ packages: resolve-pkg-maps@1.0.0: resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} - rolldown@1.2.3: - resolution: {integrity: sha512-rn9wpmxplLf7NLNyCk9FyWh3FM43DbY8jOzCdEPzH7uflhTftRbCEpqi6Ly2osgoU8OwObtmavMbWLaWy4LX7A==} - engines: {node: ^20.19.0 || >=22.12.0} - hasBin: true - - rou3@0.7.12: - resolution: {integrity: sha512-iFE4hLDuloSWcD7mjdCDhx2bKcIsYbtOTpfH5MHHLSKMOUyjqQXTeZVa289uuwEGEKFoE/BAPbhaU4B774nceg==} - - scheduler@0.27.0: - resolution: {integrity: sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==} - - semver@7.8.0: - resolution: {integrity: sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==} - engines: {node: '>=10'} - hasBin: true - - semver@7.8.5: - resolution: {integrity: sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==} - engines: {node: '>=10'} - hasBin: true - - set-cookie-parser@3.1.2: - resolution: {integrity: sha512-5/r/lTwbJ3zQ+qwdUFZYeRNqda7P5HD8zQKqlSjdGt1/S0cjLAphHusj4Y58ahDtWn/g32xrIS58/ikOvwl0Lw==} - - sharp@0.34.5: - resolution: {integrity: sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==} - engines: {node: ^18.17.0 || ^20.3.0 || >=21.0.0} - - sharp@0.35.2: - resolution: {integrity: sha512-FVtFjtBCMiJS6yb5CX7Sop45WFMpeGw6oRKuJnXYgf/f1ms/D7LE/ZUSNxnW7rZ/dbslQWYkoqFHGPaDBtaK4w==} - engines: {node: '>=20.9.0'} - - shebang-command@2.0.0: - resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} - engines: {node: '>=8'} + shebang-command@2.0.0: + resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==} + engines: {node: '>=8'} shebang-regex@3.0.0: resolution: {integrity: sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==} engines: {node: '>=8'} - signal-exit@4.1.0: - resolution: {integrity: sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==} - engines: {node: '>=14'} - smol-toml@1.8.0: resolution: {integrity: sha512-kCZr2V3ch9i00x8zXRhjUNVcjG9ijES5dDudkXvUVCT5QlJNQWElSJdZqyPemffHoLNUYwOcou0Fy+ojN0uHSQ==} engines: {node: '>= 18'} - source-map-js@1.2.1: - resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} - engines: {node: '>=0.10.0'} - - source-map-support@0.5.21: - resolution: {integrity: sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==} - - source-map@0.6.1: - resolution: {integrity: sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==} - engines: {node: '>=0.10.0'} - - string-width@7.2.0: - resolution: {integrity: sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==} - engines: {node: '>=18'} - - string-width@8.2.2: - resolution: {integrity: sha512-GaPUh5gfdrYzqeVNZvUfT23vYYxXzKYidUcnMtJg/3rxRV63EFZy3k6xfKlmfeJD0176lnUV/Usr3XcwSvFzpg==} - engines: {node: '>=20'} - - strip-ansi@7.2.0: - resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==} - engines: {node: '>=12'} - strip-json-comments@3.1.1: resolution: {integrity: sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==} engines: {node: '>=8'} @@ -2008,36 +677,10 @@ packages: resolution: {integrity: sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw==} engines: {node: '>=14.16'} - styled-jsx@5.1.6: - resolution: {integrity: sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==} - engines: {node: '>= 12.0.0'} - peerDependencies: - '@babel/core': '*' - babel-plugin-macros: '*' - react: '>= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0' - peerDependenciesMeta: - '@babel/core': - optional: true - babel-plugin-macros: - optional: true - - supports-color@10.2.2: - resolution: {integrity: sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g==} - engines: {node: '>=18'} - supports-color@7.2.0: resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==} engines: {node: '>=8'} - terser@5.47.1: - resolution: {integrity: sha512-tPbLXTI6ohPASb/1YViL428oEHu6/qv1OxqYnfaonVCFHqx4+wCd95pHrQWsL5X4pl90CTyW9piSAsS2L0VoMw==} - engines: {node: '>=10'} - hasBin: true - - test-exclude@8.0.0: - resolution: {integrity: sha512-ZOffsNrXYggvU1mDGHk54I96r26P8SyMjO5slMKSc7+IWmtB/MQKnEC2fP51imB3/pT6YK5cT5E8f+Dd9KdyOQ==} - engines: {node: 20 || >=22} - tinyglobby@0.2.17: resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} engines: {node: '>=12.0.0'} @@ -2049,75 +692,13 @@ packages: resolution: {integrity: sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==} engines: {node: '>= 0.8.0'} - typescript@5.9.3: - resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} - engines: {node: '>=14.17'} - hasBin: true - unbash@4.0.10: resolution: {integrity: sha512-b7zoBQvpWp0vuN5q2vK2RRBR2SvuruQAs50DApdDveBSn3eSYd84IaHodFqQIMlvY9K2VnyBUEXgwOBuGU9GBg==} engines: {node: '>=14'} - undici-types@6.21.0: - resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==} - - undici@7.29.0: - resolution: {integrity: sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==} - engines: {node: '>=20.18.1'} - - unenv@2.0.0-rc.24: - resolution: {integrity: sha512-i7qRCmY42zmCwnYlh9H2SvLEypEFGye5iRmEMKjcGi7zk9UquigRjFtTLz0TYqr0ZGLZhaMHl/foy1bZR+Cwlw==} - uri-js@4.4.1: resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==} - v8-to-istanbul@9.3.0: - resolution: {integrity: sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA==} - engines: {node: '>=10.12.0'} - - vite@8.2.1: - resolution: {integrity: sha512-EU/eS7BH3XROHh2YnBefjM6DBKA6ZeMZEYQbj7NLWg5wHYlhB8B/Mayd5XsgWq+NFYccDOTemRpdETWR6Ka/lw==} - engines: {node: ^20.19.0 || >=22.12.0} - hasBin: true - peerDependencies: - '@types/node': ^20.19.0 || >=22.12.0 - '@vitejs/devtools': ^0.4.0 - esbuild: ^0.27.0 || ^0.28.0 - jiti: '>=1.21.0' - less: ^4.0.0 - sass: ^1.70.0 - sass-embedded: ^1.70.0 - stylus: '>=0.54.8' - sugarss: ^5.0.0 - terser: ^5.16.0 - tsx: ^4.8.1 - yaml: ^2.4.2 - peerDependenciesMeta: - '@types/node': - optional: true - '@vitejs/devtools': - optional: true - esbuild: - optional: true - jiti: - optional: true - less: - optional: true - sass: - optional: true - sass-embedded: - optional: true - stylus: - optional: true - sugarss: - optional: true - terser: - optional: true - tsx: - optional: true - yaml: - optional: true - walk-up-path@4.0.0: resolution: {integrity: sha512-3hu+tD8YzSLGuFYtPRb48vdhKMi0KQV5sn+uWr8+7dMEq/2G/dtLrdDinkLjqq5TIbIBjYJ4Ax/n3YiaW7QM8A==} engines: {node: 20 || >=22} @@ -2131,155 +712,20 @@ packages: resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} engines: {node: '>=0.10.0'} - workerd@1.20260804.1: - resolution: {integrity: sha512-b0P38g5/ssemwWxd/mafNYggEZ0ere7PCiUH6RCHkgqjRhhXTP45nDiL2L3iIvi8uF2IjNrGpVgMXEunCaeY/w==} - engines: {node: '>=16'} - hasBin: true - - wrangler@4.121.0: - resolution: {integrity: sha512-dcARWk6CyaD0vJBSLjJn4K2yo+mYko73hzryq+t/9DXnyAq877RWIMl7uOMcDKs5dDXdoickNhZTKxBYT9XKsA==} - engines: {node: '>=22.0.0'} - hasBin: true - peerDependencies: - '@cloudflare/workers-types': ^5.20260804.1 - peerDependenciesMeta: - '@cloudflare/workers-types': - optional: true - - wrap-ansi@9.0.2: - resolution: {integrity: sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==} - engines: {node: '>=18'} - - ws@8.21.0: - resolution: {integrity: sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==} - engines: {node: '>=10.0.0'} - peerDependencies: - bufferutil: ^4.0.1 - utf-8-validate: '>=5.0.2' - peerDependenciesMeta: - bufferutil: - optional: true - utf-8-validate: - optional: true - - y18n@5.0.8: - resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} - engines: {node: '>=10'} - yaml@2.9.0: resolution: {integrity: sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==} engines: {node: '>= 14.6'} hasBin: true - yargs-parser@21.1.1: - resolution: {integrity: sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==} - engines: {node: '>=12'} - - yargs-parser@22.0.0: - resolution: {integrity: sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==} - engines: {node: ^20.19.0 || ^22.12.0 || >=23} - - yargs@18.1.0: - resolution: {integrity: sha512-2rAgRKu54VsHkqI0/tYkmluGXHD4KW7yZoycuqDQ15QOTnc2VVfy0nN/1eMhnQLO00A+dwtK20xuCnc1YGeUyg==} - engines: {node: ^20.19.0 || ^22.12.0 || >=23} - yocto-queue@0.1.0: resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==} engines: {node: '>=10'} - youch-core@0.3.3: - resolution: {integrity: sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA==} - - youch@4.1.0-beta.10: - resolution: {integrity: sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==} - zod@4.4.3: resolution: {integrity: sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==} snapshots: - '@bcoe/v8-coverage@1.0.2': {} - - '@better-auth/core@1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1)': - dependencies: - '@better-auth/utils': 0.4.2 - '@better-fetch/fetch': 1.3.1 - '@opentelemetry/semantic-conventions': 1.43.0 - '@standard-schema/spec': 1.1.0 - better-call: 1.3.7(zod@4.4.3) - jose: 6.2.4 - kysely: 0.29.4 - nanostores: 1.4.1 - zod: 4.4.3 - - '@better-auth/drizzle-adapter@1.6.25(@better-auth/core@1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1))(@better-auth/utils@0.4.2)(drizzle-orm@0.45.2(kysely@0.29.4))': - dependencies: - '@better-auth/core': 1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1) - '@better-auth/utils': 0.4.2 - optionalDependencies: - drizzle-orm: 0.45.2(kysely@0.29.4) - - '@better-auth/kysely-adapter@1.6.25(@better-auth/core@1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1))(@better-auth/utils@0.4.2)(kysely@0.29.4)': - dependencies: - '@better-auth/core': 1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1) - '@better-auth/utils': 0.4.2 - optionalDependencies: - kysely: 0.29.4 - - '@better-auth/memory-adapter@1.6.25(@better-auth/core@1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1))(@better-auth/utils@0.4.2)': - dependencies: - '@better-auth/core': 1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1) - '@better-auth/utils': 0.4.2 - - '@better-auth/mongo-adapter@1.6.25(@better-auth/core@1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1))(@better-auth/utils@0.4.2)': - dependencies: - '@better-auth/core': 1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1) - '@better-auth/utils': 0.4.2 - - '@better-auth/prisma-adapter@1.6.25(@better-auth/core@1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1))(@better-auth/utils@0.4.2)': - dependencies: - '@better-auth/core': 1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1) - '@better-auth/utils': 0.4.2 - - '@better-auth/telemetry@1.6.25(@better-auth/core@1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1))(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)': - dependencies: - '@better-auth/core': 1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1) - '@better-auth/utils': 0.4.2 - '@better-fetch/fetch': 1.3.1 - - '@better-auth/utils@0.4.2': - dependencies: - '@noble/hashes': 2.2.0 - - '@better-fetch/fetch@1.3.1': {} - - '@cloudflare/kv-asset-handler@0.5.0': {} - - '@cloudflare/unenv-preset@2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260804.1)': - dependencies: - unenv: 2.0.0-rc.24 - optionalDependencies: - workerd: 1.20260804.1 - - '@cloudflare/workerd-darwin-64@1.20260804.1': - optional: true - - '@cloudflare/workerd-darwin-arm64@1.20260804.1': - optional: true - - '@cloudflare/workerd-linux-64@1.20260804.1': - optional: true - - '@cloudflare/workerd-linux-arm64@1.20260804.1': - optional: true - - '@cloudflare/workerd-windows-64@1.20260804.1': - optional: true - - '@cspotcode/source-map-support@0.8.1': - dependencies: - '@jridgewell/trace-mapping': 0.3.9 - '@emnapi/core@1.11.2': dependencies: '@emnapi/wasi-threads': 1.2.2 @@ -2296,84 +742,6 @@ snapshots: tslib: 2.8.1 optional: true - '@esbuild/aix-ppc64@0.28.1': - optional: true - - '@esbuild/android-arm64@0.28.1': - optional: true - - '@esbuild/android-arm@0.28.1': - optional: true - - '@esbuild/android-x64@0.28.1': - optional: true - - '@esbuild/darwin-arm64@0.28.1': - optional: true - - '@esbuild/darwin-x64@0.28.1': - optional: true - - '@esbuild/freebsd-arm64@0.28.1': - optional: true - - '@esbuild/freebsd-x64@0.28.1': - optional: true - - '@esbuild/linux-arm64@0.28.1': - optional: true - - '@esbuild/linux-arm@0.28.1': - optional: true - - '@esbuild/linux-ia32@0.28.1': - optional: true - - '@esbuild/linux-loong64@0.28.1': - optional: true - - '@esbuild/linux-mips64el@0.28.1': - optional: true - - '@esbuild/linux-ppc64@0.28.1': - optional: true - - '@esbuild/linux-riscv64@0.28.1': - optional: true - - '@esbuild/linux-s390x@0.28.1': - optional: true - - '@esbuild/linux-x64@0.28.1': - optional: true - - '@esbuild/netbsd-arm64@0.28.1': - optional: true - - '@esbuild/netbsd-x64@0.28.1': - optional: true - - '@esbuild/openbsd-arm64@0.28.1': - optional: true - - '@esbuild/openbsd-x64@0.28.1': - optional: true - - '@esbuild/openharmony-arm64@0.28.1': - optional: true - - '@esbuild/sunos-x64@0.28.1': - optional: true - - '@esbuild/win32-arm64@0.28.1': - optional: true - - '@esbuild/win32-ia32@0.28.1': - optional: true - - '@esbuild/win32-x64@0.28.1': - optional: true - '@eslint-community/eslint-utils@4.9.1(eslint@9.39.4(jiti@2.7.0))': dependencies: eslint: 9.39.4(jiti@2.7.0) @@ -2428,241 +796,13 @@ snapshots: dependencies: '@humanfs/core': 0.19.2 '@humanfs/types': 0.15.0 - '@humanwhocodes/retry': 0.4.3 - - '@humanfs/types@0.15.0': {} - - '@humanwhocodes/module-importer@1.0.1': {} - - '@humanwhocodes/retry@0.4.3': {} - - '@img/colour@1.1.0': {} - - '@img/sharp-darwin-arm64@0.34.5': - optionalDependencies: - '@img/sharp-libvips-darwin-arm64': 1.2.4 - optional: true - - '@img/sharp-darwin-arm64@0.35.2': - optionalDependencies: - '@img/sharp-libvips-darwin-arm64': 1.3.1 - optional: true - - '@img/sharp-darwin-x64@0.34.5': - optionalDependencies: - '@img/sharp-libvips-darwin-x64': 1.2.4 - optional: true - - '@img/sharp-darwin-x64@0.35.2': - optionalDependencies: - '@img/sharp-libvips-darwin-x64': 1.3.1 - optional: true - - '@img/sharp-freebsd-wasm32@0.35.2': - dependencies: - '@img/sharp-wasm32': 0.35.2 - optional: true - - '@img/sharp-libvips-darwin-arm64@1.2.4': - optional: true - - '@img/sharp-libvips-darwin-arm64@1.3.1': - optional: true - - '@img/sharp-libvips-darwin-x64@1.2.4': - optional: true - - '@img/sharp-libvips-darwin-x64@1.3.1': - optional: true - - '@img/sharp-libvips-linux-arm64@1.2.4': - optional: true - - '@img/sharp-libvips-linux-arm64@1.3.1': - optional: true - - '@img/sharp-libvips-linux-arm@1.2.4': - optional: true - - '@img/sharp-libvips-linux-arm@1.3.1': - optional: true - - '@img/sharp-libvips-linux-ppc64@1.2.4': - optional: true - - '@img/sharp-libvips-linux-ppc64@1.3.1': - optional: true - - '@img/sharp-libvips-linux-riscv64@1.2.4': - optional: true - - '@img/sharp-libvips-linux-riscv64@1.3.1': - optional: true - - '@img/sharp-libvips-linux-s390x@1.2.4': - optional: true - - '@img/sharp-libvips-linux-s390x@1.3.1': - optional: true - - '@img/sharp-libvips-linux-x64@1.2.4': - optional: true - - '@img/sharp-libvips-linux-x64@1.3.1': - optional: true - - '@img/sharp-libvips-linuxmusl-arm64@1.2.4': - optional: true - - '@img/sharp-libvips-linuxmusl-arm64@1.3.1': - optional: true - - '@img/sharp-libvips-linuxmusl-x64@1.2.4': - optional: true - - '@img/sharp-libvips-linuxmusl-x64@1.3.1': - optional: true - - '@img/sharp-linux-arm64@0.34.5': - optionalDependencies: - '@img/sharp-libvips-linux-arm64': 1.2.4 - optional: true - - '@img/sharp-linux-arm64@0.35.2': - optionalDependencies: - '@img/sharp-libvips-linux-arm64': 1.3.1 - optional: true - - '@img/sharp-linux-arm@0.34.5': - optionalDependencies: - '@img/sharp-libvips-linux-arm': 1.2.4 - optional: true - - '@img/sharp-linux-arm@0.35.2': - optionalDependencies: - '@img/sharp-libvips-linux-arm': 1.3.1 - optional: true - - '@img/sharp-linux-ppc64@0.34.5': - optionalDependencies: - '@img/sharp-libvips-linux-ppc64': 1.2.4 - optional: true - - '@img/sharp-linux-ppc64@0.35.2': - optionalDependencies: - '@img/sharp-libvips-linux-ppc64': 1.3.1 - optional: true - - '@img/sharp-linux-riscv64@0.34.5': - optionalDependencies: - '@img/sharp-libvips-linux-riscv64': 1.2.4 - optional: true - - '@img/sharp-linux-riscv64@0.35.2': - optionalDependencies: - '@img/sharp-libvips-linux-riscv64': 1.3.1 - optional: true - - '@img/sharp-linux-s390x@0.34.5': - optionalDependencies: - '@img/sharp-libvips-linux-s390x': 1.2.4 - optional: true - - '@img/sharp-linux-s390x@0.35.2': - optionalDependencies: - '@img/sharp-libvips-linux-s390x': 1.3.1 - optional: true - - '@img/sharp-linux-x64@0.34.5': - optionalDependencies: - '@img/sharp-libvips-linux-x64': 1.2.4 - optional: true - - '@img/sharp-linux-x64@0.35.2': - optionalDependencies: - '@img/sharp-libvips-linux-x64': 1.3.1 - optional: true - - '@img/sharp-linuxmusl-arm64@0.34.5': - optionalDependencies: - '@img/sharp-libvips-linuxmusl-arm64': 1.2.4 - optional: true - - '@img/sharp-linuxmusl-arm64@0.35.2': - optionalDependencies: - '@img/sharp-libvips-linuxmusl-arm64': 1.3.1 - optional: true - - '@img/sharp-linuxmusl-x64@0.34.5': - optionalDependencies: - '@img/sharp-libvips-linuxmusl-x64': 1.2.4 - optional: true - - '@img/sharp-linuxmusl-x64@0.35.2': - optionalDependencies: - '@img/sharp-libvips-linuxmusl-x64': 1.3.1 - optional: true - - '@img/sharp-wasm32@0.34.5': - dependencies: - '@emnapi/runtime': 1.11.2 - optional: true - - '@img/sharp-wasm32@0.35.2': - dependencies: - '@emnapi/runtime': 1.11.2 - optional: true - - '@img/sharp-webcontainers-wasm32@0.35.2': - dependencies: - '@img/sharp-wasm32': 0.35.2 - optional: true - - '@img/sharp-win32-arm64@0.34.5': - optional: true - - '@img/sharp-win32-arm64@0.35.2': - optional: true - - '@img/sharp-win32-ia32@0.34.5': - optional: true - - '@img/sharp-win32-ia32@0.35.2': - optional: true - - '@img/sharp-win32-x64@0.34.5': - optional: true - - '@img/sharp-win32-x64@0.35.2': - optional: true - - '@istanbuljs/schema@0.1.6': {} - - '@jridgewell/gen-mapping@0.3.13': - dependencies: - '@jridgewell/sourcemap-codec': 1.5.5 - '@jridgewell/trace-mapping': 0.3.31 - optional: true - - '@jridgewell/resolve-uri@3.1.2': {} - - '@jridgewell/source-map@0.3.11': - dependencies: - '@jridgewell/gen-mapping': 0.3.13 - '@jridgewell/trace-mapping': 0.3.31 - optional: true + '@humanwhocodes/retry': 0.4.3 - '@jridgewell/sourcemap-codec@1.5.5': {} + '@humanfs/types@0.15.0': {} - '@jridgewell/trace-mapping@0.3.31': - dependencies: - '@jridgewell/resolve-uri': 3.1.2 - '@jridgewell/sourcemap-codec': 1.5.5 + '@humanwhocodes/module-importer@1.0.1': {} - '@jridgewell/trace-mapping@0.3.9': - dependencies: - '@jridgewell/resolve-uri': 3.1.2 - '@jridgewell/sourcemap-codec': 1.5.5 + '@humanwhocodes/retry@0.4.3': {} '@napi-rs/wasm-runtime@1.2.3(@emnapi/core@1.11.2)(@emnapi/runtime@1.11.2)': dependencies: @@ -2671,39 +811,6 @@ snapshots: '@tybys/wasm-util': 0.10.3 optional: true - '@next/env@16.2.12': - optional: true - - '@next/swc-darwin-arm64@16.2.12': - optional: true - - '@next/swc-darwin-x64@16.2.12': - optional: true - - '@next/swc-linux-arm64-gnu@16.2.12': - optional: true - - '@next/swc-linux-arm64-musl@16.2.12': - optional: true - - '@next/swc-linux-x64-gnu@16.2.12': - optional: true - - '@next/swc-linux-x64-musl@16.2.12': - optional: true - - '@next/swc-win32-arm64-msvc@16.2.12': - optional: true - - '@next/swc-win32-x64-msvc@16.2.12': - optional: true - - '@noble/ciphers@2.2.0': {} - - '@noble/hashes@2.2.0': {} - - '@opentelemetry/semantic-conventions@1.43.0': {} - '@oxc-parser/binding-android-arm-eabi@0.143.0': optional: true @@ -2824,73 +931,6 @@ snapshots: '@oxc-resolver/binding-win32-x64-msvc@11.24.2': optional: true - '@poppinss/colors@4.1.6': - dependencies: - kleur: 4.1.5 - - '@poppinss/dumper@0.6.5': - dependencies: - '@poppinss/colors': 4.1.6 - '@sindresorhus/is': 7.2.0 - supports-color: 10.2.2 - - '@poppinss/exception@1.2.3': {} - - '@rolldown/binding-android-arm64@1.2.3': - optional: true - - '@rolldown/binding-darwin-arm64@1.2.3': - optional: true - - '@rolldown/binding-darwin-x64@1.2.3': - optional: true - - '@rolldown/binding-freebsd-x64@1.2.3': - optional: true - - '@rolldown/binding-linux-arm-gnueabihf@1.2.3': - optional: true - - '@rolldown/binding-linux-arm64-gnu@1.2.3': - optional: true - - '@rolldown/binding-linux-arm64-musl@1.2.3': - optional: true - - '@rolldown/binding-linux-ppc64-gnu@1.2.3': - optional: true - - '@rolldown/binding-linux-s390x-gnu@1.2.3': - optional: true - - '@rolldown/binding-linux-x64-gnu@1.2.3': - optional: true - - '@rolldown/binding-linux-x64-musl@1.2.3': - optional: true - - '@rolldown/binding-openharmony-arm64@1.2.3': - optional: true - - '@rolldown/binding-win32-arm64-msvc@1.2.3': - optional: true - - '@rolldown/binding-win32-x64-msvc@1.2.3': - optional: true - - '@rolldown/pluginutils@1.0.1': {} - - '@sindresorhus/is@7.2.0': {} - - '@speed-highlight/core@1.2.15': {} - - '@standard-schema/spec@1.1.0': {} - - '@swc/helpers@0.5.15': - dependencies: - tslib: 2.8.1 - optional: true - '@tybys/wasm-util@0.10.3': dependencies: tslib: 2.8.1 @@ -2898,14 +938,8 @@ snapshots: '@types/estree@1.0.9': {} - '@types/istanbul-lib-coverage@2.0.6': {} - '@types/json-schema@7.0.15': {} - '@types/node@22.19.19': - dependencies: - undici-types: 6.21.0 - acorn-jsx@5.3.2(acorn@8.16.0): dependencies: acorn: 8.16.0 @@ -2919,122 +953,34 @@ snapshots: json-schema-traverse: 0.4.1 uri-js: 4.4.1 - ansi-regex@6.2.2: {} - ansi-styles@4.3.0: dependencies: color-convert: 2.0.1 - ansi-styles@6.2.3: {} - argparse@2.0.1: {} balanced-match@1.0.2: {} - balanced-match@4.0.4: {} - - baseline-browser-mapping@2.10.30: - optional: true - - better-auth@1.6.25(drizzle-orm@0.45.2(kysely@0.29.4))(next@16.2.12(react-dom@19.2.6(react@19.2.6))(react@19.2.6))(react-dom@19.2.6(react@19.2.6))(react@19.2.6): - dependencies: - '@better-auth/core': 1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1) - '@better-auth/drizzle-adapter': 1.6.25(@better-auth/core@1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1))(@better-auth/utils@0.4.2)(drizzle-orm@0.45.2(kysely@0.29.4)) - '@better-auth/kysely-adapter': 1.6.25(@better-auth/core@1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1))(@better-auth/utils@0.4.2)(kysely@0.29.4) - '@better-auth/memory-adapter': 1.6.25(@better-auth/core@1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1))(@better-auth/utils@0.4.2) - '@better-auth/mongo-adapter': 1.6.25(@better-auth/core@1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1))(@better-auth/utils@0.4.2) - '@better-auth/prisma-adapter': 1.6.25(@better-auth/core@1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1))(@better-auth/utils@0.4.2) - '@better-auth/telemetry': 1.6.25(@better-auth/core@1.6.25(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1)(better-call@1.3.7(zod@4.4.3))(jose@6.2.4)(kysely@0.29.4)(nanostores@1.4.1))(@better-auth/utils@0.4.2)(@better-fetch/fetch@1.3.1) - '@better-auth/utils': 0.4.2 - '@better-fetch/fetch': 1.3.1 - '@noble/ciphers': 2.2.0 - '@noble/hashes': 2.2.0 - better-call: 1.3.7(zod@4.4.3) - defu: 6.1.7 - jose: 6.2.4 - kysely: 0.29.4 - nanostores: 1.4.1 - zod: 4.4.3 - optionalDependencies: - drizzle-orm: 0.45.2(kysely@0.29.4) - next: 16.2.12(react-dom@19.2.6(react@19.2.6))(react@19.2.6) - react: 19.2.6 - react-dom: 19.2.6(react@19.2.6) - transitivePeerDependencies: - - '@cloudflare/workers-types' - - '@opentelemetry/api' - - better-call@1.3.7(zod@4.4.3): - dependencies: - '@better-auth/utils': 0.4.2 - '@better-fetch/fetch': 1.3.1 - rou3: 0.7.12 - set-cookie-parser: 3.1.2 - optionalDependencies: - zod: 4.4.3 - - blake3-wasm@2.1.5: {} - brace-expansion@1.1.14: dependencies: balanced-match: 1.0.2 concat-map: 0.0.1 - brace-expansion@5.0.6: - dependencies: - balanced-match: 4.0.4 - - buffer-from@1.1.2: - optional: true - - c8@12.0.0: - dependencies: - '@bcoe/v8-coverage': 1.0.2 - '@istanbuljs/schema': 0.1.6 - find-up: 5.0.0 - foreground-child: 3.3.1 - istanbul-lib-coverage: 3.2.2 - istanbul-lib-report: 3.0.1 - istanbul-reports: 3.2.0 - test-exclude: 8.0.0 - v8-to-istanbul: 9.3.0 - yargs: 18.1.0 - yargs-parser: 21.1.1 - callsites@3.1.0: {} - caniuse-lite@1.0.30001793: - optional: true - chalk@4.1.2: dependencies: ansi-styles: 4.3.0 supports-color: 7.2.0 - client-only@0.0.1: - optional: true - - cliui@9.0.1: - dependencies: - string-width: 7.2.0 - strip-ansi: 7.2.0 - wrap-ansi: 9.0.2 - color-convert@2.0.1: dependencies: color-name: 1.1.4 color-name@1.1.4: {} - commander@2.20.3: - optional: true - concat-map@0.0.1: {} - convert-source-map@2.0.0: {} - - cookie@1.1.1: {} - cross-spawn@7.0.6: dependencies: path-key: 3.1.1 @@ -3047,49 +993,6 @@ snapshots: deep-is@0.1.4: {} - defu@6.1.7: {} - - detect-libc@2.1.2: {} - - drizzle-orm@0.45.2(kysely@0.29.4): - optionalDependencies: - kysely: 0.29.4 - - emoji-regex@10.6.0: {} - - error-stack-parser-es@1.0.5: {} - - esbuild@0.28.1: - optionalDependencies: - '@esbuild/aix-ppc64': 0.28.1 - '@esbuild/android-arm': 0.28.1 - '@esbuild/android-arm64': 0.28.1 - '@esbuild/android-x64': 0.28.1 - '@esbuild/darwin-arm64': 0.28.1 - '@esbuild/darwin-x64': 0.28.1 - '@esbuild/freebsd-arm64': 0.28.1 - '@esbuild/freebsd-x64': 0.28.1 - '@esbuild/linux-arm': 0.28.1 - '@esbuild/linux-arm64': 0.28.1 - '@esbuild/linux-ia32': 0.28.1 - '@esbuild/linux-loong64': 0.28.1 - '@esbuild/linux-mips64el': 0.28.1 - '@esbuild/linux-ppc64': 0.28.1 - '@esbuild/linux-riscv64': 0.28.1 - '@esbuild/linux-s390x': 0.28.1 - '@esbuild/linux-x64': 0.28.1 - '@esbuild/netbsd-arm64': 0.28.1 - '@esbuild/netbsd-x64': 0.28.1 - '@esbuild/openbsd-arm64': 0.28.1 - '@esbuild/openbsd-x64': 0.28.1 - '@esbuild/openharmony-arm64': 0.28.1 - '@esbuild/sunos-x64': 0.28.1 - '@esbuild/win32-arm64': 0.28.1 - '@esbuild/win32-ia32': 0.28.1 - '@esbuild/win32-x64': 0.28.1 - - escalade@3.2.0: {} - escape-string-regexp@4.0.0: {} eslint-scope@8.4.0: @@ -3190,22 +1093,10 @@ snapshots: flatted@3.4.2: {} - foreground-child@3.3.1: - dependencies: - cross-spawn: 7.0.6 - signal-exit: 4.1.0 - formatly@0.3.0: dependencies: fd-package-json: 2.0.0 - fsevents@2.3.3: - optional: true - - get-caller-file@2.0.5: {} - - get-east-asian-width@1.6.0: {} - get-tsconfig@4.14.1: dependencies: resolve-pkg-maps: 1.0.0 @@ -3214,18 +1105,10 @@ snapshots: dependencies: is-glob: 4.0.3 - glob@13.0.6: - dependencies: - minimatch: 10.2.5 - minipass: 7.1.3 - path-scurry: 2.0.2 - globals@14.0.0: {} has-flag@4.0.0: {} - html-escaper@2.0.2: {} - ignore@5.3.2: {} import-fresh@3.3.1: @@ -3243,23 +1126,8 @@ snapshots: isexe@2.0.0: {} - istanbul-lib-coverage@3.2.2: {} - - istanbul-lib-report@3.0.1: - dependencies: - istanbul-lib-coverage: 3.2.2 - make-dir: 4.0.0 - supports-color: 7.2.0 - - istanbul-reports@3.2.0: - dependencies: - html-escaper: 2.0.2 - istanbul-lib-report: 3.0.1 - jiti@2.7.0: {} - jose@6.2.4: {} - js-yaml@4.1.1: dependencies: argparse: 2.0.1 @@ -3301,8 +1169,6 @@ snapshots: dependencies: json-buffer: 3.0.1 - kleur@4.1.5: {} - knip@6.32.2: dependencies: fdir: 6.5.0(picomatch@4.0.5) @@ -3319,129 +1185,25 @@ snapshots: yaml: 2.9.0 zod: 4.4.3 - kysely@0.29.4: {} - levn@0.4.1: dependencies: prelude-ls: 1.2.1 type-check: 0.4.0 - lightningcss-android-arm64@1.33.0: - optional: true - - lightningcss-darwin-arm64@1.33.0: - optional: true - - lightningcss-darwin-x64@1.33.0: - optional: true - - lightningcss-freebsd-x64@1.33.0: - optional: true - - lightningcss-linux-arm-gnueabihf@1.33.0: - optional: true - - lightningcss-linux-arm64-gnu@1.33.0: - optional: true - - lightningcss-linux-arm64-musl@1.33.0: - optional: true - - lightningcss-linux-x64-gnu@1.33.0: - optional: true - - lightningcss-linux-x64-musl@1.33.0: - optional: true - - lightningcss-win32-arm64-msvc@1.33.0: - optional: true - - lightningcss-win32-x64-msvc@1.33.0: - optional: true - - lightningcss@1.33.0: - dependencies: - detect-libc: 2.1.2 - optionalDependencies: - lightningcss-android-arm64: 1.33.0 - lightningcss-darwin-arm64: 1.33.0 - lightningcss-darwin-x64: 1.33.0 - lightningcss-freebsd-x64: 1.33.0 - lightningcss-linux-arm-gnueabihf: 1.33.0 - lightningcss-linux-arm64-gnu: 1.33.0 - lightningcss-linux-arm64-musl: 1.33.0 - lightningcss-linux-x64-gnu: 1.33.0 - lightningcss-linux-x64-musl: 1.33.0 - lightningcss-win32-arm64-msvc: 1.33.0 - lightningcss-win32-x64-msvc: 1.33.0 - locate-path@6.0.0: dependencies: p-locate: 5.0.0 lodash.merge@4.6.2: {} - lru-cache@11.5.2: {} - - make-dir@4.0.0: - dependencies: - semver: 7.8.0 - - miniflare@5.20260804.1-alpha: - dependencies: - '@cspotcode/source-map-support': 0.8.1 - sharp: 0.35.2 - undici: 7.29.0 - workerd: 1.20260804.1 - ws: 8.21.0 - youch: 4.1.0-beta.10 - transitivePeerDependencies: - - bufferutil - - utf-8-validate - - minimatch@10.2.5: - dependencies: - brace-expansion: 5.0.6 - minimatch@3.1.5: dependencies: brace-expansion: 1.1.14 - minipass@7.1.3: {} - ms@2.1.3: {} - nanoid@3.3.18: {} - - nanostores@1.4.1: {} - natural-compare@1.4.0: {} - next@16.2.12(react-dom@19.2.6(react@19.2.6))(react@19.2.6): - dependencies: - '@next/env': 16.2.12 - '@swc/helpers': 0.5.15 - baseline-browser-mapping: 2.10.30 - caniuse-lite: 1.0.30001793 - postcss: 8.4.31 - react: 19.2.6 - react-dom: 19.2.6(react@19.2.6) - styled-jsx: 5.1.6(react@19.2.6) - optionalDependencies: - '@next/swc-darwin-arm64': 16.2.12 - '@next/swc-darwin-x64': 16.2.12 - '@next/swc-linux-arm64-gnu': 16.2.12 - '@next/swc-linux-arm64-musl': 16.2.12 - '@next/swc-linux-x64-gnu': 16.2.12 - '@next/swc-linux-x64-musl': 16.2.12 - '@next/swc-win32-arm64-msvc': 16.2.12 - '@next/swc-win32-x64-msvc': 16.2.12 - sharp: 0.34.5 - transitivePeerDependencies: - - '@babel/core' - - babel-plugin-macros - optional: true - optionator@0.9.4: dependencies: deep-is: 0.1.4 @@ -3513,212 +1275,34 @@ snapshots: path-key@3.1.1: {} - path-scurry@2.0.2: - dependencies: - lru-cache: 11.5.2 - minipass: 7.1.3 - - path-to-regexp@6.3.0: {} - - pathe@2.0.3: {} - - picocolors@1.1.1: {} - picomatch@4.0.5: {} - postcss@8.4.31: - dependencies: - nanoid: 3.3.18 - picocolors: 1.1.1 - source-map-js: 1.2.1 - optional: true - - postcss@8.5.26: - dependencies: - nanoid: 3.3.18 - picocolors: 1.1.1 - source-map-js: 1.2.1 - prelude-ls@1.2.1: {} prettier@3.9.6: {} punycode@2.3.1: {} - react-dom@19.2.6(react@19.2.6): - dependencies: - react: 19.2.6 - scheduler: 0.27.0 - optional: true - - react@19.2.6: - optional: true - resolve-from@4.0.0: {} resolve-pkg-maps@1.0.0: {} - rolldown@1.2.3: - dependencies: - '@oxc-project/types': 0.143.0 - '@rolldown/pluginutils': 1.0.1 - optionalDependencies: - '@rolldown/binding-android-arm64': 1.2.3 - '@rolldown/binding-darwin-arm64': 1.2.3 - '@rolldown/binding-darwin-x64': 1.2.3 - '@rolldown/binding-freebsd-x64': 1.2.3 - '@rolldown/binding-linux-arm-gnueabihf': 1.2.3 - '@rolldown/binding-linux-arm64-gnu': 1.2.3 - '@rolldown/binding-linux-arm64-musl': 1.2.3 - '@rolldown/binding-linux-ppc64-gnu': 1.2.3 - '@rolldown/binding-linux-s390x-gnu': 1.2.3 - '@rolldown/binding-linux-x64-gnu': 1.2.3 - '@rolldown/binding-linux-x64-musl': 1.2.3 - '@rolldown/binding-openharmony-arm64': 1.2.3 - '@rolldown/binding-win32-arm64-msvc': 1.2.3 - '@rolldown/binding-win32-x64-msvc': 1.2.3 - - rou3@0.7.12: {} - - scheduler@0.27.0: - optional: true - - semver@7.8.0: {} - - semver@7.8.5: {} - - set-cookie-parser@3.1.2: {} - - sharp@0.34.5: - dependencies: - '@img/colour': 1.1.0 - detect-libc: 2.1.2 - semver: 7.8.5 - optionalDependencies: - '@img/sharp-darwin-arm64': 0.34.5 - '@img/sharp-darwin-x64': 0.34.5 - '@img/sharp-libvips-darwin-arm64': 1.2.4 - '@img/sharp-libvips-darwin-x64': 1.2.4 - '@img/sharp-libvips-linux-arm': 1.2.4 - '@img/sharp-libvips-linux-arm64': 1.2.4 - '@img/sharp-libvips-linux-ppc64': 1.2.4 - '@img/sharp-libvips-linux-riscv64': 1.2.4 - '@img/sharp-libvips-linux-s390x': 1.2.4 - '@img/sharp-libvips-linux-x64': 1.2.4 - '@img/sharp-libvips-linuxmusl-arm64': 1.2.4 - '@img/sharp-libvips-linuxmusl-x64': 1.2.4 - '@img/sharp-linux-arm': 0.34.5 - '@img/sharp-linux-arm64': 0.34.5 - '@img/sharp-linux-ppc64': 0.34.5 - '@img/sharp-linux-riscv64': 0.34.5 - '@img/sharp-linux-s390x': 0.34.5 - '@img/sharp-linux-x64': 0.34.5 - '@img/sharp-linuxmusl-arm64': 0.34.5 - '@img/sharp-linuxmusl-x64': 0.34.5 - '@img/sharp-wasm32': 0.34.5 - '@img/sharp-win32-arm64': 0.34.5 - '@img/sharp-win32-ia32': 0.34.5 - '@img/sharp-win32-x64': 0.34.5 - optional: true - - sharp@0.35.2: - dependencies: - '@img/colour': 1.1.0 - detect-libc: 2.1.2 - semver: 7.8.5 - optionalDependencies: - '@img/sharp-darwin-arm64': 0.35.2 - '@img/sharp-darwin-x64': 0.35.2 - '@img/sharp-freebsd-wasm32': 0.35.2 - '@img/sharp-libvips-darwin-arm64': 1.3.1 - '@img/sharp-libvips-darwin-x64': 1.3.1 - '@img/sharp-libvips-linux-arm': 1.3.1 - '@img/sharp-libvips-linux-arm64': 1.3.1 - '@img/sharp-libvips-linux-ppc64': 1.3.1 - '@img/sharp-libvips-linux-riscv64': 1.3.1 - '@img/sharp-libvips-linux-s390x': 1.3.1 - '@img/sharp-libvips-linux-x64': 1.3.1 - '@img/sharp-libvips-linuxmusl-arm64': 1.3.1 - '@img/sharp-libvips-linuxmusl-x64': 1.3.1 - '@img/sharp-linux-arm': 0.35.2 - '@img/sharp-linux-arm64': 0.35.2 - '@img/sharp-linux-ppc64': 0.35.2 - '@img/sharp-linux-riscv64': 0.35.2 - '@img/sharp-linux-s390x': 0.35.2 - '@img/sharp-linux-x64': 0.35.2 - '@img/sharp-linuxmusl-arm64': 0.35.2 - '@img/sharp-linuxmusl-x64': 0.35.2 - '@img/sharp-webcontainers-wasm32': 0.35.2 - '@img/sharp-win32-arm64': 0.35.2 - '@img/sharp-win32-ia32': 0.35.2 - '@img/sharp-win32-x64': 0.35.2 - shebang-command@2.0.0: dependencies: shebang-regex: 3.0.0 shebang-regex@3.0.0: {} - signal-exit@4.1.0: {} - smol-toml@1.8.0: {} - source-map-js@1.2.1: {} - - source-map-support@0.5.21: - dependencies: - buffer-from: 1.1.2 - source-map: 0.6.1 - optional: true - - source-map@0.6.1: - optional: true - - string-width@7.2.0: - dependencies: - emoji-regex: 10.6.0 - get-east-asian-width: 1.6.0 - strip-ansi: 7.2.0 - - string-width@8.2.2: - dependencies: - get-east-asian-width: 1.6.0 - strip-ansi: 7.2.0 - - strip-ansi@7.2.0: - dependencies: - ansi-regex: 6.2.2 - strip-json-comments@3.1.1: {} strip-json-comments@5.0.3: {} - styled-jsx@5.1.6(react@19.2.6): - dependencies: - client-only: 0.0.1 - react: 19.2.6 - optional: true - - supports-color@10.2.2: {} - supports-color@7.2.0: dependencies: has-flag: 4.0.0 - terser@5.47.1: - dependencies: - '@jridgewell/source-map': 0.3.11 - acorn: 8.16.0 - commander: 2.20.3 - source-map-support: 0.5.21 - optional: true - - test-exclude@8.0.0: - dependencies: - '@istanbuljs/schema': 0.1.6 - glob: 13.0.6 - minimatch: 10.2.5 - tinyglobby@0.2.17: dependencies: fdir: 6.5.0(picomatch@4.0.5) @@ -3731,43 +1315,12 @@ snapshots: dependencies: prelude-ls: 1.2.1 - typescript@5.9.3: {} - unbash@4.0.10: {} - undici-types@6.21.0: {} - - undici@7.29.0: {} - - unenv@2.0.0-rc.24: - dependencies: - pathe: 2.0.3 - uri-js@4.4.1: dependencies: punycode: 2.3.1 - v8-to-istanbul@9.3.0: - dependencies: - '@jridgewell/trace-mapping': 0.3.31 - '@types/istanbul-lib-coverage': 2.0.6 - convert-source-map: 2.0.0 - - vite@8.2.1(@types/node@22.19.19)(esbuild@0.28.1)(jiti@2.7.0)(terser@5.47.1)(yaml@2.9.0): - dependencies: - lightningcss: 1.33.0 - picomatch: 4.0.5 - postcss: 8.5.26 - rolldown: 1.2.3 - tinyglobby: 0.2.17 - optionalDependencies: - '@types/node': 22.19.19 - esbuild: 0.28.1 - fsevents: 2.3.3 - jiti: 2.7.0 - terser: 5.47.1 - yaml: 2.9.0 - walk-up-path@4.0.0: {} which@2.0.2: @@ -3776,68 +1329,8 @@ snapshots: word-wrap@1.2.5: {} - workerd@1.20260804.1: - optionalDependencies: - '@cloudflare/workerd-darwin-64': 1.20260804.1 - '@cloudflare/workerd-darwin-arm64': 1.20260804.1 - '@cloudflare/workerd-linux-64': 1.20260804.1 - '@cloudflare/workerd-linux-arm64': 1.20260804.1 - '@cloudflare/workerd-windows-64': 1.20260804.1 - - wrangler@4.121.0: - dependencies: - '@cloudflare/kv-asset-handler': 0.5.0 - '@cloudflare/unenv-preset': 2.16.1(unenv@2.0.0-rc.24)(workerd@1.20260804.1) - blake3-wasm: 2.1.5 - esbuild: 0.28.1 - miniflare: 5.20260804.1-alpha - path-to-regexp: 6.3.0 - unenv: 2.0.0-rc.24 - workerd: 1.20260804.1 - optionalDependencies: - fsevents: 2.3.3 - transitivePeerDependencies: - - bufferutil - - utf-8-validate - - wrap-ansi@9.0.2: - dependencies: - ansi-styles: 6.2.3 - string-width: 7.2.0 - strip-ansi: 7.2.0 - - ws@8.21.0: {} - - y18n@5.0.8: {} - yaml@2.9.0: {} - yargs-parser@21.1.1: {} - - yargs-parser@22.0.0: {} - - yargs@18.1.0: - dependencies: - cliui: 9.0.1 - escalade: 3.2.0 - get-caller-file: 2.0.5 - string-width: 8.2.2 - y18n: 5.0.8 - yargs-parser: 22.0.0 - yocto-queue@0.1.0: {} - youch-core@0.3.3: - dependencies: - '@poppinss/exception': 1.2.3 - error-stack-parser-es: 1.0.5 - - youch@4.1.0-beta.10: - dependencies: - '@poppinss/colors': 4.1.6 - '@poppinss/dumper': 0.6.5 - '@speed-highlight/core': 1.2.15 - cookie: 1.1.1 - youch-core: 0.3.3 - zod@4.4.3: {} diff --git a/public/.nojekyll b/public/.nojekyll new file mode 100644 index 0000000..e69de29 diff --git a/public/CNAME b/public/CNAME new file mode 100644 index 0000000..ead38c4 --- /dev/null +++ b/public/CNAME @@ -0,0 +1 @@ +setline.significanthobbies.com diff --git a/public/api-ai.json b/public/api/ai similarity index 69% rename from public/api-ai.json rename to public/api/ai index eb2173e..31b331b 100644 --- a/public/api-ai.json +++ b/public/api/ai @@ -16,32 +16,32 @@ "url": "https://setline.significanthobbies.com/", "md": "https://setline.significanthobbies.com/index.md", "kind": "static", - "description": "Product home" + "description": "What Setline does, how one set is recorded, and what it refuses to do" }, { "id": "privacy", "url": "https://setline.significanthobbies.com/privacy", "md": "https://setline.significanthobbies.com/privacy.md", "kind": "static", - "description": "Device and private cloud data handling" + "description": "How the app handles data: no account, no server, nothing collected; plus this site's third-party scripts" }, { "id": "terms", "url": "https://setline.significanthobbies.com/terms", "md": "https://setline.significanthobbies.com/terms.md", "kind": "static", - "description": "Product terms" + "description": "Terms of use, the health disclaimer, and what calculated values do and do not mean" }, { "id": "changelog", "url": "https://setline.significanthobbies.com/changelog", "md": "https://setline.significanthobbies.com/changelog.md", "kind": "static", - "description": "Verified product releases" + "description": "What shipped, newest first, including what was removed" } ], "auth": { "public": true, - "notes": "Auth-walled app routes are not agent-indexed unless listed here." + "notes": "Every surface here is public. Setline has no accounts and no auth-walled routes; recorded training never leaves the device." } } diff --git a/public/changelog.html b/public/changelog.html index 179b34d..12436c2 100644 --- a/public/changelog.html +++ b/public/changelog.html @@ -4,24 +4,81 @@ Setline — Changelog - + - + -
-

Setline changelog

-

Setline's owned changelog records verified releases for authored programme order, device-first execution, rest timing, explicit workout deviations, history, optional private sync, and responsive PWA support.

- ← Back to Setline +
+
+ SETLINE +

Changelog

+

What shipped, newest first — including what was taken back out. Setline is pre-release, so there are no version numbers yet.

+
+ +
+

16 August 2026

+

Apple-only, and no backend at all

+

The Cloudflare Worker, its D1 database, and the whole account layer are gone: Google sign-in, Sign in with Apple, private server-side state, and the sync-conflict flow. Every table in that database held zero rows, so nothing was lost — nobody had ever signed in. The web app went with it.

+

Setline is now one iPhone app with no server, no account and no hosting account, and this site is static files. Training lives on the device that recorded it, and the JSON export is the only way to move or back it up. Syncing across devices through iCloud is the next thing being built.

+
+ +
+

16 August 2026

+

Set targets that can express a real programme

+

Planned sets used to carry a line of free text, which meant a programme with rep ranges, percentages, reps in reserve, tempo, per-side work and rest bands could not actually be represented. Targets are now structured, and warm-up sets are excluded from volume, records and progression rather than quietly counted.

+

The author's dated twelve-week strength, cardio and mobility block now resolves natively for each of its 84 days, including week-dependent volume, the cardio interval build, and the pull-up checkpoints. Progression follows the increments the plan itself specifies.

+
+ +
+

16 August 2026

+

Current, ideal, and the distance between them

+

Every exercise now has an identity, a measured current value, and a target you author. Current values — estimated one-rep max, top set, max reps, best hold, longest distance, best pace, range of motion — are derived only from completed working sets, and each one cites the session that produced it. Progress shows the gap, the weekly rate, a projected arrival date and a trend chart. With no evidence there is no chart, rather than an invented one.

+

A bundled movement catalogue covers strength, stamina, mobility and flexibility, plus the CrossFit movement vocabulary.

+
+ +
+

16 August 2026

+

One set, recorded the way it happened

+

A set can now hold as many segments as it took: 5 reps × 40 kg then 2 reps × 30 kg records as one set, not two. Shorthand entry accepts 5x40, bw+10 x 8, assist 15kg x 6, 45s and 5km 25min, and shows its interpretation before anything is recorded — the parser is rule-based, so entry is never a guess.

+

A set timer now runs alongside the rest timer, and a local notification fires when rest ends so the timer survives leaving the app.

+
+ +
+

12 August 2026

+

First native iPhone build

+

Complete workout execution on device: authored-order session snapshots, activity-specific recording, skips, session-only extra sets, deferrals, timestamp-derived rest, and recovery after relaunch. Plus planning, history, versioned export and import, and accessibility work.

+
+ +
+

31 July 2026

+

Progress from recorded history, and nothing else

+

Static example charts were replaced with analytics computed from real recorded sessions, with bounded trends, explicit provenance for every value, and honest empty states. Missing history is never treated as a missed workout.

+
+ +
+

28 July 2026

+

Sessions that survive contact with a real workout

+

Partial and drop segments, extra sets, explicit deferral, and actual rest cadence — recorded as deviations from the plan rather than edits to it. The authored programme stays immutable; execution is a separate record.

+
+ +
+

27 July 2026

+

First release

+

The workout player: one authored programme, presented one action at a time, with explicit recording and controlled rest.

+
+ +
diff --git a/public/changelog.md b/public/changelog.md index d73aaef..98950f6 100644 --- a/public/changelog.md +++ b/public/changelog.md @@ -1,3 +1,75 @@ # Setline changelog -Setline's owned changelog records verified releases for authored programme order, device-first execution, rest timing, explicit workout deviations, history, optional private sync, and responsive PWA support. +What shipped, newest first — including what was taken back out. Setline is +pre-release, so there are no version numbers yet. + +## 16 August 2026 — Apple-only, and no backend at all + +The Cloudflare Worker, its D1 database, and the whole account layer are gone: +Google sign-in, Sign in with Apple, private server-side state, and the +sync-conflict flow. Every table in that database held zero rows, so nothing was +lost — nobody had ever signed in. The web app went with it. + +Setline is now one iPhone app with no server, no account and no hosting account, +and this site is static files. Training lives on the device that recorded it, and +the JSON export is the only way to move or back it up. Syncing across devices +through iCloud is the next thing being built. + +## 16 August 2026 — Set targets that can express a real programme + +Planned sets used to carry a line of free text, which meant a programme with rep +ranges, percentages, reps in reserve, tempo, per-side work and rest bands could +not actually be represented. Targets are now structured, and warm-up sets are +excluded from volume, records and progression rather than quietly counted. + +The author's dated twelve-week strength, cardio and mobility block now resolves +natively for each of its 84 days, including week-dependent volume, the cardio +interval build, and the pull-up checkpoints. Progression follows the increments +the plan itself specifies. + +## 16 August 2026 — Current, ideal, and the distance between them + +Every exercise now has an identity, a measured current value, and a target you +author. Current values — estimated one-rep max, top set, max reps, best hold, +longest distance, best pace, range of motion — are derived only from completed +working sets, and each one cites the session that produced it. Progress shows the +gap, the weekly rate, a projected arrival date and a trend chart. With no +evidence there is no chart, rather than an invented one. + +A bundled movement catalogue covers strength, stamina, mobility and flexibility, +plus the CrossFit movement vocabulary. + +## 16 August 2026 — One set, recorded the way it happened + +A set can now hold as many segments as it took: **5 reps × 40 kg** then +**2 reps × 30 kg** records as one set, not two. Shorthand entry accepts `5x40`, +`bw+10 x 8`, `assist 15kg x 6`, `45s` and `5km 25min`, and shows its +interpretation before anything is recorded — the parser is rule-based, so entry is +never a guess. + +A set timer now runs alongside the rest timer, and a local notification fires +when rest ends so the timer survives leaving the app. + +## 12 August 2026 — First native iPhone build + +Complete workout execution on device: authored-order session snapshots, +activity-specific recording, skips, session-only extra sets, deferrals, +timestamp-derived rest, and recovery after relaunch. Plus planning, history, +versioned export and import, and accessibility work. + +## 31 July 2026 — Progress from recorded history, and nothing else + +Static example charts were replaced with analytics computed from real recorded +sessions, with bounded trends, explicit provenance for every value, and honest +empty states. Missing history is never treated as a missed workout. + +## 28 July 2026 — Sessions that survive contact with a real workout + +Partial and drop segments, extra sets, explicit deferral, and actual rest +cadence — recorded as deviations from the plan rather than edits to it. The +authored programme stays immutable; execution is a separate record. + +## 27 July 2026 — First release + +The workout player: one authored programme, presented one action at a time, with +explicit recording and controlled rest. diff --git a/public/index.html b/public/index.html index df538d9..8016161 100644 --- a/public/index.html +++ b/public/index.html @@ -3,37 +3,694 @@ - Setline — Workout execution tracker - + Setline — Follow your training plan. Record the truth. + - - + + + + + -

Setline

-

Build the plan once. Follow it precisely every day with guided sets, rest timing, and device-local workout history.

- + + +
+ +
+ +
+ +
+
+
+ iPhone · in development +

Stop reading your plan off a PDF between sets.

+

+ Setline runs your written programme one set at a time — every rep range, + rest band and coaching cue — then records what you actually lifted. + It tells you the load your last three sets earned, not the load you + half-remember. +

+ +
+
84dated days
+
4pillars measured
+
0invented numbers
+
+ +
+ See a set recorded → +

+ Not on the App Store yet. The + source is public + while it is built. +

+
+
+ +
+
Setline's Today screen showing week 3 of 12, an easy cardio and mobility session, its exercise and step counts, the four pillars it trains, and the authored rules for the day.
+
Today, resolved from a dated 12-week block — not a list you re-pick every morning.
+
+
+
+ + +
+
+ Why another one +

Your plan is precise. Your tracker isn't.

+

+ A written programme carries rep ranges, reps in reserve, rest bands, + per-side work, tempo and progression rules. Most trackers give you two + boxes and forget the rest. +

+
    +
  • + 01 +
    + “3 × 6–10, 1–2 reps in reserve, rest 2.5–3 min.” +

    Typed into a box for weight and a box for reps, that instruction is gone. Nothing can check whether you earned the next load.

    +
    +
  • +
  • + 02 +
    + Five at 40 kg, then two at 30 kg. That is one set. +

    Split it into two rows and your set count lies. Drop the second half and your volume does.

    +
    +
  • +
  • + 03 +
    + A warm-up is not a working set. +

    Count a 20 kg bar ramp toward your volume and every trend you look at is wrong.

    +
    +
  • +
  • + 04 +
    + Your rest timer dies when you put the phone down. +

    Which is exactly when you need it.

    +
    +
  • +
+
+
+ + +
+
+
+
Setline's workout player showing a 40 kg by 8 reps warm-up target, the authored rest of one minute, a coaching cue, a set timer at zero with a Start set button, and reps and weight fields with an Add segment control.
+
One set. Target above, timer beside it, segments below.
+
+
+ One set at a time +

Everything the set needs, and nothing else.

+
    +
  • + +
    + The target, as written +

    Rep range, load or percentage, reps in reserve, tempo, per-side, and rest as a band — because “2.5–3 min” is not the same instruction as “150 seconds”.

    +
    +
  • +
  • + +
    + A timer for the set, separate from the rest timer +

    Time under load gets recorded instead of guessed. Holds and carries count down; sets count up.

    +
    +
  • +
  • + +
    + Segments, so one set stays one set +

    Add as many as the set had. Or type 5x40, 2x30 and Setline shows you how it read that before anything is recorded.

    +
    +
  • +
  • + +
    + Rest that survives your pocket +

    Anchored to a wall-clock end time and it notifies you when it's up. Authored, adjusted and actual rest are all kept apart.

    +
    +
  • +
+
+
+
+ + +
+
+
+
Setline's bench press screen showing measured current values of 91.8 kg estimated one-rep max, 72.5 kg top set load and 8 max repetitions, each citing the session that produced it, above an authored 90 kg target with 17.5 kg to go at 2.5 kg per week.
+
Bench press: measured, authored, and the distance between them.
+
+
+ Current vs ideal +

The number you have. The number you want.

+

+ Set a target per exercise — estimated 1RM, top set at a rep count, max + reps, best hold, distance, pace, or measured range. Setline works out + where you are and how fast you're closing the gap. +

+
    +
  • + +
    + Measured from working sets only +

    A 200 kg leg-press warm-up can never become your record.

    +
    +
  • +
  • + +
    + Every value names the session that produced it +

    “72.5 kg · Upper · 16 Aug”. You can always go and check.

    +
    +
  • +
  • + +
    + Rate and arrival, from your own data +

    2.5 kg a week and 17.5 kg to go. If the trend points the wrong way, Setline says nothing rather than promising a date.

    +
    +
  • +
  • + +
    + Progression that follows your rules +

    Hit the top of the range on every working set and it says add load — by your programme's increment, with the three sets that earned it printed underneath.

    +
    +
  • +
+
+
+
+ + +
+
+ Four pillars +

Strength isn't the only thing worth a number.

+

+ A hold is not a rep and a pace is not a load. Each pillar is measured in + the units that pillar actually improves in. +

+
+
+

Strength

+

Working sets, load, reps in reserve, tonnage per muscle group.

+
Estimated 1RM · top set at reps
+
+
+

Stamina

+

Intervals, easy aerobic work, and controlled hard efforts kept apart.

+
Distance · duration · pace
+
+
+

Mobility

+

Active range and control, per side, with the doses your routine prescribes.

+
Reps per side · measured range
+
+
+

Flexibility

+

Passive range and how long you can actually hold it.

+
Hold length · measured range
+
+
+

+ A bundled library of movements across all four pillars — plus the CrossFit + movement vocabulary — carries the muscles, equipment and measurable + metrics for each one. Apple Health heart-rate zones, range-of-motion + assessments and AMRAP/EMOM scoring are being built next; they are not + claimed as shipped. +

+
+
+ + +
+
+ Character +

What Setline refuses to do.

+

+ A training log is only worth keeping if you trust every number in it. +

+
+
+

No invented numbers

+

If nothing comparable has been recorded, the value reads “unavailable”. It is never estimated, interpolated, or filled in from an average.

+
+
+

No chart before there is data

+

A trend needs at least two comparable sessions. Until then you get a sentence explaining why, not a flat line pretending to be progress.

+
+
+

No rewriting your plan

+

Skip a set, defer it, or add one, and the authored position is kept. A deviation is recorded as a deviation — never as a plan you never wrote.

+
+
+

No account required

+

Every workout action works with no signal and no sign-in. Your training stays on your iPhone unless you choose otherwise.

+
+
+
+
+ + +
+
+ Fit +

Who this is for.

+
+
+

A good fit if

+
    +
  • You already follow a written programme — yours, a coach's, or a book's.
  • +
  • You want the number in the app to be the number you actually lifted.
  • +
  • You care about mobility and conditioning, not only the barbell.
  • +
  • You'd rather see “unavailable” than a plausible guess.
  • +
+
+
+

A poor fit if

+
    +
  • You want an app to invent your training for you.
  • +
  • You want a social feed, streaks, or badges.
  • +
  • You're on Android — Setline is iPhone only.
  • +
  • You want it today. It is still in development.
  • +
+
+
+
+
+ +
+
+ Questions +

Straight answers.

+
+
+ Can I download it? +

Not yet. Setline is an iPhone app in active development and is not on the App Store. The source is public if you want to read it or build it yourself.

+
+
+ Does it work without signal? +

Yes — entirely. Starting a workout, recording sets, resting, and finishing all happen on the device. There is no request in the middle of your set.

+
+
+ Do I need an account? +

There isn't one. Setline has no sign-in, no server and no database — nothing to register for and nothing to breach. The trade-off is real: your training lives on one iPhone until iCloud sync ships, so use the export if you want a backup.

+
+
+ Can I use my own programme? +

Yes. Build templates with structured targets and schedule them across a 1–16 week block. A dated 12-week strength, cardio and mobility programme ships bundled as an example of what the format can carry.

+
+
+ How do I record a drop set or a rest-pause set? +

As one set with several segments. Add a segment per piece, or type shorthand like 5x40, 2x30 or bw+10x8. Setline shows its reading of the shorthand before it applies anything, so entry is never a guess.

+
+
+ Does it do CrossFit? +

Partly, today. The movement vocabulary — thrusters, wall balls, toes-to-bar, double-unders, muscle-ups and the rest — is in the bundled library. AMRAP, EMOM, For Time and benchmark-WOD scoring are being built and are not claimed as working yet.

+
+
+ Does it read Apple Health? +

Not yet. Heart-rate zones, VO2 max and writing completed sessions back to Health are the next block of work.

+
+
+ What does it cost? +

Nothing. It is a personal project built for one person's training block, published because the approach might be useful to someone else.

+
+
+ Where does my data live, and can I get it out? +

On your iPhone, in one file, and nowhere else. There is a versioned JSON export of everything, and an import that previews what it will replace before it replaces it. Since there is no server copy, that export is also your only backup. See the privacy notice.

+
+
+
+
+
+ +
+
+

+ The goal is not twelve perfect weeks. It's twelve weeks where one + imperfect day never becomes an abandoned programme. +

+

+ I built Setline because I was carrying a 12-week plan into the gym as a PDF + and guessing at loads I'd already earned. It does what I needed it to do, + and it says “unavailable” whenever it doesn't know. + — Sarthak Agrawal +

+ +

Setline · iPhone app in development · Not on the App Store yet

+
+
+ diff --git a/public/index.md b/public/index.md index bee442a..9935fbf 100644 --- a/public/index.md +++ b/public/index.md @@ -1,13 +1,49 @@ # Setline -Build the plan once. Follow it precisely every day. +Follow your training plan. Record the truth. -## What it is +An iPhone app that runs a written strength, cardio and mobility programme one set +at a time, records what was actually lifted, and shows how far each exercise is +from an authored target. -- Mobile-first workout execution for a structured programme -- Exact authored exercise and set order -- Explicit recorded, calculated, adjusted, and unavailable values -- Device-first active workouts with optional private sync +Status: in development. Not on the App Store yet. Free. iPhone only. + +## What it does + +- Resolves a dated programme day by day, including week-dependent rules such as + added sets, interval round counts and scheduled reassessments +- Structured set targets: rep ranges, absolute, relative, bodyweight or assisted + load, reps in reserve, RPE, tempo, per-side work, and rest as a band +- Excludes warm-up, preparation and cooldown work from volume, records and + progression decisions +- Records one set as several segments, so 5 reps x 40 kg followed by + 2 reps x 30 kg stays a single set +- Times the set itself, separately from rest; rest is anchored to a wall-clock end + time and notifies on completion +- Measures a current value per exercise (estimated 1RM, top set load, max + repetitions, best hold, longest distance, best pace, range of motion) against an + authored target, with rate of change and projected arrival +- Cites the session behind every measured value +- Applies double progression using the programme's own load increments +- Carries a bundled movement library across strength, stamina, mobility and + flexibility, plus the CrossFit movement vocabulary +- Exports and imports all local data as versioned JSON + +## What it refuses to do + +- Invent, estimate or interpolate a value it has not recorded +- Draw a trend from fewer than two comparable sessions +- Rewrite an authored plan when a session deviates; deviations are recorded as + deviations and authored positions are kept +- Require an account or a network connection to run a workout + +## Not yet built + +Syncing across devices through iCloud, Apple Health heart-rate zones and VO2 +max, an Apple Watch app, AMRAP, EMOM and For Time scoring, range-of-motion +assessments, and on-device workout generation. These are not claimed as shipped. +Until iCloud sync lands, training lives only on the device that recorded it and +the JSON export is the only backup. ## Agent entrypoints diff --git a/public/legal.css b/public/legal.css new file mode 100644 index 0000000..dd38799 --- /dev/null +++ b/public/legal.css @@ -0,0 +1,178 @@ +/* Shared style for the secondary pages: privacy, terms, changelog. + One file rather than three copies, on the same tracked tokens as the landing + page so a legal page never looks like a different product. */ + +:root { + --chalk: #f7f6f0; + --paper: #ffffff; + --ink: #18262e; + --steel: #dde1dc; + --lime: #b9e83f; + --ink-62: rgba(24, 38, 46, 0.62); + --ink-12: rgba(24, 38, 46, 0.12); + --sans: -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif; +} + +*, +*::before, +*::after { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +html { + -webkit-text-size-adjust: 100%; +} + +body { + font-family: var(--sans); + background: var(--chalk); + color: var(--ink); + line-height: 1.6; + font-size: 17px; + -webkit-font-smoothing: antialiased; + padding: 0 20px 72px; +} + +.wrap { + width: 100%; + max-width: 46rem; + margin: 0 auto; +} + +header { + padding: 28px 0 20px; + border-bottom: 2px solid var(--ink); + margin-bottom: 36px; +} + +.wordmark { + font-size: 0.8rem; + font-weight: 900; + letter-spacing: 0.14em; + color: var(--ink); + text-decoration: none; +} + +h1 { + font-size: clamp(1.9rem, 5vw, 2.6rem); + font-weight: 900; + letter-spacing: -0.02em; + line-height: 1.1; + margin-top: 14px; +} + +.lede { + color: var(--ink-62); + margin-top: 12px; +} + +.updated { + font-size: 0.85rem; + color: var(--ink-62); + margin-top: 10px; +} + +h2 { + font-size: 1.15rem; + font-weight: 800; + letter-spacing: -0.01em; + margin: 36px 0 12px; +} + +h3 { + font-size: 1rem; + font-weight: 800; + margin: 22px 0 8px; +} + +p { + margin-bottom: 14px; +} + +ul { + margin: 0 0 14px 1.1rem; +} + +li { + margin-bottom: 8px; +} + +a { + color: var(--ink); + text-decoration: underline; + text-decoration-thickness: 2px; + text-underline-offset: 3px; + text-decoration-color: var(--lime); +} + +a:hover { + text-decoration-color: var(--ink); +} + +strong { + font-weight: 800; +} + +/* A stated fact worth not skimming past — used sparingly. */ +.callout { + background: var(--paper); + border: 1px solid var(--ink-12); + border-left: 4px solid var(--lime); + border-radius: 10px; + padding: 16px 18px; + margin: 20px 0; +} + +.callout p:last-child { + margin-bottom: 0; +} + +code { + font-size: 0.92em; + background: var(--paper); + border: 1px solid var(--ink-12); + border-radius: 5px; + padding: 1px 5px; +} + +.entry { + padding: 20px 0; + border-bottom: 1px solid var(--steel); +} + +.entry:last-of-type { + border-bottom: 0; +} + +.entry h2 { + margin: 0 0 4px; +} + +.date { + font-size: 0.8rem; + font-weight: 800; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--ink-62); +} + +footer { + margin-top: 48px; + padding-top: 20px; + border-top: 1px solid var(--steel); + font-size: 0.9rem; +} + +footer nav { + display: flex; + flex-wrap: wrap; + gap: 18px; +} + +.fine { + color: var(--ink-62); + font-size: 0.85rem; + margin-top: 14px; +} diff --git a/public/llms-full.txt b/public/llms-full.txt index d0d108b..c0fbb88 100644 --- a/public/llms-full.txt +++ b/public/llms-full.txt @@ -1,19 +1,55 @@ # Setline — full agent brief -Mobile-first execution layer for following a structured workout programme precisely. +iPhone app that runs a written strength, cardio and mobility programme one set at a time, records what was actually lifted, and measures each exercise against an authored target. ## Index # Setline -Build the plan once. Follow it precisely every day. +Follow your training plan. Record the truth. -## What it is +An iPhone app that runs a written strength, cardio and mobility programme one set +at a time, records what was actually lifted, and shows how far each exercise is +from an authored target. -- Mobile-first workout execution for a structured programme -- Exact authored exercise and set order -- Explicit recorded, calculated, adjusted, and unavailable values -- Device-first active workouts with optional private sync +Status: in development. Not on the App Store yet. Free. iPhone only. + +## What it does + +- Resolves a dated programme day by day, including week-dependent rules such as + added sets, interval round counts and scheduled reassessments +- Structured set targets: rep ranges, absolute, relative, bodyweight or assisted + load, reps in reserve, RPE, tempo, per-side work, and rest as a band +- Excludes warm-up, preparation and cooldown work from volume, records and + progression decisions +- Records one set as several segments, so 5 reps x 40 kg followed by + 2 reps x 30 kg stays a single set +- Times the set itself, separately from rest; rest is anchored to a wall-clock end + time and notifies on completion +- Measures a current value per exercise (estimated 1RM, top set load, max + repetitions, best hold, longest distance, best pace, range of motion) against an + authored target, with rate of change and projected arrival +- Cites the session behind every measured value +- Applies double progression using the programme's own load increments +- Carries a bundled movement library across strength, stamina, mobility and + flexibility, plus the CrossFit movement vocabulary +- Exports and imports all local data as versioned JSON + +## What it refuses to do + +- Invent, estimate or interpolate a value it has not recorded +- Draw a trend from fewer than two comparable sessions +- Rewrite an authored plan when a session deviates; deviations are recorded as + deviations and authored positions are kept +- Require an account or a network connection to run a workout + +## Not yet built + +Syncing across devices through iCloud, Apple Health heart-rate zones and VO2 +max, an Apple Watch app, AMRAP, EMOM and For Time scoring, range-of-motion +assessments, and on-device workout generation. These are not claimed as shipped. +Until iCloud sync lands, training lives only on the device that recorded it and +the JSON export is the only backup. ## Agent entrypoints @@ -23,10 +59,10 @@ Build the plan once. Follow it precisely every day. ## Product links -- Home: https://setline.significanthobbies.com/ — Workout execution app -- Privacy: https://setline.significanthobbies.com/privacy — Device and private cloud data handling -- Terms: https://setline.significanthobbies.com/terms — Product terms -- Changelog: https://setline.significanthobbies.com/changelog — Verified product releases +- Home: https://setline.significanthobbies.com/ — What Setline does, how one set is recorded, and what it refuses to do +- Privacy: https://setline.significanthobbies.com/privacy — How the app handles data: no account, no server, nothing collected; plus this site's third-party scripts +- Terms: https://setline.significanthobbies.com/terms — Terms of use, the health disclaimer, and what calculated values do and do not mean +- Changelog: https://setline.significanthobbies.com/changelog — What shipped, newest first, including what was removed ## Machine surfaces diff --git a/public/llms.txt b/public/llms.txt index 1210472..9b5110a 100644 --- a/public/llms.txt +++ b/public/llms.txt @@ -1,13 +1,13 @@ # Setline -> Mobile-first execution layer for following a structured workout programme precisely. +> iPhone app that runs a written strength, cardio and mobility programme one set at a time, records what was actually lifted, and measures each exercise against an authored target. ## Product -- [Home](https://setline.significanthobbies.com/): Workout execution app -- [Privacy](https://setline.significanthobbies.com/privacy): Device and private cloud data handling -- [Terms](https://setline.significanthobbies.com/terms): Product terms -- [Changelog](https://setline.significanthobbies.com/changelog): Verified product releases +- [Home](https://setline.significanthobbies.com/): What Setline does, how one set is recorded, and what it refuses to do +- [Privacy](https://setline.significanthobbies.com/privacy): How the app handles data: no account, no server, nothing collected; plus this site's third-party scripts +- [Terms](https://setline.significanthobbies.com/terms): Terms of use, the health disclaimer, and what calculated values do and do not mean +- [Changelog](https://setline.significanthobbies.com/changelog): What shipped, newest first, including what was removed ## Machine surfaces diff --git a/public/manifest.webmanifest b/public/manifest.webmanifest index f7f38c9..e3338c6 100644 --- a/public/manifest.webmanifest +++ b/public/manifest.webmanifest @@ -1,11 +1,11 @@ { "name": "Setline", "short_name": "Setline", - "description": "Build the plan once. Follow it precisely every day.", + "description": "Follow your training plan. Record the truth.", "start_url": "/", "display": "standalone", - "background_color": "#0f172a", - "theme_color": "#0f172a", + "background_color": "#f7f6f0", + "theme_color": "#18262e", "icons": [ { "src": "/icon-192.png", diff --git a/public/privacy.html b/public/privacy.html index 2e9ac09..aa2d4d6 100644 --- a/public/privacy.html +++ b/public/privacy.html @@ -4,24 +4,78 @@ Setline — Privacy - + - + -
-

Setline privacy

-

Active workouts work device-first. Optional Google sign-in stores one private, user-scoped state copy. Workout progress and history are not public agent surfaces.

- ← Back to Setline +
+
+ SETLINE +

Privacy

+

Setline has no account and no server. Your training is a file on your iPhone.

+

Last updated 16 August 2026

+
+ +
+

The app collects nothing. Setline has no sign-in, no analytics and makes no network requests. Every workout, target and measurement is written to the app's own container on your device. There is no copy anywhere else, and the developer cannot see your data.

+
+ +

What the app stores, and where

+

Setline keeps one JSON document in its own private container on your iPhone. It holds your programme, workout templates, recorded sets, exercise targets and history. iOS protects it with the same sandbox and device encryption it applies to any app's private storage.

+

That document is the only copy. If you delete the app, iOS deletes it with the app, and the data is gone. If you lose the device, the data is gone with it.

+ +

Your data leaves only when you send it

+
    +
  • Export writes the complete document to a file you choose the destination for, using the standard iOS share sheet. Where it goes after that — Files, iCloud Drive, a message, another app — is your choice and that service's privacy policy, not Setline's.
  • +
  • Import reads a file you pick and, after showing you what it contains, replaces the data on the device. Nothing is uploaded.
  • +
  • Reset local data erases the document on the device immediately.
  • +
+ +

Notifications

+

If you allow notifications, Setline schedules a local alert so a rest timer still finishes when you leave the app. Local notifications are scheduled by iOS on the device; nothing is sent to a push server, and no notification content reaches the developer.

+ +

What Setline does not do

+
    +
  • No account, sign-in, or user identity.
  • +
  • No backend, database, or hosting account. There is no server to hold your data or to breach.
  • +
  • No analytics, telemetry, crash reporting, or advertising SDK in the app.
  • +
  • No tracking across apps or websites, and no data shared with or sold to anyone.
  • +
  • No sensors, contacts, photos, location, or Apple Health access. The app requests no permissions beyond notifications, and only if you enable them.
  • +
+

Planned features — syncing across your devices through iCloud, and reading and writing Apple Health — are not built. When either ships, this page will change before it does, and both will be something you turn on rather than a default.

+ +

This website

+

The website is separate from the app and is not needed to use it. It is static files served by GitHub Pages, which records request logs including IP addresses as any web host does. See the GitHub Privacy Statement.

+

Two third-party scripts run on these pages:

+

PostHog analytics

+

Counts page views, so the developer knows whether anyone reads these pages. It handles the page URL, referrer, browser and device type, approximate location derived from your IP address, and a stored identifier. Autocapture of clicks and typing is switched off, so it records that a page was viewed and not what you did on it.

+

Portfolio strip (sassmaker.com)

+

Shows the developer's other projects at the bottom of the page. Loading it requests a file from that domain, which exposes your IP address to it as any embedded script does.

+

No workout data reaches either one, because the app never sends anything to the website. Blocking both, or blocking cookies, does not affect the app.

+ +

Children

+

Setline is not directed at children under 13 and collects nothing from anyone.

+ +

Your rights

+

Rights to access, correct, export and erase personal data generally assume someone else is holding it. For the app, nobody is: you already hold the only copy, Export produces it in full, and Reset local data or deleting the app erases it. For website analytics, ask for removal at the contact below and it will be deleted.

+ +

Changes

+

If this notice changes, the date above changes with it, and the reason appears in the changelog. It will not be changed to retroactively permit collecting something that was previously stated as not collected.

+ +

Contact

+

Raise a privacy question as a GitHub issue, or through sarthakagrawal.dev.

+ +
diff --git a/public/privacy.md b/public/privacy.md index 0fe7bce..5b5f9f7 100644 --- a/public/privacy.md +++ b/public/privacy.md @@ -1,3 +1,103 @@ # Setline privacy -Active workouts work device-first. Optional Google sign-in stores one private, user-scoped state copy. Workout progress and history are not public agent surfaces. +Setline has no account and no server. Your training is a file on your iPhone. + +Last updated 16 August 2026. + +**The app collects nothing.** Setline has no sign-in, no analytics and makes no +network requests. Every workout, target and measurement is written to the app's +own container on your device. There is no copy anywhere else, and the developer +cannot see your data. + +## What the app stores, and where + +Setline keeps one JSON document in its own private container on your iPhone. It +holds your programme, workout templates, recorded sets, exercise targets and +history. iOS protects it with the same sandbox and device encryption it applies +to any app's private storage. + +That document is the only copy. If you delete the app, iOS deletes it with the +app, and the data is gone. If you lose the device, the data is gone with it. + +### Your data leaves only when you send it + +- **Export** writes the complete document to a file you choose the destination + for, using the standard iOS share sheet. Where it goes after that — Files, + iCloud Drive, a message, another app — is your choice and that service's + privacy policy, not Setline's. +- **Import** reads a file you pick and, after showing you what it contains, + replaces the data on the device. Nothing is uploaded. +- **Reset local data** erases the document on the device immediately. + +### Notifications + +If you allow notifications, Setline schedules a local alert so a rest timer +still finishes when you leave the app. Local notifications are scheduled by iOS +on the device; nothing is sent to a push server, and no notification content +reaches the developer. + +## What Setline does not do + +- No account, sign-in, or user identity. +- No backend, database, or hosting account. There is no server to hold your data + or to breach. +- No analytics, telemetry, crash reporting, or advertising SDK in the app. +- No tracking across apps or websites, and no data shared with or sold to + anyone. +- No sensors, contacts, photos, location, or Apple Health access. The app + requests no permissions beyond notifications, and only if you enable them. + +Planned features — syncing across your devices through iCloud, and reading and +writing Apple Health — are not built. When either ships, this page will change +before it does, and both will be something you turn on rather than a default. + +## This website + +The website is separate from the app and is not needed to use it. It is static +files served by GitHub Pages, which records request logs including IP addresses +as any web host does. See the +[GitHub Privacy Statement](https://docs.github.com/en/site-policy/privacy-policies/github-general-privacy-statement). + +Two third-party scripts run on these pages: + +### PostHog analytics + +Counts page views, so the developer knows whether anyone reads these pages. It +handles the page URL, referrer, browser and device type, approximate location +derived from your IP address, and a stored identifier. Autocapture of clicks and +typing is switched off, so it records that a page was viewed and not what you did +on it. + +### Portfolio strip (`sassmaker.com`) + +Shows the developer's other projects at the bottom of the page. Loading it +requests a file from that domain, which exposes your IP address to it as any +embedded script does. + +No workout data reaches either one, because the app never sends anything to the +website. Blocking both, or blocking cookies, does not affect the app. + +## Children + +Setline is not directed at children under 13 and collects nothing from anyone. + +## Your rights + +Rights to access, correct, export and erase personal data generally assume +someone else is holding it. For the app, nobody is: you already hold the only +copy, Export produces it in full, and Reset local data or deleting the app +erases it. For website analytics, ask for removal at the contact below and it +will be deleted. + +## Changes + +If this notice changes, the date above changes with it, and the reason appears +in the [changelog](https://setline.significanthobbies.com/changelog). It will not +be changed to retroactively permit collecting something that was previously +stated as not collected. + +## Contact + +Raise a privacy question as a +[GitHub issue](https://github.com/Significant-Hobbies/setline/issues), or through +[sarthakagrawal.dev](https://sarthakagrawal.dev). diff --git a/public/shot-exercise-detail.png b/public/shot-exercise-detail.png new file mode 100644 index 0000000..18029fa Binary files /dev/null and b/public/shot-exercise-detail.png differ diff --git a/public/shot-today.png b/public/shot-today.png new file mode 100644 index 0000000..c1a1774 Binary files /dev/null and b/public/shot-today.png differ diff --git a/public/shot-workout-player.png b/public/shot-workout-player.png new file mode 100644 index 0000000..14caf00 Binary files /dev/null and b/public/shot-workout-player.png differ diff --git a/public/sw.js b/public/sw.js index fe66cac..28577e3 100644 --- a/public/sw.js +++ b/public/sw.js @@ -1,54 +1,19 @@ -const CACHE_NAME = "setline-shell-v4"; -const APP_SHELL = [ - "/", - "/privacy", - "/terms", - "/manifest.webmanifest", - "/icon-192.png", - "/icon-512.png", - "/favicon.png", -]; - -self.addEventListener("install", (event) => { - event.waitUntil( - caches.open(CACHE_NAME).then((cache) => cache.addAll(APP_SHELL)).then(() => self.skipWaiting()), - ); +// Setline no longer ships a web app, so there is no shell worth caching. Earlier +// visitors may still have the previous service worker installed, which would keep +// serving them pages that no longer exist. This replacement exists solely to +// evict those caches and unregister itself. +self.addEventListener("install", () => { + self.skipWaiting(); }); self.addEventListener("activate", (event) => { event.waitUntil( - caches - .keys() - .then((keys) => - Promise.all(keys.filter((key) => key !== CACHE_NAME).map((key) => caches.delete(key))), - ) - .then(() => self.clients.claim()), - ); -}); - -self.addEventListener("fetch", (event) => { - const url = new URL(event.request.url); - if ( - event.request.method !== "GET" || - url.origin !== self.location.origin || - url.pathname.startsWith("/api/") - ) { - return; - } - - event.respondWith( (async () => { - try { - const response = await fetch(event.request); - if (response.ok) { - const copy = response.clone(); - event.waitUntil(caches.open(CACHE_NAME).then((cache) => cache.put(event.request, copy))); - } - return response; - } catch { - const cached = await caches.match(event.request); - return cached ?? caches.match("/"); - } + const names = await caches.keys(); + await Promise.all(names.map((name) => caches.delete(name))); + await self.registration.unregister(); + const clients = await self.clients.matchAll({ type: "window" }); + for (const client of clients) client.navigate(client.url); })(), ); }); diff --git a/public/terms.html b/public/terms.html index 4d6554f..646c7c8 100644 --- a/public/terms.html +++ b/public/terms.html @@ -4,24 +4,61 @@ Setline — Terms - + - + -
-

Setline terms

-

Setline is a workout execution tool, not medical advice, coaching, or a substitute for professional guidance. Users control their programme and recorded results.

- ← Back to Setline +
+
+ SETLINE +

Terms of use

+

Setline records what you decide to do. It does not decide what you should do.

+

Last updated 16 August 2026

+
+ +
+

Setline is not medical advice, coaching, physiotherapy, or a substitute for professional guidance. It does not know your injuries, your history, or your limits. Loads, rep ranges, rest and progression are whatever you authored. Deciding whether a session is safe for you today is yours alone, and if a movement causes pain you should stop and consult a qualified professional.

+
+ +

What Setline is

+

Setline is an iPhone app for following a written training programme one set at a time, recording what was actually lifted, and comparing each exercise against a target you set. It runs entirely on your device.

+ +

Your programme and your data are yours

+
    +
  • You author the programme. Setline presents it and records results; it does not silently rewrite what you wrote. Skips, extra sets, deferrals and partial sets are kept as explicit records of what happened.
  • +
  • Your recorded training belongs to you. It lives on your device, and Export produces the complete document in an open JSON format at any time. See the privacy notice.
  • +
  • Because there is no server, keeping a backup is your responsibility. Delete the app and the data goes with it.
  • +
+ +

Calculated values are estimates

+

Estimated one-rep maxes, projected target dates, rates of change and progression suggestions are arithmetic over sets you recorded, not measurements and not predictions. Setline shows which values were recorded and which were calculated so the two are never confused. Treat a suggestion as a prompt to decide, not an instruction to follow.

+ +

Bundled programme content

+

The app ships with one dated twelve-week strength, cardio and mobility block written for its author, including that author's own starting loads. It is included as an example of a fully specified programme, not as a recommendation for anyone else. Replace it or edit it before using it.

+ +

Pre-release status

+

Setline is in development and is not on the App Store. It is provided as-is, without warranty of any kind, and may contain defects, lose data, or change incompatibly between versions. To the fullest extent the law allows, the developer is not liable for injury, lost data, or any other loss arising from using it. Nothing here limits liability that cannot lawfully be limited.

+ +

Acceptable use

+

The source is public under the terms in the repository. Do not present Setline as medical or professional advice, and do not represent modified copies as the original.

+ +

Changes

+

These terms may change as the app does; the date above changes with them, and material changes are noted in the changelog.

+ +

Contact

+

Questions and reports belong in GitHub issues.

+ +
diff --git a/public/terms.md b/public/terms.md index d20fb02..1c10d66 100644 --- a/public/terms.md +++ b/public/terms.md @@ -1,3 +1,68 @@ -# Setline terms +# Setline terms of use -Setline is a workout execution tool, not medical advice, coaching, or a substitute for professional guidance. Users control their programme and recorded results. +Setline records what you decide to do. It does not decide what you should do. + +Last updated 16 August 2026. + +**Setline is not medical advice, coaching, physiotherapy, or a substitute for +professional guidance.** It does not know your injuries, your history, or your +limits. Loads, rep ranges, rest and progression are whatever you authored. +Deciding whether a session is safe for you today is yours alone, and if a +movement causes pain you should stop and consult a qualified professional. + +## What Setline is + +Setline is an iPhone app for following a written training programme one set at a +time, recording what was actually lifted, and comparing each exercise against a +target you set. It runs entirely on your device. + +## Your programme and your data are yours + +- You author the programme. Setline presents it and records results; it does not + silently rewrite what you wrote. Skips, extra sets, deferrals and partial sets + are kept as explicit records of what happened. +- Your recorded training belongs to you. It lives on your device, and Export + produces the complete document in an open JSON format at any time. See the + [privacy notice](https://setline.significanthobbies.com/privacy). +- Because there is no server, keeping a backup is your responsibility. Delete the + app and the data goes with it. + +## Calculated values are estimates + +Estimated one-rep maxes, projected target dates, rates of change and progression +suggestions are arithmetic over sets you recorded, not measurements and not +predictions. Setline shows which values were recorded and which were calculated +so the two are never confused. Treat a suggestion as a prompt to decide, not an +instruction to follow. + +## Bundled programme content + +The app ships with one dated twelve-week strength, cardio and mobility block +written for its author, including that author's own starting loads. It is +included as an example of a fully specified programme, not as a recommendation +for anyone else. Replace it or edit it before using it. + +## Pre-release status + +Setline is in development and is not on the App Store. It is provided as-is, +without warranty of any kind, and may contain defects, lose data, or change +incompatibly between versions. To the fullest extent the law allows, the +developer is not liable for injury, lost data, or any other loss arising from +using it. Nothing here limits liability that cannot lawfully be limited. + +## Acceptable use + +The source is public under the terms in the repository. Do not present Setline as +medical or professional advice, and do not represent modified copies as the +original. + +## Changes + +These terms may change as the app does; the date above changes with them, and +material changes are noted in the +[changelog](https://setline.significanthobbies.com/changelog). + +## Contact + +Questions and reports belong in +[GitHub issues](https://github.com/Significant-Hobbies/setline/issues). diff --git a/scripts/check-code-health.mjs b/scripts/check-code-health.mjs index 74dddea..008bb2d 100644 --- a/scripts/check-code-health.mjs +++ b/scripts/check-code-health.mjs @@ -9,13 +9,9 @@ import { fileURLToPath } from "node:url"; const currentFile = fileURLToPath(import.meta.url); const projectRoot = resolve(dirname(currentFile), ".."); -const productionPaths = [ - "src", - "worker", - "public/sw.js", - "ios/Sources", - "vite.config.ts", -]; +// The TypeScript backend was removed when Setline became device-first, so the +// production surface is the native app plus the one script the static site ships. +const productionPaths = ["ios/Sources", "public/sw.js"]; const hygienePaths = [ ...productionPaths, ".github", @@ -25,8 +21,6 @@ const hygienePaths = [ "knip.json", "package.json", "pnpm-lock.yaml", - "tsconfig.json", - "wrangler.jsonc", ]; const sourceExtensions = new Set([ ".js", @@ -37,12 +31,23 @@ const sourceExtensions = new Set([ ".tsx", ]); const baselines = { - complexity: { violations: 20, maxCcn: 52, maxLength: 283, maxParams: 14 }, - duplication: { clones: 3, duplicatedLines: 28 }, + // Measured against the native sources alone, now that the TypeScript library and + // Worker are gone — they held every high-CCN and long function. All nine + // remaining violations are memberwise initializers on Codable value types with + // more than 7 stored properties; WorkoutStep is the 19-parameter case. Grouping + // those fields into nested structs is the only way to shrink the count, and it + // would change the persisted JSON shape the version 1 migration reads, so the + // parameter counts are accepted rather than traded for a schema break. + complexity: { violations: 9, maxCcn: 15, maxLength: 73, maxParams: 19 }, + // Zero after the shared legacy decoder, programme set builders and cardio + // definition builder replaced the copied blocks. Keep it at zero. + duplication: { clones: 0, duplicatedLines: 0 }, + // Zero once the TypeScript library and Worker were deleted; the remaining + // JavaScript is test and tooling code with no unused surface. unused: { files: 0, - exports: 21, - types: 5, + exports: 0, + types: 0, dependencies: 0, devDependencies: 0, unlisted: 0, @@ -54,10 +59,7 @@ const acceptedHighAdvisories = new Set([ "GHSA-3jxr-9vmj-r5cp", "GHSA-52cp-r559-cp3m", "GHSA-5p4m-2wfm-xmqj", - "GHSA-6g55-p6wh-862q", - "GHSA-f88m-g3jw-g9cj", "GHSA-mh99-v99m-4gvg", - "GHSA-r28c-9q8g-f849", "GHSA-rgw5-rvv9-x895", ]); @@ -293,19 +295,9 @@ function sourceFiles(root) { } function checkSuppressions() { - const files = [ - "src", - "worker", - "public/sw.js", - "ios/Sources", - "ios/Tests", - "tests", - ] + const files = [...productionPaths, "ios/Tests", "tests"] .flatMap((root) => sourceFiles(resolve(projectRoot, root))) - .filter( - (file) => - file !== currentFile && !file.endsWith("/worker/agent-edge.mjs"), - ); + .filter((file) => file !== currentFile); const matches = files.flatMap((file) => readFileSync(file, "utf8") .split("\n") diff --git a/scripts/check-native-code-health.mjs b/scripts/check-native-code-health.mjs index 4bb68f2..0984ee1 100644 --- a/scripts/check-native-code-health.mjs +++ b/scripts/check-native-code-health.mjs @@ -8,7 +8,10 @@ import process from "node:process"; import { fileURLToPath } from "node:url"; const projectRoot = resolve(dirname(fileURLToPath(import.meta.url)), ".."); -const minimumProductionCoverage = 0.653; +// Raised from 0.653 once the structured model landed with its own tests and the +// untested account layer left. Measured 84.1628% on 2026-08-16; the floor sits +// just under that so the gain cannot quietly erode. +const minimumProductionCoverage = 0.838; function capture(command, args) { const result = spawnSync(command, args, { @@ -125,8 +128,10 @@ try { `${(minimumProductionCoverage * 100).toFixed(2)}%`, ); } + // Deliberately no test counts here: they were hardcoded once and went stale + // silently. xcodebuild above already prints the real totals it executed. console.log( - "Native gate: 10 unit tests, 4 UI tests, release build, and coverage pass.", + "Native gate: unit tests, UI tests, release build, and coverage pass.", ); } catch (error) { console.error(error instanceof Error ? error.message : String(error)); diff --git a/src/lib/custom-programme.ts b/src/lib/custom-programme.ts deleted file mode 100644 index 5eb8f1a..0000000 --- a/src/lib/custom-programme.ts +++ /dev/null @@ -1,225 +0,0 @@ -import type { CustomWorkoutId } from "./programme"; - -export type CustomProgrammeAssignment = { - weekNumber: number; - dayIndex: number; - workoutId: CustomWorkoutId; -}; - -export type CustomProgramme = { - name: string; - startsOn: string; - weekCount: number; - enabled: boolean; - assignments: CustomProgrammeAssignment[]; - createdAt: number; - updatedAt: number; -}; - -export type CustomProgrammeDayResolution = - | { - status: "outside"; - reason: "paused" | "before" | "after"; - } - | { - status: "unplanned"; - weekNumber: number; - dayIndex: number; - } - | { - status: "scheduled"; - weekNumber: number; - dayIndex: number; - workoutId: CustomWorkoutId; - }; - -export const MAX_CUSTOM_PROGRAMME_WEEKS = 16; -export const MAX_CUSTOM_PROGRAMME_NAME_LENGTH = 80; - -const DAYS_PER_WEEK = 7; -const MILLISECONDS_PER_DAY = 86_400_000; -const ISO_DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/; - -function isRecord(value: unknown): value is Record { - return value !== null && typeof value === "object" && !Array.isArray(value); -} - -function parseIsoCalendarDay(value: unknown): number | null { - if (typeof value !== "string") return null; - const match = ISO_DATE_PATTERN.exec(value); - if (!match) return null; - const year = Number(match[1]); - const month = Number(match[2]); - const day = Number(match[3]); - const ordinal = Date.UTC(year, month - 1, day); - const parsed = new Date(ordinal); - if ( - parsed.getUTCFullYear() !== year || - parsed.getUTCMonth() !== month - 1 || - parsed.getUTCDate() !== day - ) { - return null; - } - return ordinal; -} - -function localCalendarDay(date: Date): number | null { - if (!Number.isFinite(date.getTime())) return null; - return Date.UTC(date.getFullYear(), date.getMonth(), date.getDate()); -} - -function isMonday(ordinal: number) { - return new Date(ordinal).getUTCDay() === 1; -} - -export function isMondayIsoDate(value: string) { - const ordinal = parseIsoCalendarDay(value); - return ordinal !== null && isMonday(ordinal); -} - -export function mondayIsoForIsoDate(value: string) { - const ordinal = parseIsoCalendarDay(value); - if (ordinal === null) return ""; - const dayIndex = (new Date(ordinal).getUTCDay() + 6) % DAYS_PER_WEEK; - return new Date(ordinal - dayIndex * MILLISECONDS_PER_DAY) - .toISOString() - .slice(0, 10); -} - -export function isCustomProgramme( - value: unknown, - validWorkoutIds: ReadonlySet, -): value is CustomProgramme { - if (!isRecord(value)) return false; - const startsOn = parseIsoCalendarDay(value.startsOn); - if ( - typeof value.name !== "string" || - value.name.trim().length === 0 || - value.name.length > MAX_CUSTOM_PROGRAMME_NAME_LENGTH || - startsOn === null || - !isMonday(startsOn) || - !Number.isInteger(value.weekCount) || - Number(value.weekCount) < 1 || - Number(value.weekCount) > MAX_CUSTOM_PROGRAMME_WEEKS || - typeof value.enabled !== "boolean" || - !Array.isArray(value.assignments) || - value.assignments.length > Number(value.weekCount) * DAYS_PER_WEEK || - typeof value.createdAt !== "number" || - !Number.isFinite(value.createdAt) || - value.createdAt < 0 || - typeof value.updatedAt !== "number" || - !Number.isFinite(value.updatedAt) || - value.updatedAt < value.createdAt - ) { - return false; - } - - const slots = new Set(); - for (const assignment of value.assignments) { - if (!isRecord(assignment)) return false; - if ( - !Number.isInteger(assignment.weekNumber) || - Number(assignment.weekNumber) < 1 || - Number(assignment.weekNumber) > Number(value.weekCount) || - !Number.isInteger(assignment.dayIndex) || - Number(assignment.dayIndex) < 0 || - Number(assignment.dayIndex) >= DAYS_PER_WEEK || - typeof assignment.workoutId !== "string" || - !assignment.workoutId.startsWith("custom:") || - !validWorkoutIds.has(assignment.workoutId) - ) { - return false; - } - const slot = `${assignment.weekNumber}:${assignment.dayIndex}`; - if (slots.has(slot)) return false; - slots.add(slot); - } - return true; -} - -export function resolveCustomProgrammeDay( - programme: CustomProgramme, - date: Date, -): CustomProgrammeDayResolution { - if (!programme.enabled) return { status: "outside", reason: "paused" }; - const start = parseIsoCalendarDay(programme.startsOn); - const current = localCalendarDay(date); - if (start === null || current === null || current < start) { - return { status: "outside", reason: "before" }; - } - const offset = Math.round((current - start) / MILLISECONDS_PER_DAY); - if (offset >= programme.weekCount * DAYS_PER_WEEK) { - return { status: "outside", reason: "after" }; - } - const weekNumber = Math.floor(offset / DAYS_PER_WEEK) + 1; - const dayIndex = offset % DAYS_PER_WEEK; - const assignment = programme.assignments.find( - (candidate) => - candidate.weekNumber === weekNumber && candidate.dayIndex === dayIndex, - ); - return assignment - ? { - status: "scheduled", - weekNumber, - dayIndex, - workoutId: assignment.workoutId, - } - : { status: "unplanned", weekNumber, dayIndex }; -} - -export function copyProgrammeWeekForward( - assignments: CustomProgrammeAssignment[], - sourceWeek: number, - weekCount: number, -): CustomProgrammeAssignment[] { - if ( - !Number.isInteger(sourceWeek) || - !Number.isInteger(weekCount) || - sourceWeek < 1 || - weekCount < 1 || - sourceWeek > weekCount || - weekCount > MAX_CUSTOM_PROGRAMME_WEEKS - ) { - return assignments; - } - const source = assignments.filter( - (assignment) => assignment.weekNumber === sourceWeek, - ); - return [ - ...assignments.filter((assignment) => assignment.weekNumber <= sourceWeek), - ...Array.from( - { length: weekCount - sourceWeek }, - (_, index) => sourceWeek + index + 1, - ).flatMap((weekNumber) => - source.map((assignment) => ({ ...assignment, weekNumber })), - ), - ]; -} - -export function removeProgrammeWorkoutAssignments( - programme: CustomProgramme | null, - workoutId: CustomWorkoutId, - updatedAt = Date.now(), -): CustomProgramme | null { - if (!programme) return null; - const assignments = programme.assignments.filter( - (assignment) => assignment.workoutId !== workoutId, - ); - return assignments.length === programme.assignments.length - ? programme - : { ...programme, assignments, updatedAt }; -} - -export function mondayIsoForLocalDate(date: Date) { - if (!Number.isFinite(date.getTime())) return ""; - const dayIndex = (date.getDay() + 6) % DAYS_PER_WEEK; - const monday = new Date( - date.getFullYear(), - date.getMonth(), - date.getDate() - dayIndex, - ); - const year = monday.getFullYear(); - const month = String(monday.getMonth() + 1).padStart(2, "0"); - const day = String(monday.getDate()).padStart(2, "0"); - return `${year}-${month}-${day}`; -} diff --git a/src/lib/custom-workouts.ts b/src/lib/custom-workouts.ts deleted file mode 100644 index 8901193..0000000 --- a/src/lib/custom-workouts.ts +++ /dev/null @@ -1,234 +0,0 @@ -import type { - CustomWorkoutId, - PlannedStep, - TrackingKind, - WorkoutTemplate, -} from "./programme"; - -export type CustomWorkoutTemplate = WorkoutTemplate & { - id: CustomWorkoutId; - createdAt: number; - updatedAt: number; -}; - -export const MAX_CUSTOM_WORKOUTS = 50; -export const MAX_CUSTOM_WORKOUT_STEPS = 100; -const MAX_CUSTOM_WORKOUT_NAME_LENGTH = 80; - -const MAX_STEP_TEXT_LENGTH = 240; -const MAX_NOTE_LENGTH = 500; -const MAX_NOTES = 10; -const MAX_EXPECTED_MINUTES = 480; -const MAX_TARGET_VALUE = 10_000; -const MAX_REST_SECONDS = 3_600; -const TRACKING_KINDS = new Set([ - "weight-reps", - "reps", - "duration", - "weight-duration", - "completion", -]); -const STEP_TYPES = new Set([ - "Preparation", - "Warm-up", - "Working", - "Cardio", - "Mobility", - "Cooldown", - "Check", -]); - -function isRecord(value: unknown): value is Record { - return value !== null && typeof value === "object" && !Array.isArray(value); -} - -function boundedText( - value: unknown, - maximum: number, - allowEmpty = false, -): value is string { - return ( - typeof value === "string" && - value.length <= maximum && - (allowEmpty || value.trim().length > 0) - ); -} - -function nullableBoundedNumber(value: unknown): value is number | null { - return ( - value === null || - (typeof value === "number" && - Number.isFinite(value) && - value >= 0 && - value <= MAX_TARGET_VALUE) - ); -} - -function positiveInteger( - value: unknown, - maximum = MAX_TARGET_VALUE, -): value is number { - return ( - Number.isInteger(value) && Number(value) > 0 && Number(value) <= maximum - ); -} - -function targetShapeIsValid( - step: Record, - tracking: TrackingKind, -) { - const weight = step.targetWeight; - const reps = step.targetReps; - const repsMax = step.targetRepsMax; - const duration = step.targetDurationSeconds; - if ( - !nullableBoundedNumber(weight) || - !nullableBoundedNumber(reps) || - !nullableBoundedNumber(repsMax) || - !nullableBoundedNumber(duration) - ) { - return false; - } - if (repsMax !== null && (reps === null || repsMax < reps)) return false; - if (tracking === "completion") { - return ( - weight === null && reps === null && repsMax === null && duration === null - ); - } - if (tracking === "reps") { - return ( - weight === null && - positiveInteger(reps) && - (repsMax === null || positiveInteger(repsMax)) && - duration === null - ); - } - if (tracking === "duration") { - return ( - weight === null && - reps === null && - repsMax === null && - positiveInteger(duration) - ); - } - if (tracking === "weight-duration") { - return reps === null && repsMax === null && positiveInteger(duration); - } - return ( - positiveInteger(reps) && - (repsMax === null || positiveInteger(repsMax)) && - duration === null - ); -} - -function isCustomWorkoutStep(value: unknown): value is PlannedStep { - if (!isRecord(value)) return false; - const tracking = value.tracking; - return ( - boundedText(value.id, MAX_STEP_TEXT_LENGTH) && - boundedText(value.exercise, MAX_STEP_TEXT_LENGTH) && - STEP_TYPES.has(String(value.setType)) && - boundedText(value.setLabel, MAX_STEP_TEXT_LENGTH) && - TRACKING_KINDS.has(tracking as TrackingKind) && - targetShapeIsValid(value, tracking as TrackingKind) && - Number.isInteger(value.restSeconds) && - Number(value.restSeconds) >= 0 && - Number(value.restSeconds) <= MAX_REST_SECONDS && - (value.targetRpe === undefined || - (typeof value.targetRpe === "number" && - Number.isFinite(value.targetRpe) && - value.targetRpe >= 0 && - value.targetRpe <= 10)) && - boundedText(value.cue, MAX_STEP_TEXT_LENGTH, true) && - (value.optional === undefined || typeof value.optional === "boolean") - ); -} - -export function isCustomWorkoutTemplate( - value: unknown, -): value is CustomWorkoutTemplate { - if (!isRecord(value)) return false; - if ( - typeof value.id !== "string" || - !value.id.startsWith("custom:") || - value.id.length > MAX_STEP_TEXT_LENGTH || - !boundedText(value.name, MAX_CUSTOM_WORKOUT_NAME_LENGTH) || - !boundedText(value.scheduleName, MAX_CUSTOM_WORKOUT_NAME_LENGTH) || - !positiveInteger(value.expectedMinutes, MAX_EXPECTED_MINUTES) || - !Array.isArray(value.steps) || - value.steps.length < 1 || - value.steps.length > MAX_CUSTOM_WORKOUT_STEPS || - !value.steps.every(isCustomWorkoutStep) || - new Set(value.steps.map((step) => step.id)).size !== value.steps.length || - !Array.isArray(value.notes) || - value.notes.length > MAX_NOTES || - !value.notes.every((note) => boundedText(note, MAX_NOTE_LENGTH, true)) || - typeof value.createdAt !== "number" || - !Number.isFinite(value.createdAt) || - value.createdAt < 0 || - typeof value.updatedAt !== "number" || - !Number.isFinite(value.updatedAt) || - value.updatedAt < value.createdAt - ) { - return false; - } - return true; -} - -export function duplicateWorkoutTemplate( - source: WorkoutTemplate, - id: CustomWorkoutId, - now = Date.now(), -): CustomWorkoutTemplate { - const name = `${source.name} copy`.slice(0, MAX_CUSTOM_WORKOUT_NAME_LENGTH); - return { - id, - name, - scheduleName: name, - expectedMinutes: source.expectedMinutes, - steps: source.steps.map((step, index) => ({ - ...step, - id: `${id}:step:${index + 1}`, - })), - notes: [...source.notes], - createdAt: now, - updatedAt: now, - }; -} - -export function customWorkoutId( - now = Date.now(), - suffix = crypto.randomUUID(), -): CustomWorkoutId { - return `custom:${now}:${suffix}`; -} - -export function blankCustomWorkoutTemplate( - id: CustomWorkoutId, - now = Date.now(), -): CustomWorkoutTemplate { - return { - id, - name: "", - scheduleName: "", - expectedMinutes: 45, - steps: [ - { - id: `${id}:step:1`, - exercise: "", - setType: "Working", - setLabel: "Set 1", - tracking: "weight-reps", - targetWeight: null, - targetReps: 8, - targetRepsMax: null, - targetDurationSeconds: null, - restSeconds: 90, - cue: "", - }, - ], - notes: [], - createdAt: now, - updatedAt: now, - }; -} diff --git a/src/lib/history-analytics.ts b/src/lib/history-analytics.ts deleted file mode 100644 index 025c67f..0000000 --- a/src/lib/history-analytics.ts +++ /dev/null @@ -1,411 +0,0 @@ -import type { HistoryEntry } from "./workout-state"; - -type ExerciseTrendMetric = - "weight" | "duration" | "repetitions" | "completions"; - -export type ExerciseTrendPoint = { - historyId: string; - workoutName: string; - completedAt: number; - completedExecutions: number; - bestWeight: number | null; - repetitionsAtBestWeight: number | null; - bestRepetitions: number | null; - longestDurationSeconds: number | null; - workingVolume: number; - averageRpe: number | null; - rpeCount: number; -}; - -export type ExerciseAnalytics = { - id: string; - name: string; - recordedSessions: number; - completedExecutions: number; - bestWeight: number | null; - repetitionsAtBestWeight: number | null; - bestRepetitions: number | null; - longestDurationSeconds: number | null; - totalWorkingVolume: number; - averageRpe: number | null; - rpeCount: number; - trendMetric: ExerciseTrendMetric; - latest: ExerciseTrendPoint; - trend: ExerciseTrendPoint[]; -}; - -type WorkoutAnalytics = { - workoutId: HistoryEntry["workoutId"]; - workoutName: string; - recordedSessions: number; - detailedSessions: number; - latestCompletedAt: number; - totalDurationSeconds: number; - averageDurationSeconds: number; - totalWorkingVolume: number; - completedSets: number; - modifiedSets: number; - skippedSets: number; -}; - -type ProgrammeWeekAnalytics = { - weekNumber: number; - recordedSessions: number; - latestCompletedAt: number; - totalWorkingVolume: number; - completedSets: number; - modifiedSets: number; - skippedSets: number; -}; - -export type HistoryAnalytics = { - overview: { - recordedSessions: number; - detailedSessions: number; - customSessions: number; - totalDurationSeconds: number; - totalWorkingVolume: number; - latestCompletedAt: number | null; - }; - exercises: ExerciseAnalytics[]; - workouts: WorkoutAnalytics[]; - programmeWeeks: ProgrammeWeekAnalytics[]; -}; - -type MutableExercisePoint = ExerciseTrendPoint & { - name: string; - rpeTotal: number; -}; - -type MutableExercise = { - id: string; - name: string; - points: ExerciseTrendPoint[]; -}; - -type MutableWorkout = Omit; - -function normalizeExerciseName(name: string) { - return name.trim().replace(/\s+/g, " ").toLocaleLowerCase(); -} - -function positive(value: number | null | undefined): value is number { - return typeof value === "number" && Number.isFinite(value) && value > 0; -} - -function nonNegative(value: number) { - return Number.isFinite(value) && value >= 0 ? value : 0; -} - -function trendValue(point: ExerciseTrendPoint, metric: ExerciseTrendMetric) { - if (metric === "weight") return point.bestWeight; - if (metric === "duration") return point.longestDurationSeconds; - if (metric === "repetitions") return point.bestRepetitions; - return point.completedExecutions; -} - -function summarizeExercisePoints(points: ExerciseTrendPoint[]) { - let bestWeight: number | null = null; - let repetitionsAtBestWeight: number | null = null; - let bestRepetitions: number | null = null; - let longestDurationSeconds: number | null = null; - let completedExecutions = 0; - let totalWorkingVolume = 0; - let rpeCount = 0; - let rpeTotal = 0; - - for (const point of points) { - completedExecutions += point.completedExecutions; - totalWorkingVolume += point.workingVolume; - rpeCount += point.rpeCount; - rpeTotal += (point.averageRpe ?? 0) * point.rpeCount; - - if (point.bestWeight !== null) { - if (bestWeight === null || point.bestWeight > bestWeight) { - bestWeight = point.bestWeight; - repetitionsAtBestWeight = point.repetitionsAtBestWeight; - } else if ( - point.bestWeight === bestWeight && - point.repetitionsAtBestWeight !== null - ) { - repetitionsAtBestWeight = Math.max( - repetitionsAtBestWeight ?? 0, - point.repetitionsAtBestWeight, - ); - } - } - if ( - point.bestRepetitions !== null && - (bestRepetitions === null || point.bestRepetitions > bestRepetitions) - ) { - bestRepetitions = point.bestRepetitions; - } - if ( - point.longestDurationSeconds !== null && - (longestDurationSeconds === null || - point.longestDurationSeconds > longestDurationSeconds) - ) { - longestDurationSeconds = point.longestDurationSeconds; - } - } - - const trendMetric: ExerciseTrendMetric = - bestWeight !== null - ? "weight" - : longestDurationSeconds !== null - ? "duration" - : bestRepetitions !== null - ? "repetitions" - : "completions"; - return { - bestWeight, - repetitionsAtBestWeight, - bestRepetitions, - longestDurationSeconds, - completedExecutions, - totalWorkingVolume, - averageRpe: rpeCount ? rpeTotal / rpeCount : null, - rpeCount, - trendMetric, - metricPoints: points.filter( - (point) => trendValue(point, trendMetric) !== null, - ), - }; -} - -function makeExercisePoint( - historyId: string, - workoutName: string, - completedAt: number, - name: string, -): MutableExercisePoint { - return { - historyId, - workoutName, - completedAt, - name, - completedExecutions: 0, - bestWeight: null, - repetitionsAtBestWeight: null, - bestRepetitions: null, - longestDurationSeconds: null, - workingVolume: 0, - averageRpe: null, - rpeCount: 0, - rpeTotal: 0, - }; -} - -export function deriveHistoryAnalytics( - history: HistoryEntry[], -): HistoryAnalytics { - const ordered = [...history].sort( - (left, right) => right.completedAt - left.completedAt, - ); - const exerciseGroups = new Map(); - const workoutGroups = new Map(); - const programmeWeeks = new Map(); - - for (const entry of ordered) { - const existingWorkout = workoutGroups.get(entry.workoutId); - const workout = - existingWorkout ?? - ({ - workoutId: entry.workoutId, - workoutName: entry.workoutName, - recordedSessions: 0, - detailedSessions: 0, - latestCompletedAt: entry.completedAt, - totalDurationSeconds: 0, - totalWorkingVolume: 0, - completedSets: 0, - modifiedSets: 0, - skippedSets: 0, - } satisfies MutableWorkout); - workout.recordedSessions += 1; - workout.detailedSessions += entry.detailsAvailable ? 1 : 0; - workout.totalDurationSeconds += nonNegative(entry.durationSeconds); - workout.totalWorkingVolume += nonNegative(entry.workingVolume); - workout.completedSets += nonNegative(entry.completedSets); - workout.modifiedSets += nonNegative(entry.modifiedSets); - workout.skippedSets += nonNegative(entry.skippedSets); - workoutGroups.set(entry.workoutId, workout); - - if ( - !entry.workoutId.startsWith("custom:") && - Number.isInteger(entry.weekNumber) && - entry.weekNumber > 0 - ) { - const existingWeek = programmeWeeks.get(entry.weekNumber); - const week = - existingWeek ?? - ({ - weekNumber: entry.weekNumber, - recordedSessions: 0, - latestCompletedAt: entry.completedAt, - totalWorkingVolume: 0, - completedSets: 0, - modifiedSets: 0, - skippedSets: 0, - } satisfies ProgrammeWeekAnalytics); - week.recordedSessions += 1; - week.totalWorkingVolume += nonNegative(entry.workingVolume); - week.completedSets += nonNegative(entry.completedSets); - week.modifiedSets += nonNegative(entry.modifiedSets); - week.skippedSets += nonNegative(entry.skippedSets); - programmeWeeks.set(entry.weekNumber, week); - } - - if (!entry.detailsAvailable) continue; - const exercisePoints = new Map(); - - for (const execution of entry.executions) { - if (execution.status !== "completed") continue; - const exerciseId = normalizeExerciseName(execution.step.exercise); - if (!exerciseId) continue; - const point = - exercisePoints.get(exerciseId) ?? - makeExercisePoint( - entry.id, - entry.workoutName, - entry.completedAt, - execution.step.exercise.trim().replace(/\s+/g, " "), - ); - point.completedExecutions += 1; - - for (const segment of execution.segments) { - if (positive(segment.reps)) { - point.bestRepetitions = Math.max( - point.bestRepetitions ?? 0, - segment.reps, - ); - } - if (positive(segment.durationSeconds)) { - point.longestDurationSeconds = Math.max( - point.longestDurationSeconds ?? 0, - segment.durationSeconds, - ); - } - if (positive(segment.weight)) { - if (point.bestWeight === null || segment.weight > point.bestWeight) { - point.bestWeight = segment.weight; - point.repetitionsAtBestWeight = positive(segment.reps) - ? segment.reps - : null; - } else if ( - segment.weight === point.bestWeight && - positive(segment.reps) - ) { - point.repetitionsAtBestWeight = Math.max( - point.repetitionsAtBestWeight ?? 0, - segment.reps, - ); - } - } - if ( - execution.step.setType === "Working" && - positive(segment.weight) && - positive(segment.reps) - ) { - point.workingVolume += segment.weight * segment.reps; - } - } - - if ( - typeof execution.actualRpe === "number" && - Number.isFinite(execution.actualRpe) - ) { - point.rpeTotal += execution.actualRpe; - point.rpeCount += 1; - point.averageRpe = point.rpeTotal / point.rpeCount; - } - exercisePoints.set(exerciseId, point); - } - - for (const [exerciseId, mutablePoint] of exercisePoints) { - const point: ExerciseTrendPoint = { - historyId: mutablePoint.historyId, - workoutName: mutablePoint.workoutName, - completedAt: mutablePoint.completedAt, - completedExecutions: mutablePoint.completedExecutions, - bestWeight: mutablePoint.bestWeight, - repetitionsAtBestWeight: mutablePoint.repetitionsAtBestWeight, - bestRepetitions: mutablePoint.bestRepetitions, - longestDurationSeconds: mutablePoint.longestDurationSeconds, - workingVolume: mutablePoint.workingVolume, - averageRpe: mutablePoint.averageRpe, - rpeCount: mutablePoint.rpeCount, - }; - const group = - exerciseGroups.get(exerciseId) ?? - ({ - id: exerciseId, - name: mutablePoint.name, - points: [], - } satisfies MutableExercise); - group.points.push(point); - exerciseGroups.set(exerciseId, group); - } - } - - const exercises = Array.from(exerciseGroups.values()) - .map((group): ExerciseAnalytics => { - const summary = summarizeExercisePoints(group.points); - return { - id: group.id, - name: group.name, - recordedSessions: group.points.length, - completedExecutions: summary.completedExecutions, - bestWeight: summary.bestWeight, - repetitionsAtBestWeight: summary.repetitionsAtBestWeight, - bestRepetitions: summary.bestRepetitions, - longestDurationSeconds: summary.longestDurationSeconds, - totalWorkingVolume: summary.totalWorkingVolume, - averageRpe: summary.averageRpe, - rpeCount: summary.rpeCount, - trendMetric: summary.trendMetric, - latest: summary.metricPoints[0] ?? group.points[0], - trend: summary.metricPoints.slice(0, 8).reverse(), - }; - }) - .sort((left, right) => { - const recent = right.latest.completedAt - left.latest.completedAt; - return recent || left.name.localeCompare(right.name); - }); - - return { - overview: { - recordedSessions: ordered.length, - detailedSessions: ordered.filter((entry) => entry.detailsAvailable) - .length, - customSessions: ordered.filter((entry) => - entry.workoutId.startsWith("custom:"), - ).length, - totalDurationSeconds: ordered.reduce( - (total, entry) => total + nonNegative(entry.durationSeconds), - 0, - ), - totalWorkingVolume: ordered.reduce( - (total, entry) => total + nonNegative(entry.workingVolume), - 0, - ), - latestCompletedAt: ordered[0]?.completedAt ?? null, - }, - exercises, - workouts: Array.from(workoutGroups.values()) - .map((workout): WorkoutAnalytics => ({ - ...workout, - averageDurationSeconds: - workout.recordedSessions > 0 - ? workout.totalDurationSeconds / workout.recordedSessions - : 0, - })) - .sort((left, right) => { - const recent = right.latestCompletedAt - left.latestCompletedAt; - return recent || left.workoutName.localeCompare(right.workoutName); - }), - programmeWeeks: Array.from(programmeWeeks.values()).sort( - (left, right) => left.weekNumber - right.weekNumber, - ), - }; -} diff --git a/src/lib/programme.ts b/src/lib/programme.ts deleted file mode 100644 index 8d9eb22..0000000 --- a/src/lib/programme.ts +++ /dev/null @@ -1,958 +0,0 @@ -export type BuiltInWorkoutId = - | "upper" - | "lower" - | "easy-mobility" - | "upper-hard" - | "mobility" - | "legacy-upper-a"; -export type CustomWorkoutId = `custom:${string}`; -export type WorkoutId = BuiltInWorkoutId | CustomWorkoutId; - -export type TrackingKind = - "weight-reps" | "reps" | "duration" | "weight-duration" | "completion"; - -export type StepType = - | "Preparation" - | "Warm-up" - | "Working" - | "Cardio" - | "Mobility" - | "Cooldown" - | "Check"; - -export type PlannedStep = { - id: string; - exercise: string; - setType: StepType; - setLabel: string; - tracking: TrackingKind; - targetWeight: number | null; - targetReps: number | null; - targetRepsMax: number | null; - targetDurationSeconds: number | null; - restSeconds: number; - targetRpe?: number; - cue: string; - optional?: boolean; -}; - -export type WorkoutTemplate = { - id: WorkoutId; - name: string; - scheduleName: string; - expectedMinutes: number; - steps: PlannedStep[]; - notes: string[]; -}; - -export type ScheduleEntry = { - dayIndex: number; - day: string; - name: string; - time: string; - workoutId: Exclude; - required: boolean; -}; - -export const PROGRAMME = { - name: "Sarthak’s 12-Week Strength, Cardio & Mobility Plan", - shortName: "12-Week Strength · Cardio · Mobility", - startLabel: "27 Jul 2026", - endLabel: "18 Oct 2026", - durationWeeks: 12, -} as const; - -export const PROGRAMME_SCHEDULE: ScheduleEntry[] = [ - { - dayIndex: 0, - day: "MON", - name: "Upper", - time: "19:00", - workoutId: "upper", - required: true, - }, - { - dayIndex: 1, - day: "TUE", - name: "Lower", - time: "19:00", - workoutId: "lower", - required: true, - }, - { - dayIndex: 2, - day: "WED", - name: "Easy + mobility", - time: "Flexible", - workoutId: "easy-mobility", - required: true, - }, - { - dayIndex: 3, - day: "THU", - name: "Upper + hard", - time: "19:00", - workoutId: "upper-hard", - required: true, - }, - { - dayIndex: 4, - day: "FRI", - name: "Mobility", - time: "Flexible", - workoutId: "mobility", - required: true, - }, - { - dayIndex: 5, - day: "SAT", - name: "Lower", - time: "11:00", - workoutId: "lower", - required: true, - }, - { - dayIndex: 6, - day: "SUN", - name: "Easy + mobility", - time: "Flexible", - workoutId: "easy-mobility", - required: true, - }, -]; - -const step = ( - id: string, - exercise: string, - setType: StepType, - setLabel: string, - tracking: TrackingKind, - targets: Partial< - Pick< - PlannedStep, - | "targetWeight" - | "targetReps" - | "targetRepsMax" - | "targetDurationSeconds" - | "restSeconds" - | "targetRpe" - | "optional" - > - >, - cue: string, -): PlannedStep => ({ - id, - exercise, - setType, - setLabel, - tracking, - targetWeight: targets.targetWeight ?? null, - targetReps: targets.targetReps ?? null, - targetRepsMax: targets.targetRepsMax ?? null, - targetDurationSeconds: targets.targetDurationSeconds ?? null, - restSeconds: targets.restSeconds ?? 0, - targetRpe: targets.targetRpe, - optional: targets.optional, - cue, -}); - -const repeated = ( - prefix: string, - count: number, - make: (index: number) => PlannedStep, -) => Array.from({ length: count }, (_, index) => make(index + 1)); - -function fullMobility(prefix: string): PlannedStep[] { - return [ - ...repeated(`${prefix}-ankle`, 2, (setNumber) => - step( - `${prefix}-ankle-${setNumber}`, - "Knee-to-wall ankle rocks", - "Mobility", - `Set ${setNumber} of 2 · each side`, - "reps", - { targetReps: 10 }, - "Use controlled ankle travel; keep the heel down.", - ), - ), - ...repeated(`${prefix}-squat-hold`, 2, (setNumber) => - step( - `${prefix}-squat-hold-${setNumber}`, - "Supported squat hold", - "Mobility", - `Hold ${setNumber} of 2`, - "duration", - { targetDurationSeconds: 45 }, - "Hold a rack or post. Elevate heels when needed; do not force depth.", - ), - ), - ...repeated(`${prefix}-goblet`, 2, (setNumber) => - step( - `${prefix}-goblet-${setNumber}`, - "Light goblet squat", - "Mobility", - `Set ${setNumber} of 2`, - "weight-reps", - { targetReps: 6 }, - "Use a slow descent and control the available range.", - ), - ), - ...repeated(`${prefix}-9090`, 2, (setNumber) => - step( - `${prefix}-9090-${setNumber}`, - "90/90 hip switches", - "Mobility", - `Set ${setNumber} of 2 · each side`, - "reps", - { targetReps: 6 }, - "Move through hip rotation without forcing the knees.", - ), - ), - step( - `${prefix}-hip-flexor`, - "Half-kneeling hip-flexor stretch", - "Mobility", - "1 hold per side", - "duration", - { targetDurationSeconds: 90 }, - "Use 45 seconds per side without arching the lower back.", - ), - ...repeated(`${prefix}-wall-slide`, 2, (setNumber) => - step( - `${prefix}-wall-slide-${setNumber}`, - "Wall slides", - "Mobility", - `Set ${setNumber} of 2`, - "reps", - { targetReps: 8 }, - "Move smoothly through a comfortable shoulder range.", - ), - ), - step( - `${prefix}-lat-stretch`, - "Bench lat stretch", - "Mobility", - "1 hold", - "duration", - { targetDurationSeconds: 45 }, - "Keep the ribs controlled while reaching overhead.", - ), - step( - `${prefix}-pec-stretch`, - "Doorway pec stretch", - "Mobility", - "1 hold per side", - "duration", - { targetDurationSeconds: 90 }, - "Use 30–45 seconds per side; stop for sharp or radiating pain.", - ), - ]; -} - -function upperSteps(prefix: string, includePullUpTest: boolean): PlannedStep[] { - const preparation = [ - step( - `${prefix}-prep-cardio`, - "Easy treadmill, bike or rower", - "Preparation", - "General preparation · 1 of 4", - "duration", - { targetDurationSeconds: 180 }, - "Use an easy pace for 2–3 minutes.", - ), - step( - `${prefix}-prep-circles`, - "Arm circles", - "Preparation", - "General preparation · 2 of 4", - "reps", - { targetReps: 20 }, - "Complete 10 forward and 10 backward.", - ), - step( - `${prefix}-prep-wall-slides`, - "Wall slides", - "Preparation", - "General preparation · 3 of 4", - "reps", - { targetReps: 8 }, - "Stay controlled through a comfortable range.", - ), - step( - `${prefix}-prep-scapular`, - "Very light scapular pulldown", - "Preparation", - "General preparation · 4 of 4", - "weight-reps", - { targetReps: 10 }, - "Move the shoulder blades without turning this into a working set.", - ), - ]; - - const bench = [ - step( - `${prefix}-bench-warmup-1`, - "Bench press", - "Warm-up", - "20 kg bar · ramp 1 of 3", - "weight-reps", - { targetWeight: 20, targetReps: 10, restSeconds: 60 }, - "Set shoulder blades and repeat the same touch point.", - ), - step( - `${prefix}-bench-warmup-2`, - "Bench press", - "Warm-up", - "40 kg · ramp 2 of 3", - "weight-reps", - { targetWeight: 40, targetReps: 5, restSeconds: 60 }, - "Keep the setup identical to the working sets.", - ), - step( - `${prefix}-bench-warmup-3`, - "Bench press", - "Warm-up", - "55 kg · ramp 3 of 3", - "weight-reps", - { targetWeight: 55, targetReps: 3, targetRepsMax: 3, restSeconds: 90 }, - "Use 2–3 clean repetitions; warm up without accumulating fatigue.", - ), - ...repeated(`${prefix}-bench-working`, 3, (setNumber) => - step( - `${prefix}-bench-working-${setNumber}`, - "Bench press", - "Working", - `Working set ${setNumber} of 3`, - "weight-reps", - { - targetWeight: 65, - targetReps: 5, - targetRepsMax: 8, - restSeconds: 180, - targetRpe: 8, - }, - "Keep 2–3 reps in reserve in Weeks 1–2; do not train to failure.", - ), - ), - ]; - - const pullUpTest = includePullUpTest - ? [ - step( - `${prefix}-pullup-test`, - "Strict pull-up checkpoint", - "Check", - "One test before pulldowns", - "reps", - { targetReps: 1, optional: true }, - "Attempt one clean strict pull-up only. Do not repeat-test.", - ), - ] - : []; - - return [ - ...preparation, - ...bench, - ...pullUpTest, - step( - `${prefix}-pulldown-warmup`, - "Lat pulldown", - "Warm-up", - "1 light set", - "weight-reps", - { targetReps: 8, restSeconds: 60 }, - "Use a comfortable neutral or shoulder-width grip.", - ), - ...repeated(`${prefix}-pulldown-working`, 3, (setNumber) => - step( - `${prefix}-pulldown-working-${setNumber}`, - "Lat pulldown", - "Working", - `Working set ${setNumber} of 3`, - "weight-reps", - { targetReps: 6, targetRepsMax: 10, restSeconds: 120, targetRpe: 8 }, - "Lead with the elbows; do not shorten the range.", - ), - ), - step( - `${prefix}-press-warmup`, - "Machine or DB shoulder press", - "Warm-up", - "1 light set", - "weight-reps", - { targetReps: 6, targetRepsMax: 8, restSeconds: 60 }, - "Choose a machine or neutral-grip dumbbells; do not force a barbell position.", - ), - ...repeated(`${prefix}-press-working`, 2, (setNumber) => - step( - `${prefix}-press-working-${setNumber}`, - "Machine or DB shoulder press", - "Working", - `Working set ${setNumber} of 2`, - "weight-reps", - { targetReps: 6, targetRepsMax: 10, restSeconds: 120, targetRpe: 8 }, - "Protect technique and shoulder comfort.", - ), - ), - step( - `${prefix}-row-warmup`, - "Chest-supported or cable row", - "Warm-up", - "Optional light set", - "weight-reps", - { targetReps: 8, restSeconds: 60, optional: true }, - "Use this familiarisation set only if needed.", - ), - ...repeated(`${prefix}-row-working`, 3, (setNumber) => - step( - `${prefix}-row-working-${setNumber}`, - "Chest-supported or cable row", - "Working", - `Working set ${setNumber} of 3`, - "weight-reps", - { targetReps: 8, targetRepsMax: 12, restSeconds: 120, targetRpe: 8 }, - "Row without using lower-back momentum.", - ), - ), - ...repeated(`${prefix}-ab-wheel`, 2, (setNumber) => - step( - `${prefix}-ab-wheel-${setNumber}`, - "Ab wheel from knees", - "Working", - `Working set ${setNumber} of 2`, - "reps", - { targetReps: 6, targetRepsMax: 12, restSeconds: 90 }, - "Stop before the lower back sags or arches.", - ), - ), - ...repeated(`${prefix}-farmer`, 2, (setNumber) => - step( - `${prefix}-farmer-${setNumber}`, - "Farmer carry", - "Working", - `Carry ${setNumber} of 2`, - "weight-duration", - { targetDurationSeconds: 30, restSeconds: 120 }, - "Stay tall; avoid leaning or excessive shrugging. Build toward 45 seconds.", - ), - ), - step( - `${prefix}-pec-stretch`, - "Doorway pec stretch", - "Cooldown", - "1 hold per side", - "duration", - { targetDurationSeconds: 90 }, - "Use 30–45 seconds per side.", - ), - step( - `${prefix}-lat-stretch`, - "Bench lat stretch", - "Cooldown", - "1 hold", - "duration", - { targetDurationSeconds: 45 }, - "Keep the ribs controlled.", - ), - step( - `${prefix}-open-book`, - "Open-book rotation", - "Cooldown", - "Optional · each side", - "reps", - { targetReps: 5, optional: true }, - "Use only if it feels useful; do not force range.", - ), - ]; -} - -function lowerSteps(weekNumber: number): PlannedStep[] { - const rdlSets = weekNumber <= 2 ? 2 : 3; - return [ - step( - "lower-prep-cardio", - "Easy bike or treadmill", - "Preparation", - "General preparation · 1 of 5", - "duration", - { targetDurationSeconds: 180 }, - "Use an easy pace for 3 minutes.", - ), - step( - "lower-prep-ankle", - "Knee-to-wall ankle rocks", - "Preparation", - "General preparation · 2 of 5 · each side", - "reps", - { targetReps: 10 }, - "Keep the heel down and movement controlled.", - ), - step( - "lower-prep-squat", - "Supported squat repetitions", - "Preparation", - "General preparation · 3 of 5", - "reps", - { targetReps: 5 }, - "Use a short pause and heel elevation when needed.", - ), - step( - "lower-prep-goblet", - "Light goblet squat", - "Preparation", - "General preparation · 4 of 5", - "weight-reps", - { targetReps: 6, targetRepsMax: 8 }, - "Elevate the heels when needed.", - ), - step( - "lower-prep-hinge", - "Unloaded hip hinges", - "Preparation", - "General preparation · 5 of 5", - "reps", - { targetReps: 8 }, - "Push the hips back while keeping a small knee bend.", - ), - step( - "lower-squat-warmup-1", - "Hack squat or leg press", - "Warm-up", - "Light × 10 · ramp 1 of 3", - "weight-reps", - { targetReps: 10, restSeconds: 60 }, - "Keep the same chosen machine and repeatable depth for the full block.", - ), - step( - "lower-squat-warmup-2", - "Hack squat or leg press", - "Warm-up", - "About 50% × 5 · ramp 2 of 3", - "weight-reps", - { targetReps: 5, restSeconds: 60 }, - "Warm up without turning this into a working set.", - ), - step( - "lower-squat-warmup-3", - "Hack squat or leg press", - "Warm-up", - "About 70% × 3 · ramp 3 of 3", - "weight-reps", - { targetReps: 3, restSeconds: 90 }, - "Repeat the working-set stance and depth.", - ), - ...repeated("lower-squat-working", 3, (setNumber) => - step( - `lower-squat-working-${setNumber}`, - "Hack squat or leg press", - "Working", - `Working set ${setNumber} of 3`, - "weight-reps", - { targetReps: 6, targetRepsMax: 10, restSeconds: 180, targetRpe: 8 }, - "Do not train to failure; keep depth repeatable.", - ), - ), - step( - "lower-rdl-warmup-1", - "Romanian deadlift", - "Warm-up", - "Bar × 8 · ramp 1 of 2", - "weight-reps", - { targetWeight: 20, targetReps: 8, restSeconds: 60 }, - "Push hips backward and keep the bar close.", - ), - step( - "lower-rdl-warmup-2", - "Romanian deadlift", - "Warm-up", - "50–60% × 5 · ramp 2 of 2", - "weight-reps", - { targetReps: 5, restSeconds: 90 }, - "Stop when further descent would require spinal movement.", - ), - ...repeated("lower-rdl-working", rdlSets, (setNumber) => - step( - `lower-rdl-working-${setNumber}`, - "Romanian deadlift", - "Working", - setNumber === 3 - ? "Conditional working set 3 of 3" - : `Working set ${setNumber} of ${rdlSets}`, - "weight-reps", - { - targetReps: 6, - targetRepsMax: 10, - restSeconds: 180, - targetRpe: 8, - optional: setNumber === 3, - }, - setNumber === 3 - ? "Complete only when technique is stable and lower-back fatigue is reasonable." - : "Keep the hinge in hamstrings and glutes; never train this to failure.", - ), - ), - step( - "lower-bulgarian-warmup", - "Supported Bulgarian split squat", - "Warm-up", - "Bodyweight or light × 5 per leg", - "weight-reps", - { targetReps: 5, restSeconds: 60 }, - "Use support so balance does not limit the legs.", - ), - ...repeated("lower-bulgarian-working", 2, (setNumber) => - step( - `lower-bulgarian-working-${setNumber}`, - "Supported Bulgarian split squat", - "Working", - `Working set ${setNumber} of 2 · per leg`, - "weight-reps", - { targetReps: 8, targetRepsMax: 12, restSeconds: 150, targetRpe: 8 }, - "Keep 1–2 reps in reserve and let the legs, not balance, limit the set.", - ), - ), - step( - "lower-curl-warmup", - "Lying leg curl", - "Warm-up", - "1 light set", - "weight-reps", - { targetReps: 8, targetRepsMax: 10, restSeconds: 60 }, - "Use a controlled eccentric.", - ), - ...repeated("lower-curl-working", 2, (setNumber) => - step( - `lower-curl-working-${setNumber}`, - "Lying leg curl", - "Working", - `Working set ${setNumber} of 2`, - "weight-reps", - { targetReps: 10, targetRepsMax: 15, restSeconds: 90, targetRpe: 8 }, - "Control the return; do not shorten range.", - ), - ), - step( - "lower-calf-warmup", - "Standing calf raise", - "Warm-up", - "Bodyweight × 10", - "reps", - { targetReps: 10, restSeconds: 60 }, - "Use a Smith machine, single-leg dumbbell raise, or straight-knee leg-press calf press.", - ), - ...repeated("lower-calf-working", 3, (setNumber) => - step( - `lower-calf-working-${setNumber}`, - "Standing calf raise", - "Working", - `Working set ${setNumber} of 3`, - "weight-reps", - { targetReps: 10, targetRepsMax: 20, restSeconds: 90, targetRpe: 8 }, - "Control the descent, pause in the stretch, rise fully, and do not bounce.", - ), - ), - step( - "lower-cooldown-calf-straight", - "Straight-knee calf stretch", - "Cooldown", - "1 hold per side", - "duration", - { targetDurationSeconds: 90 }, - "Use 30–45 seconds per side.", - ), - step( - "lower-cooldown-calf-bent", - "Bent-knee calf stretch", - "Cooldown", - "1 hold per side", - "duration", - { targetDurationSeconds: 90 }, - "Use 30–45 seconds per side.", - ), - step( - "lower-cooldown-hip", - "Half-kneeling hip-flexor stretch", - "Cooldown", - "1 hold per side", - "duration", - { targetDurationSeconds: 90 }, - "Avoid arching the lower back.", - ), - ]; -} - -function hardCardioSteps(weekNumber: number): PlannedStep[] { - const rounds = weekNumber <= 2 ? 4 : 5; - return [ - step( - "hard-cardio-warmup", - "Bike or elliptical", - "Cardio", - "Easy warm-up", - "duration", - { targetDurationSeconds: 480 }, - "Use 7–8 easy minutes after the full Upper session.", - ), - ...Array.from({ length: rounds }, (_, index) => { - const round = index + 1; - return [ - step( - `hard-cardio-${round}`, - "Controlled hard interval", - "Cardio", - `Hard round ${round} of ${rounds}`, - "duration", - { targetDurationSeconds: 120 }, - "Use 8/10 effort: demanding and controlled, never all-out.", - ), - step( - `hard-cardio-recovery-${round}`, - "Easy interval recovery", - "Cardio", - `Easy recovery ${round} of ${rounds}`, - "duration", - { targetDurationSeconds: 180 }, - "Recover at an easy pace for 3 minutes.", - ), - ]; - }).flat(), - step( - "hard-cardio-cooldown", - "Bike or elliptical cooldown", - "Cooldown", - "Easy cooldown", - "duration", - { targetDurationSeconds: 300 }, - "Finish with 5 easy minutes.", - ), - ]; -} - -const easyCardio = [ - step( - "easy-cardio-warmup", - "Easy cardio", - "Cardio", - "Very easy start · 1 of 3", - "duration", - { targetDurationSeconds: 300 }, - "Use treadmill walking, incline walking, bike, or elliptical.", - ), - step( - "easy-cardio-main", - "Conversational cardio", - "Cardio", - "Aerobic work · 2 of 3", - "duration", - { targetDurationSeconds: 2100 }, - "Stay around 3–4/10; full sentences should remain possible.", - ), - step( - "easy-cardio-cooldown", - "Easy cardio cooldown", - "Cooldown", - "Easy finish · 3 of 3", - "duration", - { targetDurationSeconds: 300 }, - "Finish fresh; do not turn the session into a race.", - ), -]; - -export const LEGACY_UPPER_STEPS: PlannedStep[] = [ - ...[ - [20, 15, 45], - [40, 10, 60], - [60, 3, 120], - ].map(([weight, reps, rest], index) => - step( - `bench-warmup-${index + 1}`, - "Bench press", - "Warm-up", - `Warm-up ${index + 1} of 3`, - "weight-reps", - { targetWeight: weight, targetReps: reps, restSeconds: rest }, - "Legacy sample session.", - ), - ), - ...repeated("legacy-bench", 3, (setNumber) => - step( - `bench-working-${setNumber}`, - "Bench press", - "Working", - `Working set ${setNumber} of 3`, - "weight-reps", - { targetWeight: 70, targetReps: 5, restSeconds: 180, targetRpe: 8 }, - "Legacy sample session.", - ), - ), - ...repeated("legacy-pulldown", 3, (setNumber) => - step( - `pulldown-${setNumber}`, - "Lat pulldown", - "Working", - `Working set ${setNumber} of 3`, - "weight-reps", - { targetWeight: 55, targetReps: 10, restSeconds: 90, targetRpe: 8 }, - "Legacy sample session.", - ), - ), - ...repeated("legacy-row", 3, (setNumber) => - step( - `row-${setNumber}`, - "Seated cable row", - "Working", - `Working set ${setNumber} of 3`, - "weight-reps", - { - targetWeight: 50, - targetReps: 12, - restSeconds: setNumber === 3 ? 0 : 90, - targetRpe: 8, - }, - "Legacy sample session.", - ), - ), -]; - -export function resolveWorkout( - workoutId: BuiltInWorkoutId, - weekNumber: number, - dayIndex = 0, -): WorkoutTemplate { - const week = Math.min(12, Math.max(1, Math.trunc(weekNumber))); - if (workoutId === "legacy-upper-a") { - return { - id: workoutId, - name: "Upper A · legacy sample", - scheduleName: "Legacy Upper A", - expectedMinutes: 60, - steps: LEGACY_UPPER_STEPS, - notes: ["Finish this restored session in its original order."], - }; - } - if (workoutId === "upper" || workoutId === "upper-hard") { - const pullUpTest = - (dayIndex === 0 && (week === 5 || week === 9)) || - (dayIndex === 3 && week === 12); - const steps = upperSteps("upper", pullUpTest); - const hard = workoutId === "upper-hard" ? hardCardioSteps(week) : []; - return { - id: workoutId, - name: workoutId === "upper-hard" ? "Upper + hard cardio" : "Upper", - scheduleName: workoutId === "upper-hard" ? "Upper + hard" : "Upper", - expectedMinutes: workoutId === "upper-hard" ? 105 : 65, - steps: [...steps, ...hard], - notes: [ - "Bench begins at 65 kg for 3 × 5–8. Add load only after 3 × 8 is clean.", - "Weeks 1–2: keep 2–3 reps in reserve. Thereafter use 1–2 on compounds.", - ...(week >= 5 - ? [ - "Optional lateral raises remain excluded unless recovery and shoulders are clearly good.", - ] - : []), - ], - }; - } - if (workoutId === "lower") { - return { - id: workoutId, - name: "Lower", - scheduleName: "Lower", - expectedMinutes: 70, - steps: lowerSteps(week), - notes: [ - "Choose hack squat or leg press once and keep it for all 12 weeks.", - week <= 2 - ? "Weeks 1–2 use exactly two RDL working sets." - : "The third RDL set is conditional on stable technique and reasonable lower-back fatigue.", - ], - }; - } - if (workoutId === "easy-mobility") { - return { - id: workoutId, - name: "Easy cardio + full mobility", - scheduleName: "Easy + mobility", - expectedMinutes: 60, - steps: [...easyCardio, ...fullMobility("full")], - notes: [ - "Start around the existing 5 km/h baseline when walking.", - "Increase speed or incline only after two comfortable weeks.", - ], - }; - } - return { - id: workoutId, - name: "Full mobility", - scheduleName: "Mobility", - expectedMinutes: 15, - steps: fullMobility("friday"), - notes: [ - "An optional 20–40 minute walk is allowed only when recovery is good.", - "Sharp pain, radiating symptoms, or worsening back pain are stop signals.", - ], - }; -} - -export type ProgrammePosition = { - weekNumber: number; - dayIndex: number; - inBlock: boolean; - beforeBlock: boolean; - afterBlock: boolean; - schedule: ScheduleEntry; - workout: WorkoutTemplate; -}; - -export function getProgrammePosition(date: Date): ProgrammePosition { - const start = new Date(2026, 6, 27); - start.setHours(0, 0, 0, 0); - const localDate = new Date( - date.getFullYear(), - date.getMonth(), - date.getDate(), - ); - const offset = Math.floor( - (localDate.getTime() - start.getTime()) / 86_400_000, - ); - const beforeBlock = offset < 0; - const afterBlock = offset >= 84; - const boundedOffset = Math.min(83, Math.max(0, offset)); - const weekNumber = Math.floor(boundedOffset / 7) + 1; - const dayIndex = boundedOffset % 7; - const schedule = PROGRAMME_SCHEDULE[dayIndex]; - return { - weekNumber, - dayIndex, - inBlock: !beforeBlock && !afterBlock, - beforeBlock, - afterBlock, - schedule, - workout: resolveWorkout(schedule.workoutId, weekNumber, dayIndex), - }; -} - -export function formatStepTarget(planned: PlannedStep): string { - const reps = - planned.targetReps === null - ? "" - : planned.targetRepsMax && planned.targetRepsMax !== planned.targetReps - ? `${planned.targetReps}–${planned.targetRepsMax} reps` - : `${planned.targetReps} reps`; - const duration = - planned.targetDurationSeconds === null - ? "" - : planned.targetDurationSeconds >= 60 && - planned.targetDurationSeconds % 60 === 0 - ? `${planned.targetDurationSeconds / 60} min` - : `${planned.targetDurationSeconds} sec`; - if (planned.tracking === "weight-reps") { - return `${planned.targetWeight === null ? "Choose load" : `${planned.targetWeight} kg`} · ${reps}`; - } - if (planned.tracking === "weight-duration") { - return `${planned.targetWeight === null ? "Choose load" : `${planned.targetWeight} kg`} · ${duration}`; - } - if (planned.tracking === "reps") return reps; - if (planned.tracking === "duration") return duration; - return "Complete"; -} diff --git a/src/lib/progression.ts b/src/lib/progression.ts deleted file mode 100644 index 073db62..0000000 --- a/src/lib/progression.ts +++ /dev/null @@ -1,123 +0,0 @@ -import type { - ExecutionRecord, - HistoryEntry, - StepSnapshot, -} from "./workout-state"; - -export type ProgressionRecommendation = { - sourceHistoryId: string; - sourceWorkoutName: string; - sourceCompletedAt: number; - evidenceSetCount: number; - previousWeight: number; - repetitionThreshold: number; - rpeCeiling: number; - suggestedWeight: number; - suggestedReps: number; -}; - -export function applyProgressionValues( - record: ExecutionRecord, - weight: number, - reps: number, -): ExecutionRecord { - if ( - record.step.tracking !== "weight-reps" || - record.segments.length !== 1 || - !Number.isFinite(weight) || - weight < 0 || - !Number.isInteger(reps) || - reps <= 0 - ) { - return record; - } - - return { - ...record, - segments: [ - { - ...record.segments[0], - weight, - reps, - }, - ], - }; -} - -function normalizedExerciseName(name: string) { - return name.trim().toLocaleLowerCase("en-US").replace(/\s+/g, " "); -} - -function comparableExecutions( - history: HistoryEntry, - exerciseName: string, -): ExecutionRecord[] { - const normalizedName = normalizedExerciseName(exerciseName); - return history.executions.filter( - (record) => - record.source === "planned" && - record.status === "completed" && - record.step.setType === "Working" && - record.step.tracking === "weight-reps" && - record.segments.length === 1 && - normalizedExerciseName(record.step.exercise) === normalizedName, - ); -} - -export function getProgressionRecommendation( - step: StepSnapshot, - history: HistoryEntry[], -): ProgressionRecommendation | null { - if ( - step.setType !== "Working" || - step.tracking !== "weight-reps" || - step.targetWeight === null || - step.targetWeight <= 0 || - step.targetReps === null || - step.targetReps <= 0 || - step.targetRepsMax === null || - step.targetRepsMax <= step.targetReps || - step.targetRpe === undefined || - step.targetRpe < 0 || - step.targetRpe > 10 - ) { - return null; - } - - const latestComparable = [...history] - .sort((left, right) => right.completedAt - left.completedAt) - .map((entry) => ({ - entry, - executions: comparableExecutions(entry, step.exercise), - })) - .find(({ executions }) => executions.length > 0); - - if (!latestComparable || latestComparable.executions.length < 2) { - return null; - } - - const clearsThreshold = latestComparable.executions.every((record) => { - const segment = record.segments[0]; - return ( - segment.weight === step.targetWeight && - segment.reps !== null && - segment.reps >= step.targetRepsMax! && - record.actualRpe !== null && - record.actualRpe <= step.targetRpe! - ); - }); - - if (!clearsThreshold) return null; - - return { - sourceHistoryId: latestComparable.entry.id, - sourceWorkoutName: latestComparable.entry.workoutName, - sourceCompletedAt: latestComparable.entry.completedAt, - evidenceSetCount: latestComparable.executions.length, - previousWeight: step.targetWeight, - repetitionThreshold: step.targetRepsMax, - rpeCeiling: step.targetRpe, - suggestedWeight: step.targetWeight + 2.5, - suggestedReps: step.targetReps, - }; -} diff --git a/src/lib/workout-data-transfer.ts b/src/lib/workout-data-transfer.ts deleted file mode 100644 index 4c4fd3a..0000000 --- a/src/lib/workout-data-transfer.ts +++ /dev/null @@ -1,232 +0,0 @@ -import { - parseStoredState, - type StoredState, - type WorkoutSession, -} from "./workout-state"; - -const WORKOUT_DATA_FORMAT = "setline-workout-data"; -const WORKOUT_DATA_FORMAT_VERSION = 1; -export const MAX_WORKOUT_DATA_FILE_BYTES = 2 * 1024 * 1024; - -export type WorkoutDataFileMetadata = { - name: string; - size: number; - type?: string; -}; - -export type WorkoutDataEnvelope = { - format: typeof WORKOUT_DATA_FORMAT; - formatVersion: typeof WORKOUT_DATA_FORMAT_VERSION; - exportedAt: string; - state: StoredState; -}; - -export type WorkoutDataImportPreview = { - exportedAt: string; - state: StoredState; - activeSession: { - workoutId: WorkoutSession["workoutId"]; - workoutName: string; - weekNumber: number; - phase: WorkoutSession["phase"]; - completedExecutions: number; - totalExecutions: number; - } | null; - historyCount: number; - customWorkoutCount: number; - customProgramme: { - name: string; - enabled: boolean; - startsOn: string; - weekCount: number; - assignmentCount: number; - } | null; - latestWorkout: { - workoutName: string; - completedAt: number; - } | null; -}; - -export type WorkoutDataImportResult = - | { status: "ok"; preview: WorkoutDataImportPreview } - | { status: "error"; message: string }; - -const envelopeKeys = ["exportedAt", "format", "formatVersion", "state"]; -const acceptedJsonTypes = new Set(["", "application/json", "text/json"]); - -function isRecord(value: unknown): value is Record { - return value !== null && typeof value === "object" && !Array.isArray(value); -} - -function isIsoTimestamp(value: unknown): value is string { - if (typeof value !== "string") return false; - const timestamp = Date.parse(value); - return ( - Number.isFinite(timestamp) && new Date(timestamp).toISOString() === value - ); -} - -export function validateWorkoutDataFileMetadata( - file: WorkoutDataFileMetadata, -): string | null { - if (!file.name.toLowerCase().endsWith(".json")) { - return "Choose a Setline .json file."; - } - if ( - file.type !== undefined && - !acceptedJsonTypes.has(file.type.toLowerCase()) - ) { - return "Choose a JSON file exported by Setline."; - } - if (!Number.isFinite(file.size) || file.size <= 0) { - return "The selected file is empty."; - } - if (file.size > MAX_WORKOUT_DATA_FILE_BYTES) { - return "The selected file is larger than Setline’s 2 MiB import limit."; - } - return null; -} - -export function createWorkoutDataEnvelope( - state: StoredState, - exportedAt = new Date(), -): WorkoutDataEnvelope { - return { - format: WORKOUT_DATA_FORMAT, - formatVersion: WORKOUT_DATA_FORMAT_VERSION, - exportedAt: exportedAt.toISOString(), - state, - }; -} - -export function serializeWorkoutData( - state: StoredState, - exportedAt = new Date(), -) { - const envelope = createWorkoutDataEnvelope(state, exportedAt); - return { - fileName: `setline-workout-data-${envelope.exportedAt.slice(0, 10)}.json`, - json: `${JSON.stringify(envelope, null, 2)}\n`, - }; -} - -function buildImportPreview( - state: StoredState, - exportedAt: string, -): WorkoutDataImportPreview { - const activeSession = state.session; - const latestHistoryEntry = state.history.reduce( - (latest, entry) => - latest === null || entry.completedAt > latest.completedAt - ? entry - : latest, - null as StoredState["history"][number] | null, - ); - return { - exportedAt, - state, - activeSession: activeSession - ? { - workoutId: activeSession.workoutId, - workoutName: activeSession.workoutName, - weekNumber: activeSession.weekNumber, - phase: activeSession.phase, - completedExecutions: activeSession.records.filter( - (record) => record.status !== "pending", - ).length, - totalExecutions: activeSession.records.length, - } - : null, - historyCount: state.history.length, - customWorkoutCount: state.customWorkouts.length, - customProgramme: state.customProgramme - ? { - name: state.customProgramme.name, - enabled: state.customProgramme.enabled, - startsOn: state.customProgramme.startsOn, - weekCount: state.customProgramme.weekCount, - assignmentCount: state.customProgramme.assignments.length, - } - : null, - latestWorkout: latestHistoryEntry - ? { - workoutName: latestHistoryEntry.workoutName, - completedAt: latestHistoryEntry.completedAt, - } - : null, - }; -} - -export function parseWorkoutDataImport( - raw: string, - importTime = Date.now(), -): WorkoutDataImportResult { - let parsed: unknown; - try { - parsed = JSON.parse(raw) as unknown; - } catch { - return { - status: "error", - message: "This file is not valid JSON.", - }; - } - - if (!isRecord(parsed)) { - return { - status: "error", - message: "This file is not a Setline workout-data export.", - }; - } - const keys = Object.keys(parsed).sort(); - if ( - keys.length !== envelopeKeys.length || - !keys.every((key, index) => key === envelopeKeys[index]) - ) { - return { - status: "error", - message: "This file has an unsupported Setline transfer shape.", - }; - } - if (parsed.format !== WORKOUT_DATA_FORMAT) { - return { - status: "error", - message: "This file is not a Setline workout-data export.", - }; - } - if (parsed.formatVersion !== WORKOUT_DATA_FORMAT_VERSION) { - return { - status: "error", - message: "This Setline export version is not supported.", - }; - } - if (!isIsoTimestamp(parsed.exportedAt)) { - return { - status: "error", - message: "This Setline export has an invalid export time.", - }; - } - - const state = parseStoredState(parsed.state, importTime); - if (!state) { - return { - status: "error", - message: - "This Setline export contains invalid workout data or exercise order.", - }; - } - return { - status: "ok", - preview: buildImportPreview(state, parsed.exportedAt), - }; -} - -export function activateImportedWorkoutData( - importedState: StoredState, - currentState: StoredState, - activatedAt = Date.now(), -): StoredState { - return { - ...importedState, - updatedAt: Math.max(activatedAt, currentState.updatedAt + 1), - }; -} diff --git a/src/lib/workout-state.ts b/src/lib/workout-state.ts deleted file mode 100644 index 86d5d12..0000000 --- a/src/lib/workout-state.ts +++ /dev/null @@ -1,1094 +0,0 @@ -import { - LEGACY_UPPER_STEPS, - resolveWorkout, - type BuiltInWorkoutId, - type PlannedStep, - type StepType, - type TrackingKind, - type WorkoutId, - type WorkoutTemplate, -} from "./programme"; -import { - isCustomWorkoutTemplate, - MAX_CUSTOM_WORKOUTS, - type CustomWorkoutTemplate, -} from "./custom-workouts"; -import { - isCustomProgramme, - MAX_CUSTOM_PROGRAMME_WEEKS, - type CustomProgramme, -} from "./custom-programme"; - -export type SessionPhase = "active" | "rest" | "summary"; -export type ExecutionStatus = "pending" | "completed" | "skipped"; -export type ExecutionSource = "planned" | "extra"; - -export type SetSegment = { - id: string; - weight: number | null; - reps: number | null; - durationSeconds: number | null; -}; - -export type StepSnapshot = { - id: string; - plannedStepId: string | null; - exercise: string; - setType: StepType; - setLabel: string; - tracking: TrackingKind; - targetWeight: number | null; - targetReps: number | null; - targetRepsMax: number | null; - targetDurationSeconds: number | null; - restSeconds: number; - targetRpe?: number; - cue: string; - optional: boolean; -}; - -export type ExecutionRecord = { - id: string; - source: ExecutionSource; - clonedFromId: string | null; - plannedPosition: number | null; - performedPosition: number | null; - deferred: boolean; - status: ExecutionStatus; - step: StepSnapshot; - segments: SetSegment[]; - actualRpe: number | null; - startedAt: number | null; - completedAt: number | null; - authoredRestSeconds: number; - adjustedRestSeconds: number; - actualRestSeconds: number | null; -}; - -export type WorkoutSession = { - id: string; - workoutId: WorkoutId; - workoutName: string; - weekNumber: number; - dayIndex: number; - startedAt: number; - completedAt: number | null; - phase: SessionPhase; - activeIndex: number; - queue: string[]; - restEndsAt: number | null; - pausedRestSeconds: number | null; - authoredRestSeconds: number; - adjustedRestSeconds: number; - restFromExecutionId: string | null; - records: ExecutionRecord[]; - quality: number | null; -}; - -export type HistoryEntry = { - id: string; - workoutId: WorkoutId; - workoutName: string; - weekNumber: number; - completedAt: number; - durationSeconds: number; - completedSets: number; - modifiedSets: number; - extraSets: number; - deferredSets: number; - skippedSets: number; - workingVolume: number; - warmupVolume: number; - completedDurationSeconds: number; - totalActualRestSeconds: number; - averageRpe: number | null; - quality: number | null; - detailsAvailable: boolean; - executions: ExecutionRecord[]; -}; - -export type StoredState = { - version: 6; - updatedAt: number; - session: WorkoutSession | null; - history: HistoryEntry[]; - customWorkouts: CustomWorkoutTemplate[]; - customProgramme: CustomProgramme | null; -}; - -export type SessionMetrics = { - completedSets: number; - modifiedSets: number; - extraSets: number; - deferredSets: number; - skippedSets: number; - workingVolume: number; - warmupVolume: number; - completedDurationSeconds: number; - totalActualRestSeconds: number; - averageRpe: number | null; -}; - -export const STORAGE_KEY = "setline:v1"; -export const PENDING_SYNC_KEY = "setline:sync-pending"; - -const workoutIds: BuiltInWorkoutId[] = [ - "upper", - "lower", - "easy-mobility", - "upper-hard", - "mobility", - "legacy-upper-a", -]; -const trackingKinds: TrackingKind[] = [ - "weight-reps", - "reps", - "duration", - "weight-duration", - "completion", -]; -const stepTypes: StepType[] = [ - "Preparation", - "Warm-up", - "Working", - "Cardio", - "Mobility", - "Cooldown", - "Check", -]; - -function isFiniteNumber(value: unknown): value is number { - return typeof value === "number" && Number.isFinite(value); -} - -function isNonNegativeNumber(value: unknown): value is number { - return isFiniteNumber(value) && value >= 0; -} - -function isNullableNumber(value: unknown): value is number | null { - return value === null || isFiniteNumber(value); -} - -function isNullableNonNegativeNumber(value: unknown): value is number | null { - return value === null || isNonNegativeNumber(value); -} - -function isNullableString(value: unknown): value is string | null { - return value === null || typeof value === "string"; -} - -function isBuiltInWorkoutId(value: unknown): value is BuiltInWorkoutId { - return workoutIds.includes(value as BuiltInWorkoutId); -} - -function isWorkoutId(value: unknown): value is WorkoutId { - return ( - isBuiltInWorkoutId(value) || - (typeof value === "string" && - value.startsWith("custom:") && - value.length <= 240) - ); -} - -function isSegment(value: unknown): value is SetSegment { - if (!value || typeof value !== "object") return false; - const segment = value as Partial; - return ( - typeof segment.id === "string" && - segment.id.length > 0 && - isNullableNonNegativeNumber(segment.weight) && - isNullableNonNegativeNumber(segment.reps) && - isNullableNonNegativeNumber(segment.durationSeconds) - ); -} - -function isStepSnapshot(value: unknown): value is StepSnapshot { - if (!value || typeof value !== "object") return false; - const step = value as Partial; - return ( - typeof step.id === "string" && - step.id.length > 0 && - isNullableString(step.plannedStepId) && - typeof step.exercise === "string" && - step.exercise.length > 0 && - stepTypes.includes(step.setType as StepType) && - typeof step.setLabel === "string" && - trackingKinds.includes(step.tracking as TrackingKind) && - isNullableNonNegativeNumber(step.targetWeight) && - isNullableNonNegativeNumber(step.targetReps) && - isNullableNonNegativeNumber(step.targetRepsMax) && - isNullableNonNegativeNumber(step.targetDurationSeconds) && - isNonNegativeNumber(step.restSeconds) && - (step.targetRpe === undefined || isNonNegativeNumber(step.targetRpe)) && - typeof step.cue === "string" && - typeof step.optional === "boolean" - ); -} - -function isExecutionRecord(value: unknown): value is ExecutionRecord { - if (!value || typeof value !== "object") return false; - const record = value as Partial; - return ( - typeof record.id === "string" && - record.id.length > 0 && - ["planned", "extra"].includes(record.source ?? "") && - isNullableString(record.clonedFromId) && - isNullableNonNegativeNumber(record.plannedPosition) && - isNullableNonNegativeNumber(record.performedPosition) && - typeof record.deferred === "boolean" && - ["pending", "completed", "skipped"].includes(record.status ?? "") && - isStepSnapshot(record.step) && - Array.isArray(record.segments) && - record.segments.length >= 1 && - record.segments.length <= 20 && - record.segments.every(isSegment) && - isNullableNumber(record.actualRpe) && - (record.actualRpe === null || - (record.actualRpe >= 0 && record.actualRpe <= 10)) && - isNullableNonNegativeNumber(record.startedAt) && - isNullableNonNegativeNumber(record.completedAt) && - isNonNegativeNumber(record.authoredRestSeconds) && - isNonNegativeNumber(record.adjustedRestSeconds) && - isNullableNonNegativeNumber(record.actualRestSeconds) - ); -} - -function queueMatchesRecords(queue: unknown, records: ExecutionRecord[]) { - if ( - !Array.isArray(queue) || - queue.length !== records.length || - !queue.every((id) => typeof id === "string") - ) { - return false; - } - const ids = new Set(records.map((record) => record.id)); - return ( - ids.size === records.length && - new Set(queue).size === queue.length && - queue.every((id) => ids.has(id)) - ); -} - -function isWorkoutSession(value: unknown): value is WorkoutSession { - if (!value || typeof value !== "object") return false; - const session = value as Partial; - if ( - typeof session.id !== "string" || - !session.id || - !isWorkoutId(session.workoutId) || - typeof session.workoutName !== "string" || - !session.workoutName || - !Number.isInteger(session.weekNumber) || - (session.weekNumber ?? 0) < 1 || - (session.weekNumber ?? MAX_CUSTOM_PROGRAMME_WEEKS + 1) > - (String(session.workoutId).startsWith("custom:") - ? MAX_CUSTOM_PROGRAMME_WEEKS - : 12) || - !Number.isInteger(session.dayIndex) || - (session.dayIndex ?? -1) < 0 || - (session.dayIndex ?? 7) > 6 || - !isNonNegativeNumber(session.startedAt) || - !isNullableNonNegativeNumber(session.completedAt) || - !["active", "rest", "summary"].includes(session.phase ?? "") || - !Number.isInteger(session.activeIndex) || - !isNullableNonNegativeNumber(session.restEndsAt) || - !isNullableNonNegativeNumber(session.pausedRestSeconds) || - !isNonNegativeNumber(session.authoredRestSeconds) || - !isNonNegativeNumber(session.adjustedRestSeconds) || - !isNullableString(session.restFromExecutionId) || - !Array.isArray(session.records) || - session.records.length < 1 || - session.records.length > 2000 || - !session.records.every(isExecutionRecord) || - !isNullableNumber(session.quality) - ) { - return false; - } - if ( - !queueMatchesRecords(session.queue, session.records) || - (session.activeIndex ?? -1) < 0 || - (session.activeIndex ?? session.records.length) >= session.records.length - ) { - return false; - } - if ( - session.restFromExecutionId !== null && - !session.records.some((record) => record.id === session.restFromExecutionId) - ) { - return false; - } - - const planned = session.records.filter( - (record) => record.source === "planned", - ); - if (String(session.workoutId).startsWith("custom:")) { - return ( - planned.length >= 1 && - planned.every( - (record, index) => - record.step.plannedStepId === record.step.id && - record.plannedPosition === index + 1, - ) - ); - } - const template = resolveWorkout( - session.workoutId as BuiltInWorkoutId, - session.weekNumber as number, - session.dayIndex as number, - ); - return ( - planned.length === template.steps.length && - planned.every((record, index) => { - const target = template.steps[index]; - return ( - record.step.plannedStepId === target.id && - record.plannedPosition === index + 1 - ); - }) - ); -} - -function isHistoryEntry(value: unknown): value is HistoryEntry { - if (!value || typeof value !== "object") return false; - const entry = value as Partial; - return ( - typeof entry.id === "string" && - entry.id.length > 0 && - isWorkoutId(entry.workoutId) && - typeof entry.workoutName === "string" && - entry.workoutName.length > 0 && - Number.isInteger(entry.weekNumber) && - (entry.weekNumber ?? 0) >= 1 && - (entry.weekNumber ?? MAX_CUSTOM_PROGRAMME_WEEKS + 1) <= - (String(entry.workoutId).startsWith("custom:") - ? MAX_CUSTOM_PROGRAMME_WEEKS - : 12) && - isNonNegativeNumber(entry.completedAt) && - isNonNegativeNumber(entry.durationSeconds) && - isNonNegativeNumber(entry.completedSets) && - isNonNegativeNumber(entry.modifiedSets) && - isNonNegativeNumber(entry.extraSets) && - isNonNegativeNumber(entry.deferredSets) && - isNonNegativeNumber(entry.skippedSets) && - isNonNegativeNumber(entry.workingVolume) && - isNonNegativeNumber(entry.warmupVolume) && - isNonNegativeNumber(entry.completedDurationSeconds) && - isNonNegativeNumber(entry.totalActualRestSeconds) && - isNullableNumber(entry.averageRpe) && - isNullableNumber(entry.quality) && - typeof entry.detailsAvailable === "boolean" && - Array.isArray(entry.executions) && - entry.executions.length <= 2000 && - entry.executions.every(isExecutionRecord) && - (entry.detailsAvailable || entry.executions.length === 0) - ); -} - -function snapshotStep(planned: PlannedStep): StepSnapshot { - return { - id: planned.id, - plannedStepId: planned.id, - exercise: planned.exercise, - setType: planned.setType, - setLabel: planned.setLabel, - tracking: planned.tracking, - targetWeight: planned.targetWeight, - targetReps: planned.targetReps, - targetRepsMax: planned.targetRepsMax, - targetDurationSeconds: planned.targetDurationSeconds, - restSeconds: planned.restSeconds, - targetRpe: planned.targetRpe, - cue: planned.cue, - optional: planned.optional ?? false, - }; -} - -export function makeInitialSegment(step: StepSnapshot, id: string): SetSegment { - return { - id, - weight: - step.tracking === "weight-reps" || step.tracking === "weight-duration" - ? (step.targetWeight ?? 0) - : null, - reps: - step.tracking === "weight-reps" || step.tracking === "reps" - ? step.targetReps - : null, - durationSeconds: - step.tracking === "duration" || step.tracking === "weight-duration" - ? step.targetDurationSeconds - : null, - }; -} - -export function makeExecutionRecord( - planned: PlannedStep, - plannedIndex: number, - startedAt: number | null, -): ExecutionRecord { - const step = snapshotStep(planned); - const id = `planned:${planned.id}`; - return { - id, - source: "planned", - clonedFromId: null, - plannedPosition: plannedIndex + 1, - performedPosition: null, - deferred: false, - status: "pending", - step, - segments: [makeInitialSegment(step, `${id}:segment:1`)], - actualRpe: null, - startedAt, - completedAt: null, - authoredRestSeconds: planned.restSeconds, - adjustedRestSeconds: planned.restSeconds, - actualRestSeconds: null, - }; -} - -export function makeWorkoutSession( - template: WorkoutTemplate, - weekNumber: number, - dayIndex: number, - startedAt = Date.now(), -): WorkoutSession { - const records = template.steps.map((step, index) => - makeExecutionRecord(step, index, index === 0 ? startedAt : null), - ); - return { - id: `session-${startedAt}`, - workoutId: template.id, - workoutName: template.name, - weekNumber, - dayIndex, - startedAt, - completedAt: null, - phase: "active", - activeIndex: 0, - queue: records.map((record) => record.id), - restEndsAt: null, - pausedRestSeconds: null, - authoredRestSeconds: 0, - adjustedRestSeconds: 0, - restFromExecutionId: null, - records, - quality: null, - }; -} - -export function getExecution( - session: WorkoutSession, - executionId: string | null | undefined, -) { - return executionId - ? (session.records.find((record) => record.id === executionId) ?? null) - : null; -} - -export function getActiveExecution(session: WorkoutSession) { - return getExecution(session, session.queue[session.activeIndex]); -} - -export function makeExtraExecution( - source: ExecutionRecord, - executionId: string, -): ExecutionRecord { - return { - ...source, - id: executionId, - source: "extra", - clonedFromId: source.id, - plannedPosition: null, - performedPosition: null, - deferred: false, - status: "pending", - step: { - ...source.step, - id: executionId, - plannedStepId: null, - setLabel: `Extra set · ${source.step.setLabel}`, - }, - segments: source.segments.map((segment, index) => ({ - ...segment, - id: `${executionId}:segment:${index + 1}`, - })), - actualRpe: null, - startedAt: null, - completedAt: null, - actualRestSeconds: null, - }; -} - -export function insertExtraExecution( - session: WorkoutSession, - source: ExecutionRecord, - executionId: string, -): WorkoutSession { - const extra = makeExtraExecution(source, executionId); - const insertAt = - session.phase === "rest" ? session.activeIndex : session.activeIndex + 1; - return { - ...session, - queue: [ - ...session.queue.slice(0, insertAt), - extra.id, - ...session.queue.slice(insertAt), - ], - records: [...session.records, extra], - }; -} - -export function deferActiveExecution( - session: WorkoutSession, - nextStartedAt: number, -): WorkoutSession { - if ( - session.phase !== "active" || - session.activeIndex >= session.queue.length - 1 - ) { - return session; - } - const queue = [...session.queue]; - const [deferredId] = queue.splice(session.activeIndex, 1); - queue.push(deferredId); - const nextId = queue[session.activeIndex]; - return { - ...session, - queue, - records: session.records.map((record) => - record.id === deferredId - ? { ...record, deferred: true, startedAt: null } - : record.id === nextId && record.startedAt === null - ? { ...record, startedAt: nextStartedAt } - : record, - ), - }; -} - -export function startQueuedExecution( - session: WorkoutSession, - startedAt: number, -): WorkoutSession { - const currentId = session.queue[session.activeIndex]; - const previous = getExecution(session, session.restFromExecutionId); - const actualRestSeconds = - previous?.completedAt === null || previous?.completedAt === undefined - ? null - : Math.max(0, Math.round((startedAt - previous.completedAt) / 1000)); - return { - ...session, - phase: "active", - restEndsAt: null, - pausedRestSeconds: null, - records: session.records.map((record) => - record.id === currentId - ? { ...record, startedAt } - : record.id === previous?.id - ? { ...record, actualRestSeconds } - : record, - ), - restFromExecutionId: null, - }; -} - -export function segmentVolume(segment: SetSegment) { - return (segment.weight ?? 0) * (segment.reps ?? 0); -} - -export function executionVolume(record: ExecutionRecord) { - return record.segments.reduce( - (total, segment) => total + segmentVolume(segment), - 0, - ); -} - -export function executionDuration(record: ExecutionRecord) { - return record.segments.reduce( - (total, segment) => total + (segment.durationSeconds ?? 0), - 0, - ); -} - -export function executionIsValid(record: ExecutionRecord | null | undefined) { - if (!record) return false; - if (record.step.tracking === "completion") return true; - return record.segments.every((segment) => { - if (record.step.tracking === "reps") return (segment.reps ?? 0) > 0; - if (record.step.tracking === "duration") { - return (segment.durationSeconds ?? 0) > 0; - } - if (record.step.tracking === "weight-duration") { - return (segment.weight ?? 0) >= 0 && (segment.durationSeconds ?? 0) > 0; - } - return (segment.weight ?? 0) >= 0 && (segment.reps ?? 0) > 0; - }); -} - -export function executionIsModified(record: ExecutionRecord) { - if ( - record.source === "extra" || - record.deferred || - record.segments.length !== 1 - ) { - return true; - } - const segment = record.segments[0]; - const step = record.step; - if (step.tracking === "weight-reps") { - return ( - (segment.weight ?? 0) !== (step.targetWeight ?? 0) || - segment.reps !== step.targetReps - ); - } - if (step.tracking === "reps") return segment.reps !== step.targetReps; - if (step.tracking === "duration" || step.tracking === "weight-duration") { - return ( - segment.durationSeconds !== step.targetDurationSeconds || - (step.tracking === "weight-duration" && - (segment.weight ?? 0) !== (step.targetWeight ?? 0)) - ); - } - return false; -} - -export function getSessionMetrics(session: WorkoutSession): SessionMetrics { - let workingVolume = 0; - let warmupVolume = 0; - let completedDurationSeconds = 0; - let totalActualRestSeconds = 0; - const rpes: number[] = []; - const resolved = session.records.filter( - (record) => record.status !== "pending", - ); - - for (const record of resolved) { - if (record.status !== "completed") continue; - const volume = executionVolume(record); - if ( - record.step.setType === "Warm-up" || - record.step.setType === "Preparation" - ) { - warmupVolume += volume; - } else if (record.step.setType === "Working") { - workingVolume += volume; - } - completedDurationSeconds += executionDuration(record); - totalActualRestSeconds += record.actualRestSeconds ?? 0; - if (record.actualRpe !== null) rpes.push(record.actualRpe); - } - - return { - completedSets: resolved.filter((record) => record.status === "completed") - .length, - modifiedSets: resolved.filter( - (record) => record.status === "completed" && executionIsModified(record), - ).length, - extraSets: resolved.filter((record) => record.source === "extra").length, - deferredSets: resolved.filter((record) => record.deferred).length, - skippedSets: resolved.filter((record) => record.status === "skipped") - .length, - workingVolume, - warmupVolume, - completedDurationSeconds, - totalActualRestSeconds, - averageRpe: rpes.length - ? rpes.reduce((total, value) => total + value, 0) / rpes.length - : null, - }; -} - -type V3Record = { - setId?: unknown; - status?: unknown; - actualWeight?: unknown; - actualReps?: unknown; - actualDurationSeconds?: unknown; - actualRpe?: unknown; - completedAt?: unknown; -}; - -type V3Session = { - id?: unknown; - workoutId?: unknown; - workoutName?: unknown; - weekNumber?: unknown; - dayIndex?: unknown; - startedAt?: unknown; - completedAt?: unknown; - phase?: unknown; - activeIndex?: unknown; - restEndsAt?: unknown; - pausedRestSeconds?: unknown; - plannedRestSeconds?: unknown; - records?: unknown; - quality?: unknown; -}; - -type V3History = { - id?: unknown; - workoutId?: unknown; - workoutName?: unknown; - weekNumber?: unknown; - completedAt?: unknown; - durationSeconds?: unknown; - completedSets?: unknown; - skippedSets?: unknown; - workingVolume?: unknown; - warmupVolume?: unknown; - completedDurationSeconds?: unknown; - averageRpe?: unknown; - quality?: unknown; -}; - -function migrateV3Record( - value: unknown, - planned: PlannedStep, - index: number, - sessionStartedAt: number, -): ExecutionRecord | null { - if (!value || typeof value !== "object") return null; - const legacy = value as V3Record; - if ( - legacy.setId !== planned.id || - !["pending", "completed", "skipped"].includes(String(legacy.status)) || - !isNullableNonNegativeNumber(legacy.actualWeight) || - !isNullableNonNegativeNumber(legacy.actualReps) || - !isNullableNonNegativeNumber(legacy.actualDurationSeconds) || - !isNullableNumber(legacy.actualRpe) || - !isNullableNonNegativeNumber(legacy.completedAt) - ) { - return null; - } - const record = makeExecutionRecord( - planned, - index, - index === 0 ? sessionStartedAt : null, - ); - record.status = legacy.status as ExecutionStatus; - record.actualRpe = legacy.actualRpe; - record.completedAt = legacy.completedAt; - record.performedPosition = record.status === "pending" ? null : index + 1; - record.segments = [ - { - id: `${record.id}:segment:1`, - weight: legacy.actualWeight, - reps: legacy.actualReps, - durationSeconds: legacy.actualDurationSeconds, - }, - ]; - return record; -} - -function migrateV3Session(value: unknown): WorkoutSession | null | undefined { - if (value === null) return null; - if (!value || typeof value !== "object") return undefined; - const legacy = value as V3Session; - if ( - typeof legacy.id !== "string" || - !isBuiltInWorkoutId(legacy.workoutId) || - typeof legacy.workoutName !== "string" || - !Number.isInteger(legacy.weekNumber) || - !Number.isInteger(legacy.dayIndex) || - !isNonNegativeNumber(legacy.startedAt) || - !isNullableNonNegativeNumber(legacy.completedAt) || - !["active", "rest", "summary"].includes(String(legacy.phase)) || - !Number.isInteger(legacy.activeIndex) || - !isNullableNonNegativeNumber(legacy.restEndsAt) || - !isNullableNonNegativeNumber(legacy.pausedRestSeconds) || - !isNonNegativeNumber(legacy.plannedRestSeconds) || - !Array.isArray(legacy.records) || - !isNullableNumber(legacy.quality) - ) { - return undefined; - } - const template = resolveWorkout( - legacy.workoutId, - legacy.weekNumber as number, - legacy.dayIndex as number, - ); - if (legacy.records.length !== template.steps.length) return undefined; - const records = legacy.records.map((record, index) => - migrateV3Record( - record, - template.steps[index], - index, - legacy.startedAt as number, - ), - ); - if (records.some((record) => record === null)) return undefined; - const typedRecords = records as ExecutionRecord[]; - const activeIndex = legacy.activeIndex as number; - const previous = typedRecords[Math.max(0, activeIndex - 1)] ?? null; - return { - id: legacy.id, - workoutId: legacy.workoutId, - workoutName: legacy.workoutName, - weekNumber: legacy.weekNumber as number, - dayIndex: legacy.dayIndex as number, - startedAt: legacy.startedAt, - completedAt: legacy.completedAt, - phase: legacy.phase as SessionPhase, - activeIndex, - queue: typedRecords.map((record) => record.id), - restEndsAt: legacy.restEndsAt, - pausedRestSeconds: legacy.pausedRestSeconds, - authoredRestSeconds: legacy.plannedRestSeconds, - adjustedRestSeconds: legacy.plannedRestSeconds, - restFromExecutionId: - legacy.phase === "rest" && previous ? previous.id : null, - records: typedRecords, - quality: legacy.quality, - }; -} - -function migrateSummaryHistory( - value: unknown, - fallback: { - workoutId: WorkoutId; - workoutName: string; - weekNumber: number; - }, -): HistoryEntry[] | undefined { - if (!Array.isArray(value) || value.length > 500) return undefined; - const entries = value.map((item) => { - if (!item || typeof item !== "object") return null; - const legacy = item as V3History; - const workoutId = isWorkoutId(legacy.workoutId) - ? legacy.workoutId - : fallback.workoutId; - const workoutName = - typeof legacy.workoutName === "string" - ? legacy.workoutName - : fallback.workoutName; - const weekNumber = Number.isInteger(legacy.weekNumber) - ? (legacy.weekNumber as number) - : fallback.weekNumber; - if ( - typeof legacy.id !== "string" || - !isNonNegativeNumber(legacy.completedAt) || - !isNonNegativeNumber(legacy.durationSeconds) || - !isNonNegativeNumber(legacy.completedSets) || - !isNonNegativeNumber(legacy.skippedSets) || - !isNonNegativeNumber(legacy.workingVolume) || - !isNonNegativeNumber(legacy.warmupVolume) || - !isNullableNumber(legacy.averageRpe) || - !isNullableNumber(legacy.quality) - ) { - return null; - } - return { - id: legacy.id, - workoutId, - workoutName, - weekNumber, - completedAt: legacy.completedAt, - durationSeconds: legacy.durationSeconds, - completedSets: legacy.completedSets, - modifiedSets: 0, - extraSets: 0, - deferredSets: 0, - skippedSets: legacy.skippedSets, - workingVolume: legacy.workingVolume, - warmupVolume: legacy.warmupVolume, - completedDurationSeconds: isNonNegativeNumber( - legacy.completedDurationSeconds, - ) - ? legacy.completedDurationSeconds - : 0, - totalActualRestSeconds: 0, - averageRpe: legacy.averageRpe, - quality: legacy.quality, - detailsAvailable: false, - executions: [], - } satisfies HistoryEntry; - }); - return entries.some((entry) => entry === null) - ? undefined - : (entries as HistoryEntry[]); -} - -function migrateV1OrV2Session( - value: unknown, -): WorkoutSession | null | undefined { - if (value === null) return null; - if (!value || typeof value !== "object") return undefined; - const legacy = value as V3Session; - return migrateV3Session({ - ...legacy, - workoutId: "legacy-upper-a", - workoutName: "Upper A · legacy sample", - weekNumber: 1, - dayIndex: 0, - records: - Array.isArray(legacy.records) && - legacy.records.length === LEGACY_UPPER_STEPS.length - ? legacy.records.map((record) => - record && typeof record === "object" - ? { actualDurationSeconds: null, ...record } - : record, - ) - : legacy.records, - }); -} - -export function emptyStoredState(): StoredState { - return { - version: 6, - updatedAt: 0, - session: null, - history: [], - customWorkouts: [], - customProgramme: null, - }; -} - -export function parseStoredState( - value: unknown, - migrationTime = Date.now(), -): StoredState | null { - if (!value || typeof value !== "object") return null; - const candidate = value as { - version?: unknown; - updatedAt?: unknown; - session?: unknown; - history?: unknown; - customWorkouts?: unknown; - customProgramme?: unknown; - }; - - if (candidate.version === 6) { - const session = - candidate.session === null || isWorkoutSession(candidate.session) - ? candidate.session - : undefined; - const history = - Array.isArray(candidate.history) && - candidate.history.length <= 500 && - candidate.history.every(isHistoryEntry) - ? candidate.history - : undefined; - const customWorkouts = - Array.isArray(candidate.customWorkouts) && - candidate.customWorkouts.length <= MAX_CUSTOM_WORKOUTS && - candidate.customWorkouts.every(isCustomWorkoutTemplate) && - new Set(candidate.customWorkouts.map((workout) => workout.id)).size === - candidate.customWorkouts.length - ? candidate.customWorkouts - : undefined; - const customProgramme = - candidate.customProgramme === null || - isCustomProgramme( - candidate.customProgramme, - new Set(customWorkouts?.map((workout) => workout.id) ?? []), - ) - ? candidate.customProgramme - : undefined; - if ( - session === undefined || - history === undefined || - customWorkouts === undefined || - customProgramme === undefined || - !isNonNegativeNumber(candidate.updatedAt) - ) { - return null; - } - return { - version: 6, - updatedAt: candidate.updatedAt, - session, - history, - customWorkouts, - customProgramme, - }; - } - - if (candidate.version === 5) { - return parseStoredState({ - ...candidate, - version: 6, - customProgramme: null, - }); - } - - if (candidate.version === 4) { - const migrated = parseStoredState({ - ...candidate, - version: 5, - customWorkouts: [], - }); - return migrated; - } - - if (candidate.version === 3) { - const session = migrateV3Session(candidate.session); - const history = migrateSummaryHistory(candidate.history, { - workoutId: "legacy-upper-a", - workoutName: "Legacy workout", - weekNumber: 1, - }); - if ( - session === undefined || - history === undefined || - !isNonNegativeNumber(candidate.updatedAt) - ) { - return null; - } - return { - version: 6, - updatedAt: candidate.updatedAt, - session, - history, - customWorkouts: [], - customProgramme: null, - }; - } - - if (candidate.version === 1 || candidate.version === 2) { - const session = migrateV1OrV2Session(candidate.session); - const history = migrateSummaryHistory(candidate.history, { - workoutId: "legacy-upper-a", - workoutName: "Upper A · legacy sample", - weekNumber: 1, - }); - if (session === undefined || history === undefined) return null; - return { - version: 6, - updatedAt: - candidate.version === 2 && isNonNegativeNumber(candidate.updatedAt) - ? candidate.updatedAt - : migrationTime, - session, - history, - customWorkouts: [], - customProgramme: null, - }; - } - return null; -} - -export function parseStoredStateJson(raw: string | null) { - if (!raw) return null; - try { - return parseStoredState(JSON.parse(raw) as unknown); - } catch { - return null; - } -} - -export function updateStoredState( - current: StoredState, - patch: Partial< - Pick< - StoredState, - "session" | "history" | "customWorkouts" | "customProgramme" - > - >, -): StoredState { - return { - ...current, - ...patch, - version: 6, - updatedAt: Math.max(Date.now(), current.updatedAt + 1), - }; -} diff --git a/tests/account-deletion.test.mjs b/tests/account-deletion.test.mjs deleted file mode 100644 index 608a014..0000000 --- a/tests/account-deletion.test.mjs +++ /dev/null @@ -1,27 +0,0 @@ -import assert from "node:assert/strict"; -import { readFile } from "node:fs/promises"; -import test from "node:test"; - -test("account deletion uses Better Auth and the existing D1 ownership cascades", async () => { - const [auth, migration] = await Promise.all([ - readFile(new URL("../worker/auth.ts", import.meta.url), "utf8"), - readFile( - new URL("../migrations/0001_auth_and_state.sql", import.meta.url), - "utf8", - ), - ]); - - assert.match(auth, /user:\s*\{\s*deleteUser:\s*\{\s*enabled:\s*true/); - for (const table of ["session", "account"]) { - assert.match( - migration, - new RegExp( - `CREATE TABLE ${table}[\\s\\S]*?userId TEXT NOT NULL REFERENCES user\\(id\\) ON DELETE CASCADE`, - ), - ); - } - assert.match( - migration, - /CREATE TABLE workout_state[\s\S]*?user_id TEXT PRIMARY KEY NOT NULL REFERENCES user\(id\) ON DELETE CASCADE/, - ); -}); diff --git a/tests/agent-edge.test.mjs b/tests/agent-edge.test.mjs deleted file mode 100644 index 2cbd4fb..0000000 --- a/tests/agent-edge.test.mjs +++ /dev/null @@ -1,36 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { handleAgentEdge } from "../worker/agent-edge.mjs"; - -const ORIGINS = [ - "https://setline.significanthobbies.com", - "https://setline-preview.example", -]; - -for (const origin of ORIGINS) { - test(`keeps sitemap and robots on the request origin: ${origin}`, async () => { - const sitemap = handleAgentEdge(new Request(`${origin}/sitemap.xml`)); - assert.ok(sitemap); - assert.equal(sitemap.status, 200); - assert.match(sitemap.headers.get("content-type") ?? "", /application\/xml/); - - const sitemapBody = await sitemap.text(); - for (const path of ["/", "/privacy", "/terms", "/changelog"]) { - assert.match(sitemapBody, new RegExp(`${origin}${path}`)); - } - if (origin !== "https://setline.significanthobbies.com") { - assert.doesNotMatch( - sitemapBody, - /https:\/\/setline\.significanthobbies\.com/, - ); - } - - const robots = handleAgentEdge(new Request(`${origin}/robots.txt`)); - assert.ok(robots); - assert.equal(robots.status, 200); - assert.match( - await robots.text(), - new RegExp(`Sitemap: ${origin}/sitemap\\.xml`), - ); - }); -} diff --git a/tests/agent-surface-parity.test.mjs b/tests/agent-surface-parity.test.mjs new file mode 100644 index 0000000..0ab722e --- /dev/null +++ b/tests/agent-surface-parity.test.mjs @@ -0,0 +1,346 @@ +import assert from "node:assert/strict"; +import { readFile, stat } from "node:fs/promises"; +import test from "node:test"; + +const ORIGIN = "https://setline.significanthobbies.com"; + +/** + * The public site is plain files on GitHub Pages. Nothing runs at request time, so + * nothing can reconcile the agent surfaces with each other or rewrite a path. + * These tests are that reconciliation: the sitemap, the agent catalog, `llms.txt` + * and the landing page have to agree, and every path any of them advertises has to + * resolve to a file that is actually published. + */ +function publicFile(name) { + return new URL(`../public/${name}`, import.meta.url); +} + +async function readPublic(name) { + return readFile(publicFile(name), "utf8"); +} + +/** + * Asserts a public path resolves to a file, in the order GitHub Pages tries: the + * exact file, then `.html`, then a directory index. + */ +async function assertServable(path) { + const trimmed = path === "/" ? "index.html" : path.replace(/^\//, ""); + const candidates = trimmed.includes(".") + ? [trimmed] + : [trimmed, `${trimmed}.html`, `${trimmed}/index.html`]; + for (const candidate of candidates) { + try { + await stat(publicFile(candidate)); + return candidate; + } catch { + continue; + } + } + assert.fail(`${path} resolves to none of: ${candidates.join(", ")}`); +} + +test("the agent catalog lives at the path robots.txt advertises", async () => { + const catalog = JSON.parse(await readPublic("api/ai")); + assert.equal(catalog.url, ORIGIN); + const robots = await readPublic("robots.txt"); + assert.match(robots, /Allow: \/api\/ai/); + // A second copy would drift; api/ai is the only one. + await assert.rejects(stat(publicFile("api-ai.json"))); +}); + +test("the agent catalog is valid JSON at its advertised path", async () => { + // GitHub Pages serves files as-is and cannot set a Content-Type for an + // extensionless path, so the body itself has to be unambiguously parsable. + const raw = await readPublic("api/ai"); + const catalog = JSON.parse(raw); + for (const field of [ + "name", + "url", + "llms", + "sitemap", + "markdown", + "surfaces", + ]) { + assert.ok(field in catalog, `/api/ai must carry ${field}`); + } + assert.doesNotMatch( + raw.trimStart()[0], + /[<#]/, + "must not be HTML or markdown", + ); +}); + +test("the site is published as-is under its own domain", async () => { + // Jekyll would otherwise drop dotfiles and reinterpret the markdown mirrors. + await stat(publicFile(".nojekyll")); + const cname = (await readPublic("CNAME")).trim(); + assert.equal(cname, ORIGIN.replace("https://", "")); +}); + +test("no Cloudflare-specific configuration survives", async () => { + for (const cloudflareOnly of ["_headers", "_redirects", "_worker.js"]) { + await assert.rejects( + stat(publicFile(cloudflareOnly)), + `${cloudflareOnly} is Cloudflare-only and would be dead config on GitHub Pages`, + ); + } + await assert.rejects(stat(new URL("../wrangler.jsonc", import.meta.url))); +}); + +test("every catalogued surface is in the sitemap and exists as a file", async () => { + const catalog = JSON.parse(await readPublic("api/ai")); + const sitemap = await readPublic("sitemap.xml"); + assert.ok(catalog.surfaces.length > 0); + for (const surface of catalog.surfaces) { + assert.ok( + surface.url.startsWith(ORIGIN), + `${surface.url} must be on the canonical origin`, + ); + assert.ok( + sitemap.includes(`${surface.url}`), + `${surface.url} is catalogued but missing from sitemap.xml`, + ); + await assertServable(surface.url.slice(ORIGIN.length)); + if (surface.md) { + await stat(publicFile(surface.md.slice(ORIGIN.length + 1))); + } + } +}); + +test("every sitemap entry is catalogued, so neither list can drift", async () => { + const catalog = JSON.parse(await readPublic("api/ai")); + const sitemap = await readPublic("sitemap.xml"); + const catalogued = new Set(catalog.surfaces.map((surface) => surface.url)); + const listed = [...sitemap.matchAll(/([^<]+)<\/loc>/g)].map((m) => m[1]); + assert.ok(listed.length > 0); + for (const url of listed) { + assert.ok( + catalogued.has(url), + `${url} is in the sitemap but not in /api/ai`, + ); + } +}); + +test("llms.txt points only at surfaces that exist", async () => { + const llms = await readPublic("llms.txt"); + const links = [...llms.matchAll(/\]\((https:\/\/[^)]+)\)/g)].map((m) => m[1]); + assert.ok(links.length > 0); + for (const link of links) { + assert.ok( + link.startsWith(ORIGIN), + `${link} must be on the canonical origin`, + ); + await assertServable(link.slice(ORIGIN.length)); + } +}); + +test("llms-full.txt embeds the homepage markdown verbatim", async () => { + const [full, index] = await Promise.all([ + readPublic("llms-full.txt"), + readPublic("index.md"), + ]); + assert.ok( + full.includes(index.trim()), + "the full brief must not paraphrase index.md", + ); +}); + +test("the landing page declares the canonical URL and its own OG image", async () => { + const html = await readPublic("index.html"); + assert.match(html, new RegExp(``)); + assert.match( + html, + new RegExp(``), + ); + // The analytics identifier is a tracked value and must survive page rewrites. + assert.match(html, /phc_qgiAarw4Co4pw9fz3Fxj4UJaHmqzFetqs4JrXhGc35Nd/); + assert.match(html, /project_id:"setline"/); +}); + +test("every asset the landing page references exists", async () => { + const html = await readPublic("index.html"); + const references = [ + ...[...html.matchAll(/]+src="\/([^"]+)"/g)].map((m) => m[1]), + ...[...html.matchAll(/]+href="\/([^"]+)"/g)].map((m) => m[1]), + ]; + assert.ok( + references.length > 0, + "expected the landing page to show the product", + ); + for (const reference of references) { + await stat(publicFile(reference)); + } +}); + +test("the landing page states its pre-release status rather than implying a download", async () => { + const html = await readPublic("index.html"); + assert.match(html, /Not on the App Store yet/); + assert.doesNotMatch( + html, + /apps\.apple\.com|Download on the App Store|testflight\.apple\.com/i, + "no store or TestFlight link may appear until one genuinely exists", + ); +}); + +test("the landing page avoids the weak words the landing standard bans", async () => { + const html = await readPublic("index.html"); + const body = html + .replace(//g, "") + .replace(//g, ""); + for (const word of [ + "powerful", + "seamless", + "robust", + "amazing", + "cutting-edge", + "revolutionary", + ]) { + assert.doesNotMatch( + body, + new RegExp(`\\b${word}\\b`, "i"), + `"${word}" is banned copy`, + ); + } +}); + +test("the manifest uses the tracked palette rather than the old placeholder navy", async () => { + const manifest = JSON.parse(await readPublic("manifest.webmanifest")); + assert.equal(manifest.background_color, "#f7f6f0"); + assert.equal(manifest.theme_color, "#18262e"); + for (const icon of manifest.icons) { + await stat(publicFile(icon.src.replace(/^\//, ""))); + } +}); + +test("the service worker only evicts its own caches and unregisters", async () => { + const sw = await readPublic("sw.js"); + assert.match(sw, /caches\.delete/); + assert.match(sw, /registration\.unregister\(\)/); + // A returning visitor must never be served a shell for a site that is gone. + assert.doesNotMatch(sw, /addAll|APP_SHELL/); +}); + +const PAGES = ["index.html", "privacy.html", "terms.html", "changelog.html"]; + +test("every page ships on the tracked palette, not the placeholder navy", async () => { + for (const page of PAGES) { + const html = await readPublic(page); + for (const placeholder of ["#0f172a", "#fbbf24", "#e2e8f0", "#38bdf8"]) { + assert.ok( + !html.includes(placeholder), + `${page} still uses the placeholder colour ${placeholder}`, + ); + } + assert.ok( + html.includes("#f7f6f0") || html.includes("/legal.css"), + `${page} must use the tracked tokens directly or via legal.css`, + ); + } +}); + +test("every asset any page references exists", async () => { + for (const page of PAGES) { + const html = await readPublic(page); + const references = [ + ...[...html.matchAll(/]+src="\/([^"]+)"/g)].map((m) => m[1]), + ...[...html.matchAll(/]+href="\/([^"]+)"/g)].map((m) => m[1]), + ]; + assert.ok(references.length > 0, `${page} references no local assets`); + for (const reference of references) { + await stat(publicFile(reference)); + } + } +}); + +test("no page claims an account, a sign-in or a server copy", async () => { + // The account layer was deleted. A public page that still offers it would be a + // false statement about where a person's training data goes. + const claims = [ + /Google sign-in/i, + /Sign in with Apple/i, + /\bsign in to\b/i, + /private cloud/i, + // \b keeps this off "iCloud sync", which is a named Apple feature the pages + // may legitimately describe as not yet built. + /\bcloud (copy|sync)\b/i, + /user-scoped/i, + ]; + for (const page of [...PAGES, "privacy.md", "terms.md", "changelog.md"]) { + const text = await readPublic(page); + for (const claim of claims) { + const match = text.match(claim); + // The changelog records the removal, so it may name what was removed. + if (match && page.startsWith("changelog")) continue; + assert.ok(!match, `${page} still claims "${match?.[0]}"`); + } + } +}); + +test("the privacy notice discloses every third-party script the site loads", async () => { + // Tying disclosure to the actual markup means adding a tracker without saying + // so in the notice fails here rather than shipping quietly. + const hosts = new Set(); + for (const page of PAGES) { + const html = await readPublic(page); + for (const [, host] of html.matchAll( + /(?:src|href)="https?:\/\/([^/"]+)/g, + )) { + if (host.endsWith("setline.significanthobbies.com")) continue; + hosts.add(host); + } + } + const [privacyHtml, privacyMd] = await Promise.all([ + readPublic("privacy.html"), + readPublic("privacy.md"), + ]); + // Documentation links are not scripts; only script/style origins need naming. + const scriptHosts = [...hosts].filter( + (host) => host === "us.i.posthog.com" || host === "sassmaker.com", + ); + assert.ok(scriptHosts.length > 0, "expected to find the analytics origins"); + const named = { "us.i.posthog.com": "PostHog", "sassmaker.com": "sassmaker" }; + for (const host of scriptHosts) { + for (const [label, copy] of [ + ["privacy.html", privacyHtml], + ["privacy.md", privacyMd], + ]) { + assert.match( + copy, + new RegExp(named[host], "i"), + `${label} must disclose ${host}`, + ); + } + } +}); + +test("the privacy notice and terms carry a date and the health disclaimer", async () => { + for (const page of ["privacy.html", "privacy.md", "terms.html", "terms.md"]) { + const text = await readPublic(page); + assert.match( + text, + /(Last updated|updated) 16 August 2026/, + `${page} must state when it was last updated`, + ); + } + for (const page of ["terms.html", "terms.md"]) { + const text = await readPublic(page); + assert.match(text, /not medical advice/i, `${page} must disclaim advice`); + } +}); + +test("no source file still references Cloudflare or the removed backend", async () => { + for (const [name, file] of [["package manifest", "../package.json"]]) { + const contents = await readFile(new URL(file, import.meta.url), "utf8"); + for (const gone of [ + "worker/index.ts", + "d1_databases", + "better-auth", + "drizzle", + ]) { + assert.ok( + !contents.includes(gone), + `${name} still references ${gone} after the backend removal`, + ); + } + } +}); diff --git a/tests/custom-programme.test.mjs b/tests/custom-programme.test.mjs deleted file mode 100644 index 00d4217..0000000 --- a/tests/custom-programme.test.mjs +++ /dev/null @@ -1,304 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { createServer } from "vite"; - -let customProgramme; -let customWorkouts; -let workoutState; -let vite; - -const validWorkoutIds = new Set(["custom:upper", "custom:lower"]); -const baseProgramme = { - name: "My strength block", - startsOn: "2026-10-26", - weekCount: 4, - enabled: true, - assignments: [ - { weekNumber: 1, dayIndex: 0, workoutId: "custom:upper" }, - { weekNumber: 1, dayIndex: 3, workoutId: "custom:lower" }, - ], - createdAt: 1_000, - updatedAt: 1_000, -}; - -test.before(async () => { - vite = await createServer({ - appType: "custom", - configFile: false, - server: { middlewareMode: true }, - }); - customProgramme = await vite.ssrLoadModule("/src/lib/custom-programme.ts"); - customWorkouts = await vite.ssrLoadModule("/src/lib/custom-workouts.ts"); - workoutState = await vite.ssrLoadModule("/src/lib/workout-state.ts"); -}); - -test.after(async () => { - await vite.close(); -}); - -test("accepts one bounded Monday-based programme", () => { - assert.equal( - customProgramme.isCustomProgramme(baseProgramme, validWorkoutIds), - true, - ); - assert.equal( - customProgramme.isCustomProgramme( - { ...baseProgramme, startsOn: "2026-10-27" }, - validWorkoutIds, - ), - false, - ); - assert.equal( - customProgramme.isCustomProgramme( - { ...baseProgramme, weekCount: 17 }, - validWorkoutIds, - ), - false, - ); - assert.equal( - customProgramme.isCustomProgramme( - { - ...baseProgramme, - assignments: [ - ...baseProgramme.assignments, - { weekNumber: 1, dayIndex: 0, workoutId: "custom:lower" }, - ], - }, - validWorkoutIds, - ), - false, - ); - assert.equal( - customProgramme.isCustomProgramme( - { - ...baseProgramme, - assignments: [ - { weekNumber: 1, dayIndex: 0, workoutId: "custom:missing" }, - ], - }, - validWorkoutIds, - ), - false, - ); -}); - -test("resolves scheduled, unplanned, before, after, and paused dates", () => { - assert.deepEqual( - customProgramme.resolveCustomProgrammeDay( - baseProgramme, - new Date(2026, 9, 26, 23, 30), - ), - { - status: "scheduled", - weekNumber: 1, - dayIndex: 0, - workoutId: "custom:upper", - }, - ); - assert.deepEqual( - customProgramme.resolveCustomProgrammeDay( - baseProgramme, - new Date(2026, 9, 27, 0, 30), - ), - { status: "unplanned", weekNumber: 1, dayIndex: 1 }, - ); - assert.deepEqual( - customProgramme.resolveCustomProgrammeDay( - baseProgramme, - new Date(2026, 9, 25, 12), - ), - { status: "outside", reason: "before" }, - ); - assert.deepEqual( - customProgramme.resolveCustomProgrammeDay( - baseProgramme, - new Date(2026, 10, 23, 12), - ), - { status: "outside", reason: "after" }, - ); - assert.deepEqual( - customProgramme.resolveCustomProgrammeDay( - { ...baseProgramme, enabled: false }, - new Date(2026, 9, 26, 12), - ), - { status: "outside", reason: "paused" }, - ); -}); - -test("uses calendar days across a daylight-saving transition", () => { - const programme = { - ...baseProgramme, - startsOn: "2026-10-26", - weekCount: 2, - assignments: [{ weekNumber: 2, dayIndex: 0, workoutId: "custom:upper" }], - }; - assert.deepEqual( - customProgramme.resolveCustomProgrammeDay( - programme, - new Date(2026, 10, 2, 0, 5), - ), - { - status: "scheduled", - weekNumber: 2, - dayIndex: 0, - workoutId: "custom:upper", - }, - ); -}); - -test("copies a week's exact slots into every later week", () => { - assert.deepEqual( - customProgramme.copyProgrammeWeekForward( - [ - ...baseProgramme.assignments, - { weekNumber: 2, dayIndex: 6, workoutId: "custom:lower" }, - ], - 1, - 3, - ), - [ - ...baseProgramme.assignments, - { weekNumber: 2, dayIndex: 0, workoutId: "custom:upper" }, - { weekNumber: 2, dayIndex: 3, workoutId: "custom:lower" }, - { weekNumber: 3, dayIndex: 0, workoutId: "custom:upper" }, - { weekNumber: 3, dayIndex: 3, workoutId: "custom:lower" }, - ], - ); -}); - -test("removes every future assignment for a deleted template", () => { - assert.deepEqual( - customProgramme.removeProgrammeWorkoutAssignments( - { - ...baseProgramme, - assignments: [ - ...baseProgramme.assignments, - { weekNumber: 2, dayIndex: 0, workoutId: "custom:upper" }, - ], - }, - "custom:upper", - 2_000, - ), - { - ...baseProgramme, - assignments: [{ weekNumber: 1, dayIndex: 3, workoutId: "custom:lower" }], - updatedAt: 2_000, - }, - ); -}); - -test("returns the local week's Monday as an ISO date", () => { - assert.equal( - customProgramme.mondayIsoForLocalDate(new Date(2026, 6, 31, 18)), - "2026-07-27", - ); - assert.equal(customProgramme.isMondayIsoDate("2026-07-27"), true); - assert.equal(customProgramme.isMondayIsoDate("2026-07-31"), false); - assert.equal(customProgramme.mondayIsoForIsoDate("2026-07-31"), "2026-07-27"); -}); - -test("migrates version 5 state and validates programme references in version 6", () => { - const migrated = workoutState.parseStoredState({ - version: 5, - updatedAt: 42, - session: null, - history: [], - customWorkouts: [], - }); - assert.deepEqual(migrated, { - version: 6, - updatedAt: 42, - session: null, - history: [], - customWorkouts: [], - customProgramme: null, - }); - - const custom = customWorkouts.duplicateWorkoutTemplate( - { - id: "upper", - name: "Upper", - scheduleName: "Upper", - expectedMinutes: 10, - notes: [], - steps: [ - { - id: "upper-step", - exercise: "Press", - setType: "Working", - setLabel: "Set 1", - tracking: "reps", - targetWeight: null, - targetReps: 8, - targetRepsMax: null, - targetDurationSeconds: null, - restSeconds: 60, - cue: "", - }, - ], - }, - "custom:upper", - 1_000, - ); - const valid = { - ...workoutState.emptyStoredState(), - customWorkouts: [custom], - customProgramme: { - ...baseProgramme, - assignments: [{ weekNumber: 1, dayIndex: 0, workoutId: "custom:upper" }], - }, - }; - assert.deepEqual(workoutState.parseStoredState(valid), valid); - assert.equal( - workoutState.parseStoredState({ - ...valid, - customWorkouts: [], - }), - null, - ); -}); - -test("round-trips a scheduled Week 16 custom session with its programme context", () => { - const custom = customWorkouts.duplicateWorkoutTemplate( - { - id: "lower", - name: "Lower", - scheduleName: "Lower", - expectedMinutes: 20, - notes: [], - steps: [ - { - id: "lower-step", - exercise: "Squat", - setType: "Working", - setLabel: "Set 1", - tracking: "reps", - targetWeight: null, - targetReps: 6, - targetRepsMax: null, - targetDurationSeconds: null, - restSeconds: 90, - cue: "", - }, - ], - }, - "custom:lower", - 1_000, - ); - const session = workoutState.makeWorkoutSession(custom, 16, 6, 2_000); - const state = { - ...workoutState.emptyStoredState(), - session, - customWorkouts: [custom], - customProgramme: { - ...baseProgramme, - weekCount: 16, - assignments: [{ weekNumber: 16, dayIndex: 6, workoutId: custom.id }], - }, - }; - const parsed = workoutState.parseStoredState(state); - assert.equal(parsed?.session?.weekNumber, 16); - assert.equal(parsed?.session?.dayIndex, 6); - assert.equal(parsed?.session?.workoutId, custom.id); - assert.equal(parsed?.session?.records[0].step.exercise, "Squat"); -}); diff --git a/tests/custom-workouts.test.mjs b/tests/custom-workouts.test.mjs deleted file mode 100644 index 1ca0826..0000000 --- a/tests/custom-workouts.test.mjs +++ /dev/null @@ -1,152 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { createServer } from "vite"; - -import { resolveWorkout } from "../src/lib/programme.ts"; - -let customWorkouts; -let workoutState; -let vite; - -test.before(async () => { - vite = await createServer({ - appType: "custom", - configFile: false, - server: { middlewareMode: true }, - }); - customWorkouts = await vite.ssrLoadModule("/src/lib/custom-workouts.ts"); - workoutState = await vite.ssrLoadModule("/src/lib/workout-state.ts"); -}); - -test.after(async () => { - await vite.close(); -}); - -test("duplicates a bundled workout as an independent custom template", () => { - const source = resolveWorkout("upper", 1, 0); - const sourceBefore = structuredClone(source); - const duplicate = customWorkouts.duplicateWorkoutTemplate( - source, - "custom:upper-copy", - 1_000, - ); - - assert.equal(customWorkouts.isCustomWorkoutTemplate(duplicate), true); - assert.equal(duplicate.name, "Upper copy"); - assert.equal(duplicate.steps.length, source.steps.length); - assert.equal( - new Set(duplicate.steps.map((step) => step.id)).size, - duplicate.steps.length, - ); - assert.ok( - duplicate.steps.every((step) => - step.id.startsWith("custom:upper-copy:step:"), - ), - ); - - duplicate.steps[0].exercise = "Changed only in the copy"; - assert.deepEqual(source, sourceBefore); -}); - -test("rejects empty, reordered-id, unbounded, and modality-invalid templates", () => { - const valid = customWorkouts.duplicateWorkoutTemplate( - resolveWorkout("mobility", 1, 4), - "custom:mobility-copy", - 2_000, - ); - assert.equal(customWorkouts.isCustomWorkoutTemplate(valid), true); - - assert.equal( - customWorkouts.isCustomWorkoutTemplate({ ...valid, name: " " }), - false, - ); - assert.equal( - customWorkouts.isCustomWorkoutTemplate({ - ...valid, - steps: Array.from({ length: 101 }, () => valid.steps[0]), - }), - false, - ); - assert.equal( - customWorkouts.isCustomWorkoutTemplate({ - ...valid, - steps: [ - { - ...valid.steps[0], - tracking: "duration", - targetDurationSeconds: null, - }, - ], - }), - false, - ); -}); - -test("migrates version 4 state and round-trips valid version 6 templates", () => { - const versionFour = { - version: 4, - updatedAt: 42, - session: null, - history: [], - }; - const migrated = workoutState.parseStoredState(versionFour, 99); - assert.deepEqual(migrated, { - version: 6, - updatedAt: 42, - session: null, - history: [], - customWorkouts: [], - customProgramme: null, - }); - - const custom = customWorkouts.duplicateWorkoutTemplate( - resolveWorkout("lower", 1, 1), - "custom:lower-copy", - 3_000, - ); - const parsed = workoutState.parseStoredState({ - ...workoutState.emptyStoredState(), - updatedAt: 3_001, - customWorkouts: [custom], - }); - assert.deepEqual(parsed?.customWorkouts, [custom]); - - assert.equal( - workoutState.parseStoredState({ - ...workoutState.emptyStoredState(), - customWorkouts: [custom, custom], - }), - null, - ); -}); - -test("custom sessions retain snapshots after their template changes or disappears", () => { - const custom = customWorkouts.duplicateWorkoutTemplate( - resolveWorkout("mobility", 1, 4), - "custom:snapshot", - 4_000, - ); - const session = workoutState.makeWorkoutSession(custom, 1, 0, 5_000); - const authoredExercises = session.records.map( - (record) => record.step.exercise, - ); - - custom.steps[0].exercise = "Edited after start"; - assert.deepEqual( - session.records.map((record) => record.step.exercise), - authoredExercises, - ); - - const parsedWithoutTemplate = workoutState.parseStoredState({ - ...workoutState.emptyStoredState(), - updatedAt: 5_001, - session, - customWorkouts: [], - }); - assert.deepEqual( - parsedWithoutTemplate?.session?.records.map( - (record) => record.step.exercise, - ), - authoredExercises, - ); -}); diff --git a/tests/history-analytics-performance.test.mjs b/tests/history-analytics-performance.test.mjs deleted file mode 100644 index 61f94b3..0000000 --- a/tests/history-analytics-performance.test.mjs +++ /dev/null @@ -1,140 +0,0 @@ -import assert from "node:assert/strict"; -import { createHash } from "node:crypto"; -import { performance } from "node:perf_hooks"; -import test from "node:test"; -import { createServer } from "vite"; - -const SIZES = [50, 250, 500]; -const ITERATIONS = 25; -const EXPECTED_HASHES = new Map([ - [50, "4a1278846a049e8abaab37035ef5dcf1f817a22fea8512d5b5926b6a855dc9b8"], - [250, "bc7296bb5223078b7eb1810b1822ef1bc343b4a20524794c1f23e10f62726579"], - [500, "d23d83d5588606a97912239ad1b189e522a1eb70ad3feef96cdd7057889d8a38"], -]); - -let deriveHistoryAnalytics; -let vite; - -test.before(async () => { - vite = await createServer({ - appType: "custom", - configFile: false, - server: { middlewareMode: true }, - }); - ({ deriveHistoryAnalytics } = await vite.ssrLoadModule( - "/src/lib/history-analytics.ts", - )); -}); - -test.after(async () => { - await vite.close(); -}); - -test("history analytics scales across the supported session limit", () => { - const metrics = []; - - for (const size of SIZES) { - const history = buildHistory(size); - const expected = JSON.stringify(deriveHistoryAnalytics(history)); - const expectedHash = createHash("sha256").update(expected).digest("hex"); - assert.equal(expectedHash, EXPECTED_HASHES.get(size)); - let durationMs = 0; - - for (let iteration = 0; iteration < ITERATIONS; iteration += 1) { - const startedAt = performance.now(); - const result = deriveHistoryAnalytics(history); - durationMs += performance.now() - startedAt; - const serialized = JSON.stringify(result); - assert.equal(serialized, expected); - assert.equal( - createHash("sha256").update(serialized).digest("hex"), - expectedHash, - ); - } - - metrics.push(`size${size}=${(durationMs / ITERATIONS).toFixed(3)}ms/op`); - } - - console.log(`[benchmark] ${metrics.join(" ")} (${ITERATIONS} iterations)`); - console.log(`[resource] maximum_supported_sessions=${SIZES.at(-1)}`); -}); - -function buildHistory(size) { - return Array.from({ length: size }, (_, historyIndex) => { - const executions = Array.from({ length: 18 }, (_, executionIndex) => { - const exerciseIndex = executionIndex % 12; - const weight = 40 + exerciseIndex * 2.5 + (historyIndex % 8) * 1.25; - const reps = 5 + ((historyIndex + executionIndex) % 8); - return { - id: `execution-${historyIndex}-${executionIndex}`, - source: "planned", - clonedFromId: null, - plannedPosition: executionIndex + 1, - performedPosition: executionIndex + 1, - deferred: false, - status: executionIndex % 17 === 0 ? "skipped" : "completed", - step: { - id: `step-${executionIndex}`, - plannedStepId: `step-${executionIndex}`, - exercise: `Exercise ${exerciseIndex}`, - setType: executionIndex % 6 === 0 ? "Warm-up" : "Working", - setLabel: `Set ${executionIndex + 1}`, - tracking: "weight-reps", - targetWeight: weight, - targetReps: reps, - targetRepsMax: reps + 2, - targetDurationSeconds: null, - restSeconds: 90, - targetRpe: 8, - cue: "", - optional: false, - }, - segments: [ - { - id: `segment-${historyIndex}-${executionIndex}`, - weight, - reps, - durationSeconds: null, - }, - ], - actualRpe: 6 + ((historyIndex + executionIndex) % 4), - startedAt: historyIndex * 100_000 + executionIndex * 1_000, - completedAt: historyIndex * 100_000 + executionIndex * 1_000 + 500, - authoredRestSeconds: 90, - adjustedRestSeconds: 90, - actualRestSeconds: 80 + (executionIndex % 20), - }; - }); - - return { - id: `history-${historyIndex}`, - workoutId: historyIndex % 10 === 0 ? "custom:conditioning" : "upper", - workoutName: historyIndex % 10 === 0 ? "Conditioning" : "Upper", - weekNumber: (historyIndex % 12) + 1, - completedAt: 2_000_000_000_000 - historyIndex * 86_400_000, - durationSeconds: 2_400 + (historyIndex % 600), - completedSets: executions.filter( - (record) => record.status === "completed", - ).length, - modifiedSets: historyIndex % 3, - extraSets: historyIndex % 2, - deferredSets: historyIndex % 4, - skippedSets: executions.filter((record) => record.status === "skipped") - .length, - workingVolume: executions.reduce( - (total, record) => - record.status === "completed" && record.step.setType === "Working" - ? total + record.segments[0].weight * record.segments[0].reps - : total, - 0, - ), - warmupVolume: 0, - completedDurationSeconds: 0, - totalActualRestSeconds: 1_400, - averageRpe: 7.5, - quality: 4, - detailsAvailable: true, - executions, - }; - }); -} diff --git a/tests/history-analytics.test.mjs b/tests/history-analytics.test.mjs deleted file mode 100644 index 2652cc8..0000000 --- a/tests/history-analytics.test.mjs +++ /dev/null @@ -1,312 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { createServer } from "vite"; - -let analytics; -let vite; - -test.before(async () => { - vite = await createServer({ - appType: "custom", - configFile: false, - server: { middlewareMode: true }, - }); - analytics = await vite.ssrLoadModule("/src/lib/history-analytics.ts"); -}); - -test.after(async () => { - await vite.close(); -}); - -function execution({ - id, - exercise = "Bench Press", - setType = "Working", - tracking = "weight-reps", - weight = 60, - reps = 8, - durationSeconds = null, - status = "completed", - actualRpe = 8, -}) { - return { - id, - source: "planned", - clonedFromId: null, - plannedPosition: 1, - performedPosition: 1, - deferred: false, - status, - step: { - id, - plannedStepId: id, - exercise, - setType, - setLabel: "Set 1", - tracking, - targetWeight: weight, - targetReps: reps, - targetRepsMax: reps, - targetDurationSeconds: durationSeconds, - restSeconds: 60, - targetRpe: 8, - cue: "", - optional: false, - }, - segments: [ - { - id: `${id}:segment:1`, - weight, - reps, - durationSeconds, - }, - ], - actualRpe, - startedAt: 1, - completedAt: 2, - authoredRestSeconds: 60, - adjustedRestSeconds: 60, - actualRestSeconds: 55, - }; -} - -function historyEntry({ - id, - completedAt, - workoutId = "upper", - workoutName = "Upper", - weekNumber = 1, - detailsAvailable = true, - executions = [], - durationSeconds = 1_800, - workingVolume = 0, - completedSets = executions.filter((record) => record.status === "completed") - .length, - modifiedSets = 0, - skippedSets = executions.filter((record) => record.status === "skipped") - .length, -}) { - return { - id, - workoutId, - workoutName, - weekNumber, - completedAt, - durationSeconds, - completedSets, - modifiedSets, - extraSets: 0, - deferredSets: 0, - skippedSets, - workingVolume, - warmupVolume: 0, - completedDurationSeconds: 0, - totalActualRestSeconds: 0, - averageRpe: null, - quality: null, - detailsAvailable, - executions, - }; -} - -test("returns an honest empty analytics model", () => { - assert.deepEqual(analytics.deriveHistoryAnalytics([]), { - overview: { - recordedSessions: 0, - detailedSessions: 0, - customSessions: 0, - totalDurationSeconds: 0, - totalWorkingVolume: 0, - latestCompletedAt: null, - }, - exercises: [], - workouts: [], - programmeWeeks: [], - }); -}); - -test("groups normalized exercise identity and calculates only recorded detail", () => { - const older = historyEntry({ - id: "older", - completedAt: 1_000, - executions: [ - execution({ - id: "old-working", - exercise: " Bench Press ", - weight: 60, - }), - ], - workingVolume: 480, - }); - const newer = historyEntry({ - id: "newer", - completedAt: 2_000, - executions: [ - execution({ - id: "new-working", - exercise: "Bench Press", - weight: 65, - reps: 5, - }), - execution({ - id: "new-warmup", - exercise: "BENCH PRESS", - setType: "Warm-up", - weight: 30, - reps: 10, - actualRpe: null, - }), - execution({ - id: "row", - exercise: "Cable row", - weight: 50, - reps: 10, - }), - ], - workingVolume: 825, - }); - - const result = analytics.deriveHistoryAnalytics([newer, older]); - const bench = result.exercises.find( - (exercise) => exercise.id === "bench press", - ); - - assert.ok(bench); - assert.equal(bench.name, "Bench Press"); - assert.equal(bench.recordedSessions, 2); - assert.equal(bench.completedExecutions, 3); - assert.equal(bench.bestWeight, 65); - assert.equal(bench.repetitionsAtBestWeight, 5); - assert.equal(bench.bestRepetitions, 10); - assert.equal(bench.totalWorkingVolume, 805); - assert.equal(bench.trendMetric, "weight"); - assert.deepEqual( - bench.trend.map((point) => point.historyId), - ["older", "newer"], - ); - assert.equal( - result.exercises.some((exercise) => exercise.id === "cable row"), - true, - ); -}); - -test("uses summary-only records only where their fields can support analytics", () => { - const legacy = historyEntry({ - id: "legacy", - completedAt: 3_000, - workoutName: "Original Upper", - detailsAvailable: false, - executions: [], - durationSeconds: 2_400, - workingVolume: 1_200, - completedSets: 8, - modifiedSets: 2, - skippedSets: 1, - }); - const result = analytics.deriveHistoryAnalytics([legacy]); - - assert.equal(result.overview.recordedSessions, 1); - assert.equal(result.overview.detailedSessions, 0); - assert.equal(result.overview.totalWorkingVolume, 1_200); - assert.equal(result.exercises.length, 0); - assert.equal(result.workouts[0].completedSets, 8); - assert.equal(result.programmeWeeks[0].modifiedSets, 2); -}); - -test("uses the latest point that actually recorded the selected metric", () => { - const result = analytics.deriveHistoryAnalytics([ - historyEntry({ - id: "weighted", - completedAt: 1_000, - executions: [execution({ id: "weighted-set", weight: 70, reps: 5 })], - }), - historyEntry({ - id: "reps-only", - completedAt: 2_000, - executions: [ - execution({ - id: "reps-only-set", - tracking: "reps", - weight: null, - reps: 12, - }), - ], - }), - ]); - - const bench = result.exercises[0]; - assert.equal(bench.recordedSessions, 2); - assert.equal(bench.trendMetric, "weight"); - assert.equal(bench.latest.historyId, "weighted"); - assert.deepEqual( - bench.trend.map((point) => point.historyId), - ["weighted"], - ); -}); - -test("groups workouts by stable id, keeps the newest name, and separates custom sessions", () => { - const result = analytics.deriveHistoryAnalytics([ - historyEntry({ - id: "old-name", - completedAt: 1_000, - workoutName: "Upper A", - durationSeconds: 1_200, - workingVolume: 500, - }), - historyEntry({ - id: "new-name", - completedAt: 2_000, - workoutName: "Upper", - durationSeconds: 1_800, - workingVolume: 700, - weekNumber: 2, - }), - historyEntry({ - id: "custom", - completedAt: 3_000, - workoutId: "custom:push", - workoutName: "Push", - weekNumber: 2, - }), - ]); - - const upper = result.workouts.find( - (workout) => workout.workoutId === "upper", - ); - assert.ok(upper); - assert.equal(upper.workoutName, "Upper"); - assert.equal(upper.recordedSessions, 2); - assert.equal(upper.averageDurationSeconds, 1_500); - assert.equal(upper.totalWorkingVolume, 1_200); - assert.equal(result.overview.customSessions, 1); - assert.deepEqual( - result.programmeWeeks.map((week) => week.weekNumber), - [1, 2], - ); - assert.equal(result.programmeWeeks[1].recordedSessions, 1); -}); - -test("bounds visible trends to the newest eight while retaining lifetime bests", () => { - const history = Array.from({ length: 10 }, (_, index) => - historyEntry({ - id: `session-${index + 1}`, - completedAt: index + 1, - executions: [ - execution({ - id: `set-${index + 1}`, - weight: index === 0 ? 100 : 50 + index, - reps: 5, - }), - ], - }), - ); - - const bench = analytics.deriveHistoryAnalytics(history).exercises[0]; - assert.equal(bench.recordedSessions, 10); - assert.equal(bench.bestWeight, 100); - assert.equal(bench.trend.length, 8); - assert.deepEqual( - bench.trend.map((point) => point.historyId), - Array.from({ length: 8 }, (_, index) => `session-${index + 3}`), - ); -}); diff --git a/tests/mcp-read.test.mjs b/tests/mcp-read.test.mjs deleted file mode 100644 index 377dc7a..0000000 --- a/tests/mcp-read.test.mjs +++ /dev/null @@ -1,131 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { createServer } from "vite"; - -let mcp; -let vite; - -test.before(async () => { - vite = await createServer({ - appType: "custom", - configFile: false, - server: { middlewareMode: true }, - }); - mcp = await vite.ssrLoadModule("/worker/mcp.ts"); -}); - -test.after(async () => { - await vite.close(); -}); - -test("read tokens are scoped, hashed, and reject browser credentials", async () => { - const token = mcp.createReadToken(); - assert.match(token, /^setline_read_[A-Za-z0-9_-]{40,}$/); - assert.match(await mcp.hashReadToken(token), /^[a-f0-9]{64}$/); - assert.equal(mcp.readBearerToken("Bearer header.payload.signature"), null); - assert.equal(mcp.readBearerToken("Bearer calorie_read_wrong_scope"), null); - assert.equal(mcp.readBearerToken("session=setline_read_cookie"), null); -}); - -test("history filtering preserves newest-first records and exact bounds", () => { - const first = { - id: "first", - workoutId: "upper", - workoutName: "Upper", - completedAt: Date.parse("2026-08-02T12:00:00Z"), - executions: [{ step: { exercise: "Bench press" } }], - }; - const second = { - ...first, - id: "second", - workoutId: "lower", - workoutName: "Lower", - completedAt: Date.parse("2026-08-03T12:00:00Z"), - executions: [{ step: { exercise: "Romanian deadlift" } }], - }; - const url = new URL( - "https://setline.example/api/mcp/history?start=2026-08-01&end=2026-08-03&workout=lower&exercise=deadlift", - ); - assert.deepEqual( - mcp.filterHistory([first, second], url).map((entry) => entry.id), - ["second"], - ); -}); - -test("MCP reads reject mutations and missing PATs before loading state", async () => { - const env = { - DB: { prepare: () => assert.fail("database should not be read") }, - }; - const mutation = await mcp.handleMcpRead( - new Request("https://setline.example/api/mcp/history", { method: "POST" }), - env, - ); - assert.equal(mutation.status, 405); - - const anonymous = await mcp.handleMcpRead( - new Request("https://setline.example/api/mcp/history"), - env, - ); - assert.equal(anonymous.status, 401); -}); - -test("active tokens bind every private read to the resolved owner", async () => { - const calls = []; - const env = { - DB: { - prepare(sql) { - return { - bind(...args) { - calls.push({ sql, args }); - return { - first: async () => - sql.includes("FROM mcp_read_tokens") - ? { user_id: "owner-a" } - : null, - }; - }, - }; - }, - }, - }; - const response = await mcp.handleMcpRead( - new Request("https://setline.example/api/mcp/history?limit=500&offset=0", { - headers: { Authorization: `Bearer ${mcp.createReadToken()}` }, - }), - env, - ); - - assert.equal(response.status, 200); - const body = await response.json(); - assert.deepEqual(body.items, []); - assert.equal(body.page.limit, 100); - assert.equal(body.page.nextOffset, null); - const stateRead = calls.find((call) => - call.sql.includes("FROM workout_state"), - ); - assert.deepEqual(stateRead?.args, ["owner-a"]); -}); - -test("revoked tokens fail before private state is read", async () => { - const calls = []; - const env = { - DB: { - prepare(sql) { - calls.push(sql); - return { bind: () => ({ first: async () => null }) }; - }, - }, - }; - const response = await mcp.handleMcpRead( - new Request("https://setline.example/api/mcp/history", { - headers: { Authorization: `Bearer ${mcp.createReadToken()}` }, - }), - env, - ); - - assert.equal(response.status, 401); - assert.equal( - calls.some((sql) => sql.includes("FROM workout_state")), - false, - ); -}); diff --git a/tests/mcp-source.test.mjs b/tests/mcp-source.test.mjs deleted file mode 100644 index 9f76e8b..0000000 --- a/tests/mcp-source.test.mjs +++ /dev/null @@ -1,44 +0,0 @@ -import assert from "node:assert/strict"; -import { readFile } from "node:fs/promises"; -import test from "node:test"; - -const [source, migration] = await Promise.all([ - readFile(new URL("../worker/mcp.ts", import.meta.url), "utf8"), - readFile( - new URL("../migrations/0002_mcp_read_tokens.sql", import.meta.url), - "utf8", - ), -]); - -test("Setline stores read-token hashes and owner-scopes revocation", () => { - assert.match(migration, /token_hash TEXT NOT NULL UNIQUE/); - assert.doesNotMatch(migration, /\btoken\s+TEXT/i); - assert.match(source, /WHERE id = \? AND user_id = \? AND revoked_at IS NULL/); - assert.match(source, /WHERE token_hash = \? AND revoked_at IS NULL/); -}); - -test("Setline MCP exposes projections without execution or whole-state writes", () => { - const readHandler = source.slice( - source.indexOf("export async function handleMcpRead"), - ); - assert.match(readHandler, /request\.method !== "GET"/); - assert.doesNotMatch( - readHandler, - /INSERT INTO workout_state|UPDATE workout_state/, - ); - assert.doesNotMatch( - readHandler, - /acceptRecommendation|startWorkout|completeSet|syncState/, - ); - assert.match(readHandler, /historySummary/); - assert.match(readHandler, /provenance: "calculated-from-recorded-history"/); -}); - -test("Setline pages remain bounded and state parsing fails closed", () => { - assert.match(source, /const MAX_LIMIT = 100/); - assert.match(source, /parseStoredState/); - assert.match( - source, - /Treat corrupt or unsupported cloud state as unavailable/, - ); -}); diff --git a/tests/native-account.test.mjs b/tests/native-account.test.mjs deleted file mode 100644 index 768c377..0000000 --- a/tests/native-account.test.mjs +++ /dev/null @@ -1,97 +0,0 @@ -import assert from "node:assert/strict"; -import { readFile } from "node:fs/promises"; -import test from "node:test"; -import { createServer } from "vite"; - -let handoff; -let nativeState; -let vite; - -test.before(async () => { - vite = await createServer({ - appType: "custom", - configFile: false, - server: { middlewareMode: true }, - }); - handoff = await vite.ssrLoadModule("/worker/native-handoff.ts"); - nativeState = await vite.ssrLoadModule("/worker/native-state.ts"); -}); - -test.after(async () => { - await vite.close(); -}); - -test("native authentication accepts only Setline's exact callback", () => { - assert.equal(handoff.isAllowedNativeCallback("setline://auth"), true); - assert.equal( - handoff.isAllowedNativeCallback("setline://auth.evil.example"), - false, - ); - assert.equal( - handoff.isAllowedNativeCallback("https://setline.example/auth"), - false, - ); -}); - -test("native handoff codes are opaque and hash deterministically", async () => { - const first = handoff.createNativeHandoffCode(); - const second = handoff.createNativeHandoffCode(); - assert.equal(first.length, 43); - assert.notEqual(first, second); - assert.equal( - await handoff.hashNativeHandoffCode(first), - await handoff.hashNativeHandoffCode(first), - ); - assert.notEqual( - await handoff.hashNativeHandoffCode(first), - await handoff.hashNativeHandoffCode(second), - ); -}); - -test("native state requires schema one and an explicit base revision", () => { - assert.deepEqual( - nativeState.parseNativeStateEnvelope({ - document: { schemaVersion: 1 }, - baseRevision: null, - }), - { document: { schemaVersion: 1 }, baseRevision: null }, - ); - assert.equal( - nativeState.parseNativeStateEnvelope({ - document: { schemaVersion: 2 }, - baseRevision: null, - }), - null, - ); - assert.equal( - nativeState.parseNativeStateEnvelope({ document: { schemaVersion: 1 } }), - null, - ); - assert.equal( - nativeState.parseNativeStateEnvelope({ - document: { schemaVersion: 1 }, - baseRevision: -1, - }), - null, - ); -}); - -test("native Apple auth validates the bundle audience and never links by email implicitly", async () => { - const [auth, client] = await Promise.all([ - readFile(new URL("../worker/auth.ts", import.meta.url), "utf8"), - readFile( - new URL( - "../ios/Sources/Setline/NativeAccountClient.swift", - import.meta.url, - ), - "utf8", - ), - ]); - - assert.match(auth, /appBundleIdentifier:\s*appleBundleIdentifier/); - assert.match(auth, /disableImplicitLinking:\s*true/); - assert.match(auth, /allowDifferentEmails:\s*true/); - assert.match(client, /\/api\/auth\/sign-in\/social/); - assert.match(client, /\/api\/auth\/link-social/); - assert.match(client, /set-auth-token/); -}); diff --git a/tests/programme.test.mjs b/tests/programme.test.mjs deleted file mode 100644 index d30705b..0000000 --- a/tests/programme.test.mjs +++ /dev/null @@ -1,422 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { createServer } from "vite"; - -import { - getProgrammePosition, - LEGACY_UPPER_STEPS, - PROGRAMME_SCHEDULE, - resolveWorkout, -} from "../src/lib/programme.ts"; - -test("resolves the dated block and all seven scheduled days", () => { - assert.equal(PROGRAMME_SCHEDULE.length, 7); - assert.deepEqual( - PROGRAMME_SCHEDULE.map((entry) => entry.workoutId), - [ - "upper", - "lower", - "easy-mobility", - "upper-hard", - "mobility", - "lower", - "easy-mobility", - ], - ); - - const start = getProgrammePosition(new Date(2026, 6, 27, 12)); - assert.equal(start.weekNumber, 1); - assert.equal(start.dayIndex, 0); - assert.equal(start.workout.id, "upper"); - assert.equal(start.inBlock, true); - - const tuesday = getProgrammePosition(new Date(2026, 6, 28, 12)); - assert.equal(tuesday.weekNumber, 1); - assert.equal(tuesday.workout.id, "lower"); - - const end = getProgrammePosition(new Date(2026, 9, 18, 12)); - assert.equal(end.weekNumber, 12); - assert.equal(end.dayIndex, 6); - assert.equal(end.workout.id, "easy-mobility"); -}); - -test("keeps the authored Upper exercise order", () => { - const steps = resolveWorkout("upper", 1, 0).steps; - const firstIndex = (name) => - steps.findIndex((planned) => planned.exercise === name); - - assert.ok( - firstIndex("Easy treadmill, bike or rower") < firstIndex("Bench press"), - ); - assert.ok(firstIndex("Bench press") < firstIndex("Lat pulldown")); - assert.ok( - firstIndex("Lat pulldown") < firstIndex("Machine or DB shoulder press"), - ); - assert.ok( - firstIndex("Machine or DB shoulder press") < - firstIndex("Chest-supported or cable row"), - ); - assert.ok( - firstIndex("Chest-supported or cable row") < - firstIndex("Ab wheel from knees"), - ); - assert.ok(firstIndex("Ab wheel from knees") < firstIndex("Farmer carry")); - assert.equal( - steps.filter((planned) => planned.id.startsWith("upper-bench-working-")) - .length, - 3, - ); - assert.deepEqual( - steps.slice(4, 7).map((planned) => planned.targetWeight), - [20, 40, 55], - ); -}); - -test("keeps the authored Lower order and week-aware RDL sets", () => { - const weekOne = resolveWorkout("lower", 1, 1).steps; - const weekThree = resolveWorkout("lower", 3, 1).steps; - const firstIndex = (steps, name) => - steps.findIndex((planned) => planned.exercise === name); - - assert.ok( - firstIndex(weekOne, "Hack squat or leg press") < - firstIndex(weekOne, "Romanian deadlift"), - ); - assert.ok( - firstIndex(weekOne, "Romanian deadlift") < - firstIndex(weekOne, "Supported Bulgarian split squat"), - ); - assert.ok( - firstIndex(weekOne, "Supported Bulgarian split squat") < - firstIndex(weekOne, "Lying leg curl"), - ); - assert.ok( - firstIndex(weekOne, "Lying leg curl") < - firstIndex(weekOne, "Standing calf raise"), - ); - - const rdlWorking = (steps) => - steps.filter((planned) => planned.id.startsWith("lower-rdl-working-")); - assert.equal(rdlWorking(weekOne).length, 2); - assert.equal(rdlWorking(weekThree).length, 3); - assert.equal(rdlWorking(weekThree)[2].optional, true); -}); - -test("runs Upper before the correct number of Thursday hard intervals", () => { - const weekOne = resolveWorkout("upper-hard", 1, 3).steps; - const weekThree = resolveWorkout("upper-hard", 3, 3).steps; - const hardRounds = (steps) => - steps.filter((planned) => /^hard-cardio-\d+$/.test(planned.id)); - - assert.equal(hardRounds(weekOne).length, 4); - assert.equal(hardRounds(weekThree).length, 5); - assert.ok( - weekOne.findIndex((planned) => planned.id === "upper-farmer-2") < - weekOne.findIndex((planned) => planned.id === "hard-cardio-warmup"), - ); -}); - -test("all startable templates have stable unique ordered ids", () => { - const trackingKinds = new Set(); - for (const schedule of PROGRAMME_SCHEDULE) { - for (const week of [1, 3, 5, 9, 12]) { - const workout = resolveWorkout( - schedule.workoutId, - week, - schedule.dayIndex, - ); - const ids = workout.steps.map((planned) => planned.id); - assert.equal( - new Set(ids).size, - ids.length, - `${schedule.workoutId} week ${week}`, - ); - workout.steps.forEach((planned) => trackingKinds.add(planned.tracking)); - } - } - assert.deepEqual([...trackingKinds].sort(), [ - "duration", - "reps", - "weight-duration", - "weight-reps", - ]); - assert.deepEqual( - LEGACY_UPPER_STEPS.map((planned) => planned.id), - [ - "bench-warmup-1", - "bench-warmup-2", - "bench-warmup-3", - "bench-working-1", - "bench-working-2", - "bench-working-3", - "pulldown-1", - "pulldown-2", - "pulldown-3", - "row-1", - "row-2", - "row-3", - ], - ); -}); - -test("migrates a version 2 session without changing its set order", async () => { - const vite = await createServer({ - appType: "custom", - configFile: false, - server: { middlewareMode: true }, - }); - try { - const { parseStoredState } = await vite.ssrLoadModule( - "/src/lib/workout-state.ts", - ); - const records = LEGACY_UPPER_STEPS.map((planned) => ({ - setId: planned.id, - status: "pending", - actualWeight: planned.targetWeight ?? 0, - actualReps: planned.targetReps ?? 0, - actualRpe: null, - completedAt: null, - })); - const legacy = { - version: 2, - updatedAt: 42, - session: { - id: "legacy-session", - startedAt: 1, - completedAt: null, - phase: "active", - activeIndex: 0, - restEndsAt: null, - pausedRestSeconds: null, - plannedRestSeconds: 0, - records, - quality: null, - }, - history: [], - }; - - const migrated = parseStoredState(legacy, 99); - assert.equal(migrated?.version, 6); - assert.deepEqual(migrated?.customWorkouts, []); - assert.equal(migrated?.customProgramme, null); - assert.equal(migrated?.updatedAt, 42); - assert.equal(migrated?.session?.workoutId, "legacy-upper-a"); - assert.deepEqual( - migrated?.session?.records.map((record) => record.step.plannedStepId), - LEGACY_UPPER_STEPS.map((planned) => planned.id), - ); - assert.deepEqual( - migrated?.session?.queue, - LEGACY_UPPER_STEPS.map((planned) => `planned:${planned.id}`), - ); - assert.ok( - migrated?.session?.records.every( - (record) => record.segments[0].durationSeconds === null, - ), - ); - - const reordered = structuredClone(legacy); - [reordered.session.records[0], reordered.session.records[1]] = [ - reordered.session.records[1], - reordered.session.records[0], - ]; - assert.equal(parseStoredState(reordered, 99), null); - } finally { - await vite.close(); - } -}); - -test("records flexible execution without mutating the authored workout", async () => { - const vite = await createServer({ - appType: "custom", - configFile: false, - server: { middlewareMode: true }, - }); - try { - const { - deferActiveExecution, - executionIsModified, - executionIsValid, - executionVolume, - getExecution, - getSessionMetrics, - insertExtraExecution, - makeWorkoutSession, - parseStoredState, - startQueuedExecution, - } = await vite.ssrLoadModule("/src/lib/workout-state.ts"); - const template = resolveWorkout("upper", 1, 0); - const authoredIds = template.steps.map((step) => step.id); - const session = makeWorkoutSession(template, 1, 0, 1_000); - - assert.deepEqual( - session.records.map((record) => record.step.plannedStepId), - authoredIds, - ); - assert.deepEqual( - session.queue, - authoredIds.map((id) => `planned:${id}`), - ); - - const working = session.records.find( - (record) => - record.step.setType === "Working" && - record.step.tracking === "weight-reps", - ); - assert.ok(working); - working.status = "completed"; - working.segments = [ - { - id: `${working.id}:segment:1`, - weight: 60, - reps: 5, - durationSeconds: null, - }, - { - id: `${working.id}:segment:2`, - weight: 50, - reps: 3, - durationSeconds: null, - }, - ]; - assert.equal(executionIsValid(working), true); - assert.equal(executionIsModified(working), true); - assert.equal(executionVolume(working), 450); - - const partial = structuredClone(working); - partial.segments = [ - { - id: `${partial.id}:segment:partial`, - weight: partial.step.targetWeight, - reps: Math.max(1, (partial.step.targetReps ?? 2) - 1), - durationSeconds: null, - }, - ]; - assert.equal(executionIsValid(partial), true); - assert.equal(executionIsModified(partial), true); - - const source = session.records[0]; - const withExtra = insertExtraExecution( - session, - source, - "extra:test-execution", - ); - assert.equal(template.steps.length, authoredIds.length); - assert.equal(withExtra.queue[1], "extra:test-execution"); - assert.equal(withExtra.records.at(-1).source, "extra"); - assert.equal(withExtra.records.at(-1).clonedFromId, source.id); - assert.equal(withExtra.records.at(-1).plannedPosition, null); - - const deferred = deferActiveExecution(session, 1_500); - assert.equal(deferred.queue.at(-1), session.queue[0]); - assert.equal(getExecution(deferred, session.queue[0]).deferred, true); - assert.equal(getExecution(deferred, deferred.queue[0]).startedAt, 1_500); - assert.deepEqual( - session.records.map((record) => record.step.plannedStepId), - authoredIds, - ); - - const priorId = session.queue[0]; - const nextId = session.queue[1]; - const resting = { - ...session, - phase: "rest", - activeIndex: 1, - restFromExecutionId: priorId, - authoredRestSeconds: 60, - adjustedRestSeconds: 90, - records: session.records.map((record) => - record.id === priorId - ? { - ...record, - status: "completed", - completedAt: 10_000, - authoredRestSeconds: 60, - adjustedRestSeconds: 90, - } - : record, - ), - }; - const resumed = startQueuedExecution(resting, 12_400); - assert.equal(getExecution(resumed, priorId).actualRestSeconds, 2); - assert.equal(getExecution(resumed, priorId).authoredRestSeconds, 60); - assert.equal(getExecution(resumed, priorId).adjustedRestSeconds, 90); - assert.equal(getExecution(resumed, nextId).startedAt, 12_400); - - const metrics = getSessionMetrics({ - ...session, - records: session.records.map((record) => - record.id === working.id ? working : record, - ), - }); - assert.equal(metrics.workingVolume, 450); - assert.equal(metrics.modifiedSets, 1); - - const historyEntry = { - id: "history-flexible", - workoutId: session.workoutId, - workoutName: session.workoutName, - weekNumber: session.weekNumber, - completedAt: 20_000, - durationSeconds: 19, - completedSets: 1, - modifiedSets: 1, - extraSets: 0, - deferredSets: 0, - skippedSets: 0, - workingVolume: 450, - warmupVolume: 0, - completedDurationSeconds: 0, - totalActualRestSeconds: 2, - averageRpe: null, - quality: null, - detailsAvailable: true, - executions: [ - { - ...working, - plannedPosition: working.plannedPosition, - performedPosition: 1, - startedAt: 15_000, - completedAt: 16_000, - actualRestSeconds: 2, - }, - ], - }; - const persisted = parseStoredState({ - version: 4, - updatedAt: 21_000, - session: null, - history: [historyEntry], - }); - assert.equal(persisted?.history[0].executions[0].segments.length, 2); - assert.equal(executionVolume(persisted?.history[0].executions[0]), 450); - - const legacyHistory = parseStoredState({ - version: 3, - updatedAt: 22_000, - session: null, - history: [ - { - id: "summary-only", - workoutId: "upper", - workoutName: "Upper", - weekNumber: 1, - completedAt: 20_000, - durationSeconds: 3_600, - completedSets: 12, - skippedSets: 1, - workingVolume: 4_000, - warmupVolume: 800, - completedDurationSeconds: 300, - averageRpe: 7.5, - quality: 4, - }, - ], - }); - assert.equal(legacyHistory?.version, 6); - assert.equal(legacyHistory?.history[0].detailsAvailable, false); - assert.deepEqual(legacyHistory?.history[0].executions, []); - } finally { - await vite.close(); - } -}); diff --git a/tests/progression.test.mjs b/tests/progression.test.mjs deleted file mode 100644 index a09ce5e..0000000 --- a/tests/progression.test.mjs +++ /dev/null @@ -1,193 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { createServer } from "vite"; - -let progression; -let vite; - -test.before(async () => { - vite = await createServer({ - appType: "custom", - configFile: false, - server: { middlewareMode: true }, - }); - progression = await vite.ssrLoadModule("/src/lib/progression.ts"); -}); - -test.after(async () => { - await vite.close(); -}); - -const currentStep = { - id: "bench-working-1", - plannedStepId: "bench-working-1", - exercise: "Bench press", - setType: "Working", - setLabel: "Working set 1 of 3", - tracking: "weight-reps", - targetWeight: 65, - targetReps: 5, - targetRepsMax: 8, - targetDurationSeconds: null, - restSeconds: 180, - targetRpe: 8, - cue: "Repeat the same touch point.", - optional: false, -}; - -function execution({ - id, - weight = 65, - reps = 8, - rpe = 8, - source = "planned", - status = "completed", - segments = 1, - setType = "Working", - tracking = "weight-reps", - exercise = "Bench press", -}) { - return { - id, - source, - status, - actualRpe: rpe, - step: { - ...currentStep, - id, - plannedStepId: source === "planned" ? id : null, - exercise, - setType, - tracking, - }, - segments: Array.from({ length: segments }, (_, index) => ({ - id: `${id}:segment:${index + 1}`, - weight, - reps, - durationSeconds: null, - })), - }; -} - -function historyEntry(id, completedAt, executions) { - return { - id, - workoutName: `Workout ${id}`, - completedAt, - executions, - }; -} - -test("recommends 2.5 kilograms after every comparable set clears the range and RPE", () => { - const recommendation = progression.getProgressionRecommendation(currentStep, [ - historyEntry("latest", 2_000, [ - execution({ id: "set-1" }), - execution({ id: "set-2", rpe: 7.5 }), - execution({ id: "set-3", reps: 9 }), - ]), - ]); - - assert.deepEqual(recommendation, { - sourceHistoryId: "latest", - sourceWorkoutName: "Workout latest", - sourceCompletedAt: 2_000, - evidenceSetCount: 3, - previousWeight: 65, - repetitionThreshold: 8, - rpeCeiling: 8, - suggestedWeight: 67.5, - suggestedReps: 5, - }); -}); - -test("uses only the newest comparable session and returns no recommendation after a miss", () => { - const recommendation = progression.getProgressionRecommendation(currentStep, [ - historyEntry("older-pass", 1_000, [ - execution({ id: "old-1" }), - execution({ id: "old-2" }), - ]), - historyEntry("newer-miss", 3_000, [ - execution({ id: "new-1" }), - execution({ id: "new-2", reps: 7 }), - ]), - ]); - - assert.equal(recommendation, null); -}); - -test("excludes extra, multi-segment, warm-up, and different-exercise executions", () => { - const recommendation = progression.getProgressionRecommendation(currentStep, [ - historyEntry("latest", 2_000, [ - execution({ id: "pass-1" }), - execution({ id: "pass-2" }), - execution({ id: "extra", source: "extra", reps: 1, rpe: 10 }), - execution({ id: "drop", segments: 2, reps: 1, rpe: 10 }), - execution({ id: "warm-up", setType: "Warm-up", reps: 1, rpe: 10 }), - execution({ id: "row", exercise: "Cable row", reps: 1, rpe: 10 }), - ]), - ]); - - assert.equal(recommendation?.evidenceSetCount, 2); - assert.equal(recommendation?.suggestedWeight, 67.5); -}); - -test("requires at least two passing sets with matching load, top reps, and recorded RPE", () => { - const cases = [ - [execution({ id: "only-one" })], - [execution({ id: "set-1" }), execution({ id: "set-2", weight: 62.5 })], - [execution({ id: "set-1" }), execution({ id: "set-2", reps: 7 })], - [execution({ id: "set-1" }), execution({ id: "set-2", rpe: null })], - [execution({ id: "set-1" }), execution({ id: "set-2", rpe: 8.5 })], - ]; - - for (const [index, executions] of cases.entries()) { - assert.equal( - progression.getProgressionRecommendation(currentStep, [ - historyEntry(`case-${index}`, 2_000, executions), - ]), - null, - ); - } -}); - -test("returns no recommendation for unsupported current steps", () => { - const passingHistory = [ - historyEntry("latest", 2_000, [ - execution({ id: "set-1" }), - execution({ id: "set-2" }), - ]), - ]; - const unsupported = [ - { ...currentStep, setType: "Warm-up" }, - { ...currentStep, tracking: "reps", targetWeight: null }, - { ...currentStep, targetWeight: null }, - { ...currentStep, targetRepsMax: null }, - { ...currentStep, targetRepsMax: 5 }, - { ...currentStep, targetRpe: undefined }, - ]; - - for (const step of unsupported) { - assert.equal( - progression.getProgressionRecommendation(step, passingHistory), - null, - ); - } -}); - -test("applies accepted or edited values to the current actuals without changing the authored step", () => { - const record = execution({ id: "current", reps: 5 }); - record.status = "pending"; - const authoredStep = structuredClone(record.step); - - const accepted = progression.applyProgressionValues(record, 67.5, 5); - const edited = progression.applyProgressionValues(record, 66, 6); - - assert.deepEqual(accepted.step, authoredStep); - assert.deepEqual(edited.step, authoredStep); - assert.equal(accepted.segments[0].weight, 67.5); - assert.equal(accepted.segments[0].reps, 5); - assert.equal(edited.segments[0].weight, 66); - assert.equal(edited.segments[0].reps, 6); - assert.equal(record.segments[0].weight, 65); - assert.equal(record.segments[0].reps, 5); -}); diff --git a/tests/workout-data-transfer.test.mjs b/tests/workout-data-transfer.test.mjs deleted file mode 100644 index 3cbfac7..0000000 --- a/tests/workout-data-transfer.test.mjs +++ /dev/null @@ -1,268 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { createServer } from "vite"; -import { resolveWorkout } from "../src/lib/programme.ts"; - -let transfer; -let workoutState; -let customWorkouts; -let vite; - -test.before(async () => { - vite = await createServer({ - appType: "custom", - configFile: false, - server: { middlewareMode: true }, - }); - transfer = await vite.ssrLoadModule("/src/lib/workout-data-transfer.ts"); - workoutState = await vite.ssrLoadModule("/src/lib/workout-state.ts"); - customWorkouts = await vite.ssrLoadModule("/src/lib/custom-workouts.ts"); -}); - -test.after(async () => { - await vite.close(); -}); - -test("exports a dated, non-sensitive Setline workout envelope", () => { - const state = workoutState.emptyStoredState(); - const exportedAt = new Date("2026-07-31T03:00:00.000Z"); - const result = transfer.serializeWorkoutData(state, exportedAt); - const parsed = JSON.parse(result.json); - - assert.equal(result.fileName, "setline-workout-data-2026-07-31.json"); - assert.deepEqual(parsed, { - format: "setline-workout-data", - formatVersion: 1, - exportedAt: exportedAt.toISOString(), - state, - }); - assert.doesNotMatch(result.json, /account|cookie|credential|oauth/i); -}); - -test("validates metadata before reading an import file", () => { - assert.equal( - transfer.validateWorkoutDataFileMetadata({ - name: "workout.txt", - size: 100, - type: "text/plain", - }), - "Choose a Setline .json file.", - ); - assert.equal( - transfer.validateWorkoutDataFileMetadata({ - name: "workout.json", - size: 100, - type: "application/octet-stream", - }), - "Choose a JSON file exported by Setline.", - ); - assert.equal( - transfer.validateWorkoutDataFileMetadata({ - name: "workout.json", - size: 0, - type: "application/json", - }), - "The selected file is empty.", - ); - assert.equal( - transfer.validateWorkoutDataFileMetadata({ - name: "workout.json", - size: transfer.MAX_WORKOUT_DATA_FILE_BYTES + 1, - type: "application/json", - }), - "The selected file is larger than Setline’s 2 MiB import limit.", - ); - assert.equal( - transfer.validateWorkoutDataFileMetadata({ - name: "workout.JSON", - size: 100, - type: "", - }), - null, - ); -}); - -test("previews a valid active session without mutating the export", () => { - const session = workoutState.makeWorkoutSession( - resolveWorkout("upper", 1, 0), - 1, - 0, - 1_000, - ); - session.records[0].status = "completed"; - const state = { - version: 4, - updatedAt: 2_000, - session, - history: [], - }; - const raw = transfer.serializeWorkoutData( - state, - new Date("2026-07-31T03:00:00.000Z"), - ).json; - const before = structuredClone(state); - const result = transfer.parseWorkoutDataImport(raw, 5_000); - - assert.equal(result.status, "ok"); - assert.deepEqual(state, before); - assert.deepEqual(result.preview.activeSession, { - workoutId: "upper", - workoutName: "Upper", - weekNumber: 1, - phase: "active", - completedExecutions: 1, - totalExecutions: session.records.length, - }); - assert.equal(result.preview.historyCount, 0); - assert.equal(result.preview.customWorkoutCount, 0); - assert.equal(result.preview.customProgramme, null); - assert.equal(result.preview.latestWorkout, null); -}); - -test("round-trips custom templates and previews their programme", () => { - const custom = customWorkouts.duplicateWorkoutTemplate( - resolveWorkout("lower", 1, 2), - "custom:backup", - 1_000, - ); - const state = { - ...workoutState.emptyStoredState(), - updatedAt: 2_000, - customWorkouts: [custom], - customProgramme: { - name: "Strength block", - startsOn: "2026-07-27", - weekCount: 4, - enabled: true, - assignments: [{ weekNumber: 1, dayIndex: 2, workoutId: custom.id }], - createdAt: 1_000, - updatedAt: 2_000, - }, - }; - const raw = transfer.serializeWorkoutData( - state, - new Date("2026-07-31T03:00:00.000Z"), - ).json; - const result = transfer.parseWorkoutDataImport(raw, 5_000); - - assert.equal(result.status, "ok"); - assert.equal(result.preview.customWorkoutCount, 1); - assert.deepEqual(result.preview.customProgramme, { - name: "Strength block", - enabled: true, - startsOn: "2026-07-27", - weekCount: 4, - assignmentCount: 1, - }); - assert.deepEqual(result.preview.state.customWorkouts, [ - JSON.parse(JSON.stringify(custom)), - ]); -}); - -test("rejects a programme with a dangling custom-workout assignment", () => { - const state = { - ...workoutState.emptyStoredState(), - customProgramme: { - name: "Broken block", - startsOn: "2026-07-27", - weekCount: 1, - enabled: true, - assignments: [ - { weekNumber: 1, dayIndex: 0, workoutId: "custom:missing" }, - ], - createdAt: 1_000, - updatedAt: 1_000, - }, - }; - const raw = JSON.stringify( - transfer.createWorkoutDataEnvelope( - state, - new Date("2026-07-31T03:00:00.000Z"), - ), - ); - assert.equal( - transfer.parseWorkoutDataImport(raw).message, - "This Setline export contains invalid workout data or exercise order.", - ); -}); - -test("rejects malformed, unknown, and invalid workout exports", () => { - assert.deepEqual(transfer.parseWorkoutDataImport("{"), { - status: "error", - message: "This file is not valid JSON.", - }); - assert.deepEqual(transfer.parseWorkoutDataImport("{}"), { - status: "error", - message: "This file has an unsupported Setline transfer shape.", - }); - - const state = workoutState.emptyStoredState(); - const envelope = transfer.createWorkoutDataEnvelope( - state, - new Date("2026-07-31T03:00:00.000Z"), - ); - assert.equal( - transfer.parseWorkoutDataImport( - JSON.stringify({ ...envelope, formatVersion: 2 }), - ).message, - "This Setline export version is not supported.", - ); - assert.equal( - transfer.parseWorkoutDataImport( - JSON.stringify({ ...envelope, exportedAt: "yesterday" }), - ).message, - "This Setline export has an invalid export time.", - ); - assert.equal( - transfer.parseWorkoutDataImport( - JSON.stringify({ - ...envelope, - state: { ...state, history: "not-history" }, - }), - ).message, - "This Setline export contains invalid workout data or exercise order.", - ); -}); - -test("migrates a supported legacy state inside the transfer envelope", () => { - const legacyState = { - version: 1, - session: null, - history: [], - }; - const result = transfer.parseWorkoutDataImport( - JSON.stringify({ - format: "setline-workout-data", - formatVersion: 1, - exportedAt: "2026-07-31T03:00:00.000Z", - state: legacyState, - }), - 7_000, - ); - - assert.equal(result.status, "ok"); - assert.equal(result.preview.state.version, 6); - assert.deepEqual(result.preview.state.customWorkouts, []); - assert.equal(result.preview.state.customProgramme, null); - assert.equal(result.preview.state.updatedAt, 7_000); -}); - -test("activates an import as a new local mutation", () => { - const imported = { - ...workoutState.emptyStoredState(), - updatedAt: 10, - }; - const current = { - ...workoutState.emptyStoredState(), - updatedAt: 20, - }; - - assert.equal( - transfer.activateImportedWorkoutData(imported, current, 15).updatedAt, - 21, - ); - assert.equal( - transfer.activateImportedWorkoutData(imported, current, 30).updatedAt, - 30, - ); -}); diff --git a/tsconfig.json b/tsconfig.json deleted file mode 100644 index 1b69322..0000000 --- a/tsconfig.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "compilerOptions": { - "target": "ES2017", - "lib": ["dom", "dom.iterable", "esnext"], - "allowJs": true, - "skipLibCheck": true, - "strict": true, - "noEmit": true, - "esModuleInterop": true, - "module": "esnext", - "moduleResolution": "bundler", - "resolveJsonModule": true, - "isolatedModules": true, - "incremental": true, - "paths": { - "@/*": ["./*"] - } - }, - "include": ["**/*.ts", "**/*.tsx", "**/*.mts"], - "exclude": ["node_modules", "dist", "app"] -} diff --git a/vite.config.ts b/vite.config.ts deleted file mode 100644 index ae9b05b..0000000 --- a/vite.config.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { defineConfig } from "vite"; - -// Minimal Vite config for test module loading (ssrLoadModule). -// The web app has been removed; Setline is now iOS-first with a -// Cloudflare Worker API backend serving static public/ assets. -export default defineConfig({ - plugins: [], -}); diff --git a/worker-configuration.d.ts b/worker-configuration.d.ts deleted file mode 100644 index 1dab0cf..0000000 --- a/worker-configuration.d.ts +++ /dev/null @@ -1,13635 +0,0 @@ -/* eslint-disable */ -// Generated by Wrangler by running `wrangler types --config wrangler.jsonc --env-interface CloudflareBindings` (hash: 43c509f2e383587be3fb4faa07d30267) -// Runtime types generated with workerd@1.20260515.1 2026-05-22 nodejs_compat -interface __BaseEnv_CloudflareBindings { - DB: D1Database; - ASSETS: Fetcher; - APPLE_APP_BUNDLE_IDENTIFIER: "com.significanthobbies.setline"; -} -declare namespace Cloudflare { - interface GlobalProps { - mainModule: typeof import("./worker/index"); - } - interface Env extends __BaseEnv_CloudflareBindings {} -} -interface CloudflareBindings extends __BaseEnv_CloudflareBindings {} -type StringifyValues> = { - [Binding in keyof EnvType]: EnvType[Binding] extends string ? EnvType[Binding] : string; -}; -declare namespace NodeJS { - interface ProcessEnv extends StringifyValues> {} -} - -// Begin runtime types -/*! ***************************************************************************** -Copyright (c) Cloudflare. All rights reserved. -Copyright (c) Microsoft Corporation. All rights reserved. - -Licensed under the Apache License, Version 2.0 (the "License"); you may not use -this file except in compliance with the License. You may obtain a copy of the -License at http://www.apache.org/licenses/LICENSE-2.0 -THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED -WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, -MERCHANTABLITY OR NON-INFRINGEMENT. -See the Apache Version 2.0 License for specific language governing permissions -and limitations under the License. -***************************************************************************** */ -/* eslint-disable */ -// noinspection JSUnusedGlobalSymbols -declare var onmessage: never; -/** - * The **`DOMException`** interface represents an abnormal event (called an **exception**) that occurs as a result of calling a method or accessing a property of a web API. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException) - */ -declare class DOMException extends Error { - constructor(message?: string, name?: string); - /** - * The **`message`** read-only property of the a message or description associated with the given error name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/message) - */ - readonly message: string; - /** - * The **`name`** read-only property of the one of the strings associated with an error name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/name) - */ - readonly name: string; - /** - * The **`code`** read-only property of the DOMException interface returns one of the legacy error code constants, or `0` if none match. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DOMException/code) - */ - readonly code: number; - static readonly INDEX_SIZE_ERR: number; - static readonly DOMSTRING_SIZE_ERR: number; - static readonly HIERARCHY_REQUEST_ERR: number; - static readonly WRONG_DOCUMENT_ERR: number; - static readonly INVALID_CHARACTER_ERR: number; - static readonly NO_DATA_ALLOWED_ERR: number; - static readonly NO_MODIFICATION_ALLOWED_ERR: number; - static readonly NOT_FOUND_ERR: number; - static readonly NOT_SUPPORTED_ERR: number; - static readonly INUSE_ATTRIBUTE_ERR: number; - static readonly INVALID_STATE_ERR: number; - static readonly SYNTAX_ERR: number; - static readonly INVALID_MODIFICATION_ERR: number; - static readonly NAMESPACE_ERR: number; - static readonly INVALID_ACCESS_ERR: number; - static readonly VALIDATION_ERR: number; - static readonly TYPE_MISMATCH_ERR: number; - static readonly SECURITY_ERR: number; - static readonly NETWORK_ERR: number; - static readonly ABORT_ERR: number; - static readonly URL_MISMATCH_ERR: number; - static readonly QUOTA_EXCEEDED_ERR: number; - static readonly TIMEOUT_ERR: number; - static readonly INVALID_NODE_TYPE_ERR: number; - static readonly DATA_CLONE_ERR: number; - get stack(): any; - set stack(value: any); -} -type WorkerGlobalScopeEventMap = { - fetch: FetchEvent; - scheduled: ScheduledEvent; - queue: QueueEvent; - unhandledrejection: PromiseRejectionEvent; - rejectionhandled: PromiseRejectionEvent; -}; -declare abstract class WorkerGlobalScope extends EventTarget { - EventTarget: typeof EventTarget; -} -/* The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). * - * The **`console`** object provides access to the debugging console (e.g., the Web console in Firefox). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console) - */ -interface Console { - "assert"(condition?: boolean, ...data: any[]): void; - /** - * The **`console.clear()`** static method clears the console if possible. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/clear_static) - */ - clear(): void; - /** - * The **`console.count()`** static method logs the number of times that this particular call to `count()` has been called. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/count_static) - */ - count(label?: string): void; - /** - * The **`console.countReset()`** static method resets counter used with console/count_static. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/countReset_static) - */ - countReset(label?: string): void; - /** - * The **`console.debug()`** static method outputs a message to the console at the 'debug' log level. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/debug_static) - */ - debug(...data: any[]): void; - /** - * The **`console.dir()`** static method displays a list of the properties of the specified JavaScript object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dir_static) - */ - dir(item?: any, options?: any): void; - /** - * The **`console.dirxml()`** static method displays an interactive tree of the descendant elements of the specified XML/HTML element. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/dirxml_static) - */ - dirxml(...data: any[]): void; - /** - * The **`console.error()`** static method outputs a message to the console at the 'error' log level. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/error_static) - */ - error(...data: any[]): void; - /** - * The **`console.group()`** static method creates a new inline group in the Web console log, causing any subsequent console messages to be indented by an additional level, until console/groupEnd_static is called. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/group_static) - */ - group(...data: any[]): void; - /** - * The **`console.groupCollapsed()`** static method creates a new inline group in the console. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupCollapsed_static) - */ - groupCollapsed(...data: any[]): void; - /** - * The **`console.groupEnd()`** static method exits the current inline group in the console. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/groupEnd_static) - */ - groupEnd(): void; - /** - * The **`console.info()`** static method outputs a message to the console at the 'info' log level. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/info_static) - */ - info(...data: any[]): void; - /** - * The **`console.log()`** static method outputs a message to the console. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/log_static) - */ - log(...data: any[]): void; - /** - * The **`console.table()`** static method displays tabular data as a table. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/table_static) - */ - table(tabularData?: any, properties?: string[]): void; - /** - * The **`console.time()`** static method starts a timer you can use to track how long an operation takes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/time_static) - */ - time(label?: string): void; - /** - * The **`console.timeEnd()`** static method stops a timer that was previously started by calling console/time_static. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeEnd_static) - */ - timeEnd(label?: string): void; - /** - * The **`console.timeLog()`** static method logs the current value of a timer that was previously started by calling console/time_static. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/timeLog_static) - */ - timeLog(label?: string, ...data: any[]): void; - timeStamp(label?: string): void; - /** - * The **`console.trace()`** static method outputs a stack trace to the console. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/trace_static) - */ - trace(...data: any[]): void; - /** - * The **`console.warn()`** static method outputs a warning message to the console at the 'warning' log level. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/console/warn_static) - */ - warn(...data: any[]): void; -} -declare const console: Console; -type BufferSource = ArrayBufferView | ArrayBuffer; -type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint16Array | Int32Array | Uint32Array | Float32Array | Float64Array | BigInt64Array | BigUint64Array; -declare namespace WebAssembly { - class CompileError extends Error { - constructor(message?: string); - } - class RuntimeError extends Error { - constructor(message?: string); - } - type ValueType = "anyfunc" | "externref" | "f32" | "f64" | "i32" | "i64" | "v128"; - interface GlobalDescriptor { - value: ValueType; - mutable?: boolean; - } - class Global { - constructor(descriptor: GlobalDescriptor, value?: any); - value: any; - valueOf(): any; - } - type ImportValue = ExportValue | number; - type ModuleImports = Record; - type Imports = Record; - type ExportValue = Function | Global | Memory | Table; - type Exports = Record; - class Instance { - constructor(module: Module, imports?: Imports); - readonly exports: Exports; - } - interface MemoryDescriptor { - initial: number; - maximum?: number; - shared?: boolean; - } - class Memory { - constructor(descriptor: MemoryDescriptor); - readonly buffer: ArrayBuffer; - grow(delta: number): number; - } - type ImportExportKind = "function" | "global" | "memory" | "table"; - interface ModuleExportDescriptor { - kind: ImportExportKind; - name: string; - } - interface ModuleImportDescriptor { - kind: ImportExportKind; - module: string; - name: string; - } - abstract class Module { - static customSections(module: Module, sectionName: string): ArrayBuffer[]; - static exports(module: Module): ModuleExportDescriptor[]; - static imports(module: Module): ModuleImportDescriptor[]; - } - type TableKind = "anyfunc" | "externref"; - interface TableDescriptor { - element: TableKind; - initial: number; - maximum?: number; - } - class Table { - constructor(descriptor: TableDescriptor, value?: any); - readonly length: number; - get(index: number): any; - grow(delta: number, value?: any): number; - set(index: number, value?: any): void; - } - function instantiate(module: Module, imports?: Imports): Promise; - function validate(bytes: BufferSource): boolean; -} -/** - * The **`ServiceWorkerGlobalScope`** interface of the Service Worker API represents the global execution context of a service worker. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ServiceWorkerGlobalScope) - */ -interface ServiceWorkerGlobalScope extends WorkerGlobalScope { - DOMException: typeof DOMException; - WorkerGlobalScope: typeof WorkerGlobalScope; - btoa(data: string): string; - atob(data: string): string; - setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; - setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; - clearTimeout(timeoutId: number | null): void; - setInterval(callback: (...args: any[]) => void, msDelay?: number): number; - setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; - clearInterval(timeoutId: number | null): void; - queueMicrotask(task: Function): void; - structuredClone(value: T, options?: StructuredSerializeOptions): T; - reportError(error: any): void; - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - self: ServiceWorkerGlobalScope; - crypto: Crypto; - caches: CacheStorage; - scheduler: Scheduler; - performance: Performance; - Cloudflare: Cloudflare; - readonly origin: string; - Event: typeof Event; - ExtendableEvent: typeof ExtendableEvent; - CustomEvent: typeof CustomEvent; - PromiseRejectionEvent: typeof PromiseRejectionEvent; - FetchEvent: typeof FetchEvent; - TailEvent: typeof TailEvent; - TraceEvent: typeof TailEvent; - ScheduledEvent: typeof ScheduledEvent; - MessageEvent: typeof MessageEvent; - CloseEvent: typeof CloseEvent; - ReadableStreamDefaultReader: typeof ReadableStreamDefaultReader; - ReadableStreamBYOBReader: typeof ReadableStreamBYOBReader; - ReadableStream: typeof ReadableStream; - WritableStream: typeof WritableStream; - WritableStreamDefaultWriter: typeof WritableStreamDefaultWriter; - TransformStream: typeof TransformStream; - ByteLengthQueuingStrategy: typeof ByteLengthQueuingStrategy; - CountQueuingStrategy: typeof CountQueuingStrategy; - ErrorEvent: typeof ErrorEvent; - MessageChannel: typeof MessageChannel; - MessagePort: typeof MessagePort; - EventSource: typeof EventSource; - ReadableStreamBYOBRequest: typeof ReadableStreamBYOBRequest; - ReadableStreamDefaultController: typeof ReadableStreamDefaultController; - ReadableByteStreamController: typeof ReadableByteStreamController; - WritableStreamDefaultController: typeof WritableStreamDefaultController; - TransformStreamDefaultController: typeof TransformStreamDefaultController; - CompressionStream: typeof CompressionStream; - DecompressionStream: typeof DecompressionStream; - TextEncoderStream: typeof TextEncoderStream; - TextDecoderStream: typeof TextDecoderStream; - Headers: typeof Headers; - Body: typeof Body; - Request: typeof Request; - Response: typeof Response; - WebSocket: typeof WebSocket; - WebSocketPair: typeof WebSocketPair; - WebSocketRequestResponsePair: typeof WebSocketRequestResponsePair; - AbortController: typeof AbortController; - AbortSignal: typeof AbortSignal; - TextDecoder: typeof TextDecoder; - TextEncoder: typeof TextEncoder; - navigator: Navigator; - Navigator: typeof Navigator; - URL: typeof URL; - URLSearchParams: typeof URLSearchParams; - URLPattern: typeof URLPattern; - Blob: typeof Blob; - File: typeof File; - FormData: typeof FormData; - Crypto: typeof Crypto; - SubtleCrypto: typeof SubtleCrypto; - CryptoKey: typeof CryptoKey; - CacheStorage: typeof CacheStorage; - Cache: typeof Cache; - FixedLengthStream: typeof FixedLengthStream; - IdentityTransformStream: typeof IdentityTransformStream; - HTMLRewriter: typeof HTMLRewriter; -} -declare function addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; -declare function removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; -/** - * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) - */ -declare function dispatchEvent(event: WorkerGlobalScopeEventMap[keyof WorkerGlobalScopeEventMap]): boolean; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/btoa) */ -declare function btoa(data: string): string; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/atob) */ -declare function atob(data: string): string; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ -declare function setTimeout(callback: (...args: any[]) => void, msDelay?: number): number; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setTimeout) */ -declare function setTimeout(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearTimeout) */ -declare function clearTimeout(timeoutId: number | null): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ -declare function setInterval(callback: (...args: any[]) => void, msDelay?: number): number; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/setInterval) */ -declare function setInterval(callback: (...args: Args) => void, msDelay?: number, ...args: Args): number; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/clearInterval) */ -declare function clearInterval(timeoutId: number | null): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/queueMicrotask) */ -declare function queueMicrotask(task: Function): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/structuredClone) */ -declare function structuredClone(value: T, options?: StructuredSerializeOptions): T; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/reportError) */ -declare function reportError(error: any): void; -/* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Window/fetch) */ -declare function fetch(input: RequestInfo | URL, init?: RequestInit): Promise; -declare const self: ServiceWorkerGlobalScope; -/** -* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. -* The Workers runtime implements the full surface of this API, but with some differences in -* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) -* compared to those implemented in most browsers. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) -*/ -declare const crypto: Crypto; -/** -* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) -*/ -declare const caches: CacheStorage; -declare const scheduler: Scheduler; -/** -* The Workers runtime supports a subset of the Performance API, used to measure timing and performance, -* as well as timing of subrequests and other operations. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) -*/ -declare const performance: Performance; -declare const Cloudflare: Cloudflare; -declare const origin: string; -declare const navigator: Navigator; -interface TestController { -} -interface ExecutionContext { - waitUntil(promise: Promise): void; - passThroughOnException(): void; - readonly exports: Cloudflare.Exports; - readonly props: Props; - cache?: CacheContext; - tracing?: Tracing; -} -type ExportedHandlerFetchHandler = (request: Request>, env: Env, ctx: ExecutionContext) => Response | Promise; -type ExportedHandlerConnectHandler = (socket: Socket, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTailHandler = (events: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTraceHandler = (traces: TraceItem[], env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTailStreamHandler = (event: TailStream.TailEvent, env: Env, ctx: ExecutionContext) => TailStream.TailEventHandlerType | Promise; -type ExportedHandlerScheduledHandler = (controller: ScheduledController, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerQueueHandler = (batch: MessageBatch, env: Env, ctx: ExecutionContext) => void | Promise; -type ExportedHandlerTestHandler = (controller: TestController, env: Env, ctx: ExecutionContext) => void | Promise; -interface ExportedHandler { - fetch?: ExportedHandlerFetchHandler; - connect?: ExportedHandlerConnectHandler; - tail?: ExportedHandlerTailHandler; - trace?: ExportedHandlerTraceHandler; - tailStream?: ExportedHandlerTailStreamHandler; - scheduled?: ExportedHandlerScheduledHandler; - test?: ExportedHandlerTestHandler; - email?: EmailExportedHandler; - queue?: ExportedHandlerQueueHandler; -} -interface StructuredSerializeOptions { - transfer?: any[]; -} -declare abstract class Navigator { - sendBeacon(url: string, body?: BodyInit): boolean; - readonly userAgent: string; - readonly hardwareConcurrency: number; - readonly platform: string; - readonly language: string; - readonly languages: string[]; -} -interface AlarmInvocationInfo { - readonly isRetry: boolean; - readonly retryCount: number; - readonly scheduledTime: number; -} -interface Cloudflare { - readonly compatibilityFlags: Record; -} -interface CachePurgeError { - code: number; - message: string; -} -interface CachePurgeResult { - success: boolean; - errors: CachePurgeError[]; -} -interface CachePurgeOptions { - tags?: string[]; - pathPrefixes?: string[]; - purgeEverything?: boolean; -} -interface CacheContext { - purge(options: CachePurgeOptions): Promise; -} -declare abstract class ColoLocalActorNamespace { - get(actorId: string): Fetcher; -} -interface DurableObject { - fetch(request: Request): Response | Promise; - connect?(socket: Socket): void | Promise; - alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; - webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; - webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; - webSocketError?(ws: WebSocket, error: unknown): void | Promise; -} -type DurableObjectStub = Fetcher & { - readonly id: DurableObjectId; - readonly name?: string; -}; -interface DurableObjectId { - toString(): string; - equals(other: DurableObjectId): boolean; - readonly name?: string; - readonly jurisdiction?: string; -} -declare abstract class DurableObjectNamespace { - newUniqueId(options?: DurableObjectNamespaceNewUniqueIdOptions): DurableObjectId; - idFromName(name: string): DurableObjectId; - idFromString(id: string): DurableObjectId; - get(id: DurableObjectId, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; - getByName(name: string, options?: DurableObjectNamespaceGetDurableObjectOptions): DurableObjectStub; - jurisdiction(jurisdiction: DurableObjectJurisdiction): DurableObjectNamespace; -} -type DurableObjectJurisdiction = "eu" | "fedramp" | "fedramp-high"; -interface DurableObjectNamespaceNewUniqueIdOptions { - jurisdiction?: DurableObjectJurisdiction; -} -type DurableObjectLocationHint = "wnam" | "enam" | "sam" | "weur" | "eeur" | "apac" | "oc" | "afr" | "me"; -type DurableObjectRoutingMode = "primary-only"; -interface DurableObjectNamespaceGetDurableObjectOptions { - locationHint?: DurableObjectLocationHint; - routingMode?: DurableObjectRoutingMode; -} -interface DurableObjectClass<_T extends Rpc.DurableObjectBranded | undefined = undefined> { -} -interface DurableObjectState { - waitUntil(promise: Promise): void; - readonly exports: Cloudflare.Exports; - readonly props: Props; - readonly id: DurableObjectId; - readonly storage: DurableObjectStorage; - container?: Container; - facets: DurableObjectFacets; - blockConcurrencyWhile(callback: () => Promise): Promise; - acceptWebSocket(ws: WebSocket, tags?: string[]): void; - getWebSockets(tag?: string): WebSocket[]; - setWebSocketAutoResponse(maybeReqResp?: WebSocketRequestResponsePair): void; - getWebSocketAutoResponse(): WebSocketRequestResponsePair | null; - getWebSocketAutoResponseTimestamp(ws: WebSocket): Date | null; - setHibernatableWebSocketEventTimeout(timeoutMs?: number): void; - getHibernatableWebSocketEventTimeout(): number | null; - getTags(ws: WebSocket): string[]; - abort(reason?: string): void; -} -interface DurableObjectTransaction { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - rollback(): void; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; -} -interface DurableObjectStorage { - get(key: string, options?: DurableObjectGetOptions): Promise; - get(keys: string[], options?: DurableObjectGetOptions): Promise>; - list(options?: DurableObjectListOptions): Promise>; - put(key: string, value: T, options?: DurableObjectPutOptions): Promise; - put(entries: Record, options?: DurableObjectPutOptions): Promise; - delete(key: string, options?: DurableObjectPutOptions): Promise; - delete(keys: string[], options?: DurableObjectPutOptions): Promise; - deleteAll(options?: DurableObjectPutOptions): Promise; - transaction(closure: (txn: DurableObjectTransaction) => Promise): Promise; - getAlarm(options?: DurableObjectGetAlarmOptions): Promise; - setAlarm(scheduledTime: number | Date, options?: DurableObjectSetAlarmOptions): Promise; - deleteAlarm(options?: DurableObjectSetAlarmOptions): Promise; - sync(): Promise; - sql: SqlStorage; - kv: SyncKvStorage; - transactionSync(closure: () => T): T; - getCurrentBookmark(): Promise; - getBookmarkForTime(timestamp: number | Date): Promise; - onNextSessionRestoreBookmark(bookmark: string): Promise; -} -interface DurableObjectListOptions { - start?: string; - startAfter?: string; - end?: string; - prefix?: string; - reverse?: boolean; - limit?: number; - allowConcurrency?: boolean; - noCache?: boolean; -} -interface DurableObjectGetOptions { - allowConcurrency?: boolean; - noCache?: boolean; -} -interface DurableObjectGetAlarmOptions { - allowConcurrency?: boolean; -} -interface DurableObjectPutOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; - noCache?: boolean; -} -interface DurableObjectSetAlarmOptions { - allowConcurrency?: boolean; - allowUnconfirmed?: boolean; -} -declare class WebSocketRequestResponsePair { - constructor(request: string, response: string); - get request(): string; - get response(): string; -} -interface DurableObjectFacets { - get(name: string, getStartupOptions: () => FacetStartupOptions | Promise>): Fetcher; - abort(name: string, reason: any): void; - delete(name: string): void; -} -interface FacetStartupOptions { - id?: DurableObjectId | string; - class: DurableObjectClass; -} -interface AnalyticsEngineDataset { - writeDataPoint(event?: AnalyticsEngineDataPoint): void; -} -interface AnalyticsEngineDataPoint { - indexes?: ((ArrayBuffer | string) | null)[]; - doubles?: number[]; - blobs?: ((ArrayBuffer | string) | null)[]; -} -/** - * The **`Event`** interface represents an event which takes place on an `EventTarget`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event) - */ -declare class Event { - constructor(type: string, init?: EventInit); - /** - * The **`type`** read-only property of the Event interface returns a string containing the event's type. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/type) - */ - get type(): string; - /** - * The **`eventPhase`** read-only property of the being evaluated. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/eventPhase) - */ - get eventPhase(): number; - /** - * The read-only **`composed`** property of the or not the event will propagate across the shadow DOM boundary into the standard DOM. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composed) - */ - get composed(): boolean; - /** - * The **`bubbles`** read-only property of the Event interface indicates whether the event bubbles up through the DOM tree or not. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/bubbles) - */ - get bubbles(): boolean; - /** - * The **`cancelable`** read-only property of the Event interface indicates whether the event can be canceled, and therefore prevented as if the event never happened. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelable) - */ - get cancelable(): boolean; - /** - * The **`defaultPrevented`** read-only property of the Event interface returns a boolean value indicating whether or not the call to Event.preventDefault() canceled the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/defaultPrevented) - */ - get defaultPrevented(): boolean; - /** - * The Event property **`returnValue`** indicates whether the default action for this event has been prevented or not. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/returnValue) - */ - get returnValue(): boolean; - /** - * The **`currentTarget`** read-only property of the Event interface identifies the element to which the event handler has been attached. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/currentTarget) - */ - get currentTarget(): EventTarget | undefined; - /** - * The read-only **`target`** property of the dispatched. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/target) - */ - get target(): EventTarget | undefined; - /** - * The deprecated **`Event.srcElement`** is an alias for the Event.target property. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/srcElement) - */ - get srcElement(): EventTarget | undefined; - /** - * The **`timeStamp`** read-only property of the Event interface returns the time (in milliseconds) at which the event was created. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/timeStamp) - */ - get timeStamp(): number; - /** - * The **`isTrusted`** read-only property of the when the event was generated by the user agent (including via user actions and programmatic methods such as HTMLElement.focus()), and `false` when the event was dispatched via The only exception is the `click` event, which initializes the `isTrusted` property to `false` in user agents. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/isTrusted) - */ - get isTrusted(): boolean; - /** - * The **`cancelBubble`** property of the Event interface is deprecated. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) - */ - get cancelBubble(): boolean; - /** - * The **`cancelBubble`** property of the Event interface is deprecated. - * @deprecated - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/cancelBubble) - */ - set cancelBubble(value: boolean); - /** - * The **`stopImmediatePropagation()`** method of the If several listeners are attached to the same element for the same event type, they are called in the order in which they were added. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopImmediatePropagation) - */ - stopImmediatePropagation(): void; - /** - * The **`preventDefault()`** method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/preventDefault) - */ - preventDefault(): void; - /** - * The **`stopPropagation()`** method of the Event interface prevents further propagation of the current event in the capturing and bubbling phases. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/stopPropagation) - */ - stopPropagation(): void; - /** - * The **`composedPath()`** method of the Event interface returns the event's path which is an array of the objects on which listeners will be invoked. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Event/composedPath) - */ - composedPath(): EventTarget[]; - static readonly NONE: number; - static readonly CAPTURING_PHASE: number; - static readonly AT_TARGET: number; - static readonly BUBBLING_PHASE: number; -} -interface EventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; -} -type EventListener = (event: EventType) => void; -interface EventListenerObject { - handleEvent(event: EventType): void; -} -type EventListenerOrEventListenerObject = EventListener | EventListenerObject; -/** - * The **`EventTarget`** interface is implemented by objects that can receive events and may have listeners for them. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget) - */ -declare class EventTarget = Record> { - constructor(); - /** - * The **`addEventListener()`** method of the EventTarget interface sets up a function that will be called whenever the specified event is delivered to the target. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/addEventListener) - */ - addEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetAddEventListenerOptions | boolean): void; - /** - * The **`removeEventListener()`** method of the EventTarget interface removes an event listener previously registered with EventTarget.addEventListener() from the target. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/removeEventListener) - */ - removeEventListener(type: Type, handler: EventListenerOrEventListenerObject, options?: EventTargetEventListenerOptions | boolean): void; - /** - * The **`dispatchEvent()`** method of the EventTarget sends an Event to the object, (synchronously) invoking the affected event listeners in the appropriate order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventTarget/dispatchEvent) - */ - dispatchEvent(event: EventMap[keyof EventMap]): boolean; -} -interface EventTargetEventListenerOptions { - capture?: boolean; -} -interface EventTargetAddEventListenerOptions { - capture?: boolean; - passive?: boolean; - once?: boolean; - signal?: AbortSignal; -} -interface EventTargetHandlerObject { - handleEvent: (event: Event) => any | undefined; -} -/** - * The **`AbortController`** interface represents a controller object that allows you to abort one or more Web requests as and when desired. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController) - */ -declare class AbortController { - constructor(); - /** - * The **`signal`** read-only property of the AbortController interface returns an AbortSignal object instance, which can be used to communicate with/abort an asynchronous operation as desired. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/signal) - */ - get signal(): AbortSignal; - /** - * The **`abort()`** method of the AbortController interface aborts an asynchronous operation before it has completed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortController/abort) - */ - abort(reason?: any): void; -} -/** - * The **`AbortSignal`** interface represents a signal object that allows you to communicate with an asynchronous operation (such as a fetch request) and abort it if required via an AbortController object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal) - */ -declare abstract class AbortSignal extends EventTarget { - /** - * The **`AbortSignal.abort()`** static method returns an AbortSignal that is already set as aborted (and which does not trigger an AbortSignal/abort_event event). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_static) - */ - static abort(reason?: any): AbortSignal; - /** - * The **`AbortSignal.timeout()`** static method returns an AbortSignal that will automatically abort after a specified time. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/timeout_static) - */ - static timeout(delay: number): AbortSignal; - /** - * The **`AbortSignal.any()`** static method takes an iterable of abort signals and returns an AbortSignal. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/any_static) - */ - static any(signals: AbortSignal[]): AbortSignal; - /** - * The **`aborted`** read-only property returns a value that indicates whether the asynchronous operations the signal is communicating with are aborted (`true`) or not (`false`). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/aborted) - */ - get aborted(): boolean; - /** - * The **`reason`** read-only property returns a JavaScript value that indicates the abort reason. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/reason) - */ - get reason(): any; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ - get onabort(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/abort_event) */ - set onabort(value: any | null); - /** - * The **`throwIfAborted()`** method throws the signal's abort AbortSignal.reason if the signal has been aborted; otherwise it does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/AbortSignal/throwIfAborted) - */ - throwIfAborted(): void; -} -interface Scheduler { - wait(delay: number, maybeOptions?: SchedulerWaitOptions): Promise; -} -interface SchedulerWaitOptions { - signal?: AbortSignal; -} -/** - * The **`ExtendableEvent`** interface extends the lifetime of the `install` and `activate` events dispatched on the global scope as part of the service worker lifecycle. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent) - */ -declare abstract class ExtendableEvent extends Event { - /** - * The **`ExtendableEvent.waitUntil()`** method tells the event dispatcher that work is ongoing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ExtendableEvent/waitUntil) - */ - waitUntil(promise: Promise): void; -} -/** - * The **`CustomEvent`** interface represents events initialized by an application for any purpose. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent) - */ -declare class CustomEvent extends Event { - constructor(type: string, init?: CustomEventCustomEventInit); - /** - * The read-only **`detail`** property of the CustomEvent interface returns any data passed when initializing the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CustomEvent/detail) - */ - get detail(): T; -} -interface CustomEventCustomEventInit { - bubbles?: boolean; - cancelable?: boolean; - composed?: boolean; - detail?: any; -} -/** - * The **`Blob`** interface represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob) - */ -declare class Blob { - constructor(bits?: ((ArrayBuffer | ArrayBufferView) | string | Blob)[], options?: BlobOptions); - /** - * The **`size`** read-only property of the Blob interface returns the size of the Blob or File in bytes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) - */ - get size(): number; - /** - * The **`type`** read-only property of the Blob interface returns the MIME type of the file. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) - */ - get type(): string; - /** - * The **`slice()`** method of the Blob interface creates and returns a new `Blob` object which contains data from a subset of the blob on which it's called. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) - */ - slice(start?: number, end?: number, type?: string): Blob; - /** - * The **`arrayBuffer()`** method of the Blob interface returns a Promise that resolves with the contents of the blob as binary data contained in an ArrayBuffer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/arrayBuffer) - */ - arrayBuffer(): Promise; - /** - * The **`bytes()`** method of the Blob interface returns a Promise that resolves with a Uint8Array containing the contents of the blob as an array of bytes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/bytes) - */ - bytes(): Promise; - /** - * The **`text()`** method of the string containing the contents of the blob, interpreted as UTF-8. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) - */ - text(): Promise; - /** - * The **`stream()`** method of the Blob interface returns a ReadableStream which upon reading returns the data contained within the `Blob`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/stream) - */ - stream(): ReadableStream; -} -interface BlobOptions { - type?: string; -} -/** - * The **`File`** interface provides information about files and allows JavaScript in a web page to access their content. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File) - */ -declare class File extends Blob { - constructor(bits: ((ArrayBuffer | ArrayBufferView) | string | Blob)[] | undefined, name: string, options?: FileOptions); - /** - * The **`name`** read-only property of the File interface returns the name of the file represented by a File object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) - */ - get name(): string; - /** - * The **`lastModified`** read-only property of the File interface provides the last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) - */ - get lastModified(): number; -} -interface FileOptions { - type?: string; - lastModified?: number; -} -/** -* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) -*/ -declare abstract class CacheStorage { - /** - * The **`open()`** method of the the Cache object matching the `cacheName`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CacheStorage/open) - */ - open(cacheName: string): Promise; - readonly default: Cache; -} -/** -* The Cache API allows fine grained control of reading and writing from the Cloudflare global network cache. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/) -*/ -declare abstract class Cache { - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#delete) */ - delete(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#match) */ - match(request: RequestInfo | URL, options?: CacheQueryOptions): Promise; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/cache/#put) */ - put(request: RequestInfo | URL, response: Response): Promise; -} -interface CacheQueryOptions { - ignoreMethod?: boolean; -} -/** -* The Web Crypto API provides a set of low-level functions for common cryptographic tasks. -* The Workers runtime implements the full surface of this API, but with some differences in -* the [supported algorithms](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/#supported-algorithms) -* compared to those implemented in most browsers. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/web-crypto/) -*/ -declare abstract class Crypto { - /** - * The **`Crypto.subtle`** read-only property returns a cryptographic operations. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/subtle) - */ - get subtle(): SubtleCrypto; - /** - * The **`Crypto.getRandomValues()`** method lets you get cryptographically strong random values. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) - */ - getRandomValues(buffer: T): T; - /** - * The **`randomUUID()`** method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID) - */ - randomUUID(): string; - DigestStream: typeof DigestStream; -} -/** - * The **`SubtleCrypto`** interface of the Web Crypto API provides a number of low-level cryptographic functions. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto) - */ -declare abstract class SubtleCrypto { - /** - * The **`encrypt()`** method of the SubtleCrypto interface encrypts data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/encrypt) - */ - encrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, plainText: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`decrypt()`** method of the SubtleCrypto interface decrypts some encrypted data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/decrypt) - */ - decrypt(algorithm: string | SubtleCryptoEncryptAlgorithm, key: CryptoKey, cipherText: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`sign()`** method of the SubtleCrypto interface generates a digital signature. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/sign) - */ - sign(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, data: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`verify()`** method of the SubtleCrypto interface verifies a digital signature. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/verify) - */ - verify(algorithm: string | SubtleCryptoSignAlgorithm, key: CryptoKey, signature: ArrayBuffer | ArrayBufferView, data: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`digest()`** method of the SubtleCrypto interface generates a _digest_ of the given data, using the specified hash function. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/digest) - */ - digest(algorithm: string | SubtleCryptoHashAlgorithm, data: ArrayBuffer | ArrayBufferView): Promise; - /** - * The **`generateKey()`** method of the SubtleCrypto interface is used to generate a new key (for symmetric algorithms) or key pair (for public-key algorithms). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/generateKey) - */ - generateKey(algorithm: string | SubtleCryptoGenerateKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /** - * The **`deriveKey()`** method of the SubtleCrypto interface can be used to derive a secret key from a master key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveKey) - */ - deriveKey(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, derivedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /** - * The **`deriveBits()`** method of the key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/deriveBits) - */ - deriveBits(algorithm: string | SubtleCryptoDeriveKeyAlgorithm, baseKey: CryptoKey, length?: number | null): Promise; - /** - * The **`importKey()`** method of the SubtleCrypto interface imports a key: that is, it takes as input a key in an external, portable format and gives you a CryptoKey object that you can use in the Web Crypto API. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/importKey) - */ - importKey(format: string, keyData: (ArrayBuffer | ArrayBufferView) | JsonWebKey, algorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - /** - * The **`exportKey()`** method of the SubtleCrypto interface exports a key: that is, it takes as input a CryptoKey object and gives you the key in an external, portable format. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/exportKey) - */ - exportKey(format: string, key: CryptoKey): Promise; - /** - * The **`wrapKey()`** method of the SubtleCrypto interface 'wraps' a key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/wrapKey) - */ - wrapKey(format: string, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: string | SubtleCryptoEncryptAlgorithm): Promise; - /** - * The **`unwrapKey()`** method of the SubtleCrypto interface 'unwraps' a key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/SubtleCrypto/unwrapKey) - */ - unwrapKey(format: string, wrappedKey: ArrayBuffer | ArrayBufferView, unwrappingKey: CryptoKey, unwrapAlgorithm: string | SubtleCryptoEncryptAlgorithm, unwrappedKeyAlgorithm: string | SubtleCryptoImportKeyAlgorithm, extractable: boolean, keyUsages: string[]): Promise; - timingSafeEqual(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean; -} -/** - * The **`CryptoKey`** interface of the Web Crypto API represents a cryptographic key obtained from one of the SubtleCrypto methods SubtleCrypto.generateKey, SubtleCrypto.deriveKey, SubtleCrypto.importKey, or SubtleCrypto.unwrapKey. - * Available only in secure contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey) - */ -declare abstract class CryptoKey { - /** - * The read-only **`type`** property of the CryptoKey interface indicates which kind of key is represented by the object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/type) - */ - readonly type: string; - /** - * The read-only **`extractable`** property of the CryptoKey interface indicates whether or not the key may be extracted using `SubtleCrypto.exportKey()` or `SubtleCrypto.wrapKey()`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/extractable) - */ - readonly extractable: boolean; - /** - * The read-only **`algorithm`** property of the CryptoKey interface returns an object describing the algorithm for which this key can be used, and any associated extra parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/algorithm) - */ - readonly algorithm: CryptoKeyKeyAlgorithm | CryptoKeyAesKeyAlgorithm | CryptoKeyHmacKeyAlgorithm | CryptoKeyRsaKeyAlgorithm | CryptoKeyEllipticKeyAlgorithm | CryptoKeyArbitraryKeyAlgorithm; - /** - * The read-only **`usages`** property of the CryptoKey interface indicates what can be done with the key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CryptoKey/usages) - */ - readonly usages: string[]; -} -interface CryptoKeyPair { - publicKey: CryptoKey; - privateKey: CryptoKey; -} -interface JsonWebKey { - kty: string; - use?: string; - key_ops?: string[]; - alg?: string; - ext?: boolean; - crv?: string; - x?: string; - y?: string; - d?: string; - n?: string; - e?: string; - p?: string; - q?: string; - dp?: string; - dq?: string; - qi?: string; - oth?: RsaOtherPrimesInfo[]; - k?: string; -} -interface RsaOtherPrimesInfo { - r?: string; - d?: string; - t?: string; -} -interface SubtleCryptoDeriveKeyAlgorithm { - name: string; - salt?: (ArrayBuffer | ArrayBufferView); - iterations?: number; - hash?: (string | SubtleCryptoHashAlgorithm); - $public?: CryptoKey; - info?: (ArrayBuffer | ArrayBufferView); -} -interface SubtleCryptoEncryptAlgorithm { - name: string; - iv?: (ArrayBuffer | ArrayBufferView); - additionalData?: (ArrayBuffer | ArrayBufferView); - tagLength?: number; - counter?: (ArrayBuffer | ArrayBufferView); - length?: number; - label?: (ArrayBuffer | ArrayBufferView); -} -interface SubtleCryptoGenerateKeyAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - modulusLength?: number; - publicExponent?: (ArrayBuffer | ArrayBufferView); - length?: number; - namedCurve?: string; -} -interface SubtleCryptoHashAlgorithm { - name: string; -} -interface SubtleCryptoImportKeyAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - length?: number; - namedCurve?: string; - compressed?: boolean; -} -interface SubtleCryptoSignAlgorithm { - name: string; - hash?: (string | SubtleCryptoHashAlgorithm); - dataLength?: number; - saltLength?: number; -} -interface CryptoKeyKeyAlgorithm { - name: string; -} -interface CryptoKeyAesKeyAlgorithm { - name: string; - length: number; -} -interface CryptoKeyHmacKeyAlgorithm { - name: string; - hash: CryptoKeyKeyAlgorithm; - length: number; -} -interface CryptoKeyRsaKeyAlgorithm { - name: string; - modulusLength: number; - publicExponent: ArrayBuffer | ArrayBufferView; - hash?: CryptoKeyKeyAlgorithm; -} -interface CryptoKeyEllipticKeyAlgorithm { - name: string; - namedCurve: string; -} -interface CryptoKeyArbitraryKeyAlgorithm { - name: string; - hash?: CryptoKeyKeyAlgorithm; - namedCurve?: string; - length?: number; -} -declare class DigestStream extends WritableStream { - constructor(algorithm: string | SubtleCryptoHashAlgorithm); - readonly digest: Promise; - get bytesWritten(): number | bigint; -} -/** - * The **`TextDecoder`** interface represents a decoder for a specific text encoding, such as `UTF-8`, `ISO-8859-2`, `KOI8-R`, `GBK`, etc. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder) - */ -declare class TextDecoder { - constructor(label?: string, options?: TextDecoderConstructorOptions); - /** - * The **`TextDecoder.decode()`** method returns a string containing text decoded from the buffer passed as a parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoder/decode) - */ - decode(input?: (ArrayBuffer | ArrayBufferView), options?: TextDecoderDecodeOptions): string; - get encoding(): string; - get fatal(): boolean; - get ignoreBOM(): boolean; -} -/** - * The **`TextEncoder`** interface takes a stream of code points as input and emits a stream of UTF-8 bytes. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder) - */ -declare class TextEncoder { - constructor(); - /** - * The **`TextEncoder.encode()`** method takes a string as input, and returns a Global_Objects/Uint8Array containing the text given in parameters encoded with the specific method for that TextEncoder object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encode) - */ - encode(input?: string): Uint8Array; - /** - * The **`TextEncoder.encodeInto()`** method takes a string to encode and a destination Uint8Array to put resulting UTF-8 encoded text into, and returns a dictionary object indicating the progress of the encoding. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoder/encodeInto) - */ - encodeInto(input: string, buffer: Uint8Array): TextEncoderEncodeIntoResult; - get encoding(): string; -} -interface TextDecoderConstructorOptions { - fatal: boolean; - ignoreBOM: boolean; -} -interface TextDecoderDecodeOptions { - stream: boolean; -} -interface TextEncoderEncodeIntoResult { - read: number; - written: number; -} -/** - * The **`ErrorEvent`** interface represents events providing information related to errors in scripts or in files. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent) - */ -declare class ErrorEvent extends Event { - constructor(type: string, init?: ErrorEventErrorEventInit); - /** - * The **`filename`** read-only property of the ErrorEvent interface returns a string containing the name of the script file in which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/filename) - */ - get filename(): string; - /** - * The **`message`** read-only property of the ErrorEvent interface returns a string containing a human-readable error message describing the problem. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/message) - */ - get message(): string; - /** - * The **`lineno`** read-only property of the ErrorEvent interface returns an integer containing the line number of the script file on which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/lineno) - */ - get lineno(): number; - /** - * The **`colno`** read-only property of the ErrorEvent interface returns an integer containing the column number of the script file on which the error occurred. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/colno) - */ - get colno(): number; - /** - * The **`error`** read-only property of the ErrorEvent interface returns a JavaScript value, such as an Error or DOMException, representing the error associated with this event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ErrorEvent/error) - */ - get error(): any; -} -interface ErrorEventErrorEventInit { - message?: string; - filename?: string; - lineno?: number; - colno?: number; - error?: any; -} -/** - * The **`MessageEvent`** interface represents a message received by a target object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent) - */ -declare class MessageEvent extends Event { - constructor(type: string, initializer: MessageEventInit); - /** - * The **`data`** read-only property of the The data sent by the message emitter; this can be any data type, depending on what originated this event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/data) - */ - readonly data: any; - /** - * The **`origin`** read-only property of the origin of the message emitter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/origin) - */ - readonly origin: string | null; - /** - * The **`lastEventId`** read-only property of the unique ID for the event. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/lastEventId) - */ - readonly lastEventId: string; - /** - * The **`source`** read-only property of the a WindowProxy, MessagePort, or a `MessageEventSource` (which can be a WindowProxy, message emitter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/source) - */ - readonly source: MessagePort | null; - /** - * The **`ports`** read-only property of the containing all MessagePort objects sent with the message, in order. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageEvent/ports) - */ - readonly ports: MessagePort[]; -} -interface MessageEventInit { - data: ArrayBuffer | string; -} -/** - * The **`PromiseRejectionEvent`** interface represents events which are sent to the global script context when JavaScript Promises are rejected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent) - */ -declare abstract class PromiseRejectionEvent extends Event { - /** - * The PromiseRejectionEvent interface's **`promise`** read-only property indicates the JavaScript rejected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/promise) - */ - readonly promise: Promise; - /** - * The PromiseRejectionEvent **`reason`** read-only property is any JavaScript value or Object which provides the reason passed into Promise.reject(). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/PromiseRejectionEvent/reason) - */ - readonly reason: any; -} -/** - * The **`FormData`** interface provides a way to construct a set of key/value pairs representing form fields and their values, which can be sent using the Window/fetch, XMLHttpRequest.send() or navigator.sendBeacon() methods. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData) - */ -declare class FormData { - constructor(); - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: string | Blob): void; - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: string): void; - /** - * The **`append()`** method of the FormData interface appends a new value onto an existing key inside a `FormData` object, or adds the key if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/append) - */ - append(name: string, value: Blob, filename?: string): void; - /** - * The **`delete()`** method of the FormData interface deletes a key and its value(s) from a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/delete) - */ - delete(name: string): void; - /** - * The **`get()`** method of the FormData interface returns the first value associated with a given key from within a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/get) - */ - get(name: string): (File | string) | null; - /** - * The **`getAll()`** method of the FormData interface returns all the values associated with a given key from within a `FormData` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/getAll) - */ - getAll(name: string): (File | string)[]; - /** - * The **`has()`** method of the FormData interface returns whether a `FormData` object contains a certain key. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/has) - */ - has(name: string): boolean; - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: string | Blob): void; - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: string): void; - /** - * The **`set()`** method of the FormData interface sets a new value for an existing key inside a `FormData` object, or adds the key/value if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FormData/set) - */ - set(name: string, value: Blob, filename?: string): void; - /* Returns an array of key, value pairs for every entry in the list. */ - entries(): IterableIterator<[ - key: string, - value: File | string - ]>; - /* Returns a list of keys in the list. */ - keys(): IterableIterator; - /* Returns a list of values in the list. */ - values(): IterableIterator<(File | string)>; - forEach(callback: (this: This, value: File | string, key: string, parent: FormData) => void, thisArg?: This): void; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: File | string - ]>; -} -interface ContentOptions { - html?: boolean; -} -declare class HTMLRewriter { - constructor(); - on(selector: string, handlers: HTMLRewriterElementContentHandlers): HTMLRewriter; - onDocument(handlers: HTMLRewriterDocumentContentHandlers): HTMLRewriter; - transform(response: Response): Response; -} -interface HTMLRewriterElementContentHandlers { - element?(element: Element): void | Promise; - comments?(comment: Comment): void | Promise; - text?(element: Text): void | Promise; -} -interface HTMLRewriterDocumentContentHandlers { - doctype?(doctype: Doctype): void | Promise; - comments?(comment: Comment): void | Promise; - text?(text: Text): void | Promise; - end?(end: DocumentEnd): void | Promise; -} -interface Doctype { - readonly name: string | null; - readonly publicId: string | null; - readonly systemId: string | null; -} -interface Element { - tagName: string; - readonly attributes: IterableIterator; - readonly removed: boolean; - readonly namespaceURI: string; - getAttribute(name: string): string | null; - hasAttribute(name: string): boolean; - setAttribute(name: string, value: string): Element; - removeAttribute(name: string): Element; - before(content: string | ReadableStream | Response, options?: ContentOptions): Element; - after(content: string | ReadableStream | Response, options?: ContentOptions): Element; - prepend(content: string | ReadableStream | Response, options?: ContentOptions): Element; - append(content: string | ReadableStream | Response, options?: ContentOptions): Element; - replace(content: string | ReadableStream | Response, options?: ContentOptions): Element; - remove(): Element; - removeAndKeepContent(): Element; - setInnerContent(content: string | ReadableStream | Response, options?: ContentOptions): Element; - onEndTag(handler: (tag: EndTag) => void | Promise): void; -} -interface EndTag { - name: string; - before(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; - after(content: string | ReadableStream | Response, options?: ContentOptions): EndTag; - remove(): EndTag; -} -interface Comment { - text: string; - readonly removed: boolean; - before(content: string, options?: ContentOptions): Comment; - after(content: string, options?: ContentOptions): Comment; - replace(content: string, options?: ContentOptions): Comment; - remove(): Comment; -} -interface Text { - readonly text: string; - readonly lastInTextNode: boolean; - readonly removed: boolean; - before(content: string | ReadableStream | Response, options?: ContentOptions): Text; - after(content: string | ReadableStream | Response, options?: ContentOptions): Text; - replace(content: string | ReadableStream | Response, options?: ContentOptions): Text; - remove(): Text; -} -interface DocumentEnd { - append(content: string, options?: ContentOptions): DocumentEnd; -} -/** - * This is the event type for `fetch` events dispatched on the ServiceWorkerGlobalScope. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent) - */ -declare abstract class FetchEvent extends ExtendableEvent { - /** - * The **`request`** read-only property of the the event handler. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/request) - */ - readonly request: Request; - /** - * The **`respondWith()`** method of allows you to provide a promise for a Response yourself. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/FetchEvent/respondWith) - */ - respondWith(promise: Response | Promise): void; - passThroughOnException(): void; -} -type HeadersInit = Headers | Iterable> | Record; -/** - * The **`Headers`** interface of the Fetch API allows you to perform various actions on HTTP request and response headers. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers) - */ -declare class Headers { - constructor(init?: HeadersInit); - /** - * The **`get()`** method of the Headers interface returns a byte string of all the values of a header within a `Headers` object with a given name. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) - */ - get(name: string): string | null; - getAll(name: string): string[]; - /** - * The **`getSetCookie()`** method of the Headers interface returns an array containing the values of all Set-Cookie headers associated with a response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) - */ - getSetCookie(): string[]; - /** - * The **`has()`** method of the Headers interface returns a boolean stating whether a `Headers` object contains a certain header. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) - */ - has(name: string): boolean; - /** - * The **`set()`** method of the Headers interface sets a new value for an existing header inside a `Headers` object, or adds the header if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) - */ - set(name: string, value: string): void; - /** - * The **`append()`** method of the Headers interface appends a new value onto an existing header inside a `Headers` object, or adds the header if it does not already exist. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) - */ - append(name: string, value: string): void; - /** - * The **`delete()`** method of the Headers interface deletes a header from the current `Headers` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) - */ - delete(name: string): void; - forEach(callback: (this: This, value: string, key: string, parent: Headers) => void, thisArg?: This): void; - /* Returns an iterator allowing to go through all key/value pairs contained in this object. */ - entries(): IterableIterator<[ - key: string, - value: string - ]>; - /* Returns an iterator allowing to go through all keys of the key/value pairs contained in this object. */ - keys(): IterableIterator; - /* Returns an iterator allowing to go through all values of the key/value pairs contained in this object. */ - values(): IterableIterator; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: string - ]>; -} -type BodyInit = ReadableStream | string | ArrayBuffer | ArrayBufferView | Blob | URLSearchParams | FormData | Iterable | AsyncIterable; -declare abstract class Body { - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) */ - get body(): ReadableStream | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ - get bodyUsed(): boolean; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ - arrayBuffer(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) */ - bytes(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/text) */ - text(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */ - json(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/formData) */ - formData(): Promise; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ - blob(): Promise; -} -/** - * The **`Response`** interface of the Fetch API represents the response to a request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) - */ -declare var Response: { - prototype: Response; - new (body?: BodyInit | null, init?: ResponseInit): Response; - error(): Response; - redirect(url: string, status?: number): Response; - json(any: any, maybeInit?: (ResponseInit | Response)): Response; -}; -/** - * The **`Response`** interface of the Fetch API represents the response to a request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response) - */ -interface Response extends Body { - /** - * The **`clone()`** method of the Response interface creates a clone of a response object, identical in every way, but stored in a different variable. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/clone) - */ - clone(): Response; - /** - * The **`status`** read-only property of the Response interface contains the HTTP status codes of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/status) - */ - status: number; - /** - * The **`statusText`** read-only property of the Response interface contains the status message corresponding to the HTTP status code in Response.status. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/statusText) - */ - statusText: string; - /** - * The **`headers`** read-only property of the with the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/headers) - */ - headers: Headers; - /** - * The **`ok`** read-only property of the Response interface contains a Boolean stating whether the response was successful (status in the range 200-299) or not. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/ok) - */ - ok: boolean; - /** - * The **`redirected`** read-only property of the Response interface indicates whether or not the response is the result of a request you made which was redirected. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/redirected) - */ - redirected: boolean; - /** - * The **`url`** read-only property of the Response interface contains the URL of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/url) - */ - url: string; - webSocket: WebSocket | null; - cf: any | undefined; - /** - * The **`type`** read-only property of the Response interface contains the type of the response. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Response/type) - */ - type: "default" | "error"; -} -interface ResponseInit { - status?: number; - statusText?: string; - headers?: HeadersInit; - cf?: any; - webSocket?: (WebSocket | null); - encodeBody?: "automatic" | "manual"; -} -type RequestInfo> = Request | string; -/** - * The **`Request`** interface of the Fetch API represents a resource request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) - */ -declare var Request: { - prototype: Request; - new >(input: RequestInfo | URL, init?: RequestInit): Request; -}; -/** - * The **`Request`** interface of the Fetch API represents a resource request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request) - */ -interface Request> extends Body { - /** - * The **`clone()`** method of the Request interface creates a copy of the current `Request` object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/clone) - */ - clone(): Request; - /** - * The **`method`** read-only property of the `POST`, etc.) A String indicating the method of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/method) - */ - method: string; - /** - * The **`url`** read-only property of the Request interface contains the URL of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/url) - */ - url: string; - /** - * The **`headers`** read-only property of the with the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/headers) - */ - headers: Headers; - /** - * The **`redirect`** read-only property of the Request interface contains the mode for how redirects are handled. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/redirect) - */ - redirect: string; - fetcher: Fetcher | null; - /** - * The read-only **`signal`** property of the Request interface returns the AbortSignal associated with the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/signal) - */ - signal: AbortSignal; - cf?: Cf; - /** - * The **`integrity`** read-only property of the Request interface contains the subresource integrity value of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/integrity) - */ - integrity: string; - /** - * The **`keepalive`** read-only property of the Request interface contains the request's `keepalive` setting (`true` or `false`), which indicates whether the browser will keep the associated request alive if the page that initiated it is unloaded before the request is complete. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/keepalive) - */ - keepalive: boolean; - /** - * The **`cache`** read-only property of the Request interface contains the cache mode of the request. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/cache) - */ - cache?: "no-store" | "no-cache"; -} -interface RequestInit { - /* A string to set request's method. */ - method?: string; - /* A Headers object, an object literal, or an array of two-item arrays to set request's headers. */ - headers?: HeadersInit; - /* A BodyInit object or null to set request's body. */ - body?: BodyInit | null; - /* A string indicating whether request follows redirects, results in an error upon encountering a redirect, or returns the redirect (in an opaque fashion). Sets request's redirect. */ - redirect?: string; - fetcher?: (Fetcher | null); - cf?: Cf; - /* A string indicating how the request will interact with the browser's cache to set request's cache. */ - cache?: "no-store" | "no-cache"; - /* A cryptographic hash of the resource to be fetched by request. Sets request's integrity. */ - integrity?: string; - /* An AbortSignal to set request's signal. */ - signal?: (AbortSignal | null); - encodeResponseBody?: "automatic" | "manual"; -} -type Service Rpc.WorkerEntrypointBranded) | Rpc.WorkerEntrypointBranded | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? Fetcher> : T extends Rpc.WorkerEntrypointBranded ? Fetcher : T extends Exclude ? never : Fetcher; -type Fetcher = (T extends Rpc.EntrypointBranded ? Rpc.Provider : unknown) & { - fetch(input: RequestInfo | URL, init?: RequestInit): Promise; - connect(address: SocketAddress | string, options?: SocketOptions): Socket; -}; -interface KVNamespaceListKey { - name: Key; - expiration?: number; - metadata?: Metadata; -} -type KVNamespaceListResult = { - list_complete: false; - keys: KVNamespaceListKey[]; - cursor: string; - cacheStatus: string | null; -} | { - list_complete: true; - keys: KVNamespaceListKey[]; - cacheStatus: string | null; -}; -interface KVNamespace { - get(key: Key, options?: Partial>): Promise; - get(key: Key, type: "text"): Promise; - get(key: Key, type: "json"): Promise; - get(key: Key, type: "arrayBuffer"): Promise; - get(key: Key, type: "stream"): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"text">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"json">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"arrayBuffer">): Promise; - get(key: Key, options?: KVNamespaceGetOptions<"stream">): Promise; - get(key: Array, type: "text"): Promise>; - get(key: Array, type: "json"): Promise>; - get(key: Array, options?: Partial>): Promise>; - get(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>; - get(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>; - list(options?: KVNamespaceListOptions): Promise>; - put(key: Key, value: string | ArrayBuffer | ArrayBufferView | ReadableStream, options?: KVNamespacePutOptions): Promise; - getWithMetadata(key: Key, options?: Partial>): Promise>; - getWithMetadata(key: Key, type: "text"): Promise>; - getWithMetadata(key: Key, type: "json"): Promise>; - getWithMetadata(key: Key, type: "arrayBuffer"): Promise>; - getWithMetadata(key: Key, type: "stream"): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"text">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"json">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"arrayBuffer">): Promise>; - getWithMetadata(key: Key, options: KVNamespaceGetOptions<"stream">): Promise>; - getWithMetadata(key: Array, type: "text"): Promise>>; - getWithMetadata(key: Array, type: "json"): Promise>>; - getWithMetadata(key: Array, options?: Partial>): Promise>>; - getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"text">): Promise>>; - getWithMetadata(key: Array, options?: KVNamespaceGetOptions<"json">): Promise>>; - delete(key: Key): Promise; -} -interface KVNamespaceListOptions { - limit?: number; - prefix?: (string | null); - cursor?: (string | null); -} -interface KVNamespaceGetOptions { - type: Type; - cacheTtl?: number; -} -interface KVNamespacePutOptions { - expiration?: number; - expirationTtl?: number; - metadata?: (any | null); -} -interface KVNamespaceGetWithMetadataResult { - value: Value | null; - metadata: Metadata | null; - cacheStatus: string | null; -} -type QueueContentType = "text" | "bytes" | "json" | "v8"; -interface Queue { - metrics(): Promise; - send(message: Body, options?: QueueSendOptions): Promise; - sendBatch(messages: Iterable>, options?: QueueSendBatchOptions): Promise; -} -interface QueueSendMetrics { - backlogCount: number; - backlogBytes: number; - oldestMessageTimestamp?: Date; -} -interface QueueSendMetadata { - metrics: QueueSendMetrics; -} -interface QueueSendResponse { - metadata: QueueSendMetadata; -} -interface QueueSendBatchMetrics { - backlogCount: number; - backlogBytes: number; - oldestMessageTimestamp?: Date; -} -interface QueueSendBatchMetadata { - metrics: QueueSendBatchMetrics; -} -interface QueueSendBatchResponse { - metadata: QueueSendBatchMetadata; -} -interface QueueSendOptions { - contentType?: QueueContentType; - delaySeconds?: number; -} -interface QueueSendBatchOptions { - delaySeconds?: number; -} -interface MessageSendRequest { - body: Body; - contentType?: QueueContentType; - delaySeconds?: number; -} -interface QueueMetrics { - backlogCount: number; - backlogBytes: number; - oldestMessageTimestamp?: Date; -} -interface MessageBatchMetrics { - backlogCount: number; - backlogBytes: number; - oldestMessageTimestamp?: Date; -} -interface MessageBatchMetadata { - metrics: MessageBatchMetrics; -} -interface QueueRetryOptions { - delaySeconds?: number; -} -interface Message { - readonly id: string; - readonly timestamp: Date; - readonly body: Body; - readonly attempts: number; - retry(options?: QueueRetryOptions): void; - ack(): void; -} -interface QueueEvent extends ExtendableEvent { - readonly messages: readonly Message[]; - readonly queue: string; - readonly metadata: MessageBatchMetadata; - retryAll(options?: QueueRetryOptions): void; - ackAll(): void; -} -interface MessageBatch { - readonly messages: readonly Message[]; - readonly queue: string; - readonly metadata: MessageBatchMetadata; - retryAll(options?: QueueRetryOptions): void; - ackAll(): void; -} -interface R2Error extends Error { - readonly name: string; - readonly code: number; - readonly message: string; - readonly action: string; - readonly stack: any; -} -interface R2ListOptions { - limit?: number; - prefix?: string; - cursor?: string; - delimiter?: string; - startAfter?: string; - include?: ("httpMetadata" | "customMetadata")[]; -} -interface R2Bucket { - head(key: string): Promise; - get(key: string, options: R2GetOptions & { - onlyIf: R2Conditional | Headers; - }): Promise; - get(key: string, options?: R2GetOptions): Promise; - put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions & { - onlyIf: R2Conditional | Headers; - }): Promise; - put(key: string, value: ReadableStream | ArrayBuffer | ArrayBufferView | string | null | Blob, options?: R2PutOptions): Promise; - createMultipartUpload(key: string, options?: R2MultipartOptions): Promise; - resumeMultipartUpload(key: string, uploadId: string): R2MultipartUpload; - delete(keys: string | string[]): Promise; - list(options?: R2ListOptions): Promise; -} -interface R2MultipartUpload { - readonly key: string; - readonly uploadId: string; - uploadPart(partNumber: number, value: ReadableStream | (ArrayBuffer | ArrayBufferView) | string | Blob, options?: R2UploadPartOptions): Promise; - abort(): Promise; - complete(uploadedParts: R2UploadedPart[]): Promise; -} -interface R2UploadedPart { - partNumber: number; - etag: string; -} -declare abstract class R2Object { - readonly key: string; - readonly version: string; - readonly size: number; - readonly etag: string; - readonly httpEtag: string; - readonly checksums: R2Checksums; - readonly uploaded: Date; - readonly httpMetadata?: R2HTTPMetadata; - readonly customMetadata?: Record; - readonly range?: R2Range; - readonly storageClass: string; - readonly ssecKeyMd5?: string; - writeHttpMetadata(headers: Headers): void; -} -interface R2ObjectBody extends R2Object { - get body(): ReadableStream; - get bodyUsed(): boolean; - arrayBuffer(): Promise; - bytes(): Promise; - text(): Promise; - json(): Promise; - blob(): Promise; -} -type R2Range = { - offset: number; - length?: number; -} | { - offset?: number; - length: number; -} | { - suffix: number; -}; -interface R2Conditional { - etagMatches?: string; - etagDoesNotMatch?: string; - uploadedBefore?: Date; - uploadedAfter?: Date; - secondsGranularity?: boolean; -} -interface R2GetOptions { - onlyIf?: (R2Conditional | Headers); - range?: (R2Range | Headers); - ssecKey?: (ArrayBuffer | string); -} -interface R2PutOptions { - onlyIf?: (R2Conditional | Headers); - httpMetadata?: (R2HTTPMetadata | Headers); - customMetadata?: Record; - md5?: ((ArrayBuffer | ArrayBufferView) | string); - sha1?: ((ArrayBuffer | ArrayBufferView) | string); - sha256?: ((ArrayBuffer | ArrayBufferView) | string); - sha384?: ((ArrayBuffer | ArrayBufferView) | string); - sha512?: ((ArrayBuffer | ArrayBufferView) | string); - storageClass?: string; - ssecKey?: (ArrayBuffer | string); -} -interface R2MultipartOptions { - httpMetadata?: (R2HTTPMetadata | Headers); - customMetadata?: Record; - storageClass?: string; - ssecKey?: (ArrayBuffer | string); -} -interface R2Checksums { - readonly md5?: ArrayBuffer; - readonly sha1?: ArrayBuffer; - readonly sha256?: ArrayBuffer; - readonly sha384?: ArrayBuffer; - readonly sha512?: ArrayBuffer; - toJSON(): R2StringChecksums; -} -interface R2StringChecksums { - md5?: string; - sha1?: string; - sha256?: string; - sha384?: string; - sha512?: string; -} -interface R2HTTPMetadata { - contentType?: string; - contentLanguage?: string; - contentDisposition?: string; - contentEncoding?: string; - cacheControl?: string; - cacheExpiry?: Date; -} -type R2Objects = { - objects: R2Object[]; - delimitedPrefixes: string[]; -} & ({ - truncated: true; - cursor: string; -} | { - truncated: false; -}); -interface R2UploadPartOptions { - ssecKey?: (ArrayBuffer | string); -} -declare abstract class ScheduledEvent extends ExtendableEvent { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; -} -interface ScheduledController { - readonly scheduledTime: number; - readonly cron: string; - noRetry(): void; -} -interface QueuingStrategy { - highWaterMark?: (number | bigint); - size?: (chunk: T) => number | bigint; -} -interface UnderlyingSink { - type?: string; - start?: (controller: WritableStreamDefaultController) => void | Promise; - write?: (chunk: W, controller: WritableStreamDefaultController) => void | Promise; - abort?: (reason: any) => void | Promise; - close?: () => void | Promise; -} -interface UnderlyingByteSource { - type: "bytes"; - autoAllocateChunkSize?: number; - start?: (controller: ReadableByteStreamController) => void | Promise; - pull?: (controller: ReadableByteStreamController) => void | Promise; - cancel?: (reason: any) => void | Promise; -} -interface UnderlyingSource { - type?: "" | undefined; - start?: (controller: ReadableStreamDefaultController) => void | Promise; - pull?: (controller: ReadableStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - expectedLength?: (number | bigint); -} -interface Transformer { - readableType?: string; - writableType?: string; - start?: (controller: TransformStreamDefaultController) => void | Promise; - transform?: (chunk: I, controller: TransformStreamDefaultController) => void | Promise; - flush?: (controller: TransformStreamDefaultController) => void | Promise; - cancel?: (reason: any) => void | Promise; - expectedLength?: number; -} -interface StreamPipeOptions { - preventAbort?: boolean; - preventCancel?: boolean; - /** - * Pipes this readable stream to a given writable stream destination. The way in which the piping process behaves under various error conditions can be customized with a number of passed options. It returns a promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * - * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - * - * Errors and closures of the source and destination streams propagate as follows: - * - * An error in this source readable stream will abort destination, unless preventAbort is truthy. The returned promise will be rejected with the source's error, or with any error that occurs during aborting the destination. - * - * An error in destination will cancel this source readable stream, unless preventCancel is truthy. The returned promise will be rejected with the destination's error, or with any error that occurs during canceling the source. - * - * When this source readable stream closes, destination will be closed, unless preventClose is truthy. The returned promise will be fulfilled once this process completes, unless an error is encountered while closing the destination, in which case it will be rejected with that error. - * - * If destination starts out closed or closing, this source readable stream will be canceled, unless preventCancel is true. The returned promise will be rejected with an error indicating piping to a closed stream failed, or with any error that occurs during canceling the source. - * - * The signal option can be set to an AbortSignal to allow aborting an ongoing pipe operation via the corresponding AbortController. In this case, this source readable stream will be canceled, and destination aborted, unless the respective options preventCancel or preventAbort are set. - */ - preventClose?: boolean; - signal?: AbortSignal; -} -type ReadableStreamReadResult = { - done: false; - value: R; -} | { - done: true; - value?: undefined; -}; -/** - * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) - */ -interface ReadableStream { - /** - * The **`locked`** read-only property of the ReadableStream interface returns whether or not the readable stream is locked to a reader. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/locked) - */ - get locked(): boolean; - /** - * The **`cancel()`** method of the ReadableStream interface returns a Promise that resolves when the stream is canceled. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/cancel) - */ - cancel(reason?: any): Promise; - /** - * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) - */ - getReader(): ReadableStreamDefaultReader; - /** - * The **`getReader()`** method of the ReadableStream interface creates a reader and locks the stream to it. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/getReader) - */ - getReader(options: ReadableStreamGetReaderOptions): ReadableStreamBYOBReader; - /** - * The **`pipeThrough()`** method of the ReadableStream interface provides a chainable way of piping the current stream through a transform stream or any other writable/readable pair. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeThrough) - */ - pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; - /** - * The **`pipeTo()`** method of the ReadableStream interface pipes the current `ReadableStream` to a given WritableStream and returns a Promise that fulfills when the piping process completes successfully, or rejects if any errors were encountered. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/pipeTo) - */ - pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; - /** - * The **`tee()`** method of the two-element array containing the two resulting branches as new ReadableStream instances. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream/tee) - */ - tee(): [ - ReadableStream, - ReadableStream - ]; - values(options?: ReadableStreamValuesOptions): AsyncIterableIterator; - [Symbol.asyncIterator](options?: ReadableStreamValuesOptions): AsyncIterableIterator; -} -/** - * The `ReadableStream` interface of the Streams API represents a readable stream of byte data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStream) - */ -declare const ReadableStream: { - prototype: ReadableStream; - new (underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; - new (underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; -}; -/** - * The **`ReadableStreamDefaultReader`** interface of the Streams API represents a default reader that can be used to read stream data supplied from a network (such as a fetch request). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader) - */ -declare class ReadableStreamDefaultReader { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * The **`read()`** method of the ReadableStreamDefaultReader interface returns a Promise providing access to the next chunk in the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/read) - */ - read(): Promise>; - /** - * The **`releaseLock()`** method of the ReadableStreamDefaultReader interface releases the reader's lock on the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultReader/releaseLock) - */ - releaseLock(): void; -} -/** - * The `ReadableStreamBYOBReader` interface of the Streams API defines a reader for a ReadableStream that supports zero-copy reading from an underlying byte source. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader) - */ -declare class ReadableStreamBYOBReader { - constructor(stream: ReadableStream); - get closed(): Promise; - cancel(reason?: any): Promise; - /** - * The **`read()`** method of the ReadableStreamBYOBReader interface is used to read data into a view on a user-supplied buffer from an associated readable byte stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/read) - */ - read(view: T): Promise>; - /** - * The **`releaseLock()`** method of the ReadableStreamBYOBReader interface releases the reader's lock on the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBReader/releaseLock) - */ - releaseLock(): void; - readAtLeast(minElements: number, view: T): Promise>; -} -interface ReadableStreamBYOBReaderReadableStreamBYOBReaderReadOptions { - min?: number; -} -interface ReadableStreamGetReaderOptions { - /** - * Creates a ReadableStreamBYOBReader and locks the stream to the new reader. - * - * This call behaves the same way as the no-argument variant, except that it only works on readable byte streams, i.e. streams which were constructed specifically with the ability to handle "bring your own buffer" reading. The returned BYOB reader provides the ability to directly read individual chunks from the stream via its read() method, into developer-supplied buffers, allowing more precise control over allocation. - */ - mode: "byob"; -} -/** - * The **`ReadableStreamBYOBRequest`** interface of the Streams API represents a 'pull request' for data from an underlying source that will made as a zero-copy transfer to a consumer (bypassing the stream's internal queues). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest) - */ -declare abstract class ReadableStreamBYOBRequest { - /** - * The **`view`** getter property of the ReadableStreamBYOBRequest interface returns the current view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/view) - */ - get view(): Uint8Array | null; - /** - * The **`respond()`** method of the ReadableStreamBYOBRequest interface is used to signal to the associated readable byte stream that the specified number of bytes were written into the ReadableStreamBYOBRequest.view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respond) - */ - respond(bytesWritten: number): void; - /** - * The **`respondWithNewView()`** method of the ReadableStreamBYOBRequest interface specifies a new view that the consumer of the associated readable byte stream should write to instead of ReadableStreamBYOBRequest.view. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamBYOBRequest/respondWithNewView) - */ - respondWithNewView(view: ArrayBuffer | ArrayBufferView): void; - get atLeast(): number | null; -} -/** - * The **`ReadableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a ReadableStream's state and internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController) - */ -declare abstract class ReadableStreamDefaultController { - /** - * The **`desiredSize`** read-only property of the required to fill the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`close()`** method of the ReadableStreamDefaultController interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/close) - */ - close(): void; - /** - * The **`enqueue()`** method of the ```js-nolint enqueue(chunk) ``` - `chunk` - : The chunk to enqueue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/enqueue) - */ - enqueue(chunk?: R): void; - /** - * The **`error()`** method of the with the associated stream to error. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableStreamDefaultController/error) - */ - error(reason: any): void; -} -/** - * The **`ReadableByteStreamController`** interface of the Streams API represents a controller for a readable byte stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController) - */ -declare abstract class ReadableByteStreamController { - /** - * The **`byobRequest`** read-only property of the ReadableByteStreamController interface returns the current BYOB request, or `null` if there are no pending requests. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/byobRequest) - */ - get byobRequest(): ReadableStreamBYOBRequest | null; - /** - * The **`desiredSize`** read-only property of the ReadableByteStreamController interface returns the number of bytes required to fill the stream's internal queue to its 'desired size'. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`close()`** method of the ReadableByteStreamController interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/close) - */ - close(): void; - /** - * The **`enqueue()`** method of the ReadableByteStreamController interface enqueues a given chunk on the associated readable byte stream (the chunk is copied into the stream's internal queues). - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/enqueue) - */ - enqueue(chunk: ArrayBuffer | ArrayBufferView): void; - /** - * The **`error()`** method of the ReadableByteStreamController interface causes any future interactions with the associated stream to error with the specified reason. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ReadableByteStreamController/error) - */ - error(reason: any): void; -} -/** - * The **`WritableStreamDefaultController`** interface of the Streams API represents a controller allowing control of a WritableStream's state. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController) - */ -declare abstract class WritableStreamDefaultController { - /** - * The read-only **`signal`** property of the WritableStreamDefaultController interface returns the AbortSignal associated with the controller. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/signal) - */ - get signal(): AbortSignal; - /** - * The **`error()`** method of the with the associated stream to error. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultController/error) - */ - error(reason?: any): void; -} -/** - * The **`TransformStreamDefaultController`** interface of the Streams API provides methods to manipulate the associated ReadableStream and WritableStream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController) - */ -declare abstract class TransformStreamDefaultController { - /** - * The **`desiredSize`** read-only property of the TransformStreamDefaultController interface returns the desired size to fill the queue of the associated ReadableStream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`enqueue()`** method of the TransformStreamDefaultController interface enqueues the given chunk in the readable side of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/enqueue) - */ - enqueue(chunk?: O): void; - /** - * The **`error()`** method of the TransformStreamDefaultController interface errors both sides of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/error) - */ - error(reason: any): void; - /** - * The **`terminate()`** method of the TransformStreamDefaultController interface closes the readable side and errors the writable side of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStreamDefaultController/terminate) - */ - terminate(): void; -} -interface ReadableWritablePair { - readable: ReadableStream; - /** - * Provides a convenient, chainable way of piping this readable stream through a transform stream (or any other { writable, readable } pair). It simply pipes the stream into the writable side of the supplied pair, and returns the readable side for further use. - * - * Piping a stream will lock it for the duration of the pipe, preventing any other consumer from acquiring a reader. - */ - writable: WritableStream; -} -/** - * The **`WritableStream`** interface of the Streams API provides a standard abstraction for writing streaming data to a destination, known as a sink. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream) - */ -declare class WritableStream { - constructor(underlyingSink?: UnderlyingSink, queuingStrategy?: QueuingStrategy); - /** - * The **`locked`** read-only property of the WritableStream interface returns a boolean indicating whether the `WritableStream` is locked to a writer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/locked) - */ - get locked(): boolean; - /** - * The **`abort()`** method of the WritableStream interface aborts the stream, signaling that the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/abort) - */ - abort(reason?: any): Promise; - /** - * The **`close()`** method of the WritableStream interface closes the associated stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/close) - */ - close(): Promise; - /** - * The **`getWriter()`** method of the WritableStream interface returns a new instance of WritableStreamDefaultWriter and locks the stream to that instance. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStream/getWriter) - */ - getWriter(): WritableStreamDefaultWriter; -} -/** - * The **`WritableStreamDefaultWriter`** interface of the Streams API is the object returned by WritableStream.getWriter() and once created locks the writer to the `WritableStream` ensuring that no other streams can write to the underlying sink. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter) - */ -declare class WritableStreamDefaultWriter { - constructor(stream: WritableStream); - /** - * The **`closed`** read-only property of the the stream errors or the writer's lock is released. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/closed) - */ - get closed(): Promise; - /** - * The **`ready`** read-only property of the that resolves when the desired size of the stream's internal queue transitions from non-positive to positive, signaling that it is no longer applying backpressure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/ready) - */ - get ready(): Promise; - /** - * The **`desiredSize`** read-only property of the to fill the stream's internal queue. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/desiredSize) - */ - get desiredSize(): number | null; - /** - * The **`abort()`** method of the the producer can no longer successfully write to the stream and it is to be immediately moved to an error state, with any queued writes discarded. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/abort) - */ - abort(reason?: any): Promise; - /** - * The **`close()`** method of the stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/close) - */ - close(): Promise; - /** - * The **`write()`** method of the operation. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/write) - */ - write(chunk?: W): Promise; - /** - * The **`releaseLock()`** method of the corresponding stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WritableStreamDefaultWriter/releaseLock) - */ - releaseLock(): void; -} -/** - * The **`TransformStream`** interface of the Streams API represents a concrete implementation of the pipe chain _transform stream_ concept. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream) - */ -declare class TransformStream { - constructor(transformer?: Transformer, writableStrategy?: QueuingStrategy, readableStrategy?: QueuingStrategy); - /** - * The **`readable`** read-only property of the TransformStream interface returns the ReadableStream instance controlled by this `TransformStream`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/readable) - */ - get readable(): ReadableStream; - /** - * The **`writable`** read-only property of the TransformStream interface returns the WritableStream instance controlled by this `TransformStream`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TransformStream/writable) - */ - get writable(): WritableStream; -} -declare class FixedLengthStream extends IdentityTransformStream { - constructor(expectedLength: number | bigint, queuingStrategy?: IdentityTransformStreamQueuingStrategy); -} -declare class IdentityTransformStream extends TransformStream { - constructor(queuingStrategy?: IdentityTransformStreamQueuingStrategy); -} -interface IdentityTransformStreamQueuingStrategy { - highWaterMark?: (number | bigint); -} -interface ReadableStreamValuesOptions { - preventCancel?: boolean; -} -/** - * The **`CompressionStream`** interface of the Compression Streams API is an API for compressing a stream of data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CompressionStream) - */ -declare class CompressionStream extends TransformStream { - constructor(format: "gzip" | "deflate" | "deflate-raw"); -} -/** - * The **`DecompressionStream`** interface of the Compression Streams API is an API for decompressing a stream of data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/DecompressionStream) - */ -declare class DecompressionStream extends TransformStream { - constructor(format: "gzip" | "deflate" | "deflate-raw"); -} -/** - * The **`TextEncoderStream`** interface of the Encoding API converts a stream of strings into bytes in the UTF-8 encoding. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextEncoderStream) - */ -declare class TextEncoderStream extends TransformStream { - constructor(); - get encoding(): string; -} -/** - * The **`TextDecoderStream`** interface of the Encoding API converts a stream of text in a binary encoding, such as UTF-8 etc., to a stream of strings. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/TextDecoderStream) - */ -declare class TextDecoderStream extends TransformStream { - constructor(label?: string, options?: TextDecoderStreamTextDecoderStreamInit); - get encoding(): string; - get fatal(): boolean; - get ignoreBOM(): boolean; -} -interface TextDecoderStreamTextDecoderStreamInit { - fatal?: boolean; - ignoreBOM?: boolean; -} -/** - * The **`ByteLengthQueuingStrategy`** interface of the Streams API provides a built-in byte length queuing strategy that can be used when constructing streams. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy) - */ -declare class ByteLengthQueuingStrategy implements QueuingStrategy { - constructor(init: QueuingStrategyInit); - /** - * The read-only **`ByteLengthQueuingStrategy.highWaterMark`** property returns the total number of bytes that can be contained in the internal queue before backpressure is applied. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/highWaterMark) - */ - get highWaterMark(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/ByteLengthQueuingStrategy/size) */ - get size(): (chunk?: any) => number; -} -/** - * The **`CountQueuingStrategy`** interface of the Streams API provides a built-in chunk counting queuing strategy that can be used when constructing streams. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy) - */ -declare class CountQueuingStrategy implements QueuingStrategy { - constructor(init: QueuingStrategyInit); - /** - * The read-only **`CountQueuingStrategy.highWaterMark`** property returns the total number of chunks that can be contained in the internal queue before backpressure is applied. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/highWaterMark) - */ - get highWaterMark(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CountQueuingStrategy/size) */ - get size(): (chunk?: any) => number; -} -interface QueuingStrategyInit { - /** - * Creates a new ByteLengthQueuingStrategy with the provided high water mark. - * - * Note that the provided high water mark will not be validated ahead of time. Instead, if it is negative, NaN, or not a number, the resulting ByteLengthQueuingStrategy will cause the corresponding stream constructor to throw. - */ - highWaterMark: number; -} -interface TracePreviewInfo { - id: string; - slug: string; - name: string; -} -interface ScriptVersion { - id?: string; - tag?: string; - message?: string; -} -declare abstract class TailEvent extends ExtendableEvent { - readonly events: TraceItem[]; - readonly traces: TraceItem[]; -} -interface TraceItem { - readonly event: (TraceItemFetchEventInfo | TraceItemJsRpcEventInfo | TraceItemConnectEventInfo | TraceItemScheduledEventInfo | TraceItemAlarmEventInfo | TraceItemQueueEventInfo | TraceItemEmailEventInfo | TraceItemTailEventInfo | TraceItemCustomEventInfo | TraceItemHibernatableWebSocketEventInfo) | null; - readonly eventTimestamp: number | null; - readonly logs: TraceLog[]; - readonly exceptions: TraceException[]; - readonly diagnosticsChannelEvents: TraceDiagnosticChannelEvent[]; - readonly scriptName: string | null; - readonly entrypoint?: string; - readonly scriptVersion?: ScriptVersion; - readonly dispatchNamespace?: string; - readonly scriptTags?: string[]; - readonly tailAttributes?: Record; - readonly preview?: TracePreviewInfo; - readonly durableObjectId?: string; - readonly outcome: string; - readonly executionModel: string; - readonly truncated: boolean; - readonly cpuTime: number; - readonly wallTime: number; -} -interface TraceItemAlarmEventInfo { - readonly scheduledTime: Date; -} -interface TraceItemConnectEventInfo { -} -interface TraceItemCustomEventInfo { -} -interface TraceItemScheduledEventInfo { - readonly scheduledTime: number; - readonly cron: string; -} -interface TraceItemQueueEventInfo { - readonly queue: string; - readonly batchSize: number; -} -interface TraceItemEmailEventInfo { - readonly mailFrom: string; - readonly rcptTo: string; - readonly rawSize: number; -} -interface TraceItemTailEventInfo { - readonly consumedEvents: TraceItemTailEventInfoTailItem[]; -} -interface TraceItemTailEventInfoTailItem { - readonly scriptName: string | null; -} -interface TraceItemFetchEventInfo { - readonly response?: TraceItemFetchEventInfoResponse; - readonly request: TraceItemFetchEventInfoRequest; -} -interface TraceItemFetchEventInfoRequest { - readonly cf?: any; - readonly headers: Record; - readonly method: string; - readonly url: string; - getUnredacted(): TraceItemFetchEventInfoRequest; -} -interface TraceItemFetchEventInfoResponse { - readonly status: number; -} -interface TraceItemJsRpcEventInfo { - readonly rpcMethod: string; -} -interface TraceItemHibernatableWebSocketEventInfo { - readonly getWebSocketEvent: TraceItemHibernatableWebSocketEventInfoMessage | TraceItemHibernatableWebSocketEventInfoClose | TraceItemHibernatableWebSocketEventInfoError; -} -interface TraceItemHibernatableWebSocketEventInfoMessage { - readonly webSocketEventType: string; -} -interface TraceItemHibernatableWebSocketEventInfoClose { - readonly webSocketEventType: string; - readonly code: number; - readonly wasClean: boolean; -} -interface TraceItemHibernatableWebSocketEventInfoError { - readonly webSocketEventType: string; -} -interface TraceLog { - readonly timestamp: number; - readonly level: string; - readonly message: any; -} -interface TraceException { - readonly timestamp: number; - readonly message: string; - readonly name: string; - readonly stack?: string; -} -interface TraceDiagnosticChannelEvent { - readonly timestamp: number; - readonly channel: string; - readonly message: any; -} -interface TraceMetrics { - readonly cpuTime: number; - readonly wallTime: number; -} -interface UnsafeTraceMetrics { - fromTrace(item: TraceItem): TraceMetrics; -} -/** - * The **`URL`** interface is used to parse, construct, normalize, and encode URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL) - */ -declare class URL { - constructor(url: string | URL, base?: string | URL); - /** - * The **`origin`** read-only property of the URL interface returns a string containing the Unicode serialization of the origin of the represented URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/origin) - */ - get origin(): string; - /** - * The **`href`** property of the URL interface is a string containing the whole URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) - */ - get href(): string; - /** - * The **`href`** property of the URL interface is a string containing the whole URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/href) - */ - set href(value: string); - /** - * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) - */ - get protocol(): string; - /** - * The **`protocol`** property of the URL interface is a string containing the protocol or scheme of the URL, including the final `':'`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/protocol) - */ - set protocol(value: string); - /** - * The **`username`** property of the URL interface is a string containing the username component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) - */ - get username(): string; - /** - * The **`username`** property of the URL interface is a string containing the username component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/username) - */ - set username(value: string); - /** - * The **`password`** property of the URL interface is a string containing the password component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) - */ - get password(): string; - /** - * The **`password`** property of the URL interface is a string containing the password component of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/password) - */ - set password(value: string); - /** - * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) - */ - get host(): string; - /** - * The **`host`** property of the URL interface is a string containing the host, which is the URL.hostname, and then, if the port of the URL is nonempty, a `':'`, followed by the URL.port of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/host) - */ - set host(value: string); - /** - * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) - */ - get hostname(): string; - /** - * The **`hostname`** property of the URL interface is a string containing either the domain name or IP address of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hostname) - */ - set hostname(value: string); - /** - * The **`port`** property of the URL interface is a string containing the port number of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) - */ - get port(): string; - /** - * The **`port`** property of the URL interface is a string containing the port number of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/port) - */ - set port(value: string); - /** - * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) - */ - get pathname(): string; - /** - * The **`pathname`** property of the URL interface represents a location in a hierarchical structure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/pathname) - */ - set pathname(value: string); - /** - * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) - */ - get search(): string; - /** - * The **`search`** property of the URL interface is a search string, also called a _query string_, that is a string containing a `'?'` followed by the parameters of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/search) - */ - set search(value: string); - /** - * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) - */ - get hash(): string; - /** - * The **`hash`** property of the URL interface is a string containing a `'#'` followed by the fragment identifier of the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/hash) - */ - set hash(value: string); - /** - * The **`searchParams`** read-only property of the access to the [MISSING: httpmethod('GET')] decoded query arguments contained in the URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/searchParams) - */ - get searchParams(): URLSearchParams; - /** - * The **`toJSON()`** method of the URL interface returns a string containing a serialized version of the URL, although in practice it seems to have the same effect as ```js-nolint toJSON() ``` None. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/toJSON) - */ - toJSON(): string; - /*function toString() { [native code] }*/ - toString(): string; - /** - * The **`URL.canParse()`** static method of the URL interface returns a boolean indicating whether or not an absolute URL, or a relative URL combined with a base URL, are parsable and valid. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/canParse_static) - */ - static canParse(url: string, base?: string): boolean; - /** - * The **`URL.parse()`** static method of the URL interface returns a newly created URL object representing the URL defined by the parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/parse_static) - */ - static parse(url: string, base?: string): URL | null; - /** - * The **`createObjectURL()`** static method of the URL interface creates a string containing a URL representing the object given in the parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/createObjectURL_static) - */ - static createObjectURL(object: File | Blob): string; - /** - * The **`revokeObjectURL()`** static method of the URL interface releases an existing object URL which was previously created by calling Call this method when you've finished using an object URL to let the browser know not to keep the reference to the file any longer. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URL/revokeObjectURL_static) - */ - static revokeObjectURL(object_url: string): void; -} -/** - * The **`URLSearchParams`** interface defines utility methods to work with the query string of a URL. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams) - */ -declare class URLSearchParams { - constructor(init?: (Iterable> | Record | string)); - /** - * The **`size`** read-only property of the URLSearchParams interface indicates the total number of search parameter entries. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/size) - */ - get size(): number; - /** - * The **`append()`** method of the URLSearchParams interface appends a specified key/value pair as a new search parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/append) - */ - append(name: string, value: string): void; - /** - * The **`delete()`** method of the URLSearchParams interface deletes specified parameters and their associated value(s) from the list of all search parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/delete) - */ - delete(name: string, value?: string): void; - /** - * The **`get()`** method of the URLSearchParams interface returns the first value associated to the given search parameter. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/get) - */ - get(name: string): string | null; - /** - * The **`getAll()`** method of the URLSearchParams interface returns all the values associated with a given search parameter as an array. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/getAll) - */ - getAll(name: string): string[]; - /** - * The **`has()`** method of the URLSearchParams interface returns a boolean value that indicates whether the specified parameter is in the search parameters. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/has) - */ - has(name: string, value?: string): boolean; - /** - * The **`set()`** method of the URLSearchParams interface sets the value associated with a given search parameter to the given value. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/set) - */ - set(name: string, value: string): void; - /** - * The **`URLSearchParams.sort()`** method sorts all key/value pairs contained in this object in place and returns `undefined`. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/URLSearchParams/sort) - */ - sort(): void; - /* Returns an array of key, value pairs for every entry in the search params. */ - entries(): IterableIterator<[ - key: string, - value: string - ]>; - /* Returns a list of keys in the search params. */ - keys(): IterableIterator; - /* Returns a list of values in the search params. */ - values(): IterableIterator; - forEach(callback: (this: This, value: string, key: string, parent: URLSearchParams) => void, thisArg?: This): void; - /*function toString() { [native code] }*/ - toString(): string; - [Symbol.iterator](): IterableIterator<[ - key: string, - value: string - ]>; -} -declare class URLPattern { - constructor(input?: (string | URLPatternInit), baseURL?: (string | URLPatternOptions), patternOptions?: URLPatternOptions); - get protocol(): string; - get username(): string; - get password(): string; - get hostname(): string; - get port(): string; - get pathname(): string; - get search(): string; - get hash(): string; - get hasRegExpGroups(): boolean; - test(input?: (string | URLPatternInit), baseURL?: string): boolean; - exec(input?: (string | URLPatternInit), baseURL?: string): URLPatternResult | null; -} -interface URLPatternInit { - protocol?: string; - username?: string; - password?: string; - hostname?: string; - port?: string; - pathname?: string; - search?: string; - hash?: string; - baseURL?: string; -} -interface URLPatternComponentResult { - input: string; - groups: Record; -} -interface URLPatternResult { - inputs: (string | URLPatternInit)[]; - protocol: URLPatternComponentResult; - username: URLPatternComponentResult; - password: URLPatternComponentResult; - hostname: URLPatternComponentResult; - port: URLPatternComponentResult; - pathname: URLPatternComponentResult; - search: URLPatternComponentResult; - hash: URLPatternComponentResult; -} -interface URLPatternOptions { - ignoreCase?: boolean; -} -/** - * A `CloseEvent` is sent to clients using WebSockets when the connection is closed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent) - */ -declare class CloseEvent extends Event { - constructor(type: string, initializer?: CloseEventInit); - /** - * The **`code`** read-only property of the CloseEvent interface returns a WebSocket connection close code indicating the reason the connection was closed. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/code) - */ - readonly code: number; - /** - * The **`reason`** read-only property of the CloseEvent interface returns the WebSocket connection close reason the server gave for closing the connection; that is, a concise human-readable prose explanation for the closure. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/reason) - */ - readonly reason: string; - /** - * The **`wasClean`** read-only property of the CloseEvent interface returns `true` if the connection closed cleanly. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/CloseEvent/wasClean) - */ - readonly wasClean: boolean; -} -interface CloseEventInit { - code?: number; - reason?: string; - wasClean?: boolean; -} -type WebSocketEventMap = { - close: CloseEvent; - message: MessageEvent; - open: Event; - error: ErrorEvent; -}; -/** - * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) - */ -declare var WebSocket: { - prototype: WebSocket; - new (url: string, protocols?: (string[] | string)): WebSocket; - readonly READY_STATE_CONNECTING: number; - readonly CONNECTING: number; - readonly READY_STATE_OPEN: number; - readonly OPEN: number; - readonly READY_STATE_CLOSING: number; - readonly CLOSING: number; - readonly READY_STATE_CLOSED: number; - readonly CLOSED: number; -}; -/** - * The `WebSocket` object provides the API for creating and managing a WebSocket connection to a server, as well as for sending and receiving data on the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket) - */ -interface WebSocket extends EventTarget { - accept(options?: WebSocketAcceptOptions): void; - /** - * The **`WebSocket.send()`** method enqueues the specified data to be transmitted to the server over the WebSocket connection, increasing the value of `bufferedAmount` by the number of bytes needed to contain the data. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/send) - */ - send(message: (ArrayBuffer | ArrayBufferView) | string): void; - /** - * The **`WebSocket.close()`** method closes the already `CLOSED`, this method does nothing. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/close) - */ - close(code?: number, reason?: string): void; - serializeAttachment(attachment: any): void; - deserializeAttachment(): any | null; - /** - * The **`WebSocket.readyState`** read-only property returns the current state of the WebSocket connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/readyState) - */ - readyState: number; - /** - * The **`WebSocket.url`** read-only property returns the absolute URL of the WebSocket as resolved by the constructor. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/url) - */ - url: string | null; - /** - * The **`WebSocket.protocol`** read-only property returns the name of the sub-protocol the server selected; this will be one of the strings specified in the `protocols` parameter when creating the WebSocket object, or the empty string if no connection is established. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/protocol) - */ - protocol: string | null; - /** - * The **`WebSocket.extensions`** read-only property returns the extensions selected by the server. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/extensions) - */ - extensions: string | null; - /** - * The **`WebSocket.binaryType`** property controls the type of binary data being received over the WebSocket connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType) - */ - binaryType: "blob" | "arraybuffer"; -} -interface WebSocketAcceptOptions { - /** - * When set to `true`, receiving a server-initiated WebSocket Close frame will not - * automatically send a reciprocal Close frame, leaving the connection in a half-open - * state. This is useful for proxying scenarios where you need to coordinate closing - * both sides independently. Defaults to `false` when the - * `no_web_socket_half_open_by_default` compatibility flag is enabled. - */ - allowHalfOpen?: boolean; -} -declare const WebSocketPair: { - new (): { - 0: WebSocket; - 1: WebSocket; - }; -}; -interface SqlStorage { - exec>(query: string, ...bindings: any[]): SqlStorageCursor; - get databaseSize(): number; - Cursor: typeof SqlStorageCursor; - Statement: typeof SqlStorageStatement; -} -declare abstract class SqlStorageStatement { -} -type SqlStorageValue = ArrayBuffer | string | number | null; -declare abstract class SqlStorageCursor> { - next(): { - done?: false; - value: T; - } | { - done: true; - value?: never; - }; - toArray(): T[]; - one(): T; - raw(): IterableIterator; - columnNames: string[]; - get rowsRead(): number; - get rowsWritten(): number; - [Symbol.iterator](): IterableIterator; -} -interface Socket { - get readable(): ReadableStream; - get writable(): WritableStream; - get closed(): Promise; - get opened(): Promise; - get upgraded(): boolean; - get secureTransport(): "on" | "off" | "starttls"; - close(): Promise; - startTls(options?: TlsOptions): Socket; -} -interface SocketOptions { - secureTransport?: string; - allowHalfOpen: boolean; - highWaterMark?: (number | bigint); -} -interface SocketAddress { - hostname: string; - port: number; -} -interface TlsOptions { - expectedServerHostname?: string; -} -interface SocketInfo { - remoteAddress?: string; - localAddress?: string; -} -/** - * The **`EventSource`** interface is web content's interface to server-sent events. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource) - */ -declare class EventSource extends EventTarget { - constructor(url: string, init?: EventSourceEventSourceInit); - /** - * The **`close()`** method of the EventSource interface closes the connection, if one is made, and sets the ```js-nolint close() ``` None. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) - */ - close(): void; - /** - * The **`url`** read-only property of the URL of the source. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) - */ - get url(): string; - /** - * The **`withCredentials`** read-only property of the the `EventSource` object was instantiated with CORS credentials set. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) - */ - get withCredentials(): boolean; - /** - * The **`readyState`** read-only property of the connection. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) - */ - get readyState(): number; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - get onopen(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - set onopen(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - get onmessage(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - set onmessage(value: any | null); - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - get onerror(): any | null; - /* [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - set onerror(value: any | null); - static readonly CONNECTING: number; - static readonly OPEN: number; - static readonly CLOSED: number; - static from(stream: ReadableStream): EventSource; -} -interface EventSourceEventSourceInit { - withCredentials?: boolean; - fetcher?: Fetcher; -} -interface Container { - get running(): boolean; - start(options?: ContainerStartupOptions): void; - monitor(): Promise; - destroy(error?: any): Promise; - signal(signo: number): void; - getTcpPort(port: number): Fetcher; - setInactivityTimeout(durationMs: number | bigint): Promise; - interceptOutboundHttp(addr: string, binding: Fetcher): Promise; - interceptAllOutboundHttp(binding: Fetcher): Promise; - snapshotDirectory(options: ContainerDirectorySnapshotOptions): Promise; - snapshotContainer(options: ContainerSnapshotOptions): Promise; - interceptOutboundHttps(addr: string, binding: Fetcher): Promise; -} -interface ContainerDirectorySnapshot { - id: string; - size: number; - dir: string; - name?: string; -} -interface ContainerDirectorySnapshotOptions { - dir: string; - name?: string; -} -interface ContainerDirectorySnapshotRestoreParams { - snapshot: ContainerDirectorySnapshot; - mountPoint?: string; -} -interface ContainerSnapshot { - id: string; - size: number; - name?: string; -} -interface ContainerSnapshotOptions { - name?: string; -} -interface ContainerStartupOptions { - entrypoint?: string[]; - enableInternet: boolean; - env?: Record; - labels?: Record; - directorySnapshots?: ContainerDirectorySnapshotRestoreParams[]; - containerSnapshot?: ContainerSnapshot; -} -/** - * The **`MessagePort`** interface of the Channel Messaging API represents one of the two ports of a MessageChannel, allowing messages to be sent from one port and listening out for them arriving at the other. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort) - */ -declare abstract class MessagePort extends EventTarget { - /** - * The **`postMessage()`** method of the transfers ownership of objects to other browsing contexts. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/postMessage) - */ - postMessage(data?: any, options?: (any[] | MessagePortPostMessageOptions)): void; - /** - * The **`close()`** method of the MessagePort interface disconnects the port, so it is no longer active. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/close) - */ - close(): void; - /** - * The **`start()`** method of the MessagePort interface starts the sending of messages queued on the port. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessagePort/start) - */ - start(): void; - get onmessage(): any | null; - set onmessage(value: any | null); -} -/** - * The **`MessageChannel`** interface of the Channel Messaging API allows us to create a new message channel and send data through it via its two MessagePort properties. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel) - */ -declare class MessageChannel { - constructor(); - /** - * The **`port1`** read-only property of the the port attached to the context that originated the channel. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port1) - */ - readonly port1: MessagePort; - /** - * The **`port2`** read-only property of the the port attached to the context at the other end of the channel, which the message is initially sent to. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/MessageChannel/port2) - */ - readonly port2: MessagePort; -} -interface MessagePortPostMessageOptions { - transfer?: any[]; -} -type LoopbackForExport Rpc.EntrypointBranded) | ExportedHandler | undefined = undefined> = T extends new (...args: any[]) => Rpc.WorkerEntrypointBranded ? LoopbackServiceStub> : T extends new (...args: any[]) => Rpc.DurableObjectBranded ? LoopbackDurableObjectClass> : T extends ExportedHandler ? LoopbackServiceStub : undefined; -type LoopbackServiceStub = Fetcher & (T extends CloudflareWorkersModule.WorkerEntrypoint ? (opts: { - props?: Props; -}) => Fetcher : (opts: { - props?: any; -}) => Fetcher); -type LoopbackDurableObjectClass = DurableObjectClass & (T extends CloudflareWorkersModule.DurableObject ? (opts: { - props?: Props; -}) => DurableObjectClass : (opts: { - props?: any; -}) => DurableObjectClass); -interface LoopbackDurableObjectNamespace extends DurableObjectNamespace { -} -interface LoopbackColoLocalActorNamespace extends ColoLocalActorNamespace { -} -interface SyncKvStorage { - get(key: string): T | undefined; - list(options?: SyncKvListOptions): Iterable<[ - string, - T - ]>; - put(key: string, value: T): void; - delete(key: string): boolean; -} -interface SyncKvListOptions { - start?: string; - startAfter?: string; - end?: string; - prefix?: string; - reverse?: boolean; - limit?: number; -} -interface WorkerStub { - getEntrypoint(name?: string, options?: WorkerStubEntrypointOptions): Fetcher; - getDurableObjectClass(name?: string, options?: WorkerStubEntrypointOptions): DurableObjectClass; -} -interface WorkerStubEntrypointOptions { - props?: any; - limits?: workerdResourceLimits; -} -interface WorkerLoader { - get(name: string | null, getCode: () => WorkerLoaderWorkerCode | Promise): WorkerStub; - load(code: WorkerLoaderWorkerCode): WorkerStub; -} -interface WorkerLoaderModule { - js?: string; - cjs?: string; - text?: string; - data?: ArrayBuffer; - json?: any; - py?: string; - wasm?: ArrayBuffer; -} -interface WorkerLoaderWorkerCode { - compatibilityDate: string; - compatibilityFlags?: string[]; - allowExperimental?: boolean; - limits?: workerdResourceLimits; - mainModule: string; - modules: Record; - env?: any; - globalOutbound?: (Fetcher | null); - tails?: Fetcher[]; - streamingTails?: Fetcher[]; -} -interface workerdResourceLimits { - cpuMs?: number; - subRequests?: number; -} -/** -* The Workers runtime supports a subset of the Performance API, used to measure timing and performance, -* as well as timing of subrequests and other operations. -* -* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/) -*/ -declare abstract class Performance { - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancetimeorigin) */ - get timeOrigin(): number; - /* [Cloudflare Docs Reference](https://developers.cloudflare.com/workers/runtime-apis/performance/#performancenow) */ - now(): number; - /** - * The **`toJSON()`** method of the Performance interface is a Serialization; it returns a JSON representation of the Performance object. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Performance/toJSON) - */ - toJSON(): object; -} -interface Tracing { - enterSpan(name: string, callback: (span: Span, ...args: A) => T, ...args: A): T; - Span: typeof Span; -} -declare abstract class Span { - get isTraced(): boolean; - setAttribute(key: string, value?: (boolean | number | string)): void; -} -// ============ AI Search Error Interfaces ============ -interface AiSearchInternalError extends Error { -} -interface AiSearchNotFoundError extends Error { -} -// ============ AI Search Common Types ============ -/** A single message in a conversation-style search or chat request. */ -type AiSearchMessage = { - role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; - content: string | null; -}; -/** - * Common shape for `ai_search_options` used by both single-instance and multi-instance requests. - * Contains retrieval, query rewrite, reranking, and cache sub-options. - */ -type AiSearchOptions = { - retrieval?: { - /** Which retrieval backend to use. Defaults to the instance's configured index_method. */ - retrieval_type?: 'vector' | 'keyword' | 'hybrid'; - /** Fusion method for combining vector + keyword results. */ - fusion_method?: 'max' | 'rrf'; - /** How keyword terms are combined: "and" = all terms must match, "or" = any term matches. */ - keyword_match_mode?: 'and' | 'or'; - /** Minimum similarity score (0-1) for a result to be included. Default 0.4. */ - match_threshold?: number; - /** Maximum number of results to return (1-50). Default 10. */ - max_num_results?: number; - /** Vectorize metadata filters applied to the search. */ - filters?: VectorizeVectorMetadataFilter; - /** Number of surrounding chunks to include for context (0-3). Default 0. */ - context_expansion?: number; - /** If true, return only item metadata without chunk text. */ - metadata_only?: boolean; - /** If true (default), return empty results on retrieval failure instead of throwing. */ - return_on_failure?: boolean; - /** Boost results by metadata field values. Max 3 entries. */ - boost_by?: Array<{ - field: string; - direction?: 'asc' | 'desc' | 'exists' | 'not_exists'; - }>; - [key: string]: unknown; - }; - query_rewrite?: { - enabled?: boolean; - model?: string; - rewrite_prompt?: string; - [key: string]: unknown; - }; - reranking?: { - enabled?: boolean; - model?: string; - /** Match threshold (0-1, default 0.4) */ - match_threshold?: number; - [key: string]: unknown; - }; - cache?: { - enabled?: boolean; - cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes'; - }; - [key: string]: unknown; -}; -// ============ AI Search Request Types ============ -/** - * Request body for single-instance search. - * Exactly one of `query` or `messages` must be provided. - */ -type AiSearchSearchRequest = { - /** Simple query string. */ - query: string; - messages?: never; - ai_search_options?: AiSearchOptions; -} | { - query?: never; - /** Conversation-style input. At least one user message with non-empty content is required. */ - messages: AiSearchMessage[]; - ai_search_options?: AiSearchOptions; -}; -type AiSearchChatCompletionsRequest = { - messages: AiSearchMessage[]; - model?: string; - stream?: boolean; - ai_search_options?: AiSearchOptions; - [key: string]: unknown; -}; -// ============ AI Search Multi-Instance Types (Namespace-Scoped) ============ -/** `ai_search_options` shape for multi-instance requests — requires `instance_ids`. */ -type AiSearchMultiSearchOptions = AiSearchOptions & { - /** Instance IDs to search across (1-10). */ - instance_ids: string[]; -}; -/** - * Request for searching across multiple instances within a namespace. - * `ai_search_options` is required and must include `instance_ids`. - * Exactly one of `query` or `messages` must be provided. - */ -type AiSearchMultiSearchRequest = { - /** Simple query string. */ - query: string; - messages?: never; - ai_search_options: AiSearchMultiSearchOptions; -} | { - query?: never; - /** Conversation-style input. */ - messages: AiSearchMessage[]; - ai_search_options: AiSearchMultiSearchOptions; -}; -/** A search result chunk tagged with the instance it originated from. */ -type AiSearchMultiSearchChunk = AiSearchSearchResponse['chunks'][number] & { - instance_id: string; -}; -/** Describes a per-instance error during a multi-instance operation. */ -type AiSearchMultiSearchError = { - instance_id: string; - message: string; -}; -/** Response from a multi-instance search, with chunks tagged by instance and optional partial-failure errors. */ -type AiSearchMultiSearchResponse = { - search_query: string; - chunks: AiSearchMultiSearchChunk[]; - errors?: AiSearchMultiSearchError[]; -}; -/** Request for chat completions across multiple instances within a namespace. `ai_search_options` is required and must include `instance_ids`. */ -type AiSearchMultiChatCompletionsRequest = Omit & { - ai_search_options: AiSearchMultiSearchOptions; -}; -/** Response from multi-instance chat completions, with chunks tagged by instance and optional partial-failure errors. */ -type AiSearchMultiChatCompletionsResponse = Omit & { - chunks: AiSearchMultiSearchChunk[]; - errors?: AiSearchMultiSearchError[]; -}; -// ============ AI Search Response Types ============ -type AiSearchSearchResponse = { - search_query: string; - chunks: Array<{ - id: string; - type: string; - /** Match score (0-1) */ - score: number; - text: string; - item: { - timestamp?: number; - key: string; - metadata?: Record; - }; - scoring_details?: { - /** Keyword match score (0-1) */ - keyword_score?: number; - /** Vector similarity score (0-1) */ - vector_score?: number; - /** Keyword rank position */ - keyword_rank?: number; - /** Vector rank position */ - vector_rank?: number; - /** Reranking model score */ - reranking_score?: number; - /** Fusion method used to combine results */ - fusion_method?: 'rrf' | 'max'; - [key: string]: unknown; - }; - }>; -}; -type AiSearchChatCompletionsResponse = { - id?: string; - object?: string; - model?: string; - choices: Array<{ - index?: number; - message: { - role: 'system' | 'developer' | 'user' | 'assistant' | 'tool'; - content: string | null; - [key: string]: unknown; - }; - [key: string]: unknown; - }>; - chunks: AiSearchSearchResponse['chunks']; - [key: string]: unknown; -}; -type AiSearchStatsResponse = { - queued?: number; - running?: number; - completed?: number; - error?: number; - skipped?: number; - outdated?: number; - last_activity?: string; - /** Storage engine statistics. */ - engine?: { - vectorize?: { - vectorsCount: number; - dimensions: number; - }; - r2?: { - payloadSizeBytes: number; - metadataSizeBytes: number; - objectCount: number; - }; - }; -}; -// ============ AI Search Instance Info Types ============ -type AiSearchInstanceInfo = { - id: string; - type?: 'r2' | 'web-crawler' | string; - source?: string; - source_params?: unknown; - paused?: boolean; - status?: string; - namespace?: string; - created_at?: string; - modified_at?: string; - token_id?: string; - ai_gateway_id?: string; - rewrite_query?: boolean; - reranking?: boolean; - embedding_model?: string; - ai_search_model?: string; - rewrite_model?: string; - reranking_model?: string; - /** @deprecated Use index_method instead. */ - hybrid_search_enabled?: boolean; - /** Controls which storage backends are active. */ - index_method?: { - vector?: boolean; - keyword?: boolean; - }; - /** Fusion method for combining vector and keyword results. */ - fusion_method?: 'max' | 'rrf'; - indexing_options?: { - keyword_tokenizer?: 'porter' | 'trigram'; - } | null; - retrieval_options?: { - keyword_match_mode?: 'and' | 'or'; - boost_by?: Array<{ - field: string; - direction?: 'asc' | 'desc' | 'exists' | 'not_exists'; - }>; - } | null; - chunk?: boolean; - chunk_size?: number; - chunk_overlap?: number; - score_threshold?: number; - max_num_results?: number; - cache?: boolean; - cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes'; - custom_metadata?: Array<{ - field_name: string; - data_type: 'text' | 'number' | 'boolean' | 'datetime'; - }>; - /** Sync interval in seconds. */ - sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400; - metadata?: Record; - [key: string]: unknown; -}; -/** Pagination, search, and ordering parameters for listing instances within a namespace. */ -type AiSearchListInstancesParams = { - page?: number; - per_page?: number; - /** Search instances by ID. */ - search?: string; - /** Field to sort by. */ - order_by?: 'created_at'; - /** Sort direction. */ - order_by_direction?: 'asc' | 'desc'; -}; -type AiSearchListResponse = { - result: AiSearchInstanceInfo[]; - result_info?: { - count: number; - page: number; - per_page: number; - total_count: number; - }; -}; -// ============ AI Search Config Types ============ -type AiSearchConfig = { - /** Instance ID (1-32 chars, pattern: ^[a-z0-9_]+(?:-[a-z0-9_]+)*$) */ - id: string; - /** Instance type. Omit to create with built-in storage. */ - type?: 'r2' | 'web-crawler' | string; - /** Source URL (required for web-crawler type). */ - source?: string; - source_params?: unknown; - /** Token ID (UUID format) */ - token_id?: string; - ai_gateway_id?: string; - /** Enable query rewriting (default false) */ - rewrite_query?: boolean; - /** Enable reranking (default false) */ - reranking?: boolean; - embedding_model?: string; - ai_search_model?: string; - rewrite_model?: string; - reranking_model?: string; - /** @deprecated Use index_method instead. */ - hybrid_search_enabled?: boolean; - /** Controls which storage backends are used during indexing. Defaults to vector-only. */ - index_method?: { - vector?: boolean; - keyword?: boolean; - }; - /** Fusion method for combining vector and keyword results. "rrf" = reciprocal rank fusion (default), "max" = maximum score. */ - fusion_method?: 'max' | 'rrf'; - indexing_options?: { - keyword_tokenizer?: 'porter' | 'trigram'; - } | null; - retrieval_options?: { - keyword_match_mode?: 'and' | 'or'; - boost_by?: Array<{ - field: string; - direction?: 'asc' | 'desc' | 'exists' | 'not_exists'; - }>; - } | null; - chunk?: boolean; - chunk_size?: number; - chunk_overlap?: number; - /** Minimum similarity score (0-1) for a result to be included. */ - score_threshold?: number; - max_num_results?: number; - cache?: boolean; - /** Similarity threshold for cache hits. Stricter = fewer cache hits but higher relevance. */ - cache_threshold?: 'super_strict_match' | 'close_enough' | 'flexible_friend' | 'anything_goes'; - custom_metadata?: Array<{ - field_name: string; - data_type: 'text' | 'number' | 'boolean' | 'datetime'; - }>; - namespace?: string; - /** Sync interval in seconds. 3600=1h, 7200=2h, 14400=4h, 21600=6h, 43200=12h, 86400=24h. */ - sync_interval?: 3600 | 7200 | 14400 | 21600 | 43200 | 86400; - metadata?: Record; - [key: string]: unknown; -}; -// ============ AI Search Item Types ============ -type AiSearchItemInfo = { - id: string; - key: string; - status: 'completed' | 'error' | 'skipped' | 'queued' | 'running' | 'outdated'; - next_action?: 'INDEX' | 'DELETE' | null; - error?: string; - checksum?: string; - namespace?: string; - chunks_count?: number | null; - file_size?: number | null; - source_id?: string | null; - last_seen_at?: string; - created_at?: string; - metadata?: Record; - [key: string]: unknown; -}; -type AiSearchItemContentResult = { - body: ReadableStream; - contentType: string; - filename: string; - size: number; -}; -type AiSearchUploadItemOptions = { - metadata?: Record; -}; -type AiSearchListItemsParams = { - page?: number; - per_page?: number; - /** Search items by key name. */ - search?: string; - /** Sort order for results. */ - sort_by?: 'status' | 'modified_at'; - /** Filter items by processing status. */ - status?: 'queued' | 'running' | 'completed' | 'error' | 'skipped' | 'outdated'; - /** Filter items by source (e.g. "builtin" or "web-crawler:https://example.com"). */ - source?: string; - /** JSON-encoded Vectorize filter for metadata filtering. */ - metadata_filter?: string; -}; -type AiSearchListItemsResponse = { - result: AiSearchItemInfo[]; - result_info?: { - count: number; - page: number; - per_page: number; - total_count: number; - }; -}; -// ============ AI Search Item Logs Types ============ -type AiSearchItemLogsParams = { - /** Maximum number of log entries to return (1-100, default 50). */ - limit?: number; - /** Opaque cursor for pagination. Pass the `cursor` value from a previous response. */ - cursor?: string; -}; -type AiSearchItemLog = { - timestamp: string; - action: string; - message: string; - fileKey?: string; - chunkCount?: number; - processingTimeMs?: number; - errorType?: string; -}; -/** Paginated response for item processing logs (cursor-based). */ -type AiSearchItemLogsResponse = { - result: AiSearchItemLog[]; - result_info: { - count: number; - per_page: number; - cursor: string | null; - truncated: boolean; - }; -}; -// ============ AI Search Item Chunks Types ============ -type AiSearchItemChunksParams = { - /** Maximum number of chunks to return (1-100, default 20). */ - limit?: number; - /** Offset into the chunks list (default 0). */ - offset?: number; -}; -/** A single indexed chunk belonging to an item, including its text content and byte range. */ -type AiSearchItemChunk = { - id: string; - text: string; - start_byte: number; - end_byte: number; - item?: { - timestamp?: number; - key: string; - metadata?: Record; - }; -}; -/** Paginated response for item chunks (offset-based). */ -type AiSearchItemChunksResponse = { - result: AiSearchItemChunk[]; - result_info: { - count: number; - total: number; - limit: number; - offset: number; - }; -}; -// ============ AI Search Job Types ============ -type AiSearchJobInfo = { - id: string; - source: 'user' | 'schedule'; - description?: string; - last_seen_at?: string; - started_at?: string; - ended_at?: string; - end_reason?: string; -}; -type AiSearchJobLog = { - id: number; - message: string; - message_type: number; - created_at: number; -}; -type AiSearchCreateJobParams = { - description?: string; -}; -type AiSearchListJobsParams = { - page?: number; - per_page?: number; -}; -type AiSearchListJobsResponse = { - result: AiSearchJobInfo[]; - result_info?: { - count: number; - page: number; - per_page: number; - total_count: number; - }; -}; -type AiSearchJobLogsParams = { - page?: number; - per_page?: number; -}; -type AiSearchJobLogsResponse = { - result: AiSearchJobLog[]; - result_info?: { - count: number; - page: number; - per_page: number; - total_count: number; - }; -}; -// ============ AI Search Sub-Service Classes ============ -/** - * Single item service for an AI Search instance. - * Provides info, download, sync, logs, and chunks operations on a specific item. - */ -declare abstract class AiSearchItem { - /** Get metadata about this item. */ - info(): Promise; - /** - * Download the item's content. - * @returns Object with body stream, content type, filename, and size. - */ - download(): Promise; - /** - * Trigger re-indexing of this item. - * @returns The updated item info. - */ - sync(): Promise; - /** - * Retrieve processing logs for this item (cursor-based pagination). - * @param params Optional pagination parameters (limit, cursor). - * @returns Paginated log entries for this item. - */ - logs(params?: AiSearchItemLogsParams): Promise; - /** - * List indexed chunks for this item (offset-based pagination). - * @param params Optional pagination parameters (limit, offset). - * @returns Paginated chunk entries for this item. - */ - chunks(params?: AiSearchItemChunksParams): Promise; -} -/** - * Items collection service for an AI Search instance. - * Provides list, upload, and access to individual items. - */ -declare abstract class AiSearchItems { - /** List items in this instance. */ - list(params?: AiSearchListItemsParams): Promise; - /** - * Upload a file as an item. Behaves as an upsert: if an item with the same - * filename already exists, it is overwritten and re-indexed. - * @param name Filename for the uploaded item. - * @param content File content as a ReadableStream, Blob, or string. - * @param options Optional metadata to attach to the item. - * @returns The created item info. - */ - upload(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions): Promise; - /** - * Upload a file and poll until processing completes. - * Behaves as an upsert: if an item with the same filename already exists, - * it is overwritten and re-indexed. - * @param name Filename for the uploaded item. - * @param content File content as a ReadableStream, Blob, or string. - * @param options Optional metadata and polling configuration. - * @returns The item info after processing completes (or timeout). - */ - uploadAndPoll(name: string, content: ReadableStream | Blob | string, options?: AiSearchUploadItemOptions & { - /** Polling interval in milliseconds (default 1000). */ - pollIntervalMs?: number; - /** Maximum time to wait in milliseconds (default 30000). */ - timeoutMs?: number; - }): Promise; - /** - * Get an item by ID. - * @param itemId The item identifier. - * @returns Item service for info, download, sync, logs, and chunks operations. - */ - get(itemId: string): AiSearchItem; - /** - * Delete an item from the instance. - * @param itemId The item identifier. - */ - delete(itemId: string): Promise; -} -/** - * Single job service for an AI Search instance. - * Provides info, logs, and cancel operations for a specific job. - */ -declare abstract class AiSearchJob { - /** Get metadata about this job. */ - info(): Promise; - /** Get logs for this job. */ - logs(params?: AiSearchJobLogsParams): Promise; - /** - * Cancel a running job. - * @returns The updated job info. - * @throws AiSearchNotFoundError if the job does not exist. - */ - cancel(): Promise; -} -/** - * Jobs collection service for an AI Search instance. - * Provides list, create, and access to individual jobs. - */ -declare abstract class AiSearchJobs { - /** List jobs for this instance. */ - list(params?: AiSearchListJobsParams): Promise; - /** - * Create a new indexing job. - * @param params Optional job parameters. - * @returns The created job info. - */ - create(params?: AiSearchCreateJobParams): Promise; - /** - * Get a job by ID. - * @param jobId The job identifier. - * @returns Job service for info, logs, and cancel operations. - */ - get(jobId: string): AiSearchJob; -} -// ============ AI Search Binding Classes ============ -/** - * Instance-level AI Search service. - * - * Used as: - * - The return type of `AiSearchNamespace.get(name)` (namespace binding) - * - The type of `env.BLOG_SEARCH` (single instance binding via `ai_search`) - * - * Provides search, chat, update, stats, items, and jobs operations. - * - * @example - * ```ts - * // Via namespace binding - * const instance = env.AI_SEARCH.get("blog"); - * const results = await instance.search({ - * query: "How does caching work?", - * }); - * - * // Via single instance binding - * const results = await env.BLOG_SEARCH.search({ - * messages: [{ role: "user", content: "How does caching work?" }], - * }); - * ``` - */ -declare abstract class AiSearchInstance { - /** - * Search the AI Search instance for relevant chunks. - * @param params Search request with query or messages and optional AI search options. - * @returns Search response with matching chunks and search query. - */ - search(params: AiSearchSearchRequest): Promise; - /** - * Generate chat completions with AI Search context (streaming). - * @param params Chat completions request with stream: true. - * @returns ReadableStream of server-sent events. - */ - chatCompletions(params: AiSearchChatCompletionsRequest & { - stream: true; - }): Promise; - /** - * Generate chat completions with AI Search context. - * @param params Chat completions request. - * @returns Chat completion response with choices and RAG chunks. - */ - chatCompletions(params: AiSearchChatCompletionsRequest): Promise; - /** - * Update the instance configuration. - * @param config Partial configuration to update. - * @returns Updated instance info. - */ - update(config: Partial): Promise; - /** Get metadata about this instance. */ - info(): Promise; - /** - * Get instance statistics (item count, indexing status, etc.). - * @returns Statistics with counts per status, last activity time, and engine details. - */ - stats(): Promise; - /** Items collection — list, upload, and manage items in this instance. */ - get items(): AiSearchItems; - /** Jobs collection — list, create, and inspect indexing jobs. */ - get jobs(): AiSearchJobs; -} -/** - * Namespace-level AI Search service. - * - * Used as the type of `env.AI_SEARCH` (namespace binding via `ai_search_namespaces`). - * Scoped to a single namespace. Provides dynamic instance access, creation, deletion, - * and multi-instance search/chat operations. - * - * @example - * ```ts - * // Access an instance within the namespace - * const blog = env.AI_SEARCH.get("blog"); - * const results = await blog.search({ query: "How does caching work?" }); - * - * // List all instances in the namespace - * const instances = await env.AI_SEARCH.list(); - * - * // Create a new instance with built-in storage - * const tenant = await env.AI_SEARCH.create({ id: "tenant-123" }); - * - * // Upload items into the instance - * await tenant.items.upload("doc.pdf", fileContent); - * - * // Search across multiple instances - * const multi = await env.AI_SEARCH.search({ - * query: "caching", - * ai_search_options: { instance_ids: ["blog", "docs"] }, - * }); - * - * // Delete an instance - * await env.AI_SEARCH.delete("tenant-123"); - * ``` - */ -declare abstract class AiSearchNamespace { - /** - * Get an instance by name within the bound namespace. - * @param name Instance name. - * @returns Instance service for search, chat, update, stats, items, and jobs. - */ - get(name: string): AiSearchInstance; - /** - * List instances in the bound namespace. - * @param params Optional pagination, search, and ordering parameters. - * @returns Array of instance metadata with pagination info. - */ - list(params?: AiSearchListInstancesParams): Promise; - /** - * Create a new instance within the bound namespace. - * @param config Instance configuration. Only `id` is required — omit `type` and `source` to create with built-in storage. - * @returns Instance service for the newly created instance. - * - * @example - * ```ts - * // Create with built-in storage (upload items manually) - * const instance = await env.AI_SEARCH.create({ id: "my-search" }); - * - * // Create with web crawler source - * const instance = await env.AI_SEARCH.create({ - * id: "docs-search", - * type: "web-crawler", - * source: "https://developers.cloudflare.com", - * }); - * ``` - */ - create(config: AiSearchConfig): Promise; - /** - * Delete an instance from the bound namespace. - * @param name Instance name to delete. - */ - delete(name: string): Promise; - /** - * Search across multiple instances within the bound namespace. - * Fans out to the specified instance_ids and merges results. - * @param params Search request with required `ai_search_options.instance_ids`. - * @returns Search response with chunks tagged by instance_id and optional partial-failure errors. - */ - search(params: AiSearchMultiSearchRequest): Promise; - /** - * Generate chat completions across multiple instances within the bound namespace (streaming). - * Fans out to the specified instance_ids, merges context, and generates a response. - * @param params Chat completions request with stream: true and required `ai_search_options.instance_ids`. - * @returns ReadableStream of server-sent events. - */ - chatCompletions(params: AiSearchMultiChatCompletionsRequest & { - stream: true; - }): Promise; - /** - * Generate chat completions across multiple instances within the bound namespace. - * Fans out to the specified instance_ids, merges context, and generates a response. - * @param params Chat completions request with required `ai_search_options.instance_ids`. - * @returns Chat completion response with choices, chunks tagged by instance_id, and optional partial-failure errors. - */ - chatCompletions(params: AiSearchMultiChatCompletionsRequest): Promise; -} -type AiImageClassificationInput = { - image: number[]; -}; -type AiImageClassificationOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiImageClassification { - inputs: AiImageClassificationInput; - postProcessedOutputs: AiImageClassificationOutput; -} -type AiImageToTextInput = { - image: number[]; - prompt?: string; - max_tokens?: number; - temperature?: number; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - raw?: boolean; - messages?: RoleScopedChatInput[]; -}; -type AiImageToTextOutput = { - description: string; -}; -declare abstract class BaseAiImageToText { - inputs: AiImageToTextInput; - postProcessedOutputs: AiImageToTextOutput; -} -type AiImageTextToTextInput = { - image: string; - prompt?: string; - max_tokens?: number; - temperature?: number; - ignore_eos?: boolean; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - raw?: boolean; - messages?: RoleScopedChatInput[]; -}; -type AiImageTextToTextOutput = { - description: string; -}; -declare abstract class BaseAiImageTextToText { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; -} -type AiMultimodalEmbeddingsInput = { - image: string; - text: string[]; -}; -type AiIMultimodalEmbeddingsOutput = { - data: number[][]; - shape: number[]; -}; -declare abstract class BaseAiMultimodalEmbeddings { - inputs: AiImageTextToTextInput; - postProcessedOutputs: AiImageTextToTextOutput; -} -type AiObjectDetectionInput = { - image: number[]; -}; -type AiObjectDetectionOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiObjectDetection { - inputs: AiObjectDetectionInput; - postProcessedOutputs: AiObjectDetectionOutput; -} -type AiSentenceSimilarityInput = { - source: string; - sentences: string[]; -}; -type AiSentenceSimilarityOutput = number[]; -declare abstract class BaseAiSentenceSimilarity { - inputs: AiSentenceSimilarityInput; - postProcessedOutputs: AiSentenceSimilarityOutput; -} -type AiAutomaticSpeechRecognitionInput = { - audio: number[]; -}; -type AiAutomaticSpeechRecognitionOutput = { - text?: string; - words?: { - word: string; - start: number; - end: number; - }[]; - vtt?: string; -}; -declare abstract class BaseAiAutomaticSpeechRecognition { - inputs: AiAutomaticSpeechRecognitionInput; - postProcessedOutputs: AiAutomaticSpeechRecognitionOutput; -} -type AiSummarizationInput = { - input_text: string; - max_length?: number; -}; -type AiSummarizationOutput = { - summary: string; -}; -declare abstract class BaseAiSummarization { - inputs: AiSummarizationInput; - postProcessedOutputs: AiSummarizationOutput; -} -type AiTextClassificationInput = { - text: string; -}; -type AiTextClassificationOutput = { - score?: number; - label?: string; -}[]; -declare abstract class BaseAiTextClassification { - inputs: AiTextClassificationInput; - postProcessedOutputs: AiTextClassificationOutput; -} -type AiTextEmbeddingsInput = { - text: string | string[]; -}; -type AiTextEmbeddingsOutput = { - shape: number[]; - data: number[][]; -}; -declare abstract class BaseAiTextEmbeddings { - inputs: AiTextEmbeddingsInput; - postProcessedOutputs: AiTextEmbeddingsOutput; -} -type RoleScopedChatInput = { - role: "user" | "assistant" | "system" | "tool" | (string & NonNullable); - content: string; - name?: string; -}; -type AiTextGenerationToolLegacyInput = { - name: string; - description: string; - parameters?: { - type: "object" | (string & NonNullable); - properties: { - [key: string]: { - type: string; - description?: string; - }; - }; - required: string[]; - }; -}; -type AiTextGenerationToolInput = { - type: "function" | (string & NonNullable); - function: { - name: string; - description: string; - parameters?: { - type: "object" | (string & NonNullable); - properties: { - [key: string]: { - type: string; - description?: string; - }; - }; - required: string[]; - }; - }; -}; -type AiTextGenerationFunctionsInput = { - name: string; - code: string; -}; -type AiTextGenerationResponseFormat = { - type: string; - json_schema?: any; -}; -type AiTextGenerationInput = { - prompt?: string; - raw?: boolean; - stream?: boolean; - max_tokens?: number; - temperature?: number; - top_p?: number; - top_k?: number; - seed?: number; - repetition_penalty?: number; - frequency_penalty?: number; - presence_penalty?: number; - messages?: RoleScopedChatInput[]; - response_format?: AiTextGenerationResponseFormat; - tools?: AiTextGenerationToolInput[] | AiTextGenerationToolLegacyInput[] | (object & NonNullable); - functions?: AiTextGenerationFunctionsInput[]; -}; -type AiTextGenerationToolLegacyOutput = { - name: string; - arguments: unknown; -}; -type AiTextGenerationToolOutput = { - id: string; - type: "function"; - function: { - name: string; - arguments: string; - }; -}; -type UsageTags = { - prompt_tokens: number; - completion_tokens: number; - total_tokens: number; -}; -type AiTextGenerationOutput = { - response?: string; - tool_calls?: AiTextGenerationToolLegacyOutput[] & AiTextGenerationToolOutput[]; - usage?: UsageTags; -}; -declare abstract class BaseAiTextGeneration { - inputs: AiTextGenerationInput; - postProcessedOutputs: AiTextGenerationOutput; -} -type AiTextToSpeechInput = { - prompt: string; - lang?: string; -}; -type AiTextToSpeechOutput = Uint8Array | { - audio: string; -}; -declare abstract class BaseAiTextToSpeech { - inputs: AiTextToSpeechInput; - postProcessedOutputs: AiTextToSpeechOutput; -} -type AiTextToImageInput = { - prompt: string; - negative_prompt?: string; - height?: number; - width?: number; - image?: number[]; - image_b64?: string; - mask?: number[]; - num_steps?: number; - strength?: number; - guidance?: number; - seed?: number; -}; -type AiTextToImageOutput = ReadableStream; -declare abstract class BaseAiTextToImage { - inputs: AiTextToImageInput; - postProcessedOutputs: AiTextToImageOutput; -} -type AiTranslationInput = { - text: string; - target_lang: string; - source_lang?: string; -}; -type AiTranslationOutput = { - translated_text?: string; -}; -declare abstract class BaseAiTranslation { - inputs: AiTranslationInput; - postProcessedOutputs: AiTranslationOutput; -} -/** - * Workers AI support for OpenAI's Chat Completions API - */ -type ChatCompletionContentPartText = { - type: "text"; - text: string; -}; -type ChatCompletionContentPartImage = { - type: "image_url"; - image_url: { - url: string; - detail?: "auto" | "low" | "high"; - }; -}; -type ChatCompletionContentPartInputAudio = { - type: "input_audio"; - input_audio: { - /** Base64 encoded audio data. */ - data: string; - format: "wav" | "mp3"; - }; -}; -type ChatCompletionContentPartFile = { - type: "file"; - file: { - /** Base64 encoded file data. */ - file_data?: string; - /** The ID of an uploaded file. */ - file_id?: string; - filename?: string; - }; -}; -type ChatCompletionContentPartRefusal = { - type: "refusal"; - refusal: string; -}; -type ChatCompletionContentPart = ChatCompletionContentPartText | ChatCompletionContentPartImage | ChatCompletionContentPartInputAudio | ChatCompletionContentPartFile; -type FunctionDefinition = { - name: string; - description?: string; - parameters?: Record; - strict?: boolean | null; -}; -type ChatCompletionFunctionTool = { - type: "function"; - function: FunctionDefinition; -}; -type ChatCompletionCustomToolGrammarFormat = { - type: "grammar"; - grammar: { - definition: string; - syntax: "lark" | "regex"; - }; -}; -type ChatCompletionCustomToolTextFormat = { - type: "text"; -}; -type ChatCompletionCustomToolFormat = ChatCompletionCustomToolTextFormat | ChatCompletionCustomToolGrammarFormat; -type ChatCompletionCustomTool = { - type: "custom"; - custom: { - name: string; - description?: string; - format?: ChatCompletionCustomToolFormat; - }; -}; -type ChatCompletionTool = ChatCompletionFunctionTool | ChatCompletionCustomTool; -type ChatCompletionMessageFunctionToolCall = { - id: string; - type: "function"; - function: { - name: string; - /** JSON-encoded arguments string. */ - arguments: string; - }; -}; -type ChatCompletionMessageCustomToolCall = { - id: string; - type: "custom"; - custom: { - name: string; - input: string; - }; -}; -type ChatCompletionMessageToolCall = ChatCompletionMessageFunctionToolCall | ChatCompletionMessageCustomToolCall; -type ChatCompletionToolChoiceFunction = { - type: "function"; - function: { - name: string; - }; -}; -type ChatCompletionToolChoiceCustom = { - type: "custom"; - custom: { - name: string; - }; -}; -type ChatCompletionToolChoiceAllowedTools = { - type: "allowed_tools"; - allowed_tools: { - mode: "auto" | "required"; - tools: Array>; - }; -}; -type ChatCompletionToolChoiceOption = "none" | "auto" | "required" | ChatCompletionToolChoiceFunction | ChatCompletionToolChoiceCustom | ChatCompletionToolChoiceAllowedTools; -type DeveloperMessage = { - role: "developer"; - content: string | Array<{ - type: "text"; - text: string; - }>; - name?: string; -}; -type SystemMessage = { - role: "system"; - content: string | Array<{ - type: "text"; - text: string; - }>; - name?: string; -}; -/** - * Permissive merged content part used inside UserMessage arrays. - * - * Cabidela has a limitation where anyOf/oneOf with enum-based discrimination - * inside nested array items does not correctly match different branches for - * different array elements, so the schema uses a single merged object. - */ -type UserMessageContentPart = { - type: "text" | "image_url" | "input_audio" | "file"; - text?: string; - image_url?: { - url?: string; - detail?: "auto" | "low" | "high"; - }; - input_audio?: { - data?: string; - format?: "wav" | "mp3"; - }; - file?: { - file_data?: string; - file_id?: string; - filename?: string; - }; -}; -type UserMessage = { - role: "user"; - content: string | Array; - name?: string; -}; -type AssistantMessageContentPart = { - type: "text" | "refusal"; - text?: string; - refusal?: string; -}; -type AssistantMessage = { - role: "assistant"; - content?: string | null | Array; - refusal?: string | null; - name?: string; - audio?: { - id: string; - }; - tool_calls?: Array; - function_call?: { - name: string; - arguments: string; - }; -}; -type ToolMessage = { - role: "tool"; - content: string | Array<{ - type: "text"; - text: string; - }>; - tool_call_id: string; -}; -type FunctionMessage = { - role: "function"; - content: string; - name: string; -}; -type ChatCompletionMessageParam = DeveloperMessage | SystemMessage | UserMessage | AssistantMessage | ToolMessage | FunctionMessage; -type ChatCompletionsResponseFormatText = { - type: "text"; -}; -type ChatCompletionsResponseFormatJSONObject = { - type: "json_object"; -}; -type ResponseFormatJSONSchema = { - type: "json_schema"; - json_schema: { - name: string; - description?: string; - schema?: Record; - strict?: boolean | null; - }; -}; -type ResponseFormat = ChatCompletionsResponseFormatText | ChatCompletionsResponseFormatJSONObject | ResponseFormatJSONSchema; -type ChatCompletionsStreamOptions = { - include_usage?: boolean; - include_obfuscation?: boolean; -}; -type PredictionContent = { - type: "content"; - content: string | Array<{ - type: "text"; - text: string; - }>; -}; -type AudioParams = { - voice: string | { - id: string; - }; - format: "wav" | "aac" | "mp3" | "flac" | "opus" | "pcm16"; -}; -type WebSearchUserLocation = { - type: "approximate"; - approximate: { - city?: string; - country?: string; - region?: string; - timezone?: string; - }; -}; -type WebSearchOptions = { - search_context_size?: "low" | "medium" | "high"; - user_location?: WebSearchUserLocation; -}; -type ChatTemplateKwargs = { - /** Whether to enable reasoning, enabled by default. */ - enable_thinking?: boolean; - /** If false, preserves reasoning context between turns. */ - clear_thinking?: boolean; -}; -/** Shared optional properties used by both Prompt and Messages input branches. */ -type ChatCompletionsCommonOptions = { - model?: string; - audio?: AudioParams; - frequency_penalty?: number | null; - logit_bias?: Record | null; - logprobs?: boolean | null; - top_logprobs?: number | null; - max_tokens?: number | null; - max_completion_tokens?: number | null; - metadata?: Record | null; - modalities?: Array<"text" | "audio"> | null; - n?: number | null; - parallel_tool_calls?: boolean; - prediction?: PredictionContent; - presence_penalty?: number | null; - reasoning_effort?: "low" | "medium" | "high" | null; - chat_template_kwargs?: ChatTemplateKwargs; - response_format?: ResponseFormat; - seed?: number | null; - service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; - stop?: string | Array | null; - store?: boolean | null; - stream?: boolean | null; - stream_options?: ChatCompletionsStreamOptions; - temperature?: number | null; - tool_choice?: ChatCompletionToolChoiceOption; - tools?: Array; - top_p?: number | null; - user?: string; - web_search_options?: WebSearchOptions; - function_call?: "none" | "auto" | { - name: string; - }; - functions?: Array; -}; -type PromptTokensDetails = { - cached_tokens?: number; - audio_tokens?: number; -}; -type CompletionTokensDetails = { - reasoning_tokens?: number; - audio_tokens?: number; - accepted_prediction_tokens?: number; - rejected_prediction_tokens?: number; -}; -type CompletionUsage = { - prompt_tokens: number; - completion_tokens: number; - total_tokens: number; - prompt_tokens_details?: PromptTokensDetails; - completion_tokens_details?: CompletionTokensDetails; -}; -type ChatCompletionTopLogprob = { - token: string; - logprob: number; - bytes: Array | null; -}; -type ChatCompletionTokenLogprob = { - token: string; - logprob: number; - bytes: Array | null; - top_logprobs: Array; -}; -type ChatCompletionAudio = { - id: string; - /** Base64 encoded audio bytes. */ - data: string; - expires_at: number; - transcript: string; -}; -type ChatCompletionUrlCitation = { - type: "url_citation"; - url_citation: { - url: string; - title: string; - start_index: number; - end_index: number; - }; -}; -type ChatCompletionResponseMessage = { - role: "assistant"; - content: string | null; - refusal: string | null; - annotations?: Array; - audio?: ChatCompletionAudio; - tool_calls?: Array; - function_call?: { - name: string; - arguments: string; - } | null; -}; -type ChatCompletionLogprobs = { - content: Array | null; - refusal?: Array | null; -}; -type ChatCompletionChoice = { - index: number; - message: ChatCompletionResponseMessage; - finish_reason: "stop" | "length" | "tool_calls" | "content_filter" | "function_call"; - logprobs: ChatCompletionLogprobs | null; -}; -type ChatCompletionsPromptInput = { - prompt: string; -} & ChatCompletionsCommonOptions; -type ChatCompletionsMessagesInput = { - messages: Array; -} & ChatCompletionsCommonOptions; -type ChatCompletionsOutput = { - id: string; - object: string; - created: number; - model: string; - choices: Array; - usage?: CompletionUsage; - system_fingerprint?: string | null; - service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; -}; -/** - * Workers AI support for OpenAI's Responses API - * Reference: https://github.com/openai/openai-node/blob/master/src/resources/responses/responses.ts - * - * It's a stripped down version from its source. - * It currently supports basic function calling, json mode and accepts images as input. - * - * It does not include types for WebSearch, CodeInterpreter, FileInputs, MCP, CustomTools. - * We plan to add those incrementally as model + platform capabilities evolve. - */ -type ResponsesInput = { - background?: boolean | null; - conversation?: string | ResponseConversationParam | null; - include?: Array | null; - input?: string | ResponseInput; - instructions?: string | null; - max_output_tokens?: number | null; - parallel_tool_calls?: boolean | null; - previous_response_id?: string | null; - prompt_cache_key?: string; - reasoning?: Reasoning | null; - safety_identifier?: string; - service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; - stream?: boolean | null; - stream_options?: StreamOptions | null; - temperature?: number | null; - text?: ResponseTextConfig; - tool_choice?: ToolChoiceOptions | ToolChoiceFunction; - tools?: Array; - top_p?: number | null; - truncation?: "auto" | "disabled" | null; -}; -type ResponsesOutput = { - id?: string; - created_at?: number; - output_text?: string; - error?: ResponseError | null; - incomplete_details?: ResponseIncompleteDetails | null; - instructions?: string | Array | null; - object?: "response"; - output?: Array; - parallel_tool_calls?: boolean; - temperature?: number | null; - tool_choice?: ToolChoiceOptions | ToolChoiceFunction; - tools?: Array; - top_p?: number | null; - max_output_tokens?: number | null; - previous_response_id?: string | null; - prompt?: ResponsePrompt | null; - reasoning?: Reasoning | null; - safety_identifier?: string; - service_tier?: "auto" | "default" | "flex" | "scale" | "priority" | null; - status?: ResponseStatus; - text?: ResponseTextConfig; - truncation?: "auto" | "disabled" | null; - usage?: ResponseUsage; -}; -type EasyInputMessage = { - content: string | ResponseInputMessageContentList; - role: "user" | "assistant" | "system" | "developer"; - type?: "message"; -}; -type ResponsesFunctionTool = { - name: string; - parameters: { - [key: string]: unknown; - } | null; - strict: boolean | null; - type: "function"; - description?: string | null; -}; -type ResponseIncompleteDetails = { - reason?: "max_output_tokens" | "content_filter"; -}; -type ResponsePrompt = { - id: string; - variables?: { - [key: string]: string | ResponseInputText | ResponseInputImage; - } | null; - version?: string | null; -}; -type Reasoning = { - effort?: ReasoningEffort | null; - generate_summary?: "auto" | "concise" | "detailed" | null; - summary?: "auto" | "concise" | "detailed" | null; -}; -type ResponseContent = ResponseInputText | ResponseInputImage | ResponseOutputText | ResponseOutputRefusal | ResponseContentReasoningText; -type ResponseContentReasoningText = { - text: string; - type: "reasoning_text"; -}; -type ResponseConversationParam = { - id: string; -}; -type ResponseCreatedEvent = { - response: Response; - sequence_number: number; - type: "response.created"; -}; -type ResponseCustomToolCallOutput = { - call_id: string; - output: string | Array; - type: "custom_tool_call_output"; - id?: string; -}; -type ResponseError = { - code: "server_error" | "rate_limit_exceeded" | "invalid_prompt" | "vector_store_timeout" | "invalid_image" | "invalid_image_format" | "invalid_base64_image" | "invalid_image_url" | "image_too_large" | "image_too_small" | "image_parse_error" | "image_content_policy_violation" | "invalid_image_mode" | "image_file_too_large" | "unsupported_image_media_type" | "empty_image_file" | "failed_to_download_image" | "image_file_not_found"; - message: string; -}; -type ResponseErrorEvent = { - code: string | null; - message: string; - param: string | null; - sequence_number: number; - type: "error"; -}; -type ResponseFailedEvent = { - response: Response; - sequence_number: number; - type: "response.failed"; -}; -type ResponseFormatText = { - type: "text"; -}; -type ResponseFormatJSONObject = { - type: "json_object"; -}; -type ResponseFormatTextConfig = ResponseFormatText | ResponseFormatTextJSONSchemaConfig | ResponseFormatJSONObject; -type ResponseFormatTextJSONSchemaConfig = { - name: string; - schema: { - [key: string]: unknown; - }; - type: "json_schema"; - description?: string; - strict?: boolean | null; -}; -type ResponseFunctionCallArgumentsDeltaEvent = { - delta: string; - item_id: string; - output_index: number; - sequence_number: number; - type: "response.function_call_arguments.delta"; -}; -type ResponseFunctionCallArgumentsDoneEvent = { - arguments: string; - item_id: string; - name: string; - output_index: number; - sequence_number: number; - type: "response.function_call_arguments.done"; -}; -type ResponseFunctionCallOutputItem = ResponseInputTextContent | ResponseInputImageContent; -type ResponseFunctionCallOutputItemList = Array; -type ResponseFunctionToolCall = { - arguments: string; - call_id: string; - name: string; - type: "function_call"; - id?: string; - status?: "in_progress" | "completed" | "incomplete"; -}; -interface ResponseFunctionToolCallItem extends ResponseFunctionToolCall { - id: string; -} -type ResponseFunctionToolCallOutputItem = { - id: string; - call_id: string; - output: string | Array; - type: "function_call_output"; - status?: "in_progress" | "completed" | "incomplete"; -}; -type ResponseIncludable = "message.input_image.image_url" | "message.output_text.logprobs"; -type ResponseIncompleteEvent = { - response: Response; - sequence_number: number; - type: "response.incomplete"; -}; -type ResponseInput = Array; -type ResponseInputContent = ResponseInputText | ResponseInputImage; -type ResponseInputImage = { - detail: "low" | "high" | "auto"; - type: "input_image"; - /** - * Base64 encoded image - */ - image_url?: string | null; -}; -type ResponseInputImageContent = { - type: "input_image"; - detail?: "low" | "high" | "auto" | null; - /** - * Base64 encoded image - */ - image_url?: string | null; -}; -type ResponseInputItem = EasyInputMessage | ResponseInputItemMessage | ResponseOutputMessage | ResponseFunctionToolCall | ResponseInputItemFunctionCallOutput | ResponseReasoningItem; -type ResponseInputItemFunctionCallOutput = { - call_id: string; - output: string | ResponseFunctionCallOutputItemList; - type: "function_call_output"; - id?: string | null; - status?: "in_progress" | "completed" | "incomplete" | null; -}; -type ResponseInputItemMessage = { - content: ResponseInputMessageContentList; - role: "user" | "system" | "developer"; - status?: "in_progress" | "completed" | "incomplete"; - type?: "message"; -}; -type ResponseInputMessageContentList = Array; -type ResponseInputMessageItem = { - id: string; - content: ResponseInputMessageContentList; - role: "user" | "system" | "developer"; - status?: "in_progress" | "completed" | "incomplete"; - type?: "message"; -}; -type ResponseInputText = { - text: string; - type: "input_text"; -}; -type ResponseInputTextContent = { - text: string; - type: "input_text"; -}; -type ResponseItem = ResponseInputMessageItem | ResponseOutputMessage | ResponseFunctionToolCallItem | ResponseFunctionToolCallOutputItem; -type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | ResponseReasoningItem; -type ResponseOutputItemAddedEvent = { - item: ResponseOutputItem; - output_index: number; - sequence_number: number; - type: "response.output_item.added"; -}; -type ResponseOutputItemDoneEvent = { - item: ResponseOutputItem; - output_index: number; - sequence_number: number; - type: "response.output_item.done"; -}; -type ResponseOutputMessage = { - id: string; - content: Array; - role: "assistant"; - status: "in_progress" | "completed" | "incomplete"; - type: "message"; -}; -type ResponseOutputRefusal = { - refusal: string; - type: "refusal"; -}; -type ResponseOutputText = { - text: string; - type: "output_text"; - logprobs?: Array; -}; -type ResponseReasoningItem = { - id: string; - summary: Array; - type: "reasoning"; - content?: Array; - encrypted_content?: string | null; - status?: "in_progress" | "completed" | "incomplete"; -}; -type ResponseReasoningSummaryItem = { - text: string; - type: "summary_text"; -}; -type ResponseReasoningContentItem = { - text: string; - type: "reasoning_text"; -}; -type ResponseReasoningTextDeltaEvent = { - content_index: number; - delta: string; - item_id: string; - output_index: number; - sequence_number: number; - type: "response.reasoning_text.delta"; -}; -type ResponseReasoningTextDoneEvent = { - content_index: number; - item_id: string; - output_index: number; - sequence_number: number; - text: string; - type: "response.reasoning_text.done"; -}; -type ResponseRefusalDeltaEvent = { - content_index: number; - delta: string; - item_id: string; - output_index: number; - sequence_number: number; - type: "response.refusal.delta"; -}; -type ResponseRefusalDoneEvent = { - content_index: number; - item_id: string; - output_index: number; - refusal: string; - sequence_number: number; - type: "response.refusal.done"; -}; -type ResponseStatus = "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete"; -type ResponseStreamEvent = ResponseCompletedEvent | ResponseCreatedEvent | ResponseErrorEvent | ResponseFunctionCallArgumentsDeltaEvent | ResponseFunctionCallArgumentsDoneEvent | ResponseFailedEvent | ResponseIncompleteEvent | ResponseOutputItemAddedEvent | ResponseOutputItemDoneEvent | ResponseReasoningTextDeltaEvent | ResponseReasoningTextDoneEvent | ResponseRefusalDeltaEvent | ResponseRefusalDoneEvent | ResponseTextDeltaEvent | ResponseTextDoneEvent; -type ResponseCompletedEvent = { - response: Response; - sequence_number: number; - type: "response.completed"; -}; -type ResponseTextConfig = { - format?: ResponseFormatTextConfig; - verbosity?: "low" | "medium" | "high" | null; -}; -type ResponseTextDeltaEvent = { - content_index: number; - delta: string; - item_id: string; - logprobs: Array; - output_index: number; - sequence_number: number; - type: "response.output_text.delta"; -}; -type ResponseTextDoneEvent = { - content_index: number; - item_id: string; - logprobs: Array; - output_index: number; - sequence_number: number; - text: string; - type: "response.output_text.done"; -}; -type Logprob = { - token: string; - logprob: number; - top_logprobs?: Array; -}; -type TopLogprob = { - token?: string; - logprob?: number; -}; -type ResponseUsage = { - input_tokens: number; - output_tokens: number; - total_tokens: number; -}; -type Tool = ResponsesFunctionTool; -type ToolChoiceFunction = { - name: string; - type: "function"; -}; -type ToolChoiceOptions = "none"; -type ReasoningEffort = "minimal" | "low" | "medium" | "high" | null; -type StreamOptions = { - include_obfuscation?: boolean; -}; -/** Marks keys from T that aren't in U as optional never */ -type Without = { - [P in Exclude]?: never; -}; -/** Either T or U, but not both (mutually exclusive) */ -type XOR = (T & Without) | (U & Without); -type Ai_Cf_Baai_Bge_Base_En_V1_5_Input = { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; -} | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; - }[]; -}; -type Ai_Cf_Baai_Bge_Base_En_V1_5_Output = { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} | Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse; -interface Ai_Cf_Baai_Bge_Base_En_V1_5_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Baai_Bge_Base_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Base_En_V1_5_Output; -} -type Ai_Cf_Openai_Whisper_Input = string | { - /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values - */ - audio: number[]; -}; -interface Ai_Cf_Openai_Whisper_Output { - /** - * The transcription - */ - text: string; - word_count?: number; - words?: { - word?: string; - /** - * The second this word begins in the recording - */ - start?: number; - /** - * The ending second when the word completes - */ - end?: number; - }[]; - vtt?: string; -} -declare abstract class Base_Ai_Cf_Openai_Whisper { - inputs: Ai_Cf_Openai_Whisper_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Output; -} -type Ai_Cf_Meta_M2M100_1_2B_Input = { - /** - * The text to be translated - */ - text: string; - /** - * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified - */ - source_lang?: string; - /** - * The language code to translate the text into (e.g., 'es' for Spanish) - */ - target_lang: string; -} | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - /** - * The text to be translated - */ - text: string; - /** - * The language code of the source text (e.g., 'en' for English). Defaults to 'en' if not specified - */ - source_lang?: string; - /** - * The language code to translate the text into (e.g., 'es' for Spanish) - */ - target_lang: string; - }[]; -}; -type Ai_Cf_Meta_M2M100_1_2B_Output = { - /** - * The translated text in the target language - */ - translated_text?: string; -} | Ai_Cf_Meta_M2M100_1_2B_AsyncResponse; -interface Ai_Cf_Meta_M2M100_1_2B_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Meta_M2M100_1_2B { - inputs: Ai_Cf_Meta_M2M100_1_2B_Input; - postProcessedOutputs: Ai_Cf_Meta_M2M100_1_2B_Output; -} -type Ai_Cf_Baai_Bge_Small_En_V1_5_Input = { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; -} | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; - }[]; -}; -type Ai_Cf_Baai_Bge_Small_En_V1_5_Output = { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} | Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse; -interface Ai_Cf_Baai_Bge_Small_En_V1_5_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Baai_Bge_Small_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Small_En_V1_5_Output; -} -type Ai_Cf_Baai_Bge_Large_En_V1_5_Input = { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; -} | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: { - text: string | string[]; - /** - * The pooling method used in the embedding process. `cls` pooling will generate more accurate embeddings on larger inputs - however, embeddings created with cls pooling are not compatible with embeddings generated with mean pooling. The default pooling method is `mean` in order for this to not be a breaking change, but we highly suggest using the new `cls` pooling for better accuracy. - */ - pooling?: "mean" | "cls"; - }[]; -}; -type Ai_Cf_Baai_Bge_Large_En_V1_5_Output = { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} | Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse; -interface Ai_Cf_Baai_Bge_Large_En_V1_5_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Baai_Bge_Large_En_V1_5 { - inputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Large_En_V1_5_Output; -} -type Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input = string | { - /** - * The input text prompt for the model to generate a response. - */ - prompt?: string; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; - image: number[] | (string & NonNullable); - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; -}; -interface Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output { - description?: string; -} -declare abstract class Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M { - inputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Input; - postProcessedOutputs: Ai_Cf_Unum_Uform_Gen2_Qwen_500M_Output; -} -type Ai_Cf_Openai_Whisper_Tiny_En_Input = string | { - /** - * An array of integers that represent the audio data constrained to 8-bit unsigned integer values - */ - audio: number[]; -}; -interface Ai_Cf_Openai_Whisper_Tiny_En_Output { - /** - * The transcription - */ - text: string; - word_count?: number; - words?: { - word?: string; - /** - * The second this word begins in the recording - */ - start?: number; - /** - * The ending second when the word completes - */ - end?: number; - }[]; - vtt?: string; -} -declare abstract class Base_Ai_Cf_Openai_Whisper_Tiny_En { - inputs: Ai_Cf_Openai_Whisper_Tiny_En_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Tiny_En_Output; -} -interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input { - audio: string | { - body?: object; - contentType?: string; - }; - /** - * Supported tasks are 'translate' or 'transcribe'. - */ - task?: string; - /** - * The language of the audio being transcribed or translated. - */ - language?: string; - /** - * Preprocess the audio with a voice activity detection model. - */ - vad_filter?: boolean; - /** - * A text prompt to help provide context to the model on the contents of the audio. - */ - initial_prompt?: string; - /** - * The prefix appended to the beginning of the output of the transcription and can guide the transcription result. - */ - prefix?: string; - /** - * The number of beams to use in beam search decoding. Higher values may improve accuracy at the cost of speed. - */ - beam_size?: number; - /** - * Whether to condition on previous text during transcription. Setting to false may help prevent hallucination loops. - */ - condition_on_previous_text?: boolean; - /** - * Threshold for detecting no-speech segments. Segments with no-speech probability above this value are skipped. - */ - no_speech_threshold?: number; - /** - * Threshold for filtering out segments with high compression ratio, which often indicate repetitive or hallucinated text. - */ - compression_ratio_threshold?: number; - /** - * Threshold for filtering out segments with low average log probability, indicating low confidence. - */ - log_prob_threshold?: number; - /** - * Optional threshold (in seconds) to skip silent periods that may cause hallucinations. - */ - hallucination_silence_threshold?: number; -} -interface Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output { - transcription_info?: { - /** - * The language of the audio being transcribed or translated. - */ - language?: string; - /** - * The confidence level or probability of the detected language being accurate, represented as a decimal between 0 and 1. - */ - language_probability?: number; - /** - * The total duration of the original audio file, in seconds. - */ - duration?: number; - /** - * The duration of the audio after applying Voice Activity Detection (VAD) to remove silent or irrelevant sections, in seconds. - */ - duration_after_vad?: number; - }; - /** - * The complete transcription of the audio. - */ - text: string; - /** - * The total number of words in the transcription. - */ - word_count?: number; - segments?: { - /** - * The starting time of the segment within the audio, in seconds. - */ - start?: number; - /** - * The ending time of the segment within the audio, in seconds. - */ - end?: number; - /** - * The transcription of the segment. - */ - text?: string; - /** - * The temperature used in the decoding process, controlling randomness in predictions. Lower values result in more deterministic outputs. - */ - temperature?: number; - /** - * The average log probability of the predictions for the words in this segment, indicating overall confidence. - */ - avg_logprob?: number; - /** - * The compression ratio of the input to the output, measuring how much the text was compressed during the transcription process. - */ - compression_ratio?: number; - /** - * The probability that the segment contains no speech, represented as a decimal between 0 and 1. - */ - no_speech_prob?: number; - words?: { - /** - * The individual word transcribed from the audio. - */ - word?: string; - /** - * The starting time of the word within the audio, in seconds. - */ - start?: number; - /** - * The ending time of the word within the audio, in seconds. - */ - end?: number; - }[]; - }[]; - /** - * The transcription in WebVTT format, which includes timing and text information for use in subtitles. - */ - vtt?: string; -} -declare abstract class Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo { - inputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Input; - postProcessedOutputs: Ai_Cf_Openai_Whisper_Large_V3_Turbo_Output; -} -type Ai_Cf_Baai_Bge_M3_Input = Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts | Ai_Cf_Baai_Bge_M3_Input_Embedding | { - /** - * Batch of the embeddings requests to run using async-queue - */ - requests: (Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 | Ai_Cf_Baai_Bge_M3_Input_Embedding_1)[]; -}; -interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts { - /** - * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts - */ - query?: string; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -interface Ai_Cf_Baai_Bge_M3_Input_Embedding { - text: string | string[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -interface Ai_Cf_Baai_Bge_M3_Input_QueryAnd_Contexts_1 { - /** - * A query you wish to perform against the provided contexts. If no query is provided the model with respond with embeddings for contexts - */ - query?: string; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -interface Ai_Cf_Baai_Bge_M3_Input_Embedding_1 { - text: string | string[]; - /** - * When provided with too long context should the model error out or truncate the context to fit? - */ - truncate_inputs?: boolean; -} -type Ai_Cf_Baai_Bge_M3_Output = Ai_Cf_Baai_Bge_M3_Output_Query | Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts | Ai_Cf_Baai_Bge_M3_Output_Embedding | Ai_Cf_Baai_Bge_M3_AsyncResponse; -interface Ai_Cf_Baai_Bge_M3_Output_Query { - response?: { - /** - * Index of the context in the request - */ - id?: number; - /** - * Score of the context under the index. - */ - score?: number; - }[]; -} -interface Ai_Cf_Baai_Bge_M3_Output_EmbeddingFor_Contexts { - response?: number[][]; - shape?: number[]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} -interface Ai_Cf_Baai_Bge_M3_Output_Embedding { - shape?: number[]; - /** - * Embeddings of the requested text values - */ - data?: number[][]; - /** - * The pooling method used in the embedding process. - */ - pooling?: "mean" | "cls"; -} -interface Ai_Cf_Baai_Bge_M3_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Baai_Bge_M3 { - inputs: Ai_Cf_Baai_Bge_M3_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_M3_Output; -} -interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * The number of diffusion steps; higher values can improve quality but take longer. - */ - steps?: number; -} -interface Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output { - /** - * The generated image in Base64 format. - */ - image?: string; -} -declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell { - inputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Input; - postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_1_Schnell_Output; -} -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input = Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt | Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages; -interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - image?: number[] | (string & NonNullable); - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; -} -interface Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - image?: number[] | (string & NonNullable); - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - /** - * If true, the response will be streamed back incrementally. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Controls the creativity of the AI's responses by adjusting how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output = { - /** - * The generated text response from the model - */ - response?: string; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct { - inputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct_Output; -} -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input = Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch; -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - content: string | { - /** - * Type of the content (text) - */ - type?: string; - /** - * Text content - */ - text?: string; - }[]; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Async_Batch { - requests?: { - /** - * User-supplied reference. This field will be present in the response as well it can be used to reference the request and response. It's NOT validated to be unique. - */ - external_reference?: string; - /** - * Prompt for the text generation model - */ - prompt?: string; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; - response_format?: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2; - }[]; -} -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_JSON_Mode_2 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -type Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -} | string | Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse; -interface Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast { - inputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast_Output; -} -interface Ai_Cf_Meta_Llama_Guard_3_8B_Input { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender must alternate between 'user' and 'assistant'. - */ - role: "user" | "assistant"; - /** - * The content of the message as a string. - */ - content: string; - }[]; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Dictate the output format of the generated response. - */ - response_format?: { - /** - * Set to json_object to process and output generated text as JSON. - */ - type?: string; - }; -} -interface Ai_Cf_Meta_Llama_Guard_3_8B_Output { - response?: string | { - /** - * Whether the conversation is safe or not. - */ - safe?: boolean; - /** - * A list of what hazard categories predicted for the conversation, if the conversation is deemed unsafe. - */ - categories?: string[]; - }; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; -} -declare abstract class Base_Ai_Cf_Meta_Llama_Guard_3_8B { - inputs: Ai_Cf_Meta_Llama_Guard_3_8B_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_Guard_3_8B_Output; -} -interface Ai_Cf_Baai_Bge_Reranker_Base_Input { - /** - * A query you wish to perform against the provided contexts. - */ - /** - * Number of returned results starting with the best score. - */ - top_k?: number; - /** - * List of provided contexts. Note that the index in this array is important, as the response will refer to it. - */ - contexts: { - /** - * One of the provided context content - */ - text?: string; - }[]; -} -interface Ai_Cf_Baai_Bge_Reranker_Base_Output { - response?: { - /** - * Index of the context in the request - */ - id?: number; - /** - * Score of the context under the index. - */ - score?: number; - }[]; -} -declare abstract class Base_Ai_Cf_Baai_Bge_Reranker_Base { - inputs: Ai_Cf_Baai_Bge_Reranker_Base_Input; - postProcessedOutputs: Ai_Cf_Baai_Bge_Reranker_Base_Output; -} -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input = Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt | Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages; -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - /** - * The content of the message as a string. - */ - content: string; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -type Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct { - inputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct_Output; -} -type Ai_Cf_Qwen_Qwq_32B_Input = Ai_Cf_Qwen_Qwq_32B_Prompt | Ai_Cf_Qwen_Qwq_32B_Messages; -interface Ai_Cf_Qwen_Qwq_32B_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwq_32B_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Qwen_Qwq_32B_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Qwen_Qwq_32B { - inputs: Ai_Cf_Qwen_Qwq_32B_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwq_32B_Output; -} -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input = Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt | Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages; -interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. Must be supplied for tool calls for Mistral-3. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct { - inputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Input; - postProcessedOutputs: Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct_Output; -} -type Ai_Cf_Google_Gemma_3_12B_It_Input = Ai_Cf_Google_Gemma_3_12B_It_Prompt | Ai_Cf_Google_Gemma_3_12B_It_Messages; -interface Ai_Cf_Google_Gemma_3_12B_It_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Google_Gemma_3_12B_It_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[]; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Google_Gemma_3_12B_It_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - /** - * The name of the tool to be called - */ - name?: string; - }[]; -}; -declare abstract class Base_Ai_Cf_Google_Gemma_3_12B_It { - inputs: Ai_Cf_Google_Gemma_3_12B_It_Input; - postProcessedOutputs: Ai_Cf_Google_Gemma_3_12B_It_Output; -} -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input = Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch; -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Async_Batch { - requests: (Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner | Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner)[]; -} -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Prompt_Inner { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * JSON schema that should be fulfilled for the response. - */ - guided_json?: object; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Messages_Inner { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role?: string; - /** - * The tool call id. If you don't know what to put here you can fall back to 000000001 - */ - tool_call_id?: string; - content?: string | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }[] | { - /** - * Type of the content provided - */ - type?: string; - text?: string; - image_url?: { - /** - * image uri with data (e.g. data:image/jpeg;base64,/9j/...). HTTP URL will not be accepted - */ - url?: string; - }; - }; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_JSON_Mode; - /** - * JSON schema that should be fufilled for the response. - */ - guided_json?: object; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -type Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output = { - /** - * The generated text response from the model - */ - response: string; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * An array of tool calls requests made during the response generation - */ - tool_calls?: { - /** - * The tool call id. - */ - id?: string; - /** - * Specifies the type of tool (e.g., 'function'). - */ - type?: string; - /** - * Details of the function tool. - */ - function?: { - /** - * The name of the tool to be called - */ - name?: string; - /** - * The arguments passed to be passed to the tool call request - */ - arguments?: object; - }; - }[]; -}; -declare abstract class Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct { - inputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Input; - postProcessedOutputs: Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct_Output; -} -type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch; -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - content: string | { - /** - * Type of the content (text) - */ - type?: string; - /** - * Text content - */ - text?: string; - }[]; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Async_Batch { - requests: (Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1)[]; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Prompt_1 { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_2 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Messages_1 { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - content: string | { - /** - * Type of the content (text) - */ - type?: string; - /** - * Text content - */ - text?: string; - }[]; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_JSON_Mode_3 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -type Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output = Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response | string | Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse; -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Chat_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: "chat.completion"; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index?: number; - /** - * The message generated by the model - */ - message?: { - /** - * Role of the message author - */ - role: string; - /** - * The content of the message - */ - content: string; - /** - * Internal reasoning content (if available) - */ - reasoning_content?: string; - /** - * Tool calls made by the assistant - */ - tool_calls?: { - /** - * Unique identifier for the tool call - */ - id: string; - /** - * Type of tool call - */ - type: "function"; - function: { - /** - * Name of the function to call - */ - name: string; - /** - * JSON string of arguments for the function - */ - arguments: string; - }; - }[]; - }; - /** - * Reason why the model stopped generating - */ - finish_reason?: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Text_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: "text_completion"; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index: number; - /** - * The generated text completion - */ - text: string; - /** - * Reason why the model stopped generating - */ - finish_reason: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; -} -interface Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8 { - inputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8_Output; -} -interface Ai_Cf_Deepgram_Nova_3_Input { - audio: { - body: object; - contentType: string; - }; - /** - * Sets how the model will interpret strings submitted to the custom_topic param. When strict, the model will only return topics submitted using the custom_topic param. When extended, the model will return its own detected topics in addition to those submitted using the custom_topic param. - */ - custom_topic_mode?: "extended" | "strict"; - /** - * Custom topics you want the model to detect within your input audio or text if present Submit up to 100 - */ - custom_topic?: string; - /** - * Sets how the model will interpret intents submitted to the custom_intent param. When strict, the model will only return intents submitted using the custom_intent param. When extended, the model will return its own detected intents in addition those submitted using the custom_intents param - */ - custom_intent_mode?: "extended" | "strict"; - /** - * Custom intents you want the model to detect within your input audio if present - */ - custom_intent?: string; - /** - * Identifies and extracts key entities from content in submitted audio - */ - detect_entities?: boolean; - /** - * Identifies the dominant language spoken in submitted audio - */ - detect_language?: boolean; - /** - * Recognize speaker changes. Each word in the transcript will be assigned a speaker number starting at 0 - */ - diarize?: boolean; - /** - * Identify and extract key entities from content in submitted audio - */ - dictation?: boolean; - /** - * Specify the expected encoding of your submitted audio - */ - encoding?: "linear16" | "flac" | "mulaw" | "amr-nb" | "amr-wb" | "opus" | "speex" | "g729"; - /** - * Arbitrary key-value pairs that are attached to the API response for usage in downstream processing - */ - extra?: string; - /** - * Filler Words can help transcribe interruptions in your audio, like 'uh' and 'um' - */ - filler_words?: boolean; - /** - * Key term prompting can boost or suppress specialized terminology and brands. - */ - keyterm?: string; - /** - * Keywords can boost or suppress specialized terminology and brands. - */ - keywords?: string; - /** - * The BCP-47 language tag that hints at the primary spoken language. Depending on the Model and API endpoint you choose only certain languages are available. - */ - language?: string; - /** - * Spoken measurements will be converted to their corresponding abbreviations. - */ - measurements?: boolean; - /** - * Opts out requests from the Deepgram Model Improvement Program. Refer to our Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip. - */ - mip_opt_out?: boolean; - /** - * Mode of operation for the model representing broad area of topic that will be talked about in the supplied audio - */ - mode?: "general" | "medical" | "finance"; - /** - * Transcribe each audio channel independently. - */ - multichannel?: boolean; - /** - * Numerals converts numbers from written format to numerical format. - */ - numerals?: boolean; - /** - * Splits audio into paragraphs to improve transcript readability. - */ - paragraphs?: boolean; - /** - * Profanity Filter looks for recognized profanity and converts it to the nearest recognized non-profane word or removes it from the transcript completely. - */ - profanity_filter?: boolean; - /** - * Add punctuation and capitalization to the transcript. - */ - punctuate?: boolean; - /** - * Redaction removes sensitive information from your transcripts. - */ - redact?: string; - /** - * Search for terms or phrases in submitted audio and replaces them. - */ - replace?: string; - /** - * Search for terms or phrases in submitted audio. - */ - search?: string; - /** - * Recognizes the sentiment throughout a transcript or text. - */ - sentiment?: boolean; - /** - * Apply formatting to transcript output. When set to true, additional formatting will be applied to transcripts to improve readability. - */ - smart_format?: boolean; - /** - * Detect topics throughout a transcript or text. - */ - topics?: boolean; - /** - * Segments speech into meaningful semantic units. - */ - utterances?: boolean; - /** - * Seconds to wait before detecting a pause between words in submitted audio. - */ - utt_split?: number; - /** - * The number of channels in the submitted audio - */ - channels?: number; - /** - * Specifies whether the streaming endpoint should provide ongoing transcription updates as more audio is received. When set to true, the endpoint sends continuous updates, meaning transcription results may evolve over time. Note: Supported only for webosockets. - */ - interim_results?: boolean; - /** - * Indicates how long model will wait to detect whether a speaker has finished speaking or pauses for a significant period of time. When set to a value, the streaming endpoint immediately finalizes the transcription for the processed time range and returns the transcript with a speech_final parameter set to true. Can also be set to false to disable endpointing - */ - endpointing?: string; - /** - * Indicates that speech has started. You'll begin receiving Speech Started messages upon speech starting. Note: Supported only for webosockets. - */ - vad_events?: boolean; - /** - * Indicates how long model will wait to send an UtteranceEnd message after a word has been transcribed. Use with interim_results. Note: Supported only for webosockets. - */ - utterance_end_ms?: boolean; -} -interface Ai_Cf_Deepgram_Nova_3_Output { - results?: { - channels?: { - alternatives?: { - confidence?: number; - transcript?: string; - words?: { - confidence?: number; - end?: number; - start?: number; - word?: string; - }[]; - }[]; - }[]; - summary?: { - result?: string; - short?: string; - }; - sentiments?: { - segments?: { - text?: string; - start_word?: number; - end_word?: number; - sentiment?: string; - sentiment_score?: number; - }[]; - average?: { - sentiment?: string; - sentiment_score?: number; - }; - }; - }; -} -declare abstract class Base_Ai_Cf_Deepgram_Nova_3 { - inputs: Ai_Cf_Deepgram_Nova_3_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Nova_3_Output; -} -interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input { - queries?: string | string[]; - /** - * Optional instruction for the task - */ - instruction?: string; - documents?: string | string[]; - text?: string | string[]; -} -interface Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output { - data?: number[][]; - shape?: number[]; -} -declare abstract class Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B { - inputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Input; - postProcessedOutputs: Ai_Cf_Qwen_Qwen3_Embedding_0_6B_Output; -} -type Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input = { - /** - * readable stream with audio data and content-type specified for that data - */ - audio: { - body: object; - contentType: string; - }; - /** - * type of data PCM data that's sent to the inference server as raw array - */ - dtype?: "uint8" | "float32" | "float64"; -} | { - /** - * base64 encoded audio data - */ - audio: string; - /** - * type of data PCM data that's sent to the inference server as raw array - */ - dtype?: "uint8" | "float32" | "float64"; -}; -interface Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output { - /** - * if true, end-of-turn was detected - */ - is_complete?: boolean; - /** - * probability of the end-of-turn detection - */ - probability?: number; -} -declare abstract class Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2 { - inputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Input; - postProcessedOutputs: Ai_Cf_Pipecat_Ai_Smart_Turn_V2_Output; -} -declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_120B { - inputs: XOR; - postProcessedOutputs: XOR; -} -declare abstract class Base_Ai_Cf_Openai_Gpt_Oss_20B { - inputs: XOR; - postProcessedOutputs: XOR; -} -interface Ai_Cf_Leonardo_Phoenix_1_0_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt - */ - guidance?: number; - /** - * Random seed for reproducibility of the image generation - */ - seed?: number; - /** - * The height of the generated image in pixels - */ - height?: number; - /** - * The width of the generated image in pixels - */ - width?: number; - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - num_steps?: number; - /** - * Specify what to exclude from the generated images - */ - negative_prompt?: string; -} -/** - * The generated image in JPEG format - */ -type Ai_Cf_Leonardo_Phoenix_1_0_Output = string; -declare abstract class Base_Ai_Cf_Leonardo_Phoenix_1_0 { - inputs: Ai_Cf_Leonardo_Phoenix_1_0_Input; - postProcessedOutputs: Ai_Cf_Leonardo_Phoenix_1_0_Output; -} -interface Ai_Cf_Leonardo_Lucid_Origin_Input { - /** - * A text description of the image you want to generate. - */ - prompt: string; - /** - * Controls how closely the generated image should adhere to the prompt; higher values make the image more aligned with the prompt - */ - guidance?: number; - /** - * Random seed for reproducibility of the image generation - */ - seed?: number; - /** - * The height of the generated image in pixels - */ - height?: number; - /** - * The width of the generated image in pixels - */ - width?: number; - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - num_steps?: number; - /** - * The number of diffusion steps; higher values can improve quality but take longer - */ - steps?: number; -} -interface Ai_Cf_Leonardo_Lucid_Origin_Output { - /** - * The generated image in Base64 format. - */ - image?: string; -} -declare abstract class Base_Ai_Cf_Leonardo_Lucid_Origin { - inputs: Ai_Cf_Leonardo_Lucid_Origin_Input; - postProcessedOutputs: Ai_Cf_Leonardo_Lucid_Origin_Output; -} -interface Ai_Cf_Deepgram_Aura_1_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: "angus" | "asteria" | "arcas" | "orion" | "orpheus" | "athena" | "luna" | "zeus" | "perseus" | "helios" | "hera" | "stella"; - /** - * Encoding of the output audio. - */ - encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: "none" | "wav" | "ogg"; - /** - * The text content to be converted to speech - */ - text: string; - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number; - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number; -} -/** - * The generated audio in MP3 format - */ -type Ai_Cf_Deepgram_Aura_1_Output = string; -declare abstract class Base_Ai_Cf_Deepgram_Aura_1 { - inputs: Ai_Cf_Deepgram_Aura_1_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Aura_1_Output; -} -interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input { - /** - * Input text to translate. Can be a single string or a list of strings. - */ - text: string | string[]; - /** - * Target langauge to translate to - */ - target_language: "asm_Beng" | "awa_Deva" | "ben_Beng" | "bho_Deva" | "brx_Deva" | "doi_Deva" | "eng_Latn" | "gom_Deva" | "gon_Deva" | "guj_Gujr" | "hin_Deva" | "hne_Deva" | "kan_Knda" | "kas_Arab" | "kas_Deva" | "kha_Latn" | "lus_Latn" | "mag_Deva" | "mai_Deva" | "mal_Mlym" | "mar_Deva" | "mni_Beng" | "mni_Mtei" | "npi_Deva" | "ory_Orya" | "pan_Guru" | "san_Deva" | "sat_Olck" | "snd_Arab" | "snd_Deva" | "tam_Taml" | "tel_Telu" | "urd_Arab" | "unr_Deva"; -} -interface Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output { - /** - * Translated texts - */ - translations: string[]; -} -declare abstract class Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B { - inputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Input; - postProcessedOutputs: Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B_Output; -} -type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch; -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - content: string | { - /** - * Type of the content (text) - */ - type?: string; - /** - * Text content - */ - text?: string; - }[]; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_1 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Async_Batch { - requests: (Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1)[]; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Prompt_1 { - /** - * The input text prompt for the model to generate a response. - */ - prompt: string; - /** - * Name of the LoRA (Low-Rank Adaptation) model to fine-tune the base model. - */ - lora?: string; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_2 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Messages_1 { - /** - * An array of message objects representing the conversation history. - */ - messages: { - /** - * The role of the message sender (e.g., 'user', 'assistant', 'system', 'tool'). - */ - role: string; - content: string | { - /** - * Type of the content (text) - */ - type?: string; - /** - * Text content - */ - text?: string; - }[]; - }[]; - functions?: { - name: string; - code: string; - }[]; - /** - * A list of tools available for the assistant to use. - */ - tools?: ({ - /** - * The name of the tool. More descriptive the better. - */ - name: string; - /** - * A brief description of what the tool does. - */ - description: string; - /** - * Schema defining the parameters accepted by the tool. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - } | { - /** - * Specifies the type of tool (e.g., 'function'). - */ - type: string; - /** - * Details of the function tool. - */ - function: { - /** - * The name of the function. - */ - name: string; - /** - * A brief description of what the function does. - */ - description: string; - /** - * Schema defining the parameters accepted by the function. - */ - parameters: { - /** - * The type of the parameters object (usually 'object'). - */ - type: string; - /** - * List of required parameter names. - */ - required?: string[]; - /** - * Definitions of each parameter. - */ - properties: { - [k: string]: { - /** - * The data type of the parameter. - */ - type: string; - /** - * A description of the expected parameter. - */ - description: string; - }; - }; - }; - }; - })[]; - response_format?: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3; - /** - * If true, a chat template is not applied and you must adhere to the specific model's expected formatting. - */ - raw?: boolean; - /** - * If true, the response will be streamed back incrementally using SSE, Server Sent Events. - */ - stream?: boolean; - /** - * The maximum number of tokens to generate in the response. - */ - max_tokens?: number; - /** - * Controls the randomness of the output; higher values produce more random results. - */ - temperature?: number; - /** - * Adjusts the creativity of the AI's responses by controlling how many possible words it considers. Lower values make outputs more predictable; higher values allow for more varied and creative responses. - */ - top_p?: number; - /** - * Limits the AI to choose from the top 'k' most probable words. Lower values make responses more focused; higher values introduce more variety and potential surprises. - */ - top_k?: number; - /** - * Random seed for reproducibility of the generation. - */ - seed?: number; - /** - * Penalty for repeated tokens; higher values discourage repetition. - */ - repetition_penalty?: number; - /** - * Decreases the likelihood of the model repeating the same lines verbatim. - */ - frequency_penalty?: number; - /** - * Increases the likelihood of the model introducing new topics. - */ - presence_penalty?: number; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_JSON_Mode_3 { - type?: "json_object" | "json_schema"; - json_schema?: unknown; -} -type Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output = Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response | string | Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse; -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Chat_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: "chat.completion"; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index?: number; - /** - * The message generated by the model - */ - message?: { - /** - * Role of the message author - */ - role: string; - /** - * The content of the message - */ - content: string; - /** - * Internal reasoning content (if available) - */ - reasoning_content?: string; - /** - * Tool calls made by the assistant - */ - tool_calls?: { - /** - * Unique identifier for the tool call - */ - id: string; - /** - * Type of tool call - */ - type: "function"; - function: { - /** - * Name of the function to call - */ - name: string; - /** - * JSON string of arguments for the function - */ - arguments: string; - }; - }[]; - }; - /** - * Reason why the model stopped generating - */ - finish_reason?: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Text_Completion_Response { - /** - * Unique identifier for the completion - */ - id?: string; - /** - * Object type identifier - */ - object?: "text_completion"; - /** - * Unix timestamp of when the completion was created - */ - created?: number; - /** - * Model used for the completion - */ - model?: string; - /** - * List of completion choices - */ - choices?: { - /** - * Index of the choice in the list - */ - index: number; - /** - * The generated text completion - */ - text: string; - /** - * Reason why the model stopped generating - */ - finish_reason: string; - /** - * Stop reason (may be null) - */ - stop_reason?: string | null; - /** - * Log probabilities (if requested) - */ - logprobs?: {} | null; - /** - * Log probabilities for the prompt (if requested) - */ - prompt_logprobs?: {} | null; - }[]; - /** - * Usage statistics for the inference request - */ - usage?: { - /** - * Total number of tokens in input - */ - prompt_tokens?: number; - /** - * Total number of tokens in output - */ - completion_tokens?: number; - /** - * Total number of input and output tokens - */ - total_tokens?: number; - }; -} -interface Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_AsyncResponse { - /** - * The async request id that can be used to obtain the results. - */ - request_id?: string; -} -declare abstract class Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It { - inputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Input; - postProcessedOutputs: Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It_Output; -} -interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Input { - /** - * Input text to embed. Can be a single string or a list of strings. - */ - text: string | string[]; -} -interface Ai_Cf_Pfnet_Plamo_Embedding_1B_Output { - /** - * Embedding vectors, where each vector is a list of floats. - */ - data: number[][]; - /** - * Shape of the embedding data as [number_of_embeddings, embedding_dimension]. - * - * @minItems 2 - * @maxItems 2 - */ - shape: [ - number, - number - ]; -} -declare abstract class Base_Ai_Cf_Pfnet_Plamo_Embedding_1B { - inputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Input; - postProcessedOutputs: Ai_Cf_Pfnet_Plamo_Embedding_1B_Output; -} -interface Ai_Cf_Deepgram_Flux_Input { - /** - * Encoding of the audio stream. Currently only supports raw signed little-endian 16-bit PCM. - */ - encoding: "linear16"; - /** - * Sample rate of the audio stream in Hz. - */ - sample_rate: string; - /** - * End-of-turn confidence required to fire an eager end-of-turn event. When set, enables EagerEndOfTurn and TurnResumed events. Valid Values 0.3 - 0.9. - */ - eager_eot_threshold?: string; - /** - * End-of-turn confidence required to finish a turn. Valid Values 0.5 - 0.9. - */ - eot_threshold?: string; - /** - * A turn will be finished when this much time has passed after speech, regardless of EOT confidence. - */ - eot_timeout_ms?: string; - /** - * Keyterm prompting can improve recognition of specialized terminology. Pass multiple keyterm query parameters to boost multiple keyterms. - */ - keyterm?: string; - /** - * Opts out requests from the Deepgram Model Improvement Program. Refer to Deepgram Docs for pricing impacts before setting this to true. https://dpgr.am/deepgram-mip - */ - mip_opt_out?: "true" | "false"; - /** - * Label your requests for the purpose of identification during usage reporting - */ - tag?: string; -} -/** - * Output will be returned as websocket messages. - */ -interface Ai_Cf_Deepgram_Flux_Output { - /** - * The unique identifier of the request (uuid) - */ - request_id?: string; - /** - * Starts at 0 and increments for each message the server sends to the client. - */ - sequence_id?: number; - /** - * The type of event being reported. - */ - event?: "Update" | "StartOfTurn" | "EagerEndOfTurn" | "TurnResumed" | "EndOfTurn"; - /** - * The index of the current turn - */ - turn_index?: number; - /** - * Start time in seconds of the audio range that was transcribed - */ - audio_window_start?: number; - /** - * End time in seconds of the audio range that was transcribed - */ - audio_window_end?: number; - /** - * Text that was said over the course of the current turn - */ - transcript?: string; - /** - * The words in the transcript - */ - words?: { - /** - * The individual punctuated, properly-cased word from the transcript - */ - word: string; - /** - * Confidence that this word was transcribed correctly - */ - confidence: number; - }[]; - /** - * Confidence that no more speech is coming in this turn - */ - end_of_turn_confidence?: number; -} -declare abstract class Base_Ai_Cf_Deepgram_Flux { - inputs: Ai_Cf_Deepgram_Flux_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Flux_Output; -} -interface Ai_Cf_Deepgram_Aura_2_En_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: "amalthea" | "andromeda" | "apollo" | "arcas" | "aries" | "asteria" | "athena" | "atlas" | "aurora" | "callista" | "cora" | "cordelia" | "delia" | "draco" | "electra" | "harmonia" | "helena" | "hera" | "hermes" | "hyperion" | "iris" | "janus" | "juno" | "jupiter" | "luna" | "mars" | "minerva" | "neptune" | "odysseus" | "ophelia" | "orion" | "orpheus" | "pandora" | "phoebe" | "pluto" | "saturn" | "thalia" | "theia" | "vesta" | "zeus"; - /** - * Encoding of the output audio. - */ - encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: "none" | "wav" | "ogg"; - /** - * The text content to be converted to speech - */ - text: string; - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number; - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number; -} -/** - * The generated audio in MP3 format - */ -type Ai_Cf_Deepgram_Aura_2_En_Output = string; -declare abstract class Base_Ai_Cf_Deepgram_Aura_2_En { - inputs: Ai_Cf_Deepgram_Aura_2_En_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_En_Output; -} -interface Ai_Cf_Deepgram_Aura_2_Es_Input { - /** - * Speaker used to produce the audio. - */ - speaker?: "sirio" | "nestor" | "carina" | "celeste" | "alvaro" | "diana" | "aquila" | "selena" | "estrella" | "javier"; - /** - * Encoding of the output audio. - */ - encoding?: "linear16" | "flac" | "mulaw" | "alaw" | "mp3" | "opus" | "aac"; - /** - * Container specifies the file format wrapper for the output audio. The available options depend on the encoding type.. - */ - container?: "none" | "wav" | "ogg"; - /** - * The text content to be converted to speech - */ - text: string; - /** - * Sample Rate specifies the sample rate for the output audio. Based on the encoding, different sample rates are supported. For some encodings, the sample rate is not configurable - */ - sample_rate?: number; - /** - * The bitrate of the audio in bits per second. Choose from predefined ranges or specific values based on the encoding type. - */ - bit_rate?: number; -} -/** - * The generated audio in MP3 format - */ -type Ai_Cf_Deepgram_Aura_2_Es_Output = string; -declare abstract class Base_Ai_Cf_Deepgram_Aura_2_Es { - inputs: Ai_Cf_Deepgram_Aura_2_Es_Input; - postProcessedOutputs: Ai_Cf_Deepgram_Aura_2_Es_Output; -} -interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input { - multipart: { - body?: object; - contentType?: string; - }; -} -interface Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output { - /** - * Generated image as Base64 string. - */ - image?: string; -} -declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev { - inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Input; - postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Dev_Output; -} -interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input { - multipart: { - body?: object; - contentType?: string; - }; -} -interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output { - /** - * Generated image as Base64 string. - */ - image?: string; -} -declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B { - inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Input; - postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B_Output; -} -interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input { - multipart: { - body?: object; - contentType?: string; - }; -} -interface Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output { - /** - * Generated image as Base64 string. - */ - image?: string; -} -declare abstract class Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B { - inputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Input; - postProcessedOutputs: Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B_Output; -} -declare abstract class Base_Ai_Cf_Zai_Org_Glm_4_7_Flash { - inputs: ChatCompletionsInput; - postProcessedOutputs: ChatCompletionsOutput; -} -declare abstract class Base_Ai_Cf_Moonshotai_Kimi_K2_5 { - inputs: ChatCompletionsInput; - postProcessedOutputs: ChatCompletionsOutput; -} -declare abstract class Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B { - inputs: ChatCompletionsInput; - postProcessedOutputs: ChatCompletionsOutput; -} -declare abstract class Base_Ai_Cf_Google_Gemma_4_26B_A4B_IT { - inputs: ChatCompletionsInput; - postProcessedOutputs: ChatCompletionsOutput; -} -interface AiModels { - "@cf/huggingface/distilbert-sst-2-int8": BaseAiTextClassification; - "@cf/stabilityai/stable-diffusion-xl-base-1.0": BaseAiTextToImage; - "@cf/runwayml/stable-diffusion-v1-5-inpainting": BaseAiTextToImage; - "@cf/runwayml/stable-diffusion-v1-5-img2img": BaseAiTextToImage; - "@cf/lykon/dreamshaper-8-lcm": BaseAiTextToImage; - "@cf/bytedance/stable-diffusion-xl-lightning": BaseAiTextToImage; - "@cf/myshell-ai/melotts": BaseAiTextToSpeech; - "@cf/google/embeddinggemma-300m": BaseAiTextEmbeddings; - "@cf/microsoft/resnet-50": BaseAiImageClassification; - "@cf/meta/llama-2-7b-chat-int8": BaseAiTextGeneration; - "@cf/mistral/mistral-7b-instruct-v0.1": BaseAiTextGeneration; - "@cf/meta/llama-2-7b-chat-fp16": BaseAiTextGeneration; - "@hf/thebloke/llama-2-13b-chat-awq": BaseAiTextGeneration; - "@hf/thebloke/mistral-7b-instruct-v0.1-awq": BaseAiTextGeneration; - "@hf/thebloke/zephyr-7b-beta-awq": BaseAiTextGeneration; - "@hf/thebloke/openhermes-2.5-mistral-7b-awq": BaseAiTextGeneration; - "@hf/thebloke/neural-chat-7b-v3-1-awq": BaseAiTextGeneration; - "@hf/thebloke/deepseek-coder-6.7b-base-awq": BaseAiTextGeneration; - "@hf/thebloke/deepseek-coder-6.7b-instruct-awq": BaseAiTextGeneration; - "@cf/deepseek-ai/deepseek-math-7b-instruct": BaseAiTextGeneration; - "@cf/defog/sqlcoder-7b-2": BaseAiTextGeneration; - "@cf/openchat/openchat-3.5-0106": BaseAiTextGeneration; - "@cf/tiiuae/falcon-7b-instruct": BaseAiTextGeneration; - "@cf/thebloke/discolm-german-7b-v1-awq": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-0.5b-chat": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-7b-chat-awq": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-14b-chat-awq": BaseAiTextGeneration; - "@cf/tinyllama/tinyllama-1.1b-chat-v1.0": BaseAiTextGeneration; - "@cf/microsoft/phi-2": BaseAiTextGeneration; - "@cf/qwen/qwen1.5-1.8b-chat": BaseAiTextGeneration; - "@cf/mistral/mistral-7b-instruct-v0.2-lora": BaseAiTextGeneration; - "@hf/nousresearch/hermes-2-pro-mistral-7b": BaseAiTextGeneration; - "@hf/nexusflow/starling-lm-7b-beta": BaseAiTextGeneration; - "@hf/google/gemma-7b-it": BaseAiTextGeneration; - "@cf/meta-llama/llama-2-7b-chat-hf-lora": BaseAiTextGeneration; - "@cf/google/gemma-2b-it-lora": BaseAiTextGeneration; - "@cf/google/gemma-7b-it-lora": BaseAiTextGeneration; - "@hf/mistral/mistral-7b-instruct-v0.2": BaseAiTextGeneration; - "@cf/meta/llama-3-8b-instruct": BaseAiTextGeneration; - "@cf/fblgit/una-cybertron-7b-v2-bf16": BaseAiTextGeneration; - "@cf/meta/llama-3-8b-instruct-awq": BaseAiTextGeneration; - "@cf/meta/llama-3.1-8b-instruct-fp8": BaseAiTextGeneration; - "@cf/meta/llama-3.1-8b-instruct-awq": BaseAiTextGeneration; - "@cf/meta/llama-3.2-3b-instruct": BaseAiTextGeneration; - "@cf/meta/llama-3.2-1b-instruct": BaseAiTextGeneration; - "@cf/deepseek-ai/deepseek-r1-distill-qwen-32b": BaseAiTextGeneration; - "@cf/ibm-granite/granite-4.0-h-micro": BaseAiTextGeneration; - "@cf/facebook/bart-large-cnn": BaseAiSummarization; - "@cf/llava-hf/llava-1.5-7b-hf": BaseAiImageToText; - "@cf/baai/bge-base-en-v1.5": Base_Ai_Cf_Baai_Bge_Base_En_V1_5; - "@cf/openai/whisper": Base_Ai_Cf_Openai_Whisper; - "@cf/meta/m2m100-1.2b": Base_Ai_Cf_Meta_M2M100_1_2B; - "@cf/baai/bge-small-en-v1.5": Base_Ai_Cf_Baai_Bge_Small_En_V1_5; - "@cf/baai/bge-large-en-v1.5": Base_Ai_Cf_Baai_Bge_Large_En_V1_5; - "@cf/unum/uform-gen2-qwen-500m": Base_Ai_Cf_Unum_Uform_Gen2_Qwen_500M; - "@cf/openai/whisper-tiny-en": Base_Ai_Cf_Openai_Whisper_Tiny_En; - "@cf/openai/whisper-large-v3-turbo": Base_Ai_Cf_Openai_Whisper_Large_V3_Turbo; - "@cf/baai/bge-m3": Base_Ai_Cf_Baai_Bge_M3; - "@cf/black-forest-labs/flux-1-schnell": Base_Ai_Cf_Black_Forest_Labs_Flux_1_Schnell; - "@cf/meta/llama-3.2-11b-vision-instruct": Base_Ai_Cf_Meta_Llama_3_2_11B_Vision_Instruct; - "@cf/meta/llama-3.3-70b-instruct-fp8-fast": Base_Ai_Cf_Meta_Llama_3_3_70B_Instruct_Fp8_Fast; - "@cf/meta/llama-guard-3-8b": Base_Ai_Cf_Meta_Llama_Guard_3_8B; - "@cf/baai/bge-reranker-base": Base_Ai_Cf_Baai_Bge_Reranker_Base; - "@cf/qwen/qwen2.5-coder-32b-instruct": Base_Ai_Cf_Qwen_Qwen2_5_Coder_32B_Instruct; - "@cf/qwen/qwq-32b": Base_Ai_Cf_Qwen_Qwq_32B; - "@cf/mistralai/mistral-small-3.1-24b-instruct": Base_Ai_Cf_Mistralai_Mistral_Small_3_1_24B_Instruct; - "@cf/google/gemma-3-12b-it": Base_Ai_Cf_Google_Gemma_3_12B_It; - "@cf/meta/llama-4-scout-17b-16e-instruct": Base_Ai_Cf_Meta_Llama_4_Scout_17B_16E_Instruct; - "@cf/qwen/qwen3-30b-a3b-fp8": Base_Ai_Cf_Qwen_Qwen3_30B_A3B_Fp8; - "@cf/deepgram/nova-3": Base_Ai_Cf_Deepgram_Nova_3; - "@cf/qwen/qwen3-embedding-0.6b": Base_Ai_Cf_Qwen_Qwen3_Embedding_0_6B; - "@cf/pipecat-ai/smart-turn-v2": Base_Ai_Cf_Pipecat_Ai_Smart_Turn_V2; - "@cf/openai/gpt-oss-120b": Base_Ai_Cf_Openai_Gpt_Oss_120B; - "@cf/openai/gpt-oss-20b": Base_Ai_Cf_Openai_Gpt_Oss_20B; - "@cf/leonardo/phoenix-1.0": Base_Ai_Cf_Leonardo_Phoenix_1_0; - "@cf/leonardo/lucid-origin": Base_Ai_Cf_Leonardo_Lucid_Origin; - "@cf/deepgram/aura-1": Base_Ai_Cf_Deepgram_Aura_1; - "@cf/ai4bharat/indictrans2-en-indic-1B": Base_Ai_Cf_Ai4Bharat_Indictrans2_En_Indic_1B; - "@cf/aisingapore/gemma-sea-lion-v4-27b-it": Base_Ai_Cf_Aisingapore_Gemma_Sea_Lion_V4_27B_It; - "@cf/pfnet/plamo-embedding-1b": Base_Ai_Cf_Pfnet_Plamo_Embedding_1B; - "@cf/deepgram/flux": Base_Ai_Cf_Deepgram_Flux; - "@cf/deepgram/aura-2-en": Base_Ai_Cf_Deepgram_Aura_2_En; - "@cf/deepgram/aura-2-es": Base_Ai_Cf_Deepgram_Aura_2_Es; - "@cf/black-forest-labs/flux-2-dev": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Dev; - "@cf/black-forest-labs/flux-2-klein-4b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_4B; - "@cf/black-forest-labs/flux-2-klein-9b": Base_Ai_Cf_Black_Forest_Labs_Flux_2_Klein_9B; - "@cf/zai-org/glm-4.7-flash": Base_Ai_Cf_Zai_Org_Glm_4_7_Flash; - "@cf/moonshotai/kimi-k2.5": Base_Ai_Cf_Moonshotai_Kimi_K2_5; - "@cf/nvidia/nemotron-3-120b-a12b": Base_Ai_Cf_Nvidia_Nemotron_3_120B_A12B; -} -type AiOptions = { - /** - * Send requests as an asynchronous batch job, only works for supported models - * https://developers.cloudflare.com/workers-ai/features/batch-api - */ - queueRequest?: boolean; - /** - * Establish websocket connections, only works for supported models - */ - websocket?: boolean; - /** - * Tag your requests to group and view them in Cloudflare dashboard. - * - * Rules: - * Tags must only contain letters, numbers, and the symbols: : - . / @ - * Each tag can have maximum 50 characters. - * Maximum 5 tags are allowed each request. - * Duplicate tags will removed. - */ - tags?: string[]; - gateway?: GatewayOptions; - returnRawResponse?: boolean; - prefix?: string; - extraHeaders?: object; - signal?: AbortSignal; -}; -type AiModelsSearchParams = { - author?: string; - hide_experimental?: boolean; - page?: number; - per_page?: number; - search?: string; - source?: number; - task?: string; -}; -type AiModelsSearchObject = { - id: string; - source: number; - name: string; - description: string; - task: { - id: string; - name: string; - description: string; - }; - tags: string[]; - properties: { - property_id: string; - value: string; - }[]; -}; -type ChatCompletionsBase = XOR; -type ChatCompletionsInput = XOR; -interface InferenceUpstreamError extends Error { -} -interface AiInternalError extends Error { -} -type AiModelListType = Record; -type AiAsyncBatchResponse = { - request_id: string; -}; -declare abstract class Ai { - aiGatewayLogId: string | null; - gateway(gatewayId: string): AiGateway; - /** - * @deprecated Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ - aiSearch(): AiSearchNamespace; - /** - * @deprecated AutoRAG has been replaced by AI Search. - * Use the standalone `ai_search_namespaces` or `ai_search` Workers bindings instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - * - * @param autoragId Instance ID - */ - autorag(autoragId: string): AutoRAG; - // Batch request - run(model: Name, inputs: { - requests: AiModelList[Name]['inputs'][]; - }, options: AiOptions & { - queueRequest: true; - }): Promise; - // Raw response - run(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & { - returnRawResponse: true; - }): Promise; - // WebSocket - run(model: Name, inputs: AiModelList[Name]['inputs'], options: AiOptions & { - websocket: true; - }): Promise; - // Streaming - run(model: Name, inputs: AiModelList[Name]['inputs'] & { - stream: true; - }, options?: AiOptions): Promise; - // Normal (default) - known model - run(model: Name, inputs: AiModelList[Name]['inputs'], options?: AiOptions): Promise; - // Unknown model (gateway fallback) - run(model: string & {}, inputs: Record, options?: AiOptions): Promise>; - models(params?: AiModelsSearchParams): Promise; - toMarkdown(): ToMarkdownService; - toMarkdown(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; - toMarkdown(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; -} -type GatewayRetries = { - maxAttempts?: 1 | 2 | 3 | 4 | 5; - retryDelayMs?: number; - backoff?: 'constant' | 'linear' | 'exponential'; -}; -type GatewayOptions = { - id: string; - cacheKey?: string; - cacheTtl?: number; - skipCache?: boolean; - metadata?: Record; - collectLog?: boolean; - eventId?: string; - requestTimeoutMs?: number; - retries?: GatewayRetries; -}; -type UniversalGatewayOptions = Exclude & { - /** - ** @deprecated - */ - id?: string; -}; -type AiGatewayPatchLog = { - score?: number | null; - feedback?: -1 | 1 | null; - metadata?: Record | null; -}; -type AiGatewayLog = { - id: string; - provider: string; - model: string; - model_type?: string; - path: string; - duration: number; - request_type?: string; - request_content_type?: string; - status_code: number; - response_content_type?: string; - success: boolean; - cached: boolean; - tokens_in?: number; - tokens_out?: number; - metadata?: Record; - step?: number; - cost?: number; - custom_cost?: boolean; - request_size: number; - request_head?: string; - request_head_complete: boolean; - response_size: number; - response_head?: string; - response_head_complete: boolean; - created_at: Date; -}; -type AIGatewayProviders = 'workers-ai' | 'anthropic' | 'aws-bedrock' | 'azure-openai' | 'google-vertex-ai' | 'huggingface' | 'openai' | 'perplexity-ai' | 'replicate' | 'groq' | 'cohere' | 'google-ai-studio' | 'mistral' | 'grok' | 'openrouter' | 'deepseek' | 'cerebras' | 'cartesia' | 'elevenlabs' | 'adobe-firefly'; -type AIGatewayHeaders = { - 'cf-aig-metadata': Record | string; - 'cf-aig-custom-cost': { - per_token_in?: number; - per_token_out?: number; - } | { - total_cost?: number; - } | string; - 'cf-aig-cache-ttl': number | string; - 'cf-aig-skip-cache': boolean | string; - 'cf-aig-cache-key': string; - 'cf-aig-event-id': string; - 'cf-aig-request-timeout': number | string; - 'cf-aig-max-attempts': number | string; - 'cf-aig-retry-delay': number | string; - 'cf-aig-backoff': string; - 'cf-aig-collect-log': boolean | string; - Authorization: string; - 'Content-Type': string; - [key: string]: string | number | boolean | object; -}; -type AIGatewayUniversalRequest = { - provider: AIGatewayProviders | string; // eslint-disable-line - endpoint: string; - headers: Partial; - query: unknown; -}; -interface AiGatewayInternalError extends Error { -} -interface AiGatewayLogNotFound extends Error { -} -declare abstract class AiGateway { - patchLog(logId: string, data: AiGatewayPatchLog): Promise; - getLog(logId: string): Promise; - run(data: AIGatewayUniversalRequest | AIGatewayUniversalRequest[], options?: { - gateway?: UniversalGatewayOptions; - extraHeaders?: object; - signal?: AbortSignal; - }): Promise; - getUrl(provider?: AIGatewayProviders | string): Promise; // eslint-disable-line -} -// Copyright (c) 2022-2025 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 -/** - * Artifacts — Git-compatible file storage on Cloudflare Workers. - * - * Provides programmatic access to create, manage, and fork repositories, - * and to issue and revoke scoped access tokens. - */ -/** Information about a repository. */ -interface ArtifactsRepoInfo { - /** Unique repository ID. */ - id: string; - /** Repository name. */ - name: string; - /** Repository description, or null if not set. */ - description: string | null; - /** Default branch name (e.g. "main"). */ - defaultBranch: string; - /** ISO 8601 creation timestamp. */ - createdAt: string; - /** ISO 8601 last-updated timestamp. */ - updatedAt: string; - /** ISO 8601 timestamp of the last push, or null if never pushed. */ - lastPushAt: string | null; - /** Fork source (e.g. "github:owner/repo", "artifacts:namespace/repo"), or null if not a fork. */ - source: string | null; - /** Whether the repository is read-only. */ - readOnly: boolean; - /** HTTPS git remote URL. */ - remote: string; -} -/** Result of creating a repository — includes the initial access token. */ -interface ArtifactsCreateRepoResult { - /** Unique repository ID. */ - id: string; - /** Repository name. */ - name: string; - /** Repository description, or null if not set. */ - description: string | null; - /** Default branch name. */ - defaultBranch: string; - /** HTTPS git remote URL. */ - remote: string; - /** Plaintext access token (only returned at creation time). */ - token: string; - /** ISO 8601 token expiry timestamp. */ - tokenExpiresAt: string; -} -/** Paginated list of repositories. */ -interface ArtifactsRepoListResult { - /** Repositories in this page (without the `remote` field). */ - repos: Omit[]; - /** Total number of repositories in the namespace. */ - total: number; - /** Cursor for the next page, if there are more results. */ - cursor?: string; -} -/** Result of creating an access token. */ -interface ArtifactsCreateTokenResult { - /** Unique token ID. */ - id: string; - /** Plaintext token (only returned at creation time). */ - plaintext: string; - /** Token scope: "read" or "write". */ - scope: 'read' | 'write'; - /** ISO 8601 token expiry timestamp. */ - expiresAt: string; -} -/** Token metadata (no plaintext). */ -interface ArtifactsTokenInfo { - /** Unique token ID. */ - id: string; - /** Token scope: "read" or "write". */ - scope: 'read' | 'write'; - /** Token state: "active", "expired", or "revoked". */ - state: 'active' | 'expired' | 'revoked'; - /** ISO 8601 creation timestamp. */ - createdAt: string; - /** ISO 8601 expiry timestamp. */ - expiresAt: string; -} -/** Paginated list of tokens for a repository. */ -interface ArtifactsTokenListResult { - /** Tokens in this page. */ - tokens: ArtifactsTokenInfo[]; - /** Total number of tokens for the repository. */ - total: number; -} -/** - * Handle for a single repository. Returned by Artifacts.get(). - * - * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs. - */ -interface ArtifactsRepo extends ArtifactsRepoInfo { - /** - * Create an access token for this repo. - * @param scope Token scope: "write" (default) or "read". - * @param ttl Time-to-live in seconds (default 86400, min 60, max 31536000). - * @throws {ArtifactsError} with code `INVALID_TTL` if ttl is out of range. - */ - createToken(scope?: 'write' | 'read', ttl?: number): Promise; - /** List tokens for this repo (metadata only, no plaintext). */ - listTokens(): Promise; - /** - * Revoke a token by plaintext or ID. - * @param tokenOrId Plaintext token or token ID. - * @returns true if revoked, false if not found. - * @throws {ArtifactsError} with code `INVALID_INPUT` if tokenOrId is empty. - */ - revokeToken(tokenOrId: string): Promise; - // ── Fork ── - /** - * Fork this repo to a new repo. - * @param name Target repository name. - * @param opts Optional: description, readOnly flag, defaultBranchOnly (default true). - * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid. - * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists. - * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if a fork is already running. - */ - fork(name: string, opts?: { - description?: string; - readOnly?: boolean; - defaultBranchOnly?: boolean; - }): Promise; -} -// ── Error types ────────────────────────────────────────────────────────────── -/** - * Error codes returned by Artifacts binding operations. - * - * Each code maps to a numeric code available on `ArtifactsError.numericCode`. - */ -type ArtifactsErrorCode = 'ALREADY_EXISTS' | 'NOT_FOUND' | 'IMPORT_IN_PROGRESS' | 'FORK_IN_PROGRESS' | 'INVALID_INPUT' | 'INVALID_REPO_NAME' | 'INVALID_TTL' | 'INVALID_URL' | 'REMOTE_AUTH_REQUIRED' | 'UPSTREAM_UNAVAILABLE' | 'MEMORY_LIMIT' | 'INTERNAL_ERROR'; -/** - * Error thrown by Artifacts binding operations. - * - * Uses a string `.code` discriminator following the Cloudflare platform - * convention (StreamError, ImagesError, etc.). The `.numericCode` matches - * the REST API `errors[].code` values. - */ -interface ArtifactsError extends Error { - readonly name: 'ArtifactsError'; - /** String error code for programmatic matching. */ - readonly code: ArtifactsErrorCode; - /** Numeric error code matching the REST API. */ - readonly numericCode: number; -} -// ── Binding ────────────────────────────────────────────────────────────────── -/** - * Artifacts binding — namespace-level operations. - * - * Methods may throw `ArtifactsError` with code `INTERNAL_ERROR` if an unexpected service error occurs. - */ -interface Artifacts { - /** - * Create a new repository with an initial access token. - * @param name Repository name (alphanumeric, dots, hyphens, underscores). - * @param opts Optional: readOnly flag, description, default branch name. - * @returns Repo metadata with initial token. - * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid. - * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the repo already exists. - */ - create(name: string, opts?: { - readOnly?: boolean; - description?: string; - setDefaultBranch?: string; - }): Promise; - /** - * Get a handle to an existing repository. - * @param name Repository name. - * @returns Repo handle. - * @throws {ArtifactsError} with code `NOT_FOUND` if the repo does not exist. - * @throws {ArtifactsError} with code `IMPORT_IN_PROGRESS` if the repo is still importing. - * @throws {ArtifactsError} with code `FORK_IN_PROGRESS` if the repo is still forking. - */ - get(name: string): Promise; - /** - * Import a repository from an external git remote. - * @param params Source URL and optional branch/depth, plus target name and options. - * @returns Repo metadata with initial token. - * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if the target name is invalid. - * @throws {ArtifactsError} with code `INVALID_INPUT` if the source URL is not valid HTTPS. - * @throws {ArtifactsError} with code `INVALID_URL` if the source URL does not point to a git repository. - * @throws {ArtifactsError} with code `REMOTE_AUTH_REQUIRED` if the remote requires authentication. - * @throws {ArtifactsError} with code `NOT_FOUND` if the remote repository does not exist. - * @throws {ArtifactsError} with code `UPSTREAM_UNAVAILABLE` if the remote cannot be reached. - * @throws {ArtifactsError} with code `MEMORY_LIMIT` if the import exceeds service memory limits. - * @throws {ArtifactsError} with code `ALREADY_EXISTS` if the target repo already exists. - */ - import(params: { - source: { - url: string; - branch?: string; - depth?: number; - }; - target: { - name: string; - opts?: { - description?: string; - readOnly?: boolean; - }; - }; - }): Promise; - /** - * List repositories with cursor-based pagination. - * @param opts Optional: limit (1–200, default 50), cursor for next page. - */ - list(opts?: { - limit?: number; - cursor?: string; - }): Promise; - /** - * Delete a repository and all associated tokens. - * @param name Repository name. - * @returns true if deleted, false if not found. - * @throws {ArtifactsError} with code `INVALID_REPO_NAME` if name is invalid. - */ - delete(name: string): Promise; -} -/** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ -interface AutoRAGInternalError extends Error { -} -/** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ -interface AutoRAGNotFoundError extends Error { -} -/** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ -interface AutoRAGUnauthorizedError extends Error { -} -/** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ -interface AutoRAGNameNotSetError extends Error { -} -type ComparisonFilter = { - key: string; - type: 'eq' | 'ne' | 'gt' | 'gte' | 'lt' | 'lte'; - value: string | number | boolean; -}; -type CompoundFilter = { - type: 'and' | 'or'; - filters: ComparisonFilter[]; -}; -/** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ -type AutoRagSearchRequest = { - query: string; - filters?: CompoundFilter | ComparisonFilter; - max_num_results?: number; - ranking_options?: { - ranker?: string; - score_threshold?: number; - }; - reranking?: { - enabled?: boolean; - model?: string; - }; - rewrite_query?: boolean; -}; -/** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ -type AutoRagAiSearchRequest = AutoRagSearchRequest & { - stream?: boolean; - system_prompt?: string; -}; -/** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ -type AutoRagAiSearchRequestStreaming = Omit & { - stream: true; -}; -/** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ -type AutoRagSearchResponse = { - object: 'vector_store.search_results.page'; - search_query: string; - data: { - file_id: string; - filename: string; - score: number; - attributes: Record; - content: { - type: 'text'; - text: string; - }[]; - }[]; - has_more: boolean; - next_page: string | null; -}; -/** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ -type AutoRagListResponse = { - id: string; - enable: boolean; - type: string; - source: string; - vectorize_name: string; - paused: boolean; - status: string; -}[]; -/** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ -type AutoRagAiSearchResponse = AutoRagSearchResponse & { - response: string; -}; -/** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ -declare abstract class AutoRAG { - /** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ - list(): Promise; - /** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ - search(params: AutoRagSearchRequest): Promise; - /** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ - aiSearch(params: AutoRagAiSearchRequestStreaming): Promise; - /** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ - aiSearch(params: AutoRagAiSearchRequest): Promise; - /** - * @deprecated Use the standalone AI Search Workers binding instead. - * See https://developers.cloudflare.com/ai-search/usage/workers-binding/ - */ - aiSearch(params: AutoRagAiSearchRequest): Promise; -} -interface BasicImageTransformations { - /** - * Maximum width in image pixels. The value must be an integer. - */ - width?: number; - /** - * Maximum height in image pixels. The value must be an integer. - */ - height?: number; - /** - * Resizing mode as a string. It affects interpretation of width and height - * options: - * - scale-down: Similar to contain, but the image is never enlarged. If - * the image is larger than given width or height, it will be resized. - * Otherwise its original size will be kept. - * - contain: Resizes to maximum size that fits within the given width and - * height. If only a single dimension is given (e.g. only width), the - * image will be shrunk or enlarged to exactly match that dimension. - * Aspect ratio is always preserved. - * - cover: Resizes (shrinks or enlarges) to fill the entire area of width - * and height. If the image has an aspect ratio different from the ratio - * of width and height, it will be cropped to fit. - * - crop: The image will be shrunk and cropped to fit within the area - * specified by width and height. The image will not be enlarged. For images - * smaller than the given dimensions it's the same as scale-down. For - * images larger than the given dimensions, it's the same as cover. - * See also trim. - * - pad: Resizes to the maximum size that fits within the given width and - * height, and then fills the remaining area with a background color - * (white by default). Use of this mode is not recommended, as the same - * effect can be more efficiently achieved with the contain mode and the - * CSS object-fit: contain property. - * - squeeze: Stretches and deforms to the width and height given, even if it - * breaks aspect ratio - */ - fit?: "scale-down" | "contain" | "cover" | "crop" | "pad" | "squeeze"; - /** - * Image segmentation using artificial intelligence models. Sets pixels not - * within selected segment area to transparent e.g "foreground" sets every - * background pixel as transparent. - */ - segment?: "foreground"; - /** - * When cropping with fit: "cover", this defines the side or point that should - * be left uncropped. The value is either a string - * "left", "right", "top", "bottom", "auto", or "center" (the default), - * or an object {x, y} containing focal point coordinates in the original - * image expressed as fractions ranging from 0.0 (top or left) to 1.0 - * (bottom or right), 0.5 being the center. {fit: "cover", gravity: "top"} will - * crop bottom or left and right sides as necessary, but won’t crop anything - * from the top. {fit: "cover", gravity: {x:0.5, y:0.2}} will crop each side to - * preserve as much as possible around a point at 20% of the height of the - * source image. - */ - gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | BasicImageTransformationsGravityCoordinates; - /** - * Background color to add underneath the image. Applies only to images with - * transparency (such as PNG). Accepts any CSS color (#RRGGBB, rgba(…), - * hsl(…), etc.) - */ - background?: string; - /** - * Number of degrees (90, 180, 270) to rotate the image by. width and height - * options refer to axes after rotation. - */ - rotate?: 0 | 90 | 180 | 270 | 360; -} -interface BasicImageTransformationsGravityCoordinates { - x?: number; - y?: number; - mode?: 'remainder' | 'box-center'; -} -/** - * In addition to the properties you can set in the RequestInit dict - * that you pass as an argument to the Request constructor, you can - * set certain properties of a `cf` object to control how Cloudflare - * features are applied to that new Request. - * - * Note: Currently, these properties cannot be tested in the - * playground. - */ -interface RequestInitCfProperties extends Record { - cacheEverything?: boolean; - /** - * A request's cache key is what determines if two requests are - * "the same" for caching purposes. If a request has the same cache key - * as some previous request, then we can serve the same cached response for - * both. (e.g. 'some-key') - * - * Only available for Enterprise customers. - */ - cacheKey?: string; - /** - * This allows you to append additional Cache-Tag response headers - * to the origin response without modifications to the origin server. - * This will allow for greater control over the Purge by Cache Tag feature - * utilizing changes only in the Workers process. - * - * Only available for Enterprise customers. - */ - cacheTags?: string[]; - /** - * Force response to be cached for a given number of seconds. (e.g. 300) - */ - cacheTtl?: number; - /** - * Force response to be cached for a given number of seconds based on the Origin status code. - * (e.g. { '200-299': 86400, '404': 1, '500-599': 0 }) - */ - cacheTtlByStatus?: Record; - /** - * Explicit Cache-Control header value to set on the response stored in cache. - * This gives full control over cache directives (e.g. 'public, max-age=3600, s-maxage=86400'). - * - * Cannot be used together with `cacheTtl` or the `cache` request option (`no-store`/`no-cache`), - * as these are mutually exclusive cache control mechanisms. Setting both will throw a TypeError. - * - * Can be used together with `cacheTtlByStatus`. - */ - cacheControl?: string; - /** - * Whether the response should be eligible for Cache Reserve storage. - */ - cacheReserveEligible?: boolean; - /** - * Whether to respect strong ETags (as opposed to weak ETags) from the origin. - */ - respectStrongEtag?: boolean; - /** - * Whether to strip ETag headers from the origin response before caching. - */ - stripEtags?: boolean; - /** - * Whether to strip Last-Modified headers from the origin response before caching. - */ - stripLastModified?: boolean; - /** - * Whether to enable Cache Deception Armor, which protects against web cache - * deception attacks by verifying the Content-Type matches the URL extension. - */ - cacheDeceptionArmor?: boolean; - /** - * Minimum file size in bytes for a response to be eligible for Cache Reserve storage. - */ - cacheReserveMinimumFileSize?: number; - scrapeShield?: boolean; - apps?: boolean; - image?: RequestInitCfPropertiesImage; - minify?: RequestInitCfPropertiesImageMinify; - mirage?: boolean; - polish?: "lossy" | "lossless" | "off"; - r2?: RequestInitCfPropertiesR2; - /** - * Redirects the request to an alternate origin server. You can use this, - * for example, to implement load balancing across several origins. - * (e.g.us-east.example.com) - * - * Note - For security reasons, the hostname set in resolveOverride must - * be proxied on the same Cloudflare zone of the incoming request. - * Otherwise, the setting is ignored. CNAME hosts are allowed, so to - * resolve to a host under a different domain or a DNS only domain first - * declare a CNAME record within your own zone’s DNS mapping to the - * external hostname, set proxy on Cloudflare, then set resolveOverride - * to point to that CNAME record. - */ - resolveOverride?: string; -} -interface RequestInitCfPropertiesImageDraw extends BasicImageTransformations { - /** - * Absolute URL of the image file to use for the drawing. It can be any of - * the supported file formats. For drawing of watermarks or non-rectangular - * overlays we recommend using PNG or WebP images. - */ - url: string; - /** - * Floating-point number between 0 (transparent) and 1 (opaque). - * For example, opacity: 0.5 makes overlay semitransparent. - */ - opacity?: number; - /** - * - If set to true, the overlay image will be tiled to cover the entire - * area. This is useful for stock-photo-like watermarks. - * - If set to "x", the overlay image will be tiled horizontally only - * (form a line). - * - If set to "y", the overlay image will be tiled vertically only - * (form a line). - */ - repeat?: true | "x" | "y"; - /** - * Position of the overlay image relative to a given edge. Each property is - * an offset in pixels. 0 aligns exactly to the edge. For example, left: 10 - * positions left side of the overlay 10 pixels from the left edge of the - * image it's drawn over. bottom: 0 aligns bottom of the overlay with bottom - * of the background image. - * - * Setting both left & right, or both top & bottom is an error. - * - * If no position is specified, the image will be centered. - */ - top?: number; - left?: number; - bottom?: number; - right?: number; -} -interface RequestInitCfPropertiesImage extends BasicImageTransformations { - /** - * Device Pixel Ratio. Default 1. Multiplier for width/height that makes it - * easier to specify higher-DPI sizes in . - */ - dpr?: number; - /** - * Allows you to trim your image. Takes dpr into account and is performed before - * resizing or rotation. - * - * It can be used as: - * - left, top, right, bottom - it will specify the number of pixels to cut - * off each side - * - width, height - the width/height you'd like to end up with - can be used - * in combination with the properties above - * - border - this will automatically trim the surroundings of an image based on - * it's color. It consists of three properties: - * - color: rgb or hex representation of the color you wish to trim (todo: verify the rgba bit) - * - tolerance: difference from color to treat as color - * - keep: the number of pixels of border to keep - */ - trim?: "border" | { - top?: number; - bottom?: number; - left?: number; - right?: number; - width?: number; - height?: number; - border?: boolean | { - color?: string; - tolerance?: number; - keep?: number; - }; - }; - /** - * Quality setting from 1-100 (useful values are in 60-90 range). Lower values - * make images look worse, but load faster. The default is 85. It applies only - * to JPEG and WebP images. It doesn’t have any effect on PNG. - */ - quality?: number | "low" | "medium-low" | "medium-high" | "high"; - /** - * Output format to generate. It can be: - * - avif: generate images in AVIF format. - * - webp: generate images in Google WebP format. Set quality to 100 to get - * the WebP-lossless format. - * - json: instead of generating an image, outputs information about the - * image, in JSON format. The JSON object will contain image size - * (before and after resizing), source image’s MIME type, file size, etc. - * - jpeg: generate images in JPEG format. - * - png: generate images in PNG format. - */ - format?: "avif" | "webp" | "json" | "jpeg" | "png" | "baseline-jpeg" | "png-force" | "svg"; - /** - * Whether to preserve animation frames from input files. Default is true. - * Setting it to false reduces animations to still images. This setting is - * recommended when enlarging images or processing arbitrary user content, - * because large GIF animations can weigh tens or even hundreds of megabytes. - * It is also useful to set anim:false when using format:"json" to get the - * response quicker without the number of frames. - */ - anim?: boolean; - /** - * What EXIF data should be preserved in the output image. Note that EXIF - * rotation and embedded color profiles are always applied ("baked in" into - * the image), and aren't affected by this option. Note that if the Polish - * feature is enabled, all metadata may have been removed already and this - * option may have no effect. - * - keep: Preserve most of EXIF metadata, including GPS location if there's - * any. - * - copyright: Only keep the copyright tag, and discard everything else. - * This is the default behavior for JPEG files. - * - none: Discard all invisible EXIF metadata. Currently WebP and PNG - * output formats always discard metadata. - */ - metadata?: "keep" | "copyright" | "none"; - /** - * Strength of sharpening filter to apply to the image. Floating-point - * number between 0 (no sharpening, default) and 10 (maximum). 1.0 is a - * recommended value for downscaled images. - */ - sharpen?: number; - /** - * Radius of a blur filter (approximate gaussian). Maximum supported radius - * is 250. - */ - blur?: number; - /** - * Overlays are drawn in the order they appear in the array (last array - * entry is the topmost layer). - */ - draw?: RequestInitCfPropertiesImageDraw[]; - /** - * Fetching image from authenticated origin. Setting this property will - * pass authentication headers (Authorization, Cookie, etc.) through to - * the origin. - */ - "origin-auth"?: "share-publicly"; - /** - * Adds a border around the image. The border is added after resizing. Border - * width takes dpr into account, and can be specified either using a single - * width property, or individually for each side. - */ - border?: { - color: string; - width: number; - } | { - color: string; - top: number; - right: number; - bottom: number; - left: number; - }; - /** - * Increase brightness by a factor. A value of 1.0 equals no change, a value - * of 0.5 equals half brightness, and a value of 2.0 equals twice as bright. - * 0 is ignored. - */ - brightness?: number; - /** - * Increase contrast by a factor. A value of 1.0 equals no change, a value of - * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is - * ignored. - */ - contrast?: number; - /** - * Increase exposure by a factor. A value of 1.0 equals no change, a value of - * 0.5 darkens the image, and a value of 2.0 lightens the image. 0 is ignored. - */ - gamma?: number; - /** - * Increase contrast by a factor. A value of 1.0 equals no change, a value of - * 0.5 equals low contrast, and a value of 2.0 equals high contrast. 0 is - * ignored. - */ - saturation?: number; - /** - * Flips the images horizontally, vertically, or both. Flipping is applied before - * rotation, so if you apply flip=h,rotate=90 then the image will be flipped - * horizontally, then rotated by 90 degrees. - */ - flip?: 'h' | 'v' | 'hv'; - /** - * Slightly reduces latency on a cache miss by selecting a - * quickest-to-compress file format, at a cost of increased file size and - * lower image quality. It will usually override the format option and choose - * JPEG over WebP or AVIF. We do not recommend using this option, except in - * unusual circumstances like resizing uncacheable dynamically-generated - * images. - */ - compression?: "fast"; -} -interface RequestInitCfPropertiesImageMinify { - javascript?: boolean; - css?: boolean; - html?: boolean; -} -interface RequestInitCfPropertiesR2 { - /** - * Colo id of bucket that an object is stored in - */ - bucketColoId?: number; -} -/** - * Request metadata provided by Cloudflare's edge. - */ -type IncomingRequestCfProperties = IncomingRequestCfPropertiesBase & IncomingRequestCfPropertiesBotManagementEnterprise & IncomingRequestCfPropertiesCloudflareForSaaSEnterprise & IncomingRequestCfPropertiesGeographicInformation & IncomingRequestCfPropertiesCloudflareAccessOrApiShield; -interface IncomingRequestCfPropertiesBase extends Record { - /** - * [ASN](https://www.iana.org/assignments/as-numbers/as-numbers.xhtml) of the incoming request. - * - * @example 395747 - */ - asn?: number; - /** - * The organization which owns the ASN of the incoming request. - * - * @example "Google Cloud" - */ - asOrganization?: string; - /** - * The original value of the `Accept-Encoding` header if Cloudflare modified it. - * - * @example "gzip, deflate, br" - */ - clientAcceptEncoding?: string; - /** - * The number of milliseconds it took for the request to reach your worker. - * - * @example 22 - */ - clientTcpRtt?: number; - /** - * The three-letter [IATA](https://en.wikipedia.org/wiki/IATA_airport_code) - * airport code of the data center that the request hit. - * - * @example "DFW" - */ - colo: string; - /** - * Represents the upstream's response to a - * [TCP `keepalive` message](https://tldp.org/HOWTO/TCP-Keepalive-HOWTO/overview.html) - * from cloudflare. - * - * For workers with no upstream, this will always be `1`. - * - * @example 3 - */ - edgeRequestKeepAliveStatus: IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus; - /** - * The HTTP Protocol the request used. - * - * @example "HTTP/2" - */ - httpProtocol: string; - /** - * The browser-requested prioritization information in the request object. - * - * If no information was set, defaults to the empty string `""` - * - * @example "weight=192;exclusive=0;group=3;group-weight=127" - * @default "" - */ - requestPriority: string; - /** - * The TLS version of the connection to Cloudflare. - * In requests served over plaintext (without TLS), this property is the empty string `""`. - * - * @example "TLSv1.3" - */ - tlsVersion: string; - /** - * The cipher for the connection to Cloudflare. - * In requests served over plaintext (without TLS), this property is the empty string `""`. - * - * @example "AEAD-AES128-GCM-SHA256" - */ - tlsCipher: string; - /** - * Metadata containing the [`HELLO`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2) and [`FINISHED`](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9) messages from this request's TLS handshake. - * - * If the incoming request was served over plaintext (without TLS) this field is undefined. - */ - tlsExportedAuthenticator?: IncomingRequestCfPropertiesExportedAuthenticatorMetadata; -} -interface IncomingRequestCfPropertiesBotManagementBase { - /** - * Cloudflare’s [level of certainty](https://developers.cloudflare.com/bots/concepts/bot-score/) that a request comes from a bot, - * represented as an integer percentage between `1` (almost certainly a bot) and `99` (almost certainly human). - * - * @example 54 - */ - score: number; - /** - * A boolean value that is true if the request comes from a good bot, like Google or Bing. - * Most customers choose to allow this traffic. For more details, see [Traffic from known bots](https://developers.cloudflare.com/firewall/known-issues-and-faq/#how-does-firewall-rules-handle-traffic-from-known-bots). - */ - verifiedBot: boolean; - /** - * A boolean value that is true if the request originates from a - * Cloudflare-verified proxy service. - */ - corporateProxy: boolean; - /** - * A boolean value that's true if the request matches [file extensions](https://developers.cloudflare.com/bots/reference/static-resources/) for many types of static resources. - */ - staticResource: boolean; - /** - * List of IDs that correlate to the Bot Management heuristic detections made on a request (you can have multiple heuristic detections on the same request). - */ - detectionIds: number[]; -} -interface IncomingRequestCfPropertiesBotManagement { - /** - * Results of Cloudflare's Bot Management analysis - */ - botManagement: IncomingRequestCfPropertiesBotManagementBase; - /** - * Duplicate of `botManagement.score`. - * - * @deprecated - */ - clientTrustScore: number; -} -interface IncomingRequestCfPropertiesBotManagementEnterprise extends IncomingRequestCfPropertiesBotManagement { - /** - * Results of Cloudflare's Bot Management analysis - */ - botManagement: IncomingRequestCfPropertiesBotManagementBase & { - /** - * A [JA3 Fingerprint](https://developers.cloudflare.com/bots/concepts/ja3-fingerprint/) to help profile specific SSL/TLS clients - * across different destination IPs, Ports, and X509 certificates. - */ - ja3Hash: string; - }; -} -interface IncomingRequestCfPropertiesCloudflareForSaaSEnterprise { - /** - * Custom metadata set per-host in [Cloudflare for SaaS](https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/). - * - * This field is only present if you have Cloudflare for SaaS enabled on your account - * and you have followed the [required steps to enable it]((https://developers.cloudflare.com/cloudflare-for-platforms/cloudflare-for-saas/domain-support/custom-metadata/)). - */ - hostMetadata?: HostMetadata; -} -interface IncomingRequestCfPropertiesCloudflareAccessOrApiShield { - /** - * Information about the client certificate presented to Cloudflare. - * - * This is populated when the incoming request is served over TLS using - * either Cloudflare Access or API Shield (mTLS) - * and the presented SSL certificate has a valid - * [Certificate Serial Number](https://ldapwiki.com/wiki/Certificate%20Serial%20Number) - * (i.e., not `null` or `""`). - * - * Otherwise, a set of placeholder values are used. - * - * The property `certPresented` will be set to `"1"` when - * the object is populated (i.e. the above conditions were met). - */ - tlsClientAuth: IncomingRequestCfPropertiesTLSClientAuth | IncomingRequestCfPropertiesTLSClientAuthPlaceholder; -} -/** - * Metadata about the request's TLS handshake - */ -interface IncomingRequestCfPropertiesExportedAuthenticatorMetadata { - /** - * The client's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal - * - * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" - */ - clientHandshake: string; - /** - * The server's [`HELLO` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.1.2), encoded in hexadecimal - * - * @example "44372ba35fa1270921d318f34c12f155dc87b682cf36a790cfaa3ba8737a1b5d" - */ - serverHandshake: string; - /** - * The client's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal - * - * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" - */ - clientFinished: string; - /** - * The server's [`FINISHED` message](https://www.rfc-editor.org/rfc/rfc5246#section-7.4.9), encoded in hexadecimal - * - * @example "084ee802fe1348f688220e2a6040a05b2199a761f33cf753abb1b006792d3f8b" - */ - serverFinished: string; -} -/** - * Geographic data about the request's origin. - */ -interface IncomingRequestCfPropertiesGeographicInformation { - /** - * The [ISO 3166-1 Alpha 2](https://www.iso.org/iso-3166-country-codes.html) country code the request originated from. - * - * If your worker is [configured to accept TOR connections](https://support.cloudflare.com/hc/en-us/articles/203306930-Understanding-Cloudflare-Tor-support-and-Onion-Routing), this may also be `"T1"`, indicating a request that originated over TOR. - * - * If Cloudflare is unable to determine where the request originated this property is omitted. - * - * The country code `"T1"` is used for requests originating on TOR. - * - * @example "GB" - */ - country?: Iso3166Alpha2Code | "T1"; - /** - * If present, this property indicates that the request originated in the EU - * - * @example "1" - */ - isEUCountry?: "1"; - /** - * A two-letter code indicating the continent the request originated from. - * - * @example "AN" - */ - continent?: ContinentCode; - /** - * The city the request originated from - * - * @example "Austin" - */ - city?: string; - /** - * Postal code of the incoming request - * - * @example "78701" - */ - postalCode?: string; - /** - * Latitude of the incoming request - * - * @example "30.27130" - */ - latitude?: string; - /** - * Longitude of the incoming request - * - * @example "-97.74260" - */ - longitude?: string; - /** - * Timezone of the incoming request - * - * @example "America/Chicago" - */ - timezone?: string; - /** - * If known, the ISO 3166-2 name for the first level region associated with - * the IP address of the incoming request - * - * @example "Texas" - */ - region?: string; - /** - * If known, the ISO 3166-2 code for the first-level region associated with - * the IP address of the incoming request - * - * @example "TX" - */ - regionCode?: string; - /** - * Metro code (DMA) of the incoming request - * - * @example "635" - */ - metroCode?: string; -} -/** Data about the incoming request's TLS certificate */ -interface IncomingRequestCfPropertiesTLSClientAuth { - /** Always `"1"`, indicating that the certificate was presented */ - certPresented: "1"; - /** - * Result of certificate verification. - * - * @example "FAILED:self signed certificate" - */ - certVerified: Exclude; - /** The presented certificate's revokation status. - * - * - A value of `"1"` indicates the certificate has been revoked - * - A value of `"0"` indicates the certificate has not been revoked - */ - certRevoked: "1" | "0"; - /** - * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) - * - * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certIssuerDN: string; - /** - * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) - * - * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certSubjectDN: string; - /** - * The certificate issuer's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) - * - * @example "CN=cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certIssuerDNRFC2253: string; - /** - * The certificate subject's [distinguished name](https://knowledge.digicert.com/generalinformation/INFO1745.html) ([RFC 2253](https://www.rfc-editor.org/rfc/rfc2253.html) formatted) - * - * @example "CN=*.cloudflareaccess.com, C=US, ST=Texas, L=Austin, O=Cloudflare" - */ - certSubjectDNRFC2253: string; - /** The certificate issuer's distinguished name (legacy policies) */ - certIssuerDNLegacy: string; - /** The certificate subject's distinguished name (legacy policies) */ - certSubjectDNLegacy: string; - /** - * The certificate's serial number - * - * @example "00936EACBE07F201DF" - */ - certSerial: string; - /** - * The certificate issuer's serial number - * - * @example "2489002934BDFEA34" - */ - certIssuerSerial: string; - /** - * The certificate's Subject Key Identifier - * - * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" - */ - certSKI: string; - /** - * The certificate issuer's Subject Key Identifier - * - * @example "BB:AF:7E:02:3D:FA:A6:F1:3C:84:8E:AD:EE:38:98:EC:D9:32:32:D4" - */ - certIssuerSKI: string; - /** - * The certificate's SHA-1 fingerprint - * - * @example "6b9109f323999e52259cda7373ff0b4d26bd232e" - */ - certFingerprintSHA1: string; - /** - * The certificate's SHA-256 fingerprint - * - * @example "acf77cf37b4156a2708e34c4eb755f9b5dbbe5ebb55adfec8f11493438d19e6ad3f157f81fa3b98278453d5652b0c1fd1d71e5695ae4d709803a4d3f39de9dea" - */ - certFingerprintSHA256: string; - /** - * The effective starting date of the certificate - * - * @example "Dec 22 19:39:00 2018 GMT" - */ - certNotBefore: string; - /** - * The effective expiration date of the certificate - * - * @example "Dec 22 19:39:00 2018 GMT" - */ - certNotAfter: string; -} -/** Placeholder values for TLS Client Authorization */ -interface IncomingRequestCfPropertiesTLSClientAuthPlaceholder { - certPresented: "0"; - certVerified: "NONE"; - certRevoked: "0"; - certIssuerDN: ""; - certSubjectDN: ""; - certIssuerDNRFC2253: ""; - certSubjectDNRFC2253: ""; - certIssuerDNLegacy: ""; - certSubjectDNLegacy: ""; - certSerial: ""; - certIssuerSerial: ""; - certSKI: ""; - certIssuerSKI: ""; - certFingerprintSHA1: ""; - certFingerprintSHA256: ""; - certNotBefore: ""; - certNotAfter: ""; -} -/** Possible outcomes of TLS verification */ -declare type CertVerificationStatus = -/** Authentication succeeded */ -"SUCCESS" -/** No certificate was presented */ - | "NONE" -/** Failed because the certificate was self-signed */ - | "FAILED:self signed certificate" -/** Failed because the certificate failed a trust chain check */ - | "FAILED:unable to verify the first certificate" -/** Failed because the certificate not yet valid */ - | "FAILED:certificate is not yet valid" -/** Failed because the certificate is expired */ - | "FAILED:certificate has expired" -/** Failed for another unspecified reason */ - | "FAILED"; -/** - * An upstream endpoint's response to a TCP `keepalive` message from Cloudflare. - */ -declare type IncomingRequestCfPropertiesEdgeRequestKeepAliveStatus = 0 /** Unknown */ | 1 /** no keepalives (not found) */ | 2 /** no connection re-use, opening keepalive connection failed */ | 3 /** no connection re-use, keepalive accepted and saved */ | 4 /** connection re-use, refused by the origin server (`TCP FIN`) */ | 5; /** connection re-use, accepted by the origin server */ -/** ISO 3166-1 Alpha-2 codes */ -declare type Iso3166Alpha2Code = "AD" | "AE" | "AF" | "AG" | "AI" | "AL" | "AM" | "AO" | "AQ" | "AR" | "AS" | "AT" | "AU" | "AW" | "AX" | "AZ" | "BA" | "BB" | "BD" | "BE" | "BF" | "BG" | "BH" | "BI" | "BJ" | "BL" | "BM" | "BN" | "BO" | "BQ" | "BR" | "BS" | "BT" | "BV" | "BW" | "BY" | "BZ" | "CA" | "CC" | "CD" | "CF" | "CG" | "CH" | "CI" | "CK" | "CL" | "CM" | "CN" | "CO" | "CR" | "CU" | "CV" | "CW" | "CX" | "CY" | "CZ" | "DE" | "DJ" | "DK" | "DM" | "DO" | "DZ" | "EC" | "EE" | "EG" | "EH" | "ER" | "ES" | "ET" | "FI" | "FJ" | "FK" | "FM" | "FO" | "FR" | "GA" | "GB" | "GD" | "GE" | "GF" | "GG" | "GH" | "GI" | "GL" | "GM" | "GN" | "GP" | "GQ" | "GR" | "GS" | "GT" | "GU" | "GW" | "GY" | "HK" | "HM" | "HN" | "HR" | "HT" | "HU" | "ID" | "IE" | "IL" | "IM" | "IN" | "IO" | "IQ" | "IR" | "IS" | "IT" | "JE" | "JM" | "JO" | "JP" | "KE" | "KG" | "KH" | "KI" | "KM" | "KN" | "KP" | "KR" | "KW" | "KY" | "KZ" | "LA" | "LB" | "LC" | "LI" | "LK" | "LR" | "LS" | "LT" | "LU" | "LV" | "LY" | "MA" | "MC" | "MD" | "ME" | "MF" | "MG" | "MH" | "MK" | "ML" | "MM" | "MN" | "MO" | "MP" | "MQ" | "MR" | "MS" | "MT" | "MU" | "MV" | "MW" | "MX" | "MY" | "MZ" | "NA" | "NC" | "NE" | "NF" | "NG" | "NI" | "NL" | "NO" | "NP" | "NR" | "NU" | "NZ" | "OM" | "PA" | "PE" | "PF" | "PG" | "PH" | "PK" | "PL" | "PM" | "PN" | "PR" | "PS" | "PT" | "PW" | "PY" | "QA" | "RE" | "RO" | "RS" | "RU" | "RW" | "SA" | "SB" | "SC" | "SD" | "SE" | "SG" | "SH" | "SI" | "SJ" | "SK" | "SL" | "SM" | "SN" | "SO" | "SR" | "SS" | "ST" | "SV" | "SX" | "SY" | "SZ" | "TC" | "TD" | "TF" | "TG" | "TH" | "TJ" | "TK" | "TL" | "TM" | "TN" | "TO" | "TR" | "TT" | "TV" | "TW" | "TZ" | "UA" | "UG" | "UM" | "US" | "UY" | "UZ" | "VA" | "VC" | "VE" | "VG" | "VI" | "VN" | "VU" | "WF" | "WS" | "YE" | "YT" | "ZA" | "ZM" | "ZW"; -/** The 2-letter continent codes Cloudflare uses */ -declare type ContinentCode = "AF" | "AN" | "AS" | "EU" | "NA" | "OC" | "SA"; -type CfProperties = IncomingRequestCfProperties | RequestInitCfProperties; -interface D1Meta { - duration: number; - size_after: number; - rows_read: number; - rows_written: number; - last_row_id: number; - changed_db: boolean; - changes: number; - /** - * The region of the database instance that executed the query. - */ - served_by_region?: string; - /** - * The three letters airport code of the colo that executed the query. - */ - served_by_colo?: string; - /** - * True if-and-only-if the database instance that executed the query was the primary. - */ - served_by_primary?: boolean; - timings?: { - /** - * The duration of the SQL query execution by the database instance. It doesn't include any network time. - */ - sql_duration_ms: number; - }; - /** - * Number of total attempts to execute the query, due to automatic retries. - * Note: All other fields in the response like `timings` only apply to the last attempt. - */ - total_attempts?: number; -} -interface D1Response { - success: true; - meta: D1Meta & Record; - error?: never; -} -type D1Result = D1Response & { - results: T[]; -}; -interface D1ExecResult { - count: number; - duration: number; -} -type D1SessionConstraint = -// Indicates that the first query should go to the primary, and the rest queries -// using the same D1DatabaseSession will go to any replica that is consistent with -// the bookmark maintained by the session (returned by the first query). -'first-primary' -// Indicates that the first query can go anywhere (primary or replica), and the rest queries -// using the same D1DatabaseSession will go to any replica that is consistent with -// the bookmark maintained by the session (returned by the first query). - | 'first-unconstrained'; -type D1SessionBookmark = string; -declare abstract class D1Database { - prepare(query: string): D1PreparedStatement; - batch(statements: D1PreparedStatement[]): Promise[]>; - exec(query: string): Promise; - /** - * Creates a new D1 Session anchored at the given constraint or the bookmark. - * All queries executed using the created session will have sequential consistency, - * meaning that all writes done through the session will be visible in subsequent reads. - * - * @param constraintOrBookmark Either the session constraint or the explicit bookmark to anchor the created session. - */ - withSession(constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession; - /** - * @deprecated dump() will be removed soon, only applies to deprecated alpha v1 databases. - */ - dump(): Promise; -} -declare abstract class D1DatabaseSession { - prepare(query: string): D1PreparedStatement; - batch(statements: D1PreparedStatement[]): Promise[]>; - /** - * @returns The latest session bookmark across all executed queries on the session. - * If no query has been executed yet, `null` is returned. - */ - getBookmark(): D1SessionBookmark | null; -} -declare abstract class D1PreparedStatement { - bind(...values: unknown[]): D1PreparedStatement; - first(colName: string): Promise; - first>(): Promise; - run>(): Promise>; - all>(): Promise>; - raw(options: { - columnNames: true; - }): Promise<[ - string[], - ...T[] - ]>; - raw(options?: { - columnNames?: false; - }): Promise; -} -// `Disposable` was added to TypeScript's standard lib types in version 5.2. -// To support older TypeScript versions, define an empty `Disposable` interface. -// Users won't be able to use `using`/`Symbol.dispose` without upgrading to 5.2, -// but this will ensure type checking on older versions still passes. -// TypeScript's interface merging will ensure our empty interface is effectively -// ignored when `Disposable` is included in the standard lib. -interface Disposable { -} -/** - * The returned data after sending an email - */ -interface EmailSendResult { - /** - * The Email Message ID - */ - messageId: string; -} -/** - * An email message that can be sent from a Worker. - */ -interface EmailMessage { - /** - * Envelope From attribute of the email message. - */ - readonly from: string; - /** - * Envelope To attribute of the email message. - */ - readonly to: string; -} -/** - * An email message that is sent to a consumer Worker and can be rejected/forwarded. - */ -interface ForwardableEmailMessage extends EmailMessage { - /** - * Stream of the email message content. - */ - readonly raw: ReadableStream; - /** - * An [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). - */ - readonly headers: Headers; - /** - * Size of the email message content. - */ - readonly rawSize: number; - /** - * Reject this email message by returning a permanent SMTP error back to the connecting client including the given reason. - * @param reason The reject reason. - * @returns void - */ - setReject(reason: string): void; - /** - * Forward this email message to a verified destination address of the account. - * @param rcptTo Verified destination address. - * @param headers A [Headers object](https://developer.mozilla.org/en-US/docs/Web/API/Headers). - * @returns A promise that resolves when the email message is forwarded. - */ - forward(rcptTo: string, headers?: Headers): Promise; - /** - * Reply to the sender of this email message with a new EmailMessage object. - * @param message The reply message. - * @returns A promise that resolves when the email message is replied. - */ - reply(message: EmailMessage): Promise; -} -/** A file attachment for an email message */ -type EmailAttachment = { - disposition: 'inline'; - contentId: string; - filename: string; - type: string; - content: string | ArrayBuffer | ArrayBufferView; -} | { - disposition: 'attachment'; - contentId?: undefined; - filename: string; - type: string; - content: string | ArrayBuffer | ArrayBufferView; -}; -/** An Email Address */ -interface EmailAddress { - name: string; - email: string; -} -/** - * A binding that allows a Worker to send email messages. - */ -interface SendEmail { - send(message: EmailMessage): Promise; - send(builder: { - from: string | EmailAddress; - to: string | string[]; - subject: string; - replyTo?: string | EmailAddress; - cc?: string | string[]; - bcc?: string | string[]; - headers?: Record; - text?: string; - html?: string; - attachments?: EmailAttachment[]; - }): Promise; -} -declare abstract class EmailEvent extends ExtendableEvent { - readonly message: ForwardableEmailMessage; -} -declare type EmailExportedHandler = (message: ForwardableEmailMessage, env: Env, ctx: ExecutionContext) => void | Promise; -declare module "cloudflare:email" { - let _EmailMessage: { - prototype: EmailMessage; - new (from: string, to: string, raw: ReadableStream | string): EmailMessage; - }; - export { _EmailMessage as EmailMessage }; -} -/** - * Evaluation context for targeting rules. - * Keys are attribute names (e.g. "userId", "country"), values are the attribute values. - */ -type FlagshipEvaluationContext = Record; -interface FlagshipEvaluationDetails { - flagKey: string; - value: T; - variant?: string | undefined; - reason?: string | undefined; - errorCode?: string | undefined; - errorMessage?: string | undefined; -} -interface FlagshipEvaluationError extends Error { -} -/** - * Feature flags binding for evaluating feature flags from a Cloudflare Workers script. - * - * @example - * ```typescript - * // Get a boolean flag value with a default - * const enabled = await env.FLAGS.getBooleanValue('my-feature', false); - * - * // Get a flag value with evaluation context for targeting - * const variant = await env.FLAGS.getStringValue('experiment', 'control', { - * userId: 'user-123', - * country: 'US', - * }); - * - * // Get full evaluation details including variant and reason - * const details = await env.FLAGS.getBooleanDetails('my-feature', false); - * console.log(details.variant, details.reason); - * ``` - */ -declare abstract class Flagship { - /** - * Get a flag value without type checking. - * @param flagKey The key of the flag to evaluate. - * @param defaultValue Optional default value returned when evaluation fails. - * @param context Optional evaluation context for targeting rules. - */ - get(flagKey: string, defaultValue?: unknown, context?: FlagshipEvaluationContext): Promise; - /** - * Get a boolean flag value. - * @param flagKey The key of the flag to evaluate. - * @param defaultValue Default value returned when evaluation fails or the flag type does not match. - * @param context Optional evaluation context for targeting rules. - */ - getBooleanValue(flagKey: string, defaultValue: boolean, context?: FlagshipEvaluationContext): Promise; - /** - * Get a string flag value. - * @param flagKey The key of the flag to evaluate. - * @param defaultValue Default value returned when evaluation fails or the flag type does not match. - * @param context Optional evaluation context for targeting rules. - */ - getStringValue(flagKey: string, defaultValue: string, context?: FlagshipEvaluationContext): Promise; - /** - * Get a number flag value. - * @param flagKey The key of the flag to evaluate. - * @param defaultValue Default value returned when evaluation fails or the flag type does not match. - * @param context Optional evaluation context for targeting rules. - */ - getNumberValue(flagKey: string, defaultValue: number, context?: FlagshipEvaluationContext): Promise; - /** - * Get an object flag value. - * @param flagKey The key of the flag to evaluate. - * @param defaultValue Default value returned when evaluation fails or the flag type does not match. - * @param context Optional evaluation context for targeting rules. - */ - getObjectValue(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise; - /** - * Get a boolean flag value with full evaluation details. - * @param flagKey The key of the flag to evaluate. - * @param defaultValue Default value returned when evaluation fails or the flag type does not match. - * @param context Optional evaluation context for targeting rules. - */ - getBooleanDetails(flagKey: string, defaultValue: boolean, context?: FlagshipEvaluationContext): Promise>; - /** - * Get a string flag value with full evaluation details. - * @param flagKey The key of the flag to evaluate. - * @param defaultValue Default value returned when evaluation fails or the flag type does not match. - * @param context Optional evaluation context for targeting rules. - */ - getStringDetails(flagKey: string, defaultValue: string, context?: FlagshipEvaluationContext): Promise>; - /** - * Get a number flag value with full evaluation details. - * @param flagKey The key of the flag to evaluate. - * @param defaultValue Default value returned when evaluation fails or the flag type does not match. - * @param context Optional evaluation context for targeting rules. - */ - getNumberDetails(flagKey: string, defaultValue: number, context?: FlagshipEvaluationContext): Promise>; - /** - * Get an object flag value with full evaluation details. - * @param flagKey The key of the flag to evaluate. - * @param defaultValue Default value returned when evaluation fails or the flag type does not match. - * @param context Optional evaluation context for targeting rules. - */ - getObjectDetails(flagKey: string, defaultValue: T, context?: FlagshipEvaluationContext): Promise>; -} -/** - * Hello World binding to serve as an explanatory example. DO NOT USE - */ -interface HelloWorldBinding { - /** - * Retrieve the current stored value - */ - get(): Promise<{ - value: string; - ms?: number; - }>; - /** - * Set a new stored value - */ - set(value: string): Promise; -} -interface Hyperdrive { - /** - * Connect directly to Hyperdrive as if it's your database, returning a TCP socket. - * - * Calling this method returns an identical socket to if you call - * `connect("host:port")` using the `host` and `port` fields from this object. - * Pick whichever approach works better with your preferred DB client library. - * - * Note that this socket is not yet authenticated -- it's expected that your - * code (or preferably, the client library of your choice) will authenticate - * using the information in this class's readonly fields. - */ - connect(): Socket; - /** - * A valid DB connection string that can be passed straight into the typical - * client library/driver/ORM. This will typically be the easiest way to use - * Hyperdrive. - */ - readonly connectionString: string; - /* - * A randomly generated hostname that is only valid within the context of the - * currently running Worker which, when passed into `connect()` function from - * the "cloudflare:sockets" module, will connect to the Hyperdrive instance - * for your database. - */ - readonly host: string; - /* - * The port that must be paired the the host field when connecting. - */ - readonly port: number; - /* - * The username to use when authenticating to your database via Hyperdrive. - * Unlike the host and password, this will be the same every time - */ - readonly user: string; - /* - * The randomly generated password to use when authenticating to your - * database via Hyperdrive. Like the host field, this password is only valid - * within the context of the currently running Worker instance from which - * it's read. - */ - readonly password: string; - /* - * The name of the database to connect to. - */ - readonly database: string; -} -// Copyright (c) 2024 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 -type ImageInfoResponse = { - format: 'image/svg+xml'; -} | { - format: string; - fileSize: number; - width: number; - height: number; -}; -type ImageTransform = { - width?: number; - height?: number; - background?: string; - blur?: number; - border?: { - color?: string; - width?: number; - } | { - top?: number; - bottom?: number; - left?: number; - right?: number; - }; - brightness?: number; - contrast?: number; - fit?: 'scale-down' | 'contain' | 'pad' | 'squeeze' | 'cover' | 'crop'; - flip?: 'h' | 'v' | 'hv'; - gamma?: number; - segment?: 'foreground'; - gravity?: 'face' | 'left' | 'right' | 'top' | 'bottom' | 'center' | 'auto' | 'entropy' | { - x?: number; - y?: number; - mode: 'remainder' | 'box-center'; - }; - rotate?: 0 | 90 | 180 | 270; - saturation?: number; - sharpen?: number; - trim?: 'border' | { - top?: number; - bottom?: number; - left?: number; - right?: number; - width?: number; - height?: number; - border?: boolean | { - color?: string; - tolerance?: number; - keep?: number; - }; - }; -}; -type ImageDrawOptions = { - opacity?: number; - repeat?: boolean | string; - top?: number; - left?: number; - bottom?: number; - right?: number; -}; -type ImageInputOptions = { - encoding?: 'base64'; -}; -type ImageOutputOptions = { - format: 'image/jpeg' | 'image/png' | 'image/gif' | 'image/webp' | 'image/avif' | 'rgb' | 'rgba'; - quality?: number; - background?: string; - anim?: boolean; -}; -interface ImageMetadata { - id: string; - filename?: string; - uploaded?: string; - requireSignedURLs: boolean; - meta?: Record; - variants: string[]; - draft?: boolean; - creator?: string; -} -interface ImageUploadOptions { - id?: string; - filename?: string; - requireSignedURLs?: boolean; - metadata?: Record; - creator?: string; - encoding?: 'base64'; -} -interface ImageUpdateOptions { - requireSignedURLs?: boolean; - metadata?: Record; - creator?: string; -} -interface ImageListOptions { - limit?: number; - cursor?: string; - sortOrder?: 'asc' | 'desc'; - creator?: string; -} -interface ImageList { - images: ImageMetadata[]; - cursor?: string; - listComplete: boolean; -} -interface ImageHandle { - /** - * Get metadata for a hosted image - * @returns Image metadata, or null if not found - */ - details(): Promise; - /** - * Get the raw image data for a hosted image - * @returns ReadableStream of image bytes, or null if not found - */ - bytes(): Promise | null>; - /** - * Update hosted image metadata - * @param options Properties to update - * @returns Updated image metadata - * @throws {@link ImagesError} if update fails - */ - update(options: ImageUpdateOptions): Promise; - /** - * Delete a hosted image - * @returns True if deleted, false if not found - */ - delete(): Promise; -} -interface HostedImagesBinding { - /** - * Get a handle for a hosted image - * @param imageId The ID of the image (UUID or custom ID) - * @returns A handle for per-image operations - */ - image(imageId: string): ImageHandle; - /** - * Upload a new hosted image - * @param image The image file to upload - * @param options Upload configuration - * @returns Metadata for the uploaded image - * @throws {@link ImagesError} if upload fails - */ - upload(image: ReadableStream | ArrayBuffer, options?: ImageUploadOptions): Promise; - /** - * List hosted images with pagination - * @param options List configuration - * @returns List of images with pagination info - * @throws {@link ImagesError} if list fails - */ - list(options?: ImageListOptions): Promise; -} -interface ImagesBinding { - /** - * Get image metadata (type, width and height) - * @throws {@link ImagesError} with code 9412 if input is not an image - * @param stream The image bytes - */ - info(stream: ReadableStream, options?: ImageInputOptions): Promise; - /** - * Begin applying a series of transformations to an image - * @param stream The image bytes - * @returns A transform handle - */ - input(stream: ReadableStream, options?: ImageInputOptions): ImageTransformer; - /** - * Access hosted images CRUD operations - */ - readonly hosted: HostedImagesBinding; -} -interface ImageTransformer { - /** - * Apply transform next, returning a transform handle. - * You can then apply more transformations, draw, or retrieve the output. - * @param transform - */ - transform(transform: ImageTransform): ImageTransformer; - /** - * Draw an image on this transformer, returning a transform handle. - * You can then apply more transformations, draw, or retrieve the output. - * @param image The image (or transformer that will give the image) to draw - * @param options The options configuring how to draw the image - */ - draw(image: ReadableStream | ImageTransformer, options?: ImageDrawOptions): ImageTransformer; - /** - * Retrieve the image that results from applying the transforms to the - * provided input - * @param options Options that apply to the output e.g. output format - */ - output(options: ImageOutputOptions): Promise; -} -type ImageTransformationOutputOptions = { - encoding?: 'base64'; -}; -interface ImageTransformationResult { - /** - * The image as a response, ready to store in cache or return to users - */ - response(): Response; - /** - * The content type of the returned image - */ - contentType(): string; - /** - * The bytes of the response - */ - image(options?: ImageTransformationOutputOptions): ReadableStream; -} -interface ImagesError extends Error { - readonly code: number; - readonly message: string; - readonly stack?: string; -} -/** - * Media binding for transforming media streams. - * Provides the entry point for media transformation operations. - */ -interface MediaBinding { - /** - * Creates a media transformer from an input stream. - * @param media - The input media bytes - * @returns A MediaTransformer instance for applying transformations - */ - input(media: ReadableStream): MediaTransformer; -} -/** - * Media transformer for applying transformation operations to media content. - * Handles sizing, fitting, and other input transformation parameters. - */ -interface MediaTransformer { - /** - * Applies transformation options to the media content. - * @param transform - Configuration for how the media should be transformed - * @returns A generator for producing the transformed media output - */ - transform(transform?: MediaTransformationInputOptions): MediaTransformationGenerator; - /** - * Generates the final media output with specified options. - * @param output - Configuration for the output format and parameters - * @returns The final transformation result containing the transformed media - */ - output(output?: MediaTransformationOutputOptions): MediaTransformationResult; -} -/** - * Generator for producing media transformation results. - * Configures the output format and parameters for the transformed media. - */ -interface MediaTransformationGenerator { - /** - * Generates the final media output with specified options. - * @param output - Configuration for the output format and parameters - * @returns The final transformation result containing the transformed media - */ - output(output?: MediaTransformationOutputOptions): MediaTransformationResult; -} -/** - * Result of a media transformation operation. - * Provides multiple ways to access the transformed media content. - */ -interface MediaTransformationResult { - /** - * Returns the transformed media as a readable stream of bytes. - * @returns A promise containing a readable stream with the transformed media - */ - media(): Promise>; - /** - * Returns the transformed media as an HTTP response object. - * @returns The transformed media as a Promise, ready to store in cache or return to users - */ - response(): Promise; - /** - * Returns the MIME type of the transformed media. - * @returns A promise containing the content type string (e.g., 'image/jpeg', 'video/mp4') - */ - contentType(): Promise; -} -/** - * Configuration options for transforming media input. - * Controls how the media should be resized and fitted. - */ -type MediaTransformationInputOptions = { - /** How the media should be resized to fit the specified dimensions */ - fit?: 'contain' | 'cover' | 'scale-down'; - /** Target width in pixels */ - width?: number; - /** Target height in pixels */ - height?: number; -}; -/** - * Configuration options for Media Transformations output. - * Controls the format, timing, and type of the generated output. - */ -type MediaTransformationOutputOptions = { - /** - * Output mode determining the type of media to generate - */ - mode?: 'video' | 'spritesheet' | 'frame' | 'audio'; - /** Whether to include audio in the output */ - audio?: boolean; - /** - * Starting timestamp for frame extraction or start time for clips. (e.g. '2s'). - */ - time?: string; - /** - * Duration for video clips, audio extraction, and spritesheet generation (e.g. '5s'). - */ - duration?: string; - /** - * Number of frames in the spritesheet. - */ - imageCount?: number; - /** - * Output format for the generated media. - */ - format?: 'jpg' | 'png' | 'm4a'; -}; -/** - * Error object for media transformation operations. - * Extends the standard Error interface with additional media-specific information. - */ -interface MediaError extends Error { - readonly code: number; - readonly message: string; - readonly stack?: string; -} -declare module 'cloudflare:node' { - interface NodeStyleServer { - listen(...args: unknown[]): this; - address(): { - port?: number | null | undefined; - }; - } - export function httpServerHandler(port: number): ExportedHandler; - export function httpServerHandler(options: { - port: number; - }): ExportedHandler; - export function httpServerHandler(server: NodeStyleServer): ExportedHandler; -} -type Params

= Record; -type EventContext = { - request: Request>; - functionPath: string; - waitUntil: (promise: Promise) => void; - passThroughOnException: () => void; - next: (input?: Request | string, init?: RequestInit) => Promise; - env: Env & { - ASSETS: { - fetch: typeof fetch; - }; - }; - params: Params

; - data: Data; -}; -type PagesFunction = Record> = (context: EventContext) => Response | Promise; -type EventPluginContext = { - request: Request>; - functionPath: string; - waitUntil: (promise: Promise) => void; - passThroughOnException: () => void; - next: (input?: Request | string, init?: RequestInit) => Promise; - env: Env & { - ASSETS: { - fetch: typeof fetch; - }; - }; - params: Params

; - data: Data; - pluginArgs: PluginArgs; -}; -type PagesPluginFunction = Record, PluginArgs = unknown> = (context: EventPluginContext) => Response | Promise; -declare module "assets:*" { - export const onRequest: PagesFunction; -} -// Copyright (c) 2022-2023 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 -declare module "cloudflare:pipelines" { - export abstract class PipelineTransformationEntrypoint { - protected env: Env; - protected ctx: ExecutionContext; - constructor(ctx: ExecutionContext, env: Env); - /** - * run receives an array of PipelineRecord which can be - * transformed and returned to the pipeline - * @param records Incoming records from the pipeline to be transformed - * @param metadata Information about the specific pipeline calling the transformation entrypoint - * @returns A promise containing the transformed PipelineRecord array - */ - public run(records: I[], metadata: PipelineBatchMetadata): Promise; - } - export type PipelineRecord = Record; - export type PipelineBatchMetadata = { - pipelineId: string; - pipelineName: string; - }; - export interface Pipeline { - /** - * The Pipeline interface represents the type of a binding to a Pipeline - * - * @param records The records to send to the pipeline - */ - send(records: T[]): Promise; - } -} -// PubSubMessage represents an incoming PubSub message. -// The message includes metadata about the broker, the client, and the payload -// itself. -// https://developers.cloudflare.com/pub-sub/ -interface PubSubMessage { - // Message ID - readonly mid: number; - // MQTT broker FQDN in the form mqtts://BROKER.NAMESPACE.cloudflarepubsub.com:PORT - readonly broker: string; - // The MQTT topic the message was sent on. - readonly topic: string; - // The client ID of the client that published this message. - readonly clientId: string; - // The unique identifier (JWT ID) used by the client to authenticate, if token - // auth was used. - readonly jti?: string; - // A Unix timestamp (seconds from Jan 1, 1970), set when the Pub/Sub Broker - // received the message from the client. - readonly receivedAt: number; - // An (optional) string with the MIME type of the payload, if set by the - // client. - readonly contentType: string; - // Set to 1 when the payload is a UTF-8 string - // https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901063 - readonly payloadFormatIndicator: number; - // Pub/Sub (MQTT) payloads can be UTF-8 strings, or byte arrays. - // You can use payloadFormatIndicator to inspect this before decoding. - payload: string | Uint8Array; -} -// JsonWebKey extended by kid parameter -interface JsonWebKeyWithKid extends JsonWebKey { - // Key Identifier of the JWK - readonly kid: string; -} -interface RateLimitOptions { - key: string; -} -interface RateLimitOutcome { - success: boolean; -} -interface RateLimit { - /** - * Rate limit a request based on the provided options. - * @see https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/ - * @returns A promise that resolves with the outcome of the rate limit. - */ - limit(options: RateLimitOptions): Promise; -} -// Namespace for RPC utility types. Unfortunately, we can't use a `module` here as these types need -// to referenced by `Fetcher`. This is included in the "importable" version of the types which -// strips all `module` blocks. -declare namespace Rpc { - // Branded types for identifying `WorkerEntrypoint`/`DurableObject`/`Target`s. - // TypeScript uses *structural* typing meaning anything with the same shape as type `T` is a `T`. - // For the classes exported by `cloudflare:workers` we want *nominal* typing (i.e. we only want to - // accept `WorkerEntrypoint` from `cloudflare:workers`, not any other class with the same shape) - export const __RPC_STUB_BRAND: '__RPC_STUB_BRAND'; - export const __RPC_TARGET_BRAND: '__RPC_TARGET_BRAND'; - export const __WORKER_ENTRYPOINT_BRAND: '__WORKER_ENTRYPOINT_BRAND'; - export const __DURABLE_OBJECT_BRAND: '__DURABLE_OBJECT_BRAND'; - export const __WORKFLOW_ENTRYPOINT_BRAND: '__WORKFLOW_ENTRYPOINT_BRAND'; - export interface RpcTargetBranded { - [__RPC_TARGET_BRAND]: never; - } - export interface WorkerEntrypointBranded { - [__WORKER_ENTRYPOINT_BRAND]: never; - } - export interface DurableObjectBranded { - [__DURABLE_OBJECT_BRAND]: never; - } - export interface WorkflowEntrypointBranded { - [__WORKFLOW_ENTRYPOINT_BRAND]: never; - } - export type EntrypointBranded = WorkerEntrypointBranded | DurableObjectBranded | WorkflowEntrypointBranded; - // Types that can be used through `Stub`s - export type Stubable = RpcTargetBranded | ((...args: any[]) => any); - // Types that can be passed over RPC - // The reason for using a generic type here is to build a serializable subset of structured - // cloneable composite types. This allows types defined with the "interface" keyword to pass the - // serializable check as well. Otherwise, only types defined with the "type" keyword would pass. - type Serializable = - // Structured cloneables - BaseType - // Structured cloneable composites - | Map ? Serializable : never, T extends Map ? Serializable : never> | Set ? Serializable : never> | ReadonlyArray ? Serializable : never> | { - [K in keyof T]: K extends number | string ? Serializable : never; - } - // Special types - | Stub - // Serialized as stubs, see `Stubify` - | Stubable; - // Base type for all RPC stubs, including common memory management methods. - // `T` is used as a marker type for unwrapping `Stub`s later. - interface StubBase extends Disposable { - [__RPC_STUB_BRAND]: T; - dup(): this; - } - export type Stub = Provider & StubBase; - // This represents all the types that can be sent as-is over an RPC boundary - type BaseType = void | undefined | null | boolean | number | bigint | string | TypedArray | ArrayBuffer | DataView | Date | Error | RegExp | ReadableStream | WritableStream | Request | Response | Headers; - // Recursively rewrite all `Stubable` types with `Stub`s - // prettier-ignore - type Stubify = T extends Stubable ? Stub : T extends Map ? Map, Stubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { - [key: string | number]: any; - } ? { - [K in keyof T]: Stubify; - } : T; - // Recursively rewrite all `Stub`s with the corresponding `T`s. - // Note we use `StubBase` instead of `Stub` here to avoid circular dependencies: - // `Stub` depends on `Provider`, which depends on `Unstubify`, which would depend on `Stub`. - // prettier-ignore - type Unstubify = T extends StubBase ? V : T extends Map ? Map, Unstubify> : T extends Set ? Set> : T extends Array ? Array> : T extends ReadonlyArray ? ReadonlyArray> : T extends BaseType ? T : T extends { - [key: string | number]: unknown; - } ? { - [K in keyof T]: Unstubify; - } : T; - type UnstubifyAll = { - [I in keyof A]: Unstubify; - }; - // Utility type for adding `Provider`/`Disposable`s to `object` types only. - // Note `unknown & T` is equivalent to `T`. - type MaybeProvider = T extends object ? Provider : unknown; - type MaybeDisposable = T extends object ? Disposable : unknown; - // Type for method return or property on an RPC interface. - // - Stubable types are replaced by stubs. - // - Serializable types are passed by value, with stubable types replaced by stubs - // and a top-level `Disposer`. - // Everything else can't be passed over PRC. - // Technically, we use custom thenables here, but they quack like `Promise`s. - // Intersecting with `(Maybe)Provider` allows pipelining. - // prettier-ignore - type Result = R extends Stubable ? Promise> & Provider : R extends Serializable ? Promise & MaybeDisposable> & MaybeProvider : never; - // Type for method or property on an RPC interface. - // For methods, unwrap `Stub`s in parameters, and rewrite returns to be `Result`s. - // Unwrapping `Stub`s allows calling with `Stubable` arguments. - // For properties, rewrite types to be `Result`s. - // In each case, unwrap `Promise`s. - type MethodOrProperty = V extends (...args: infer P) => infer R ? (...args: UnstubifyAll

) => Result> : Result>; - // Type for the callable part of an `Provider` if `T` is callable. - // This is intersected with methods/properties. - type MaybeCallableProvider = T extends (...args: any[]) => any ? MethodOrProperty : unknown; - // Base type for all other types providing RPC-like interfaces. - // Rewrites all methods/properties to be `MethodOrProperty`s, while preserving callable types. - // `Reserved` names (e.g. stub method names like `dup()`) and symbols can't be accessed over RPC. - export type Provider = MaybeCallableProvider & Pick<{ - [K in keyof T]: MethodOrProperty; - }, Exclude>>; -} -declare namespace Cloudflare { - // Type of `env`. - // - // The specific project can extend `Env` by redeclaring it in project-specific files. Typescript - // will merge all declarations. - // - // You can use `wrangler types` to generate the `Env` type automatically. - interface Env { - } - // Project-specific parameters used to inform types. - // - // This interface is, again, intended to be declared in project-specific files, and then that - // declaration will be merged with this one. - // - // A project should have a declaration like this: - // - // interface GlobalProps { - // // Declares the main module's exports. Used to populate Cloudflare.Exports aka the type - // // of `ctx.exports`. - // mainModule: typeof import("my-main-module"); - // - // // Declares which of the main module's exports are configured with durable storage, and - // // thus should behave as Durable Object namsepace bindings. - // durableNamespaces: "MyDurableObject" | "AnotherDurableObject"; - // } - // - // You can use `wrangler types` to generate `GlobalProps` automatically. - interface GlobalProps { - } - // Evaluates to the type of a property in GlobalProps, defaulting to `Default` if it is not - // present. - type GlobalProp = K extends keyof GlobalProps ? GlobalProps[K] : Default; - // The type of the program's main module exports, if known. Requires `GlobalProps` to declare the - // `mainModule` property. - type MainModule = GlobalProp<"mainModule", {}>; - // The type of ctx.exports, which contains loopback bindings for all top-level exports. - type Exports = { - [K in keyof MainModule]: LoopbackForExport - // If the export is listed in `durableNamespaces`, then it is also a - // DurableObjectNamespace. - & (K extends GlobalProp<"durableNamespaces", never> ? MainModule[K] extends new (...args: any[]) => infer DoInstance ? DoInstance extends Rpc.DurableObjectBranded ? DurableObjectNamespace : DurableObjectNamespace : DurableObjectNamespace : {}); - }; -} -declare namespace CloudflareWorkersModule { - export type RpcStub = Rpc.Stub; - export const RpcStub: { - new (value: T): Rpc.Stub; - }; - export abstract class RpcTarget implements Rpc.RpcTargetBranded { - [Rpc.__RPC_TARGET_BRAND]: never; - } - // `protected` fields don't appear in `keyof`s, so can't be accessed over RPC - export abstract class WorkerEntrypoint implements Rpc.WorkerEntrypointBranded { - [Rpc.__WORKER_ENTRYPOINT_BRAND]: never; - protected ctx: ExecutionContext; - protected env: Env; - constructor(ctx: ExecutionContext, env: Env); - email?(message: ForwardableEmailMessage): void | Promise; - fetch?(request: Request): Response | Promise; - connect?(socket: Socket): void | Promise; - queue?(batch: MessageBatch): void | Promise; - scheduled?(controller: ScheduledController): void | Promise; - tail?(events: TraceItem[]): void | Promise; - tailStream?(event: TailStream.TailEvent): TailStream.TailEventHandlerType | Promise; - test?(controller: TestController): void | Promise; - trace?(traces: TraceItem[]): void | Promise; - } - export abstract class DurableObject implements Rpc.DurableObjectBranded { - [Rpc.__DURABLE_OBJECT_BRAND]: never; - protected ctx: DurableObjectState; - protected env: Env; - constructor(ctx: DurableObjectState, env: Env); - alarm?(alarmInfo?: AlarmInvocationInfo): void | Promise; - fetch?(request: Request): Response | Promise; - connect?(socket: Socket): void | Promise; - webSocketMessage?(ws: WebSocket, message: string | ArrayBuffer): void | Promise; - webSocketClose?(ws: WebSocket, code: number, reason: string, wasClean: boolean): void | Promise; - webSocketError?(ws: WebSocket, error: unknown): void | Promise; - } - export type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; - export type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; - export type WorkflowDelayDuration = WorkflowSleepDuration; - export type WorkflowTimeoutDuration = WorkflowSleepDuration; - export type WorkflowRetentionDuration = WorkflowSleepDuration; - export type WorkflowBackoff = 'constant' | 'linear' | 'exponential'; - export type WorkflowStepConfig = { - retries?: { - limit: number; - delay: WorkflowDelayDuration | number; - backoff?: WorkflowBackoff; - }; - timeout?: WorkflowTimeoutDuration | number; - }; - export type WorkflowEvent = { - payload: Readonly; - timestamp: Date; - instanceId: string; - }; - export type WorkflowStepEvent = { - payload: Readonly; - timestamp: Date; - type: string; - }; - export type WorkflowStepContext = { - step: { - name: string; - count: number; - }; - attempt: number; - config: WorkflowStepConfig; - }; - export abstract class WorkflowStep { - do>(name: string, callback: (ctx: WorkflowStepContext) => Promise): Promise; - do>(name: string, config: WorkflowStepConfig, callback: (ctx: WorkflowStepContext) => Promise): Promise; - sleep: (name: string, duration: WorkflowSleepDuration) => Promise; - sleepUntil: (name: string, timestamp: Date | number) => Promise; - waitForEvent>(name: string, options: { - type: string; - timeout?: WorkflowTimeoutDuration | number; - }): Promise>; - } - export type WorkflowInstanceStatus = 'queued' | 'running' | 'paused' | 'errored' | 'terminated' | 'complete' | 'waiting' | 'waitingForPause' | 'unknown'; - export abstract class WorkflowEntrypoint | unknown = unknown> implements Rpc.WorkflowEntrypointBranded { - [Rpc.__WORKFLOW_ENTRYPOINT_BRAND]: never; - protected ctx: ExecutionContext; - protected env: Env; - constructor(ctx: ExecutionContext, env: Env); - run(event: Readonly>, step: WorkflowStep): Promise; - } - export function waitUntil(promise: Promise): void; - export function withEnv(newEnv: unknown, fn: () => unknown): unknown; - export function withExports(newExports: unknown, fn: () => unknown): unknown; - export function withEnvAndExports(newEnv: unknown, newExports: unknown, fn: () => unknown): unknown; - export const env: Cloudflare.Env; - export const exports: Cloudflare.Exports; - export const cache: CacheContext; - export const tracing: Tracing; -} -declare module 'cloudflare:workers' { - export = CloudflareWorkersModule; -} -interface SecretsStoreSecret { - /** - * Get a secret from the Secrets Store, returning a string of the secret value - * if it exists, or throws an error if it does not exist - */ - get(): Promise; -} -declare module "cloudflare:sockets" { - function _connect(address: string | SocketAddress, options?: SocketOptions): Socket; - export { _connect as connect }; -} -/** - * Binding entrypoint for Cloudflare Stream. - * - * Usage: - * - Binding-level operations: - * `await env.STREAM.videos.upload` - * `await env.STREAM.videos.createDirectUpload` - * `await env.STREAM.videos.*` - * `await env.STREAM.watermarks.*` - * - Per-video operations: - * `await env.STREAM.video(id).downloads.*` - * `await env.STREAM.video(id).captions.*` - * - * Example usage: - * ```ts - * await env.STREAM.video(id).downloads.generate(); - * - * const video = env.STREAM.video(id) - * const captions = video.captions.list(); - * const videoDetails = video.details() - * ``` - */ -interface StreamBinding { - /** - * Returns a handle scoped to a single video for per-video operations. - * @param id The unique identifier for the video. - * @returns A handle for per-video operations. - */ - video(id: string): StreamVideoHandle; - /** - * Uploads a new video from a provided URL. - * @param url The URL to upload from. - * @param params Optional upload parameters. - * @returns The uploaded video details. - * @throws {BadRequestError} if the upload parameter is invalid or the URL is invalid - * @throws {QuotaReachedError} if the account storage capacity is exceeded - * @throws {MaxFileSizeError} if the file size is too large - * @throws {RateLimitedError} if the server received too many requests - * @throws {AlreadyUploadedError} if a video was already uploaded to this URL - * @throws {InternalError} if an unexpected error occurs - */ - upload(url: string, params?: StreamUrlUploadParams): Promise; - /** - * Creates a direct upload that allows video uploads without an API key. - * @param params Parameters for the direct upload - * @returns The direct upload details. - * @throws {BadRequestError} if the parameters are invalid - * @throws {RateLimitedError} if the server received too many requests - * @throws {InternalError} if an unexpected error occurs - */ - createDirectUpload(params: StreamDirectUploadCreateParams): Promise; - videos: StreamVideos; - watermarks: StreamWatermarks; -} -/** - * Handle for operations scoped to a single Stream video. - */ -interface StreamVideoHandle { - /** - * The unique identifier for the video. - */ - id: string; - /** - * Get a full videos details - * @returns The full video details. - * @throws {NotFoundError} if the video is not found - * @throws {InternalError} if an unexpected error occurs - */ - details(): Promise; - /** - * Update details for a single video. - * @param params The fields to update for the video. - * @returns The updated video details. - * @throws {NotFoundError} if the video is not found - * @throws {BadRequestError} if the parameters are invalid - * @throws {InternalError} if an unexpected error occurs - */ - update(params: StreamUpdateVideoParams): Promise; - /** - * Deletes a video and its copies from Cloudflare Stream. - * @returns A promise that resolves when deletion completes. - * @throws {NotFoundError} if the video is not found - * @throws {InternalError} if an unexpected error occurs - */ - delete(): Promise; - /** - * Creates a signed URL token for a video. - * @returns The signed token that was created. - * @throws {InternalError} if the signing key cannot be retrieved or the token cannot be signed - */ - generateToken(): Promise; - downloads: StreamScopedDownloads; - captions: StreamScopedCaptions; -} -interface StreamVideo { - /** - * The unique identifier for the video. - */ - id: string; - /** - * A user-defined identifier for the media creator. - */ - creator: string | null; - /** - * The thumbnail URL for the video. - */ - thumbnail: string; - /** - * The thumbnail timestamp percentage. - */ - thumbnailTimestampPct: number; - /** - * Indicates whether the video is ready to stream. - */ - readyToStream: boolean; - /** - * The date and time the video became ready to stream. - */ - readyToStreamAt: string | null; - /** - * Processing status information. - */ - status: StreamVideoStatus; - /** - * A user modifiable key-value store. - */ - meta: Record; - /** - * The date and time the video was created. - */ - created: string; - /** - * The date and time the video was last modified. - */ - modified: string; - /** - * The date and time at which the video will be deleted. - */ - scheduledDeletion: string | null; - /** - * The size of the video in bytes. - */ - size: number; - /** - * The preview URL for the video. - */ - preview?: string; - /** - * Origins allowed to display the video. - */ - allowedOrigins: Array; - /** - * Indicates whether signed URLs are required. - */ - requireSignedURLs: boolean | null; - /** - * The date and time the video was uploaded. - */ - uploaded: string | null; - /** - * The date and time when the upload URL expires. - */ - uploadExpiry: string | null; - /** - * The maximum size in bytes for direct uploads. - */ - maxSizeBytes: number | null; - /** - * The maximum duration in seconds for direct uploads. - */ - maxDurationSeconds: number | null; - /** - * The video duration in seconds. -1 indicates unknown. - */ - duration: number; - /** - * Input metadata for the original upload. - */ - input: StreamVideoInput; - /** - * Playback URLs for the video. - */ - hlsPlaybackUrl: string; - dashPlaybackUrl: string; - /** - * The watermark applied to the video, if any. - */ - watermark: StreamWatermark | null; - /** - * The live input id associated with the video, if any. - */ - liveInputId?: string | null; - /** - * The source video id if this is a clip. - */ - clippedFromId: string | null; - /** - * Public details associated with the video. - */ - publicDetails: StreamPublicDetails | null; -} -type StreamVideoStatus = { - /** - * The current processing state. - */ - state: string; - /** - * The current processing step. - */ - step?: string; - /** - * The percent complete as a string. - */ - pctComplete?: string; - /** - * An error reason code, if applicable. - */ - errorReasonCode: string; - /** - * An error reason text, if applicable. - */ - errorReasonText: string; -}; -type StreamVideoInput = { - /** - * The input width in pixels. - */ - width: number; - /** - * The input height in pixels. - */ - height: number; -}; -type StreamPublicDetails = { - /** - * The public title for the video. - */ - title: string | null; - /** - * The public share link. - */ - share_link: string | null; - /** - * The public channel link. - */ - channel_link: string | null; - /** - * The public logo URL. - */ - logo: string | null; -}; -type StreamDirectUpload = { - /** - * The URL an unauthenticated upload can use for a single multipart request. - */ - uploadURL: string; - /** - * A Cloudflare-generated unique identifier for a media item. - */ - id: string; - /** - * The watermark profile applied to the upload. - */ - watermark: StreamWatermark | null; - /** - * The scheduled deletion time, if any. - */ - scheduledDeletion: string | null; -}; -type StreamDirectUploadCreateParams = { - /** - * The maximum duration in seconds for a video upload. - */ - maxDurationSeconds: number; - /** - * The date and time after upload when videos will not be accepted. - */ - expiry?: string; - /** - * A user-defined identifier for the media creator. - */ - creator?: string; - /** - * A user modifiable key-value store used to reference other systems of record for - * managing videos. - */ - meta?: Record; - /** - * Lists the origins allowed to display the video. - */ - allowedOrigins?: Array; - /** - * Indicates whether the video can be accessed using the id. When set to `true`, - * a signed token must be generated with a signing key to view the video. - */ - requireSignedURLs?: boolean; - /** - * The thumbnail timestamp percentage. - */ - thumbnailTimestampPct?: number; - /** - * The date and time at which the video will be deleted. Include `null` to remove - * a scheduled deletion. - */ - scheduledDeletion?: string | null; - /** - * The watermark profile to apply. - */ - watermark?: StreamDirectUploadWatermark; -}; -type StreamDirectUploadWatermark = { - /** - * The unique identifier for the watermark profile. - */ - id: string; -}; -type StreamUrlUploadParams = { - /** - * Lists the origins allowed to display the video. Enter allowed origin - * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the - * video to be viewed on any origin. - */ - allowedOrigins?: Array; - /** - * A user-defined identifier for the media creator. - */ - creator?: string; - /** - * A user modifiable key-value store used to reference other systems of - * record for managing videos. - */ - meta?: Record; - /** - * Indicates whether the video can be a accessed using the id. When - * set to `true`, a signed token must be generated with a signing key to view the - * video. - */ - requireSignedURLs?: boolean; - /** - * Indicates the date and time at which the video will be deleted. Omit - * the field to indicate no change, or include with a `null` value to remove an - * existing scheduled deletion. If specified, must be at least 30 days from upload - * time. - */ - scheduledDeletion?: string | null; - /** - * The timestamp for a thumbnail image calculated as a percentage value - * of the video's duration. To convert from a second-wise timestamp to a - * percentage, divide the desired timestamp by the total duration of the video. If - * this value is not set, the default thumbnail image is taken from 0s of the - * video. - */ - thumbnailTimestampPct?: number; - /** - * The identifier for the watermark profile - */ - watermarkId?: string; -}; -interface StreamScopedCaptions { - /** - * Uploads the caption or subtitle file to the endpoint for a specific BCP47 language. - * One caption or subtitle file per language is allowed. - * @param language The BCP 47 language tag for the caption or subtitle. - * @param input The caption or subtitle stream to upload. - * @returns The created caption entry. - * @throws {NotFoundError} if the video is not found - * @throws {BadRequestError} if the language or file is invalid - * @throws {InternalError} if an unexpected error occurs - */ - upload(language: string, input: ReadableStream): Promise; - /** - * Generate captions or subtitles for the provided language via AI. - * @param language The BCP 47 language tag to generate. - * @returns The generated caption entry. - * @throws {NotFoundError} if the video is not found - * @throws {BadRequestError} if the language is invalid - * @throws {StreamError} if a generated caption already exists - * @throws {StreamError} if the video duration is too long - * @throws {StreamError} if the video is missing audio - * @throws {StreamError} if the requested language is not supported - * @throws {InternalError} if an unexpected error occurs - */ - generate(language: string): Promise; - /** - * Lists the captions or subtitles. - * Use the language parameter to filter by a specific language. - * @param language The optional BCP 47 language tag to filter by. - * @returns The list of captions or subtitles. - * @throws {NotFoundError} if the video or caption is not found - * @throws {InternalError} if an unexpected error occurs - */ - list(language?: string): Promise; - /** - * Removes the captions or subtitles from a video. - * @param language The BCP 47 language tag to remove. - * @returns A promise that resolves when deletion completes. - * @throws {NotFoundError} if the video or caption is not found - * @throws {InternalError} if an unexpected error occurs - */ - delete(language: string): Promise; -} -interface StreamScopedDownloads { - /** - * Generates a download for a video when a video is ready to view. Available - * types are `default` and `audio`. Defaults to `default` when omitted. - * @param downloadType The download type to create. - * @returns The current downloads for the video. - * @throws {NotFoundError} if the video is not found - * @throws {BadRequestError} if the download type is invalid - * @throws {StreamError} if the video duration is too long to generate a download - * @throws {StreamError} if the video is not ready to stream - * @throws {InternalError} if an unexpected error occurs - */ - generate(downloadType?: StreamDownloadType): Promise; - /** - * Lists the downloads created for a video. - * @returns The current downloads for the video. - * @throws {NotFoundError} if the video or downloads are not found - * @throws {InternalError} if an unexpected error occurs - */ - get(): Promise; - /** - * Delete the downloads for a video. Available types are `default` and `audio`. - * Defaults to `default` when omitted. - * @param downloadType The download type to delete. - * @returns A promise that resolves when deletion completes. - * @throws {NotFoundError} if the video or downloads are not found - * @throws {InternalError} if an unexpected error occurs - */ - delete(downloadType?: StreamDownloadType): Promise; -} -interface StreamVideos { - /** - * Lists all videos in a users account. - * @returns The list of videos. - * @throws {BadRequestError} if the parameters are invalid - * @throws {InternalError} if an unexpected error occurs - */ - list(params?: StreamVideosListParams): Promise; -} -interface StreamWatermarks { - /** - * Generate a new watermark profile - * @param input The image stream to upload - * @param params The watermark creation parameters. - * @returns The created watermark profile. - * @throws {BadRequestError} if the parameters are invalid - * @throws {InvalidURLError} if the URL is invalid - * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached - * @throws {InternalError} if an unexpected error occurs - */ - generate(input: ReadableStream, params: StreamWatermarkCreateParams): Promise; - /** - * Generate a new watermark profile - * @param url The image url to upload - * @param params The watermark creation parameters. - * @returns The created watermark profile. - * @throws {BadRequestError} if the parameters are invalid - * @throws {InvalidURLError} if the URL is invalid - * @throws {TooManyWatermarksError} if the number of allowed watermarks is reached - * @throws {InternalError} if an unexpected error occurs - */ - generate(url: string, params: StreamWatermarkCreateParams): Promise; - /** - * Lists all watermark profiles for an account. - * @returns The list of watermark profiles. - * @throws {InternalError} if an unexpected error occurs - */ - list(): Promise; - /** - * Retrieves details for a single watermark profile. - * @param watermarkId The watermark profile identifier. - * @returns The watermark profile details. - * @throws {NotFoundError} if the watermark is not found - * @throws {InternalError} if an unexpected error occurs - */ - get(watermarkId: string): Promise; - /** - * Deletes a watermark profile. - * @param watermarkId The watermark profile identifier. - * @returns A promise that resolves when deletion completes. - * @throws {NotFoundError} if the watermark is not found - * @throws {InternalError} if an unexpected error occurs - */ - delete(watermarkId: string): Promise; -} -type StreamUpdateVideoParams = { - /** - * Lists the origins allowed to display the video. Enter allowed origin - * domains in an array and use `*` for wildcard subdomains. Empty arrays allow the - * video to be viewed on any origin. - */ - allowedOrigins?: Array; - /** - * A user-defined identifier for the media creator. - */ - creator?: string; - /** - * The maximum duration in seconds for a video upload. Can be set for a - * video that is not yet uploaded to limit its duration. Uploads that exceed the - * specified duration will fail during processing. A value of `-1` means the value - * is unknown. - */ - maxDurationSeconds?: number; - /** - * A user modifiable key-value store used to reference other systems of - * record for managing videos. - */ - meta?: Record; - /** - * Indicates whether the video can be a accessed using the id. When - * set to `true`, a signed token must be generated with a signing key to view the - * video. - */ - requireSignedURLs?: boolean; - /** - * Indicates the date and time at which the video will be deleted. Omit - * the field to indicate no change, or include with a `null` value to remove an - * existing scheduled deletion. If specified, must be at least 30 days from upload - * time. - */ - scheduledDeletion?: string | null; - /** - * The timestamp for a thumbnail image calculated as a percentage value - * of the video's duration. To convert from a second-wise timestamp to a - * percentage, divide the desired timestamp by the total duration of the video. If - * this value is not set, the default thumbnail image is taken from 0s of the - * video. - */ - thumbnailTimestampPct?: number; -}; -type StreamCaption = { - /** - * Whether the caption was generated via AI. - */ - generated?: boolean; - /** - * The language label displayed in the native language to users. - */ - label: string; - /** - * The language tag in BCP 47 format. - */ - language: string; - /** - * The status of a generated caption. - */ - status?: 'ready' | 'inprogress' | 'error'; -}; -type StreamDownloadStatus = 'ready' | 'inprogress' | 'error'; -type StreamDownloadType = 'default' | 'audio'; -type StreamDownload = { - /** - * Indicates the progress as a percentage between 0 and 100. - */ - percentComplete: number; - /** - * The status of a generated download. - */ - status: StreamDownloadStatus; - /** - * The URL to access the generated download. - */ - url?: string; -}; -/** - * An object with download type keys. Each key is optional and only present if that - * download type has been created. - */ -type StreamDownloadGetResponse = { - /** - * The audio-only download. Only present if this download type has been created. - */ - audio?: StreamDownload; - /** - * The default video download. Only present if this download type has been created. - */ - default?: StreamDownload; -}; -type StreamWatermarkPosition = 'upperRight' | 'upperLeft' | 'lowerLeft' | 'lowerRight' | 'center'; -type StreamWatermark = { - /** - * The unique identifier for a watermark profile. - */ - id: string; - /** - * The size of the image in bytes. - */ - size: number; - /** - * The height of the image in pixels. - */ - height: number; - /** - * The width of the image in pixels. - */ - width: number; - /** - * The date and a time a watermark profile was created. - */ - created: string; - /** - * The source URL for a downloaded image. If the watermark profile was created via - * direct upload, this field is null. - */ - downloadedFrom: string | null; - /** - * A short description of the watermark profile. - */ - name: string; - /** - * The translucency of the image. A value of `0.0` makes the image completely - * transparent, and `1.0` makes the image completely opaque. Note that if the image - * is already semi-transparent, setting this to `1.0` will not make the image - * completely opaque. - */ - opacity: number; - /** - * The whitespace between the adjacent edges (determined by position) of the video - * and the image. `0.0` indicates no padding, and `1.0` indicates a fully padded - * video width or length, as determined by the algorithm. - */ - padding: number; - /** - * The size of the image relative to the overall size of the video. This parameter - * will adapt to horizontal and vertical videos automatically. `0.0` indicates no - * scaling (use the size of the image as-is), and `1.0 `fills the entire video. - */ - scale: number; - /** - * The location of the image. Valid positions are: `upperRight`, `upperLeft`, - * `lowerLeft`, `lowerRight`, and `center`. Note that `center` ignores the - * `padding` parameter. - */ - position: StreamWatermarkPosition; -}; -type StreamWatermarkCreateParams = { - /** - * A short description of the watermark profile. - */ - name?: string; - /** - * The translucency of the image. A value of `0.0` makes the image completely - * transparent, and `1.0` makes the image completely opaque. Note that if the - * image is already semi-transparent, setting this to `1.0` will not make the - * image completely opaque. - */ - opacity?: number; - /** - * The whitespace between the adjacent edges (determined by position) of the - * video and the image. `0.0` indicates no padding, and `1.0` indicates a fully - * padded video width or length, as determined by the algorithm. - */ - padding?: number; - /** - * The size of the image relative to the overall size of the video. This - * parameter will adapt to horizontal and vertical videos automatically. `0.0` - * indicates no scaling (use the size of the image as-is), and `1.0 `fills the - * entire video. - */ - scale?: number; - /** - * The location of the image. - */ - position?: StreamWatermarkPosition; -}; -type StreamVideosListParams = { - /** - * The maximum number of videos to return. - */ - limit?: number; - /** - * Return videos created before this timestamp. - * (RFC3339/RFC3339Nano) - */ - before?: string; - /** - * Comparison operator for the `before` field. - * @default 'lt' - */ - beforeComp?: StreamPaginationComparison; - /** - * Return videos created after this timestamp. - * (RFC3339/RFC3339Nano) - */ - after?: string; - /** - * Comparison operator for the `after` field. - * @default 'gte' - */ - afterComp?: StreamPaginationComparison; -}; -type StreamPaginationComparison = 'eq' | 'gt' | 'gte' | 'lt' | 'lte'; -/** - * Error object for Stream binding operations. - */ -interface StreamError extends Error { - readonly code: number; - readonly statusCode: number; - readonly message: string; - readonly stack?: string; -} -interface InternalError extends StreamError { - name: 'InternalError'; -} -interface BadRequestError extends StreamError { - name: 'BadRequestError'; -} -interface NotFoundError extends StreamError { - name: 'NotFoundError'; -} -interface ForbiddenError extends StreamError { - name: 'ForbiddenError'; -} -interface RateLimitedError extends StreamError { - name: 'RateLimitedError'; -} -interface QuotaReachedError extends StreamError { - name: 'QuotaReachedError'; -} -interface MaxFileSizeError extends StreamError { - name: 'MaxFileSizeError'; -} -interface InvalidURLError extends StreamError { - name: 'InvalidURLError'; -} -interface AlreadyUploadedError extends StreamError { - name: 'AlreadyUploadedError'; -} -interface TooManyWatermarksError extends StreamError { - name: 'TooManyWatermarksError'; -} -type MarkdownDocument = { - name: string; - blob: Blob; -}; -type ConversionResponse = { - id: string; - name: string; - mimeType: string; - format: 'markdown'; - tokens: number; - data: string; -} | { - id: string; - name: string; - mimeType: string; - format: 'error'; - error: string; -}; -type ImageConversionOptions = { - descriptionLanguage?: 'en' | 'es' | 'fr' | 'it' | 'pt' | 'de'; -}; -type EmbeddedImageConversionOptions = ImageConversionOptions & { - convert?: boolean; - maxConvertedImages?: number; -}; -type ConversionOptions = { - html?: { - images?: EmbeddedImageConversionOptions & { - convertOGImage?: boolean; - }; - hostname?: string; - cssSelector?: string; - }; - docx?: { - images?: EmbeddedImageConversionOptions; - }; - image?: ImageConversionOptions; - pdf?: { - images?: EmbeddedImageConversionOptions; - metadata?: boolean; - }; -}; -type ConversionRequestOptions = { - gateway?: GatewayOptions; - extraHeaders?: object; - conversionOptions?: ConversionOptions; -}; -type SupportedFileFormat = { - mimeType: string; - extension: string; -}; -declare abstract class ToMarkdownService { - transform(files: MarkdownDocument[], options?: ConversionRequestOptions): Promise; - transform(files: MarkdownDocument, options?: ConversionRequestOptions): Promise; - supported(): Promise; -} -declare namespace TailStream { - interface Header { - readonly name: string; - readonly value: string; - } - interface FetchEventInfo { - readonly type: "fetch"; - readonly method: string; - readonly url: string; - readonly cfJson?: object; - readonly headers: Header[]; - } - interface JsRpcEventInfo { - readonly type: "jsrpc"; - } - interface ScheduledEventInfo { - readonly type: "scheduled"; - readonly scheduledTime: Date; - readonly cron: string; - } - interface AlarmEventInfo { - readonly type: "alarm"; - readonly scheduledTime: Date; - } - interface QueueEventInfo { - readonly type: "queue"; - readonly queueName: string; - readonly batchSize: number; - } - interface EmailEventInfo { - readonly type: "email"; - readonly mailFrom: string; - readonly rcptTo: string; - readonly rawSize: number; - } - interface TraceEventInfo { - readonly type: "trace"; - readonly traces: (string | null)[]; - } - interface HibernatableWebSocketEventInfoMessage { - readonly type: "message"; - } - interface HibernatableWebSocketEventInfoError { - readonly type: "error"; - } - interface HibernatableWebSocketEventInfoClose { - readonly type: "close"; - readonly code: number; - readonly wasClean: boolean; - } - interface HibernatableWebSocketEventInfo { - readonly type: "hibernatableWebSocket"; - readonly info: HibernatableWebSocketEventInfoClose | HibernatableWebSocketEventInfoError | HibernatableWebSocketEventInfoMessage; - } - interface CustomEventInfo { - readonly type: "custom"; - } - interface FetchResponseInfo { - readonly type: "fetch"; - readonly statusCode: number; - } - interface ConnectEventInfo { - readonly type: "connect"; - } - type EventOutcome = "ok" | "canceled" | "exception" | "unknown" | "killSwitch" | "daemonDown" | "exceededCpu" | "exceededMemory" | "loadShed" | "responseStreamDisconnected" | "scriptNotFound" | "internalError"; - interface ScriptVersion { - readonly id: string; - readonly tag?: string; - readonly message?: string; - } - interface TracePreviewInfo { - readonly id: string; - readonly slug: string; - readonly name: string; - } - interface Onset { - readonly type: "onset"; - readonly attributes: Attribute[]; - // id for the span being opened by this Onset event. - readonly spanId: string; - readonly dispatchNamespace?: string; - readonly entrypoint?: string; - readonly executionModel: string; - readonly scriptName?: string; - readonly scriptTags?: string[]; - readonly scriptVersion?: ScriptVersion; - readonly preview?: TracePreviewInfo; - readonly info: FetchEventInfo | ConnectEventInfo | JsRpcEventInfo | ScheduledEventInfo | AlarmEventInfo | QueueEventInfo | EmailEventInfo | TraceEventInfo | HibernatableWebSocketEventInfo | CustomEventInfo; - } - interface Outcome { - readonly type: "outcome"; - readonly outcome: EventOutcome; - readonly cpuTime: number; - readonly wallTime: number; - } - interface SpanOpen { - readonly type: "spanOpen"; - readonly name: string; - // id for the span being opened by this SpanOpen event. - readonly spanId: string; - readonly info?: FetchEventInfo | JsRpcEventInfo | Attributes; - } - interface SpanClose { - readonly type: "spanClose"; - readonly outcome: EventOutcome; - } - interface DiagnosticChannelEvent { - readonly type: "diagnosticChannel"; - readonly channel: string; - readonly message: any; - } - interface Exception { - readonly type: "exception"; - readonly name: string; - readonly message: string; - readonly stack?: string; - } - interface Log { - readonly type: "log"; - readonly level: "debug" | "error" | "info" | "log" | "warn"; - readonly message: object; - } - interface DroppedEventsDiagnostic { - readonly diagnosticsType: "droppedEvents"; - readonly count: number; - } - interface StreamDiagnostic { - readonly type: 'streamDiagnostic'; - // To add new diagnostic types, define a new interface and add it to this union type. - readonly diagnostic: DroppedEventsDiagnostic; - } - // This marks the worker handler return information. - // This is separate from Outcome because the worker invocation can live for a long time after - // returning. For example - Websockets that return an http upgrade response but then continue - // streaming information or SSE http connections. - interface Return { - readonly type: "return"; - readonly info?: FetchResponseInfo; - } - interface Attribute { - readonly name: string; - readonly value: string | string[] | boolean | boolean[] | number | number[] | bigint | bigint[]; - } - interface Attributes { - readonly type: "attributes"; - readonly info: Attribute[]; - } - type EventType = Onset | Outcome | SpanOpen | SpanClose | DiagnosticChannelEvent | Exception | Log | StreamDiagnostic | Return | Attributes; - // Context in which this trace event lives. - interface SpanContext { - // Single id for the entire top-level invocation - // This should be a new traceId for the first worker stage invoked in the eyeball request and then - // same-account service-bindings should reuse the same traceId but cross-account service-bindings - // should use a new traceId. - readonly traceId: string; - // spanId in which this event is handled - // for Onset and SpanOpen events this would be the parent span id - // for Outcome and SpanClose these this would be the span id of the opening Onset and SpanOpen events - // For Hibernate and Mark this would be the span under which they were emitted. - // spanId is not set ONLY if: - // 1. This is an Onset event - // 2. We are not inheriting any SpanContext. (e.g. this is a cross-account service binding or a new top-level invocation) - readonly spanId?: string; - // W3C trace flags from an upstream traceparent. Absent when no upstream - // sampling decision was made. - readonly traceFlags?: number; - } - interface TailEvent { - // invocation id of the currently invoked worker stage. - // invocation id will always be unique to every Onset event and will be the same until the Outcome event. - readonly invocationId: string; - // Inherited spanContext for this event. - readonly spanContext: SpanContext; - readonly timestamp: Date; - readonly sequence: number; - readonly event: Event; - } - type TailEventHandler = (event: TailEvent) => void | Promise; - type TailEventHandlerObject = { - outcome?: TailEventHandler; - spanOpen?: TailEventHandler; - spanClose?: TailEventHandler; - diagnosticChannel?: TailEventHandler; - exception?: TailEventHandler; - log?: TailEventHandler; - return?: TailEventHandler; - attributes?: TailEventHandler; - }; - type TailEventHandlerType = TailEventHandler | TailEventHandlerObject; -} -// Copyright (c) 2022-2023 Cloudflare, Inc. -// Licensed under the Apache 2.0 license found in the LICENSE file or at: -// https://opensource.org/licenses/Apache-2.0 -/** - * Data types supported for holding vector metadata. - */ -type VectorizeVectorMetadataValue = string | number | boolean | string[]; -/** - * Additional information to associate with a vector. - */ -type VectorizeVectorMetadata = VectorizeVectorMetadataValue | Record; -type VectorFloatArray = Float32Array | Float64Array; -interface VectorizeError { - code?: number; - error: string; -} -/** - * Comparison logic/operation to use for metadata filtering. - * - * This list is expected to grow as support for more operations are released. - */ -type VectorizeVectorMetadataFilterOp = '$eq' | '$ne' | '$lt' | '$lte' | '$gt' | '$gte'; -type VectorizeVectorMetadataFilterCollectionOp = '$in' | '$nin'; -/** - * Filter criteria for vector metadata used to limit the retrieved query result set. - */ -type VectorizeVectorMetadataFilter = { - [field: string]: Exclude | null | { - [Op in VectorizeVectorMetadataFilterOp]?: Exclude | null; - } | { - [Op in VectorizeVectorMetadataFilterCollectionOp]?: Exclude[]; - }; -}; -/** - * Supported distance metrics for an index. - * Distance metrics determine how other "similar" vectors are determined. - */ -type VectorizeDistanceMetric = "euclidean" | "cosine" | "dot-product"; -/** - * Metadata return levels for a Vectorize query. - * - * Default to "none". - * - * @property all Full metadata for the vector return set, including all fields (including those un-indexed) without truncation. This is a more expensive retrieval, as it requires additional fetching & reading of un-indexed data. - * @property indexed Return all metadata fields configured for indexing in the vector return set. This level of retrieval is "free" in that no additional overhead is incurred returning this data. However, note that indexed metadata is subject to truncation (especially for larger strings). - * @property none No indexed metadata will be returned. - */ -type VectorizeMetadataRetrievalLevel = "all" | "indexed" | "none"; -interface VectorizeQueryOptions { - topK?: number; - namespace?: string; - returnValues?: boolean; - returnMetadata?: boolean | VectorizeMetadataRetrievalLevel; - filter?: VectorizeVectorMetadataFilter; -} -/** - * Information about the configuration of an index. - */ -type VectorizeIndexConfig = { - dimensions: number; - metric: VectorizeDistanceMetric; -} | { - preset: string; // keep this generic, as we'll be adding more presets in the future and this is only in a read capacity -}; -/** - * Metadata about an existing index. - * - * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. - * See {@link VectorizeIndexInfo} for its post-beta equivalent. - */ -interface VectorizeIndexDetails { - /** The unique ID of the index */ - readonly id: string; - /** The name of the index. */ - name: string; - /** (optional) A human readable description for the index. */ - description?: string; - /** The index configuration, including the dimension size and distance metric. */ - config: VectorizeIndexConfig; - /** The number of records containing vectors within the index. */ - vectorsCount: number; -} -/** - * Metadata about an existing index. - */ -interface VectorizeIndexInfo { - /** The number of records containing vectors within the index. */ - vectorCount: number; - /** Number of dimensions the index has been configured for. */ - dimensions: number; - /** ISO 8601 datetime of the last processed mutation on in the index. All changes before this mutation will be reflected in the index state. */ - processedUpToDatetime: number; - /** UUIDv4 of the last mutation processed by the index. All changes before this mutation will be reflected in the index state. */ - processedUpToMutation: number; -} -/** - * Represents a single vector value set along with its associated metadata. - */ -interface VectorizeVector { - /** The ID for the vector. This can be user-defined, and must be unique. It should uniquely identify the object, and is best set based on the ID of what the vector represents. */ - id: string; - /** The vector values */ - values: VectorFloatArray | number[]; - /** The namespace this vector belongs to. */ - namespace?: string; - /** Metadata associated with the vector. Includes the values of other fields and potentially additional details. */ - metadata?: Record; -} -/** - * Represents a matched vector for a query along with its score and (if specified) the matching vector information. - */ -type VectorizeMatch = Pick, "values"> & Omit & { - /** The score or rank for similarity, when returned as a result */ - score: number; -}; -/** - * A set of matching {@link VectorizeMatch} for a particular query. - */ -interface VectorizeMatches { - matches: VectorizeMatch[]; - count: number; -} -/** - * Results of an operation that performed a mutation on a set of vectors. - * Here, `ids` is a list of vectors that were successfully processed. - * - * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. - * See {@link VectorizeAsyncMutation} for its post-beta equivalent. - */ -interface VectorizeVectorMutation { - /* List of ids of vectors that were successfully processed. */ - ids: string[]; - /* Total count of the number of processed vectors. */ - count: number; -} -/** - * Result type indicating a mutation on the Vectorize Index. - * Actual mutations are processed async where the `mutationId` is the unique identifier for the operation. - */ -interface VectorizeAsyncMutation { - /** The unique identifier for the async mutation operation containing the changeset. */ - mutationId: string; -} -/** - * A Vectorize Vector Search Index for querying vectors/embeddings. - * - * This type is exclusively for the Vectorize **beta** and will be deprecated once Vectorize RC is released. - * See {@link Vectorize} for its new implementation. - */ -declare abstract class VectorizeIndex { - /** - * Get information about the currently bound index. - * @returns A promise that resolves with information about the current index. - */ - public describe(): Promise; - /** - * Use the provided vector to perform a similarity search across the index. - * @param vector Input vector that will be used to drive the similarity search. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise; - /** - * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. - * @param vectors List of vectors that will be inserted. - * @returns A promise that resolves with the ids & count of records that were successfully processed. - */ - public insert(vectors: VectorizeVector[]): Promise; - /** - * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. - * @param vectors List of vectors that will be upserted. - * @returns A promise that resolves with the ids & count of records that were successfully processed. - */ - public upsert(vectors: VectorizeVector[]): Promise; - /** - * Delete a list of vectors with a matching id. - * @param ids List of vector ids that should be deleted. - * @returns A promise that resolves with the ids & count of records that were successfully processed (and thus deleted). - */ - public deleteByIds(ids: string[]): Promise; - /** - * Get a list of vectors with a matching id. - * @param ids List of vector ids that should be returned. - * @returns A promise that resolves with the raw unscored vectors matching the id set. - */ - public getByIds(ids: string[]): Promise; -} -/** - * A Vectorize Vector Search Index for querying vectors/embeddings. - * - * Mutations in this version are async, returning a mutation id. - */ -declare abstract class Vectorize { - /** - * Get information about the currently bound index. - * @returns A promise that resolves with information about the current index. - */ - public describe(): Promise; - /** - * Use the provided vector to perform a similarity search across the index. - * @param vector Input vector that will be used to drive the similarity search. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public query(vector: VectorFloatArray | number[], options?: VectorizeQueryOptions): Promise; - /** - * Use the provided vector-id to perform a similarity search across the index. - * @param vectorId Id for a vector in the index against which the index should be queried. - * @param options Configuration options to massage the returned data. - * @returns A promise that resolves with matched and scored vectors. - */ - public queryById(vectorId: string, options?: VectorizeQueryOptions): Promise; - /** - * Insert a list of vectors into the index dataset. If a provided id exists, an error will be thrown. - * @param vectors List of vectors that will be inserted. - * @returns A promise that resolves with a unique identifier of a mutation containing the insert changeset. - */ - public insert(vectors: VectorizeVector[]): Promise; - /** - * Upsert a list of vectors into the index dataset. If a provided id exists, it will be replaced with the new values. - * @param vectors List of vectors that will be upserted. - * @returns A promise that resolves with a unique identifier of a mutation containing the upsert changeset. - */ - public upsert(vectors: VectorizeVector[]): Promise; - /** - * Delete a list of vectors with a matching id. - * @param ids List of vector ids that should be deleted. - * @returns A promise that resolves with a unique identifier of a mutation containing the delete changeset. - */ - public deleteByIds(ids: string[]): Promise; - /** - * Get a list of vectors with a matching id. - * @param ids List of vector ids that should be returned. - * @returns A promise that resolves with the raw unscored vectors matching the id set. - */ - public getByIds(ids: string[]): Promise; -} -/** - * The interface for "version_metadata" binding - * providing metadata about the Worker Version using this binding. - */ -type WorkerVersionMetadata = { - /** The ID of the Worker Version using this binding */ - id: string; - /** The tag of the Worker Version using this binding */ - tag: string; - /** The timestamp of when the Worker Version was uploaded */ - timestamp: string; -}; -interface DynamicDispatchLimits { - /** - * Limit CPU time in milliseconds. - */ - cpuMs?: number; - /** - * Limit number of subrequests. - */ - subRequests?: number; -} -interface DynamicDispatchOptions { - /** - * Limit resources of invoked Worker script. - */ - limits?: DynamicDispatchLimits; - /** - * Arguments for outbound Worker script, if configured. - */ - outbound?: { - [key: string]: any; - }; -} -interface DispatchNamespace { - /** - * @param name Name of the Worker script. - * @param args Arguments to Worker script. - * @param options Options for Dynamic Dispatch invocation. - * @returns A Fetcher object that allows you to send requests to the Worker script. - * @throws If the Worker script does not exist in this dispatch namespace, an error will be thrown. - */ - get(name: string, args?: { - [key: string]: any; - }, options?: DynamicDispatchOptions): Fetcher; -} -declare module 'cloudflare:workflows' { - /** - * NonRetryableError allows for a user to throw a fatal error - * that makes a Workflow instance fail immediately without triggering a retry - */ - export class NonRetryableError extends Error { - public constructor(message: string, name?: string); - } -} -declare abstract class Workflow { - /** - * Get a handle to an existing instance of the Workflow. - * @param id Id for the instance of this Workflow - * @returns A promise that resolves with a handle for the Instance - */ - public get(id: string): Promise; - /** - * Create a new instance and return a handle to it. If a provided id exists, an error will be thrown. - * @param options Options when creating an instance including id and params - * @returns A promise that resolves with a handle for the Instance - */ - public create(options?: WorkflowInstanceCreateOptions): Promise; - /** - * Create a batch of instances and return handle for all of them. If a provided id exists, an error will be thrown. - * `createBatch` is limited at 100 instances at a time or when the RPC limit for the batch (1MiB) is reached. - * @param batch List of Options when creating an instance including name and params - * @returns A promise that resolves with a list of handles for the created instances. - */ - public createBatch(batch: WorkflowInstanceCreateOptions[]): Promise; -} -type WorkflowDurationLabel = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'year'; -type WorkflowSleepDuration = `${number} ${WorkflowDurationLabel}${'s' | ''}` | number; -type WorkflowRetentionDuration = WorkflowSleepDuration; -interface WorkflowInstanceCreateOptions { - /** - * An id for your Workflow instance. Must be unique within the Workflow. - */ - id?: string; - /** - * The event payload the Workflow instance is triggered with - */ - params?: PARAMS; - /** - * The retention policy for Workflow instance. - * Defaults to the maximum retention period available for the owner's account. - */ - retention?: { - successRetention?: WorkflowRetentionDuration; - errorRetention?: WorkflowRetentionDuration; - }; -} -type InstanceStatus = { - status: 'queued' // means that instance is waiting to be started (see concurrency limits) - | 'running' | 'paused' | 'errored' | 'terminated' // user terminated the instance while it was running - | 'complete' | 'waiting' // instance is hibernating and waiting for sleep or event to finish - | 'waitingForPause' // instance is finishing the current work to pause - | 'unknown'; - error?: { - name: string; - message: string; - }; - output?: unknown; -}; -interface WorkflowError { - code?: number; - message: string; -} -interface WorkflowInstanceRestartOptions { - /** - * Restart from a specific step. If omitted, the instance restarts from the beginning. - * The step must exist in the instance's execution history. - */ - from?: { - /** - * The step name as defined in your workflow code. - */ - name: string; - /** - * 1-indexed occurrence of this step name. Use when the same step name appears multiple times (e.g. in a loop). - * @default 1 - */ - count?: number; - /** - * Step type filter. Use when different step types share the same name. - */ - type?: 'do' | 'sleep' | 'waitForEvent'; - }; -} -declare abstract class WorkflowInstance { - public id: string; - /** - * Pause the instance. - */ - public pause(): Promise; - /** - * Resume the instance. If it is already running, an error will be thrown. - */ - public resume(): Promise; - /** - * Terminate the instance. If it is errored, terminated or complete, an error will be thrown. - */ - public terminate(): Promise; - /** - * Restart the instance. Optionally restart from a specific step, preserving - * cached results for all steps before it. - * @param options Options for the restart, including an optional step to restart from. - */ - public restart(options?: WorkflowInstanceRestartOptions): Promise; - /** - * Returns the current status of the instance. - */ - public status(): Promise; - /** - * Send an event to this instance. - */ - public sendEvent({ type, payload, }: { - type: string; - payload: unknown; - }): Promise; -} diff --git a/worker/agent-edge.d.mts b/worker/agent-edge.d.mts deleted file mode 100644 index 6ebfe58..0000000 --- a/worker/agent-edge.d.mts +++ /dev/null @@ -1,9 +0,0 @@ -export declare const AGENT_SURFACE: { - name: string; - url: string; - llmsTxt: string; - llmsFullTxt?: string; - indexMd: string; - catalog: Record; -}; -export declare function handleAgentEdge(request: Request): Response | null; diff --git a/worker/agent-edge.mjs b/worker/agent-edge.mjs deleted file mode 100644 index 0cbba30..0000000 --- a/worker/agent-edge.mjs +++ /dev/null @@ -1,188 +0,0 @@ -/** - * Portable agent-edge handler — copy or generate into each product. - * Spec: foundry/ops/docs/agent-indexing-standard.md - * - * Usage in worker.mjs (before openNext.fetch): - * import { handleAgentEdge } from './agent-edge.mjs' - * const agent = handleAgentEdge(request) - * if (agent) return agent - */ - -/** @type {{ name: string, url: string, llmsTxt: string, llmsFullTxt?: string, indexMd: string, catalog: object }} */ -// biome-ignore format: generated payload from apply-agent-surfaces (JSON keys/quotes) -export const AGENT_SURFACE = { - name: "Setline", - url: "https://setline.significanthobbies.com", - llmsFullTxt: - "# Setline — full agent brief\n\nMobile-first execution layer for following a structured workout programme precisely.\n\n## Index\n\n# Setline\n\nBuild the plan once. Follow it precisely every day.\n\n## What it is\n\n- Mobile-first workout execution for a structured programme\n- Exact authored exercise and set order\n- Explicit recorded, calculated, adjusted, and unavailable values\n- Device-first active workouts with optional private sync\n\n## Agent entrypoints\n\n- https://setline.significanthobbies.com/llms.txt\n- https://setline.significanthobbies.com/api/ai\n- https://setline.significanthobbies.com/index.md\n\n## Product links\n\n- Home: https://setline.significanthobbies.com/ — Workout execution app\n- Privacy: https://setline.significanthobbies.com/privacy — Device and private cloud data handling\n- Terms: https://setline.significanthobbies.com/terms — Product terms\n- Changelog: https://setline.significanthobbies.com/changelog — Verified product releases\n\n## Machine surfaces\n\n- https://setline.significanthobbies.com/llms.txt\n- https://setline.significanthobbies.com/llms-full.txt\n- https://setline.significanthobbies.com/api/ai\n- https://setline.significanthobbies.com/index.md\n- https://setline.significanthobbies.com/sitemap.xml\n- https://setline.significanthobbies.com/robots.txt\n\n## Contact\n\n- Owner: https://sarthakagrawal.dev\n- Agent email for directory verification: sarthakagrawal@agentmail.to\n", - llmsTxt: - "# Setline\n\n> Mobile-first execution layer for following a structured workout programme precisely.\n\n## Product\n\n- [Home](https://setline.significanthobbies.com/): Workout execution app\n- [Privacy](https://setline.significanthobbies.com/privacy): Device and private cloud data handling\n- [Terms](https://setline.significanthobbies.com/terms): Product terms\n- [Changelog](https://setline.significanthobbies.com/changelog): Verified product releases\n\n## Machine surfaces\n\n- [Agent catalog](https://setline.significanthobbies.com/api/ai): JSON inventory of public surfaces\n- [Homepage markdown](https://setline.significanthobbies.com/index.md): Product brief without JS\n- [This index](https://setline.significanthobbies.com/llms.txt)\n", - indexMd: - "# Setline\n\nBuild the plan once. Follow it precisely every day.\n\n## What it is\n\n- Mobile-first workout execution for a structured programme\n- Exact authored exercise and set order\n- Explicit recorded, calculated, adjusted, and unavailable values\n- Device-first active workouts with optional private sync\n\n## Agent entrypoints\n\n- https://setline.significanthobbies.com/llms.txt\n- https://setline.significanthobbies.com/api/ai\n- https://setline.significanthobbies.com/index.md\n", - catalog: { - name: "Setline", - version: "1", - url: "https://setline.significanthobbies.com", - llms: "https://setline.significanthobbies.com/llms.txt", - llmsFull: "https://setline.significanthobbies.com/llms-full.txt", - sitemap: "https://setline.significanthobbies.com/sitemap.xml", - robots: "https://setline.significanthobbies.com/robots.txt", - markdown: { - suffix: ".md", - negotiation: true, - }, - surfaces: [ - { - id: "home", - url: "https://setline.significanthobbies.com/", - md: "https://setline.significanthobbies.com/index.md", - kind: "static", - description: "Product home", - }, - { - id: "privacy", - url: "https://setline.significanthobbies.com/privacy", - md: "https://setline.significanthobbies.com/privacy.md", - kind: "static", - description: "Device and private cloud data handling", - }, - { - id: "terms", - url: "https://setline.significanthobbies.com/terms", - md: "https://setline.significanthobbies.com/terms.md", - kind: "static", - description: "Product terms", - }, - { - id: "changelog", - url: "https://setline.significanthobbies.com/changelog", - md: "https://setline.significanthobbies.com/changelog.md", - kind: "static", - description: "Verified product releases", - }, - ], - auth: { - public: true, - notes: "Auth-walled app routes are not agent-indexed unless listed here.", - }, - }, -}; - -/** - * @param {Request} request - * @returns {Response | null} - */ -export function handleAgentEdge(request) { - if (request.method !== "GET" && request.method !== "HEAD") return null; - const url = new URL(request.url); - const path = url.pathname === "" ? "/" : url.pathname; - - if (path === "/llms.txt") { - return text(AGENT_SURFACE.llmsTxt, "text/plain; charset=utf-8"); - } - if (path === "/llms-full.txt" && AGENT_SURFACE.llmsFullTxt) { - return text(AGENT_SURFACE.llmsFullTxt, "text/plain; charset=utf-8"); - } - if (path === "/index.md") { - return text(AGENT_SURFACE.indexMd, "text/markdown; charset=utf-8"); - } - if (path === "/sitemap.xml") { - return text( - sitemapForCatalog(catalogForOrigin(url.origin)), - "application/xml; charset=utf-8", - ); - } - if (path === "/robots.txt") { - return text(robotsForOrigin(url.origin), "text/plain; charset=utf-8"); - } - if (path === "/api/ai") { - return json(catalogForOrigin(url.origin)); - } - - // Homepage markdown negotiation - if ((path === "/" || path === "") && wantsMarkdown(request)) { - return text(AGENT_SURFACE.indexMd, "text/markdown; charset=utf-8", { - Link: '; rel="alternate"; type="text/markdown"', - Vary: "Accept", - }); - } - - return null; -} - -function catalogForOrigin(origin) { - return { - ...AGENT_SURFACE.catalog, - url: origin, - llms: `${origin}/llms.txt`, - llmsFull: `${origin}/llms-full.txt`, - sitemap: `${origin}/sitemap.xml`, - robots: `${origin}/robots.txt`, - surfaces: (AGENT_SURFACE.catalog.surfaces || []).map((surface) => ({ - ...surface, - url: forOrigin(surface.url, origin), - md: forOrigin(surface.md, origin), - })), - }; -} - -function forOrigin(value, origin) { - return String(value).split(AGENT_SURFACE.url).join(origin); -} - -function sitemapForCatalog(catalog) { - const routes = catalog.surfaces - .map((surface) => ` ${escapeXml(surface.url)}`) - .join("\n"); - return `\n\n${routes}\n\n`; -} - -function robotsForOrigin(origin) { - return `User-agent: * -Allow: / - -Sitemap: ${origin}/sitemap.xml -# Agent indexing -Allow: /llms.txt -Allow: /llms-full.txt -Allow: /index.md -Allow: /api/ai -`; -} - -function escapeXml(value) { - return String(value) - .replaceAll("&", "&") - .replaceAll("<", "<") - .replaceAll(">", ">") - .replaceAll('"', """) - .replaceAll("'", "'"); -} - -function wantsMarkdown(request) { - const accept = (request.headers.get("accept") || "").toLowerCase(); - if (!accept.includes("text/markdown")) return false; - if (!accept.includes("text/html")) return true; - return accept.indexOf("text/markdown") < accept.indexOf("text/html"); -} - -function text(body, type, extra = {}) { - return new Response(body, { - status: 200, - headers: { - "Content-Type": type, - "Cache-Control": "public, max-age=300", - ...extra, - }, - }); -} - -function json(data) { - return new Response(`${JSON.stringify(data, null, 2)}\n`, { - status: 200, - headers: { - "Content-Type": "application/json; charset=utf-8", - "Cache-Control": "public, max-age=300", - }, - }); -} diff --git a/worker/auth-guard.ts b/worker/auth-guard.ts deleted file mode 100644 index 4f2ee0d..0000000 --- a/worker/auth-guard.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { createAuth, type SetlineBindings } from "./auth"; - -async function resolveUserId( - request: Request, - env: SetlineBindings, -): Promise { - const session = await createAuth(env, request.url).api.getSession({ - headers: request.headers, - }); - return session?.user?.id ?? null; -} - -type AuthResult = - { userId: string; response: null } | { userId: null; response: Response }; - -/** - * Resolves the authenticated user or returns a 401 response. - * Shared by private state handlers that gate on browser sessions. - */ -export async function requireUserId( - request: Request, - env: SetlineBindings, -): Promise { - const userId = await resolveUserId(request, env); - if (!userId) { - return { - userId: null, - response: Response.json( - { code: "UNAUTHORIZED", message: "Sign in to continue." }, - { status: 401 }, - ), - }; - } - return { userId, response: null }; -} diff --git a/worker/auth.ts b/worker/auth.ts deleted file mode 100644 index 4c7de08..0000000 --- a/worker/auth.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { betterAuth } from "better-auth"; -import { drizzleAdapter } from "better-auth/adapters/drizzle"; -import { bearer } from "better-auth/plugins"; -import { drizzle } from "drizzle-orm/d1"; -import { account, session, user, verification } from "./schema"; - -export type SetlineBindings = CloudflareBindings & { - BETTER_AUTH_SECRET?: string; - GOOGLE_CLIENT_ID?: string; - GOOGLE_CLIENT_SECRET?: string; - APPLE_APP_BUNDLE_IDENTIFIER?: string; -}; - -const PRODUCTION_ORIGIN = "https://setline.significanthobbies.com"; -const LOCAL_ORIGINS = [ - "http://localhost:3000", - "http://localhost:3001", - "http://127.0.0.1:3000", - "http://127.0.0.1:3001", -]; - -function isLocalOrigin(origin: string) { - const hostname = new URL(origin).hostname; - return hostname === "localhost" || hostname === "127.0.0.1"; -} - -export function isGoogleConfigured(env: SetlineBindings) { - return Boolean( - env.BETTER_AUTH_SECRET?.trim() && - env.GOOGLE_CLIENT_ID?.trim() && - env.GOOGLE_CLIENT_SECRET?.trim(), - ); -} - -export function isAppleConfigured(env: SetlineBindings) { - return Boolean(env.APPLE_APP_BUNDLE_IDENTIFIER?.trim()); -} - -export function createAuth(env: SetlineBindings, requestUrl: string) { - const requestOrigin = new URL(requestUrl).origin; - const baseURL = isLocalOrigin(requestOrigin) - ? requestOrigin - : PRODUCTION_ORIGIN; - const secret = - env.BETTER_AUTH_SECRET?.trim() ?? - (isLocalOrigin(requestOrigin) - ? "setline-local-development-secret-never-use-in-production" - : undefined); - const appleBundleIdentifier = env.APPLE_APP_BUNDLE_IDENTIFIER?.trim() ?? ""; - - return betterAuth({ - database: drizzleAdapter(drizzle(env.DB), { - provider: "sqlite", - schema: { user, session, account, verification }, - }), - baseURL, - secret, - socialProviders: { - google: { - clientId: env.GOOGLE_CLIENT_ID?.trim() ?? "", - clientSecret: env.GOOGLE_CLIENT_SECRET?.trim() ?? "", - scope: ["openid", "email", "profile"], - prompt: "select_account", - }, - ...(isAppleConfigured(env) - ? { - apple: { - clientId: appleBundleIdentifier, - clientSecret: "", - appBundleIdentifier: appleBundleIdentifier, - }, - } - : {}), - }, - account: { - accountLinking: { - enabled: true, - disableImplicitLinking: true, - trustedProviders: ["google", "apple"], - allowDifferentEmails: true, - }, - }, - user: { - deleteUser: { - enabled: true, - }, - }, - plugins: [bearer()], - trustedOrigins: [ - ...new Set([ - baseURL, - ...LOCAL_ORIGINS, - "https://appleid.apple.com", - "setline://auth", - ]), - ], - rateLimit: { - enabled: false, - }, - }); -} diff --git a/worker/index.ts b/worker/index.ts deleted file mode 100644 index d445f55..0000000 --- a/worker/index.ts +++ /dev/null @@ -1,314 +0,0 @@ -/** Cloudflare Worker entry point for Setline. */ -import { handleAgentEdge } from "./agent-edge.mjs"; -import { - createAuth, - isAppleConfigured, - isGoogleConfigured, - type SetlineBindings, -} from "./auth"; -import { handleMcpRead, handleMcpTokenManagement } from "./mcp"; -import { - consumeNativeHandoff, - createNativeHandoffCode, - isAllowedNativeCallback, - NATIVE_AUTH_CALLBACK, - saveNativeHandoff, -} from "./native-handoff"; -import { handleNativeState } from "./native-state"; -import { handlePrivateState } from "./state"; - -const SECURITY_HEADERS = { - "Cache-Control": "no-store", - "Permissions-Policy": "camera=(), microphone=(), geolocation=()", - "Referrer-Policy": "strict-origin-when-cross-origin", - "X-Content-Type-Options": "nosniff", - "X-Frame-Options": "DENY", -}; - -function withApiHeaders(response: Response) { - const headers = new Headers(response.headers); - for (const [name, value] of Object.entries(SECURITY_HEADERS)) { - headers.set(name, value); - } - return new Response(response.body, { - status: response.status, - statusText: response.statusText, - headers, - }); -} - -function json(payload: unknown, status = 200) { - return withApiHeaders(Response.json(payload, { status })); -} - -const worker = { - async fetch( - request: Request, - env: SetlineBindings, - ctx: ExecutionContext, - ): Promise { - const url = new URL(request.url); - const agentResponse = handleAgentEdge(request); - if (agentResponse) return agentResponse; - - if (url.pathname === "/api/health" && request.method === "GET") { - return json({ - ok: true, - auth: { - googleConfigured: isGoogleConfigured(env), - appleConfigured: isAppleConfigured(env), - }, - storage: "d1", - }); - } - - if (url.pathname === "/api/auth/config" && request.method === "GET") { - return json({ - googleConfigured: isGoogleConfigured(env), - appleConfigured: isAppleConfigured(env), - }); - } - - if ( - url.pathname === "/api/native/auth/google/start" && - request.method === "GET" - ) { - if (!isGoogleConfigured(env)) { - return json( - { - code: "OAUTH_NOT_CONFIGURED", - message: "Google sign-in is unavailable.", - }, - 503, - ); - } - const callback = url.searchParams.get("callback") ?? NATIVE_AUTH_CALLBACK; - if (!isAllowedNativeCallback(callback)) { - return json( - { - code: "INVALID_CALLBACK", - message: "The native callback is not allowed.", - }, - 400, - ); - } - const completeURL = new URL( - "/api/native/auth/google/complete", - request.url, - ); - completeURL.searchParams.set("callback", callback); - const result = await createAuth(env, request.url).api.signInSocial({ - body: { - provider: "google", - callbackURL: completeURL.toString(), - errorCallbackURL: completeURL.toString(), - }, - headers: request.headers, - }); - if (!result.url) { - return json( - { - code: "OAUTH_START_FAILED", - message: "Google sign-in could not start.", - }, - 502, - ); - } - return Response.redirect(result.url); - } - - if ( - url.pathname === "/api/native/auth/google/complete" && - request.method === "GET" - ) { - const callback = url.searchParams.get("callback") ?? NATIVE_AUTH_CALLBACK; - if (!isAllowedNativeCallback(callback)) { - return json( - { - code: "INVALID_CALLBACK", - message: "The native callback is not allowed.", - }, - 400, - ); - } - const session = await createAuth(env, request.url).api.getSession({ - headers: request.headers, - }); - const redirect = new URL(callback); - if (!session?.session.token) { - redirect.searchParams.set("error", "google_auth_failed"); - return Response.redirect(redirect.toString()); - } - const code = createNativeHandoffCode(); - await saveNativeHandoff(env.DB, code, session.session.token); - redirect.searchParams.set("code", code); - return Response.redirect(redirect.toString()); - } - - if ( - url.pathname === "/api/native/auth/exchange" && - request.method === "POST" - ) { - const body = (await request.json().catch(() => null)) as { - code?: unknown; - } | null; - const code = typeof body?.code === "string" ? body.code.trim() : ""; - if (code.length < 32 || code.length > 128) { - return json( - { - code: "INVALID_HANDOFF", - message: "The sign-in handoff is invalid.", - }, - 400, - ); - } - const token = await consumeNativeHandoff(env.DB, code); - if (!token) { - return json( - { - code: "EXPIRED_HANDOFF", - message: "The sign-in handoff expired or was already used.", - }, - 401, - ); - } - return json({ token }); - } - - if (url.pathname.startsWith("/api/auth/")) { - if ( - url.pathname.endsWith("/sign-in/social") && - request.method === "POST" - ) { - const body = (await request - .clone() - .json() - .catch(() => null)) as { - provider?: unknown; - } | null; - if (body?.provider === "google" && !isGoogleConfigured(env)) { - return json( - { - code: "OAUTH_NOT_CONFIGURED", - message: "Google sign-in is not configured in this environment.", - }, - 503, - ); - } - if (body?.provider === "apple" && !isAppleConfigured(env)) { - return json( - { - code: "OAUTH_NOT_CONFIGURED", - message: "Apple sign-in is not configured in this environment.", - }, - 503, - ); - } - } - const response = await createAuth(env, request.url).handler(request); - return withApiHeaders(response); - } - - if (url.pathname.startsWith("/api/app/mcp-tokens")) { - try { - return withApiHeaders(await handleMcpTokenManagement(request, env)); - } catch (error) { - console.error( - JSON.stringify({ - event: "setline_mcp_token_error", - method: request.method, - path: url.pathname, - message: error instanceof Error ? error.message : "Unknown error", - }), - ); - return json( - { - code: "TOKEN_UNAVAILABLE", - message: "Read-token access is unavailable.", - }, - 503, - ); - } - } - - if (url.pathname.startsWith("/api/mcp/")) { - try { - return withApiHeaders(await handleMcpRead(request, env)); - } catch (error) { - console.error( - JSON.stringify({ - event: "setline_mcp_read_error", - method: request.method, - path: url.pathname, - message: error instanceof Error ? error.message : "Unknown error", - }), - ); - return json( - { - code: "READ_UNAVAILABLE", - message: "Workout reads are unavailable.", - }, - 503, - ); - } - } - - if (url.pathname === "/api/app/state") { - try { - return withApiHeaders(await handlePrivateState(request, env)); - } catch (error) { - console.error( - JSON.stringify({ - event: "setline_state_error", - method: request.method, - path: url.pathname, - message: error instanceof Error ? error.message : "Unknown error", - }), - ); - return json( - { - code: "STATE_UNAVAILABLE", - message: "Private workout state is temporarily unavailable.", - }, - 503, - ); - } - } - - if (url.pathname === "/api/native/state") { - try { - return withApiHeaders(await handleNativeState(request, env)); - } catch (error) { - console.error( - JSON.stringify({ - event: "setline_native_state_error", - method: request.method, - message: error instanceof Error ? error.message : "Unknown error", - }), - ); - return json( - { - code: "STATE_UNAVAILABLE", - message: "Native sync is temporarily unavailable.", - }, - 503, - ); - } - } - - if (url.pathname.startsWith("/api/")) { - return json({ code: "NOT_FOUND", message: "API route not found." }, 404); - } - - // Serve static assets (public/ files) for non-API routes. - if (env.ASSETS) { - const assetResponse = await env.ASSETS.fetch(request); - if (assetResponse.status !== 404) return assetResponse; - } - - // Fallback: return 404 for unknown routes. - return new Response("Not found", { status: 404 }); - }, -}; - -export default worker; diff --git a/worker/mcp.ts b/worker/mcp.ts deleted file mode 100644 index b925229..0000000 --- a/worker/mcp.ts +++ /dev/null @@ -1,408 +0,0 @@ -import { deriveHistoryAnalytics } from "../src/lib/history-analytics"; -import { - PROGRAMME, - PROGRAMME_SCHEDULE, - resolveWorkout, - type BuiltInWorkoutId, -} from "../src/lib/programme"; -import { - parseStoredState, - type HistoryEntry, - type StoredState, -} from "../src/lib/workout-state"; -import { createAuth, type SetlineBindings } from "./auth"; - -const TOKEN_PREFIX = "setline_read_"; -const MAX_LIMIT = 100; - -type StateRow = { payload: string }; -type TokenRow = { - id: string; - name: string; - token_hint: string; - created_at: number; -}; - -function json(payload: unknown, status = 200) { - return Response.json(payload, { status }); -} - -function toHex(bytes: Uint8Array) { - return [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join(""); -} - -export function readBearerToken(header: string | null): string | null { - if (!header?.startsWith("Bearer ")) return null; - const token = header.slice("Bearer ".length).trim(); - return token.startsWith(TOKEN_PREFIX) && /^[A-Za-z0-9_-]+$/.test(token) - ? token - : null; -} - -export async function hashReadToken(token: string) { - const digest = await crypto.subtle.digest( - "SHA-256", - new TextEncoder().encode(token), - ); - return toHex(new Uint8Array(digest)); -} - -export function createReadToken() { - const bytes = crypto.getRandomValues(new Uint8Array(32)); - const encoded = btoa(String.fromCharCode(...bytes)) - .replaceAll("+", "-") - .replaceAll("/", "_") - .replaceAll("=", ""); - return `${TOKEN_PREFIX}${encoded}`; -} - -async function resolveSessionUserId(request: Request, env: SetlineBindings) { - const session = await createAuth(env, request.url).api.getSession({ - headers: request.headers, - }); - return session?.user?.id ?? null; -} - -async function resolveReadUserId(request: Request, env: SetlineBindings) { - const token = readBearerToken(request.headers.get("Authorization")); - if (!token) return null; - const row = await env.DB.prepare( - `SELECT user_id FROM mcp_read_tokens - WHERE token_hash = ? AND revoked_at IS NULL`, - ) - .bind(await hashReadToken(token)) - .first<{ user_id: string }>(); - return row?.user_id ?? null; -} - -function parseState(row: StateRow | null): StoredState { - if (row) { - try { - const state = parseStoredState(JSON.parse(row.payload) as unknown); - if (state) return state; - } catch { - // Treat corrupt or unsupported cloud state as unavailable, never as partial data. - } - } - return { - version: 6, - updatedAt: 0, - session: null, - history: [], - customWorkouts: [], - customProgramme: null, - }; -} - -async function readState(env: SetlineBindings, userId: string) { - const row = await env.DB.prepare( - "SELECT payload FROM workout_state WHERE user_id = ?", - ) - .bind(userId) - .first(); - return parseState(row); -} - -function boundedText(value: string | null, maximum = 160) { - const trimmed = value?.trim(); - return trimmed ? trimmed.slice(0, maximum) : null; -} - -function page(url: URL) { - const rawLimit = Number(url.searchParams.get("limit")); - const rawOffset = Number(url.searchParams.get("offset")); - return { - limit: - Number.isInteger(rawLimit) && rawLimit > 0 - ? Math.min(rawLimit, MAX_LIMIT) - : 30, - offset: - Number.isInteger(rawOffset) && rawOffset >= 0 - ? Math.min(rawOffset, 10_000) - : 0, - }; -} - -function pagination(total: number, limit: number, offset: number) { - return { - limit, - offset, - total, - nextOffset: offset + limit < total ? offset + limit : null, - }; -} - -function builtInTemplates() { - const seen = new Set(); - return PROGRAMME_SCHEDULE.flatMap((schedule) => { - if (seen.has(schedule.workoutId)) return []; - seen.add(schedule.workoutId); - const workout = resolveWorkout( - schedule.workoutId as BuiltInWorkoutId, - 1, - schedule.dayIndex, - ); - return [ - { - ...workout, - provenance: "authored" as const, - representativeWeek: 1, - }, - ]; - }); -} - -function bundledProgramme() { - return { - kind: "bundled" as const, - provenance: "authored" as const, - programme: PROGRAMME, - schedule: PROGRAMME_SCHEDULE, - note: "Week-specific targets remain authored; template detail is represented at week 1.", - }; -} - -function customProgramme(state: StoredState) { - return { - kind: "custom" as const, - provenance: "authored" as const, - programme: state.customProgramme, - templates: state.customWorkouts, - }; -} - -function historySummary(entry: HistoryEntry) { - return { - id: entry.id, - workoutId: entry.workoutId, - workoutName: entry.workoutName, - weekNumber: entry.weekNumber, - completedAt: entry.completedAt, - durationSeconds: entry.durationSeconds, - completedSets: entry.completedSets, - modifiedSets: entry.modifiedSets, - extraSets: entry.extraSets, - deferredSets: entry.deferredSets, - skippedSets: entry.skippedSets, - workingVolume: entry.workingVolume, - warmupVolume: entry.warmupVolume, - completedDurationSeconds: entry.completedDurationSeconds, - totalActualRestSeconds: entry.totalActualRestSeconds, - averageRpe: entry.averageRpe, - quality: entry.quality, - detailsAvailable: entry.detailsAvailable, - provenance: "recorded" as const, - }; -} - -function dateBoundary(value: string | null, end = false) { - if (!value || !/^\d{4}-\d{2}-\d{2}$/.test(value)) return null; - const parsed = Date.parse(`${value}T00:00:00.000Z`); - return Number.isFinite(parsed) ? parsed + (end ? 86_400_000 : 0) : null; -} - -export function filterHistory(history: HistoryEntry[], url: URL) { - const start = dateBoundary(url.searchParams.get("start")); - const end = dateBoundary(url.searchParams.get("end"), true); - const workout = boundedText( - url.searchParams.get("workout"), - )?.toLocaleLowerCase(); - const exercise = boundedText( - url.searchParams.get("exercise"), - )?.toLocaleLowerCase(); - return [...history] - .sort((left, right) => right.completedAt - left.completedAt) - .filter((entry) => { - if (start !== null && entry.completedAt < start) return false; - if (end !== null && entry.completedAt >= end) return false; - if ( - workout && - !`${entry.workoutId} ${entry.workoutName}` - .toLocaleLowerCase() - .includes(workout) - ) { - return false; - } - if ( - exercise && - !entry.executions.some((record) => - record.step.exercise.toLocaleLowerCase().includes(exercise), - ) - ) { - return false; - } - return true; - }); -} - -export async function handleMcpTokenManagement( - request: Request, - env: SetlineBindings, -) { - const userId = await resolveSessionUserId(request, env); - if (!userId) - return json({ code: "UNAUTHORIZED", message: "Sign in to continue." }, 401); - const url = new URL(request.url); - if (url.pathname === "/api/app/mcp-tokens" && request.method === "GET") { - const result = await env.DB.prepare( - `SELECT id, name, token_hint, created_at FROM mcp_read_tokens - WHERE user_id = ? AND revoked_at IS NULL ORDER BY created_at DESC LIMIT 20`, - ) - .bind(userId) - .all(); - return json( - result.results.map((row) => ({ - id: row.id, - name: row.name, - tokenHint: row.token_hint, - createdAt: row.created_at, - })), - ); - } - if (url.pathname === "/api/app/mcp-tokens" && request.method === "POST") { - const body = await request - .json>() - .catch((): Record => ({})); - const requestedName = typeof body.name === "string" ? body.name.trim() : ""; - const name = requestedName.slice(0, 50) || "ChatGPT read access"; - const token = createReadToken(); - const id = crypto.randomUUID(); - const createdAt = Date.now(); - await env.DB.prepare( - `INSERT INTO mcp_read_tokens - (id, user_id, name, token_hash, token_hint, created_at, revoked_at) - VALUES (?, ?, ?, ?, ?, ?, NULL)`, - ) - .bind( - id, - userId, - name, - await hashReadToken(token), - token.slice(0, 24), - createdAt, - ) - .run(); - return json( - { id, name, token, tokenHint: token.slice(0, 24), createdAt }, - 201, - ); - } - const match = url.pathname.match(/^\/api\/app\/mcp-tokens\/([^/]+)$/); - if (match && request.method === "DELETE") { - const result = await env.DB.prepare( - `UPDATE mcp_read_tokens SET revoked_at = ? - WHERE id = ? AND user_id = ? AND revoked_at IS NULL`, - ) - .bind(Date.now(), decodeURIComponent(match[1]), userId) - .run(); - return result.meta.changes - ? new Response(null, { status: 204 }) - : json({ code: "NOT_FOUND", message: "Read token not found." }, 404); - } - return new Response("Method Not Allowed", { - status: 405, - headers: { Allow: "GET, POST, DELETE" }, - }); -} - -export async function handleMcpRead(request: Request, env: SetlineBindings) { - if (request.method !== "GET") { - return new Response("Method Not Allowed", { - status: 405, - headers: { Allow: "GET" }, - }); - } - const userId = await resolveReadUserId(request, env); - if (!userId) { - return json( - { code: "UNAUTHORIZED", message: "Provide a valid Setline read token." }, - 401, - ); - } - const url = new URL(request.url); - const state = await readState(env, userId); - - if (url.pathname === "/api/mcp/programme") { - const requested = url.searchParams.get("kind") ?? "current"; - const useCustom = - requested === "custom" || - (requested === "current" && state.customProgramme?.enabled === true); - return json({ - schemaVersion: "1", - data: useCustom ? customProgramme(state) : bundledProgramme(), - }); - } - - if (url.pathname === "/api/mcp/templates") { - const { limit, offset } = page(url); - const items = [ - ...builtInTemplates(), - ...state.customWorkouts.map((template) => ({ - ...template, - provenance: "authored" as const, - })), - ]; - return json({ - schemaVersion: "1", - items: items.slice(offset, offset + limit), - page: pagination(items.length, limit, offset), - }); - } - - if (url.pathname === "/api/mcp/history") { - const { limit, offset } = page(url); - const filtered = filterHistory(state.history, url); - return json({ - schemaVersion: "1", - items: filtered.slice(offset, offset + limit).map(historySummary), - page: pagination(filtered.length, limit, offset), - }); - } - - const sessionMatch = url.pathname.match(/^\/api\/mcp\/history\/([^/]+)$/); - if (sessionMatch) { - const id = decodeURIComponent(sessionMatch[1]); - if (!/^[A-Za-z0-9:_-]{1,120}$/.test(id)) { - return json( - { code: "NOT_FOUND", message: "Workout session not found." }, - 404, - ); - } - const entry = state.history.find((candidate) => candidate.id === id); - return entry - ? json({ schemaVersion: "1", data: { ...entry, provenance: "recorded" } }) - : json({ code: "NOT_FOUND", message: "Workout session not found." }, 404); - } - - if (url.pathname === "/api/mcp/progress") { - const exercise = boundedText( - url.searchParams.get("exercise"), - )?.toLocaleLowerCase(); - const workout = boundedText( - url.searchParams.get("workout"), - )?.toLocaleLowerCase(); - const analytics = deriveHistoryAnalytics(state.history); - return json({ - schemaVersion: "1", - provenance: "calculated-from-recorded-history", - data: { - overview: analytics.overview, - exercises: exercise - ? analytics.exercises.filter((item) => - `${item.id} ${item.name}`.toLocaleLowerCase().includes(exercise), - ) - : analytics.exercises, - workouts: workout - ? analytics.workouts.filter((item) => - `${item.workoutId} ${item.workoutName}` - .toLocaleLowerCase() - .includes(workout), - ) - : analytics.workouts, - programmeWeeks: analytics.programmeWeeks, - }, - }); - } - - return json({ code: "NOT_FOUND", message: "Read route not found." }, 404); -} diff --git a/worker/native-handoff.ts b/worker/native-handoff.ts deleted file mode 100644 index 20ed720..0000000 --- a/worker/native-handoff.ts +++ /dev/null @@ -1,61 +0,0 @@ -export const NATIVE_AUTH_CALLBACK = "setline://auth"; -const NATIVE_HANDOFF_TTL_MS = 5 * 60 * 1000; - -export function isAllowedNativeCallback(value: string) { - return value === NATIVE_AUTH_CALLBACK; -} - -export function createNativeHandoffCode() { - const bytes = crypto.getRandomValues(new Uint8Array(32)); - return btoa(String.fromCharCode(...bytes)) - .replaceAll("+", "-") - .replaceAll("/", "_") - .replaceAll("=", ""); -} - -export async function hashNativeHandoffCode(code: string) { - const digest = await crypto.subtle.digest( - "SHA-256", - new TextEncoder().encode(code), - ); - return [...new Uint8Array(digest)] - .map((byte) => byte.toString(16).padStart(2, "0")) - .join(""); -} - -export async function saveNativeHandoff( - db: D1Database, - code: string, - sessionToken: string, - now = Date.now(), -) { - const codeHash = await hashNativeHandoffCode(code); - await db - .prepare( - `INSERT INTO native_auth_handoffs (code_hash, session_token, expires_at, created_at) - VALUES (?, ?, ?, ?)`, - ) - .bind(codeHash, sessionToken, now + NATIVE_HANDOFF_TTL_MS, now) - .run(); -} - -export async function consumeNativeHandoff( - db: D1Database, - code: string, - now = Date.now(), -) { - const codeHash = await hashNativeHandoffCode(code); - const row = await db - .prepare( - `DELETE FROM native_auth_handoffs - WHERE code_hash = ? AND expires_at > ? - RETURNING session_token`, - ) - .bind(codeHash, now) - .first<{ session_token: string }>(); - await db - .prepare("DELETE FROM native_auth_handoffs WHERE expires_at <= ?") - .bind(now) - .run(); - return row?.session_token ?? null; -} diff --git a/worker/native-state.ts b/worker/native-state.ts deleted file mode 100644 index 764a34b..0000000 --- a/worker/native-state.ts +++ /dev/null @@ -1,142 +0,0 @@ -import { type SetlineBindings } from "./auth"; -import { requireUserId } from "./auth-guard"; - -const MAX_STATE_BYTES = 512 * 1024; - -type NativeStateRow = { - payload: string; - revision: number; -}; - -type NativeStateEnvelope = { - document: Record; - baseRevision: number | null; -}; - -function json(payload: unknown, status = 200) { - return Response.json(payload, { status }); -} - -export function parseNativeStateEnvelope( - value: unknown, -): NativeStateEnvelope | null { - if (!value || typeof value !== "object") return null; - const candidate = value as Record; - if (!candidate.document || typeof candidate.document !== "object") - return null; - const document = candidate.document as Record; - if (document.schemaVersion !== 1) return null; - const baseRevision = candidate.baseRevision; - if ( - baseRevision !== null && - (!Number.isSafeInteger(baseRevision) || Number(baseRevision) < 0) - ) { - return null; - } - return { document, baseRevision: baseRevision as number | null }; -} - -function parseRow(row: NativeStateRow | null) { - if (!row) return null; - try { - const document = JSON.parse(row.payload) as unknown; - if (!document || typeof document !== "object") return null; - return { document, revision: row.revision }; - } catch { - return null; - } -} - -export async function handleNativeState( - request: Request, - env: SetlineBindings, -) { - const { userId, response } = await requireUserId(request, env); - if (response) return response; - - if (request.method === "GET") { - const row = await env.DB.prepare( - "SELECT payload, revision FROM native_workout_state WHERE user_id = ?", - ) - .bind(userId) - .first(); - return json({ state: parseRow(row) }); - } - - if (request.method !== "PUT") { - return new Response("Method Not Allowed", { - status: 405, - headers: { Allow: "GET, PUT" }, - }); - } - - const declaredLength = Number(request.headers.get("content-length") ?? "0"); - if (Number.isFinite(declaredLength) && declaredLength > MAX_STATE_BYTES) { - return json( - { code: "STATE_TOO_LARGE", message: "Workout state is too large." }, - 413, - ); - } - const text = await request.text(); - if (new TextEncoder().encode(text).byteLength > MAX_STATE_BYTES) { - return json( - { code: "STATE_TOO_LARGE", message: "Workout state is too large." }, - 413, - ); - } - const envelope = parseNativeStateEnvelope( - (() => { - try { - return JSON.parse(text) as unknown; - } catch { - return null; - } - })(), - ); - if (!envelope) { - return json( - { code: "INVALID_STATE", message: "Native workout state is invalid." }, - 400, - ); - } - - const payload = JSON.stringify(envelope.document); - const now = Date.now(); - if (envelope.baseRevision === null) { - const result = await env.DB.prepare( - `INSERT OR IGNORE INTO native_workout_state - (user_id, payload, revision, created_at, updated_at) - VALUES (?, ?, 1, ?, ?)`, - ) - .bind(userId, payload, now, now) - .run(); - if (result.meta.changes > 0) { - return json({ state: { document: envelope.document, revision: 1 } }); - } - } else { - const nextRevision = envelope.baseRevision + 1; - const row = await env.DB.prepare( - `UPDATE native_workout_state - SET payload = ?, revision = ?, updated_at = ? - WHERE user_id = ? AND revision = ? - RETURNING payload, revision`, - ) - .bind(payload, nextRevision, now, userId, envelope.baseRevision) - .first(); - if (row) return json({ state: parseRow(row) }); - } - - const current = await env.DB.prepare( - "SELECT payload, revision FROM native_workout_state WHERE user_id = ?", - ) - .bind(userId) - .first(); - return json( - { - code: "STALE_STATE", - message: "A newer native workout state is already stored.", - state: parseRow(current), - }, - 409, - ); -} diff --git a/worker/schema.ts b/worker/schema.ts deleted file mode 100644 index 7821fc2..0000000 --- a/worker/schema.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"; - -export const user = sqliteTable("user", { - id: text("id").primaryKey(), - name: text("name").notNull(), - email: text("email").notNull().unique(), - emailVerified: integer("emailVerified", { mode: "boolean" }) - .notNull() - .default(false), - image: text("image"), - createdAt: integer("createdAt", { mode: "timestamp" }).notNull(), - updatedAt: integer("updatedAt", { mode: "timestamp" }).notNull(), -}); - -export const session = sqliteTable("session", { - id: text("id").primaryKey(), - expiresAt: integer("expiresAt", { mode: "timestamp" }).notNull(), - token: text("token").notNull().unique(), - createdAt: integer("createdAt", { mode: "timestamp" }).notNull(), - updatedAt: integer("updatedAt", { mode: "timestamp" }).notNull(), - ipAddress: text("ipAddress"), - userAgent: text("userAgent"), - userId: text("userId") - .notNull() - .references(() => user.id, { onDelete: "cascade" }), -}); - -export const account = sqliteTable("account", { - id: text("id").primaryKey(), - accountId: text("accountId").notNull(), - providerId: text("providerId").notNull(), - userId: text("userId") - .notNull() - .references(() => user.id, { onDelete: "cascade" }), - accessToken: text("accessToken"), - refreshToken: text("refreshToken"), - idToken: text("idToken"), - accessTokenExpiresAt: integer("accessTokenExpiresAt", { mode: "timestamp" }), - refreshTokenExpiresAt: integer("refreshTokenExpiresAt", { - mode: "timestamp", - }), - scope: text("scope"), - password: text("password"), - createdAt: integer("createdAt", { mode: "timestamp" }).notNull(), - updatedAt: integer("updatedAt", { mode: "timestamp" }).notNull(), -}); - -export const verification = sqliteTable("verification", { - id: text("id").primaryKey(), - identifier: text("identifier").notNull(), - value: text("value").notNull(), - expiresAt: integer("expiresAt", { mode: "timestamp" }).notNull(), - createdAt: integer("createdAt", { mode: "timestamp" }).notNull(), - updatedAt: integer("updatedAt", { mode: "timestamp" }).notNull(), -}); diff --git a/worker/state.ts b/worker/state.ts deleted file mode 100644 index 49a089c..0000000 --- a/worker/state.ts +++ /dev/null @@ -1,177 +0,0 @@ -import { type SetlineBindings } from "./auth"; -import { requireUserId } from "./auth-guard"; -import { parseStoredState, type StoredState } from "../src/lib/workout-state"; - -const MAX_STATE_BYTES = 512 * 1024; -const MAX_HISTORY_ENTRIES = 500; -const MAX_FUTURE_SKEW_MS = 5 * 60 * 1000; - -type StateRow = { - payload: string; - updated_at: number; -}; - -type ReadResult = - | { ok: true; value: unknown } - | { ok: false; status: 400 | 413 | 415; message: string }; - -function parseStateEnvelope(value: unknown): StoredState | null { - const state = parseStoredState(value); - if ( - !state || - state.history.length > MAX_HISTORY_ENTRIES || - state.updatedAt > Date.now() + MAX_FUTURE_SKEW_MS - ) { - return null; - } - return state; -} - -async function readJsonWithLimit(request: Request): Promise { - if ( - !request.headers - .get("content-type") - ?.toLowerCase() - .startsWith("application/json") - ) { - return { ok: false, status: 415, message: "Expected application/json." }; - } - - const declaredLength = Number(request.headers.get("content-length") ?? "0"); - if (Number.isFinite(declaredLength) && declaredLength > MAX_STATE_BYTES) { - return { ok: false, status: 413, message: "Workout state is too large." }; - } - if (!request.body) { - return { ok: false, status: 400, message: "Workout state is required." }; - } - - const reader = request.body.getReader(); - const decoder = new TextDecoder(); - let total = 0; - let text = ""; - - while (true) { - const { done, value } = await reader.read(); - if (done) break; - total += value.byteLength; - if (total > MAX_STATE_BYTES) { - await reader.cancel(); - return { ok: false, status: 413, message: "Workout state is too large." }; - } - text += decoder.decode(value, { stream: true }); - } - text += decoder.decode(); - - try { - return { ok: true, value: JSON.parse(text) }; - } catch { - return { - ok: false, - status: 400, - message: "Workout state must be valid JSON.", - }; - } -} - -function parseStoredRow(row: StateRow | null) { - if (!row) return null; - try { - const state = JSON.parse(row.payload) as unknown; - return parseStateEnvelope(state); - } catch { - return null; - } -} - -function json(payload: unknown, status = 200) { - return Response.json(payload, { status }); -} - -export async function handlePrivateState( - request: Request, - env: SetlineBindings, -) { - const { userId, response } = await requireUserId(request, env); - if (response) return response; - - if (request.method === "GET") { - const row = await env.DB.prepare( - "SELECT payload, updated_at FROM workout_state WHERE user_id = ?", - ) - .bind(userId) - .first(); - return json({ state: parseStoredRow(row) }); - } - - if (request.method !== "PUT") { - return new Response("Method Not Allowed", { - status: 405, - headers: { Allow: "GET, PUT" }, - }); - } - - const parsed = await readJsonWithLimit(request); - if (!parsed.ok) { - return json( - { code: "INVALID_STATE", message: parsed.message }, - parsed.status, - ); - } - const incomingState = parseStateEnvelope(parsed.value); - if (!incomingState) { - return json( - { - code: "INVALID_STATE", - message: - "Workout state has an unsupported version, shape, or exercise order.", - }, - 400, - ); - } - - const currentRow = await env.DB.prepare( - "SELECT payload, updated_at FROM workout_state WHERE user_id = ?", - ) - .bind(userId) - .first(); - if (currentRow && currentRow.updated_at >= incomingState.updatedAt) { - return json( - { - code: "STALE_STATE", - message: "A newer workout state is already stored.", - state: parseStoredRow(currentRow), - }, - 409, - ); - } - - const now = Date.now(); - const writeResult = await env.DB.prepare( - `INSERT INTO workout_state (user_id, payload, updated_at, created_at) - VALUES (?, ?, ?, ?) - ON CONFLICT(user_id) DO UPDATE SET - payload = excluded.payload, - updated_at = excluded.updated_at - WHERE excluded.updated_at > workout_state.updated_at`, - ) - .bind(userId, JSON.stringify(incomingState), incomingState.updatedAt, now) - .run(); - - if (writeResult.meta.changes === 0) { - const newerRow = await env.DB.prepare( - "SELECT payload, updated_at FROM workout_state WHERE user_id = ?", - ) - .bind(userId) - .first(); - return json( - { - code: "STALE_STATE", - message: "A newer workout state is already stored.", - state: parseStoredRow(newerRow), - }, - 409, - ); - } - - return json({ state: incomingState }); -} diff --git a/wrangler.jsonc b/wrangler.jsonc deleted file mode 100644 index 56a6ee4..0000000 --- a/wrangler.jsonc +++ /dev/null @@ -1,35 +0,0 @@ -{ - "$schema": "./node_modules/wrangler/config-schema.json", - "name": "setline", - "main": "worker/index.ts", - "compatibility_date": "2026-05-22", - "compatibility_flags": ["nodejs_compat"], - "vars": { - "APPLE_APP_BUNDLE_IDENTIFIER": "com.significanthobbies.setline" - }, - "routes": [ - { - "pattern": "setline.significanthobbies.com", - "custom_domain": true - } - ], - "assets": { - "binding": "ASSETS", - "directory": "public" - }, - "d1_databases": [ - { - "binding": "DB", - "database_name": "setline", - "database_id": "2b52f12a-451e-4aad-bf9f-2cc079f41f8f", - "migrations_dir": "migrations" - } - ], - "placement": { - "mode": "smart" - }, - "observability": { - "enabled": true, - "head_sampling_rate": 0.1 - } -}