npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@dofek/training

v0.2.4

Published

Training-science calculations for power, load, performance, and workout planning

Readme

@dofek/training

Framework-neutral TypeScript calculations for training load, cycling power, performance modeling, activity normalization, and workout recommendations.

Install

npm install @dofek/training

Requires Node.js 22.14 or newer.

Usage

There is no root export; import the module subpath you need.

import {
  computeTrimp,
} from "@dofek/training/pmc";

const durationMinutes = 60;
const averageHeartRate = 150;
const maximumHeartRate = 190;
const restingHeartRate = 55;

console.log({
  trimp: computeTrimp(
    durationMinutes,
    averageHeartRate,
    maximumHeartRate,
    restingHeartRate,
  ),
});

Public API

Every public module is imported as @dofek/training/<subpath>.

| Subpath | Purpose | | --- | --- | | activity-icons | Normalize activity names into framework-neutral icon categories | | activity-chart-series | Shared activity-chart timing, gap, marker, and nearest-observation presentation policy | | activity-images | Activity-image metadata, captions, and shared web/mobile query refresh policy | | climbing-grades | Validate recorded grade components; order and convert supported free-rock grades with Sandbag | | climbing-context | Validate the current Climb and Area path with recorded board, wall-angle, and grip context | | climbing-catalogue | Disposable catalogue context: attributed candidate matches, scoped locations, multiple/inherited tags and cache status, separately from recorded climbing facts | | climbing-sources | Select route destinations and match provider attribution to tick links for web and mobile using a supplied provider-label resolver | | climbing-map | Source locations and shared card-location/overview-marker builders for web and mobile; preserves server-selected ownership and full card positions | | climbing-location-map | Server-computed map circles and zoom bands shared by web and mobile; Supercluster groups nearby logged climbs while retaining individual source locations | | climbing-experience | Shared recorded board and wall-angle schemas | | climbing-tags | Attributed source-tag contract, preserving literal labels and source/category keys | | climbing-tag-presentation | Grouped tag labels, avoiding repeated known grip labels in details | | climbing-strengths-presentation | Source-aware category breakdown selection for web and mobile | | climbing-log | Area, Climb, Pitch, owned GradeComponent collections, ClimbingLogEntry, scoped ClimbingAttempt, and their canonical enums | | climbing-log-response | Supported response-version input schema and faithful version-1 projection of canonical grip collections and wall angles | | climbing-log-groups | Group log cards by their closest recorded Area identity, preserving original entry numbers, group order, and entries without an Area | | map-style | Shared light/dark MapLibre style specification using OpenFreeMap vector tiles for interactive maps and snapshots | | climbing-progression | Server-computed combined grade-stack contract, display grade labels with scale disambiguation, and period/exact-value formatting shared by web and mobile; the server pools selected types and settings using distinct climbing dates | | climbing-progression-v1 | Supported V1 lane contract for older clients; the versioned routers preserve its per-type/per-setting response while current clients explicitly request the combined V2 projection | | climbing-strengths | Success-by-style response contract: per-grade and pooled All grades profiles plus server-computed grade-adjusted strength differences, with rates from known results, total distinct-climb and unknown-result counts, baselines, nullable source outcomes, exclusion coverage, clipped monthly outcomes, and shared result/rate/count labels for web and mobile views | | climbing-strengths-views | Shared Styles / Progress navigation and chart format definitions, with fixed Styles radar and Progress views | | cycling-workout-metrics | Coverage-aware per-activity power, heart-rate, cadence, drift, zone, load, and interval calculations | | derived-cardio | Cycling and submaximal walking/running VO2 max estimates and validation | | endurance-types | Endurance and indoor-cycling type guards | | grade-adjusted-pace | Grade cost factor and adjusted running pace | | route-comparison | GPS-matched route and identified attempt response schemas, shared by web and mobile; unavailable pace remains null | | muscle-groups | Muscle-group expansion, totals, intensities, and display colors | | pmc | TRIMP and power-based performance-management contracts | | running-cadence | Cadence basis and supplied-coverage labels shared by web and mobile; values remain server-authored | | running-response | Running response versions, wire validation, and faithful legacy projection for independently released API and clients | | power-analysis | Standard curve-duration constants and chart labels | | training | Canonical activity types, provider normalization, and weekly-volume grouping | | training-distribution | Karvonen and Treff weekly intensity-distribution summaries | | training-chart-availability | Shared chart availability schema; counts and messages are computed by the server |

Model details

Activity images

The image presentation contract retains stored-image dimensions, source associations, and captions. Its query options refresh active acquisition every three seconds and renew visible stored-image links every four minutes, before the server's five-minute signed URL lifetime. Failed link renewal retries after thirty seconds while stored images remain visible. Empty completed results stop polling. Inactive queries discard their temporary links; remounting or focusing the client refreshes the query. Persistence metadata excludes them from the mobile disk cache. TanStack documents the query refresh options, and Cloudflare describes signed URLs as temporary bearer access.

Activity chart presentation

The chart-series helper positions each metric's returned observations on a proportional time axis. Continuity uses that metric's lower-median positive sample interval with 50% timing tolerance. At least two positive intervals are required to infer cadence; fewer observations remain dots. The rule scales with the returned sampling interval so downsampling a long recording does not manufacture gaps. These are Dofek display heuristics, following time-based gap handling, not a classification of sensor failure. Series with at most 20 observations and isolated observations retain markers; dense continuous segments show markers on hover or touch. Measurements are preserved without filling or smoothing. The renderer can show only gaps retained in the API's downsampled observations.

Timed climbing overlays

Climbing activity heart-rate charts on web and mobile render the server's chartAnnotations with climb names, display grades and original timestamps. The chart geometry uses the recorded activity window when supplied, keeping endpoint climbs visible when sensor observations start later or end earlier. It preserves the original samples and recording gaps; an activity without a recorded end uses the last observation for that boundary. For climbing HR, both clients instead render the server's activity.heartRateContext window and observations. Its repository adds five minutes before the recorded start and after a recorded end, retaining the selected HR source and leaving activity durations, summaries and zones scoped to the original window. Empty margins stay empty; no readings are synthesized. The server projection accepts timezone-qualified KAYA ascent and export dates from retained raw records; date-only logs, session attempt summaries and ingestion timestamps do not establish climb timing. Current KAYA records have no per-climb end boundary. The shared annotation contract represents instants as markers and bounded climbs as shaded regions, using the existing ECharts marker components and SVG shapes.

Activity icons

The activity icon metadata owns Dofek's original rounded outline SVG family for all 16 existing categories, including a neutral activity glyph for unknown types. Category resolution remains shared across web and mobile. Each glyph uses a 32-unit view box, rounded strokes, and currentColor so renderers can supply a theme-appropriate foreground; see the SVG painting specification. Web uses the shared SVG as a CSS mask, and mobile renders the same source through react-native-svg's SvgXml.

Climbing grades and attempts

GradeSystem covers recorded free, British, aid, ice, mixed, and commitment components. FreeRockGradeSystem restricts numerical conversion and display preferences to the existing Sandbag-supported free-rock scales. Grade validation preserves A/C aid prefixes and documented modifiers/ranges rather than converting recorded values; see theCrag's grade definitions, the UIAA difficulty scales, and firsthand mixed-grade and ice/mixed range examples.

Published components belong to Climb/Pitch; separately reported components belong to the log. Recorded attempts retain whole-Climb or pitch scope, original source result labels, rope method, solo, aid, protection, fall/hang, dab, beta and source history facts. The raw record schema and computed response schema are separate. Server queries derive completion, result labels and counts; see the current model and schemas.

Canonical grip collections are nullable and nonempty when supplied. Wall angles retain either numeric values with known/unknown units or explicit source categories. The response-version module defines versions 1, 2 and 3, defaults omitted requests to 1, and projects only the traits that the original scalar contract can express. A single supported grip remains scalar; multiple grips, newer grip kinds, and categorical angles become null in version 1 without altering canonical records. Version 2 retains the complete collection and angle object. Version 3 adds attributed recorded source tags through the server detail contract. The tag contract keeps source/category identity; the strengths contract adds separate recorded-category panels without changing the original panel dimensions. See the shared model, angle schema, and server response-version contract.

The log-card grouping helper groups areas across sources when their complete ordered name paths match, ignoring case and extra whitespace. Distinct parent paths remain separate. If one source has multiple Area IDs for the same path, the match is ambiguous and those areas remain separate. Grouping preserves every log and its original occurrence number.

Climbing catalogue evidence

Route discovery, provider adapters, and identity evidence live in the independent @dofek/climbing-catalogue package. This module adds Dofek's user/log seed, cache status, and shared web/mobile labels around the package's source-result contract.

Version 0.2.0 moves these public exports from @dofek/training/climbing-catalogue to @dofek/climbing-catalogue/contracts:

  • catalogueProviderSchema, catalogueLocationSchema, catalogueTagSchema, catalogueCandidateSchema, and catalogueSearchResultSchema;
  • CatalogueProviderId, CatalogueLocation, CatalogueCandidate, CatalogueSearchResult, and ClimbingCatalogueAdapter.

The former @dofek/training/gps-coordinates module also moves to @dofek/climbing-catalogue/geometry, retaining gpsCoordinatesSchema and GpsCoordinates. Training's climbing schemas compose that canonical coordinate and numeric wall-angle validation; see the geometry module.

Update those imports and add @dofek/climbing-catalogue as a direct dependency. CatalogueSeed and catalogueSeedSchema in this package retain Dofek's user/log fields; use their independent equivalents from the new package for standalone search. Cache context schemas and presentation labels remain here. This minor version marks an incompatible change during initial development, when SemVer allows public APIs to change; see SemVer section 4.

The catalogue response contract keeps disposable reference observations separate from recorded climb facts. Both clients use climbingCatalogueConfidenceLabel for Own source, Provider reference, Location corroborated, and Possible match labels; they display the server's evidence strings and optional searchArea without deciding identity. Incomplete searches remain qualified even when no candidates were returned.

Explicit provider references can link renamed climbs: the paired catalogue stories show Mountain Project's Cheddar Corner and OpenBeta's Corner Route. OpenBeta exposes the reference as metadata.mp_id in its Climb schema. A separate conflict story keeps the candidate possible and displays the server's reason. Catalogue grades and tags remain attributed observations, independent of that identity decision; see the matching design.

Cached catalogue traits in strengths

The catalogue location contract now carries optional area-only source context: URL, literal type, plain-text sections, attributed tags/counts and statistics. The paired web and mobile disclosures keep area names concise and expose inherited provenance with the source link.

The strengths contract carries route/area trait sources, pending enrichment and errors. The server's enrichment repository loads seeds in bulk, shares a user/source-fact cache across repeated log entries, and enqueues missing context through the existing worker. The cache service uses v4 keys and keeps source observations disposable; it never writes identities or traits into recorded logs.

Only cached, explicitly observed traits enter the trait projection. Accepted route identity and compatibility checks gate route evidence; independently corroborated local areas can contribute area evidence without declaring a route match. Recorded route wall/hold facts retain precedence. Descriptions, source statistics and tag counts do not become route measurements. The aggregation supports includeAreaMetadata: false to exclude area contributions and returns computed chart values with source attribution. Both web and mobile show source provenance beside the chart within the existing Styles/Progress views.

Running response versions

The existing running.dynamics and running.dynamicsV2 procedures accept responseVersion: 1 | 2, defaulting to 1, following the climbing response-version pattern. The procedure suffix and negotiated response version are separate. The running wire contract projects version 1 to the historical fields and includes only rows with finite cadence, pace and distance. Genuine numeric zeros remain zero. Version 2 retains nullable measurements, cadence basis and coverage; its wrapper has separate form/cadence availability. Canonical records remain complete; the projection runs only at the API boundary in the running router.

Both repository clients explicitly request version 2 and validate its shared schema before rendering. Unknown measurements remain missing values, and a malformed response produces an actionable error. The shared availability schema validates the wire shape; the server factory owns availability calculations and messages.

Training distributions

The Treff polarization summary uses recorded cycling time in three maximum-heart-rate zones and the published formula log10((f1 / f2) × f3 × 100), where f1, f2, and f3 are the fractions of total recorded cycling time in Zone 1, Zone 2, and Zone 3 respectively. Dofek requires recorded time in every zone instead of applying the paper's zero-Zone-2 substitution and follows the paper's rule that the index is invalid when Zone 3 exceeds Zone 1. The > 2.00 comparison is presented as a descriptive training-distribution heuristic, not a physiological or medical assessment. See Treff et al. (2019).

Workout recommendations

recommendNextWorkout combines recent activity, readiness, muscle-group freshness, and intensity distribution. Its low/moderate/high distribution model is informed by the three-zone observations in Seiler and Kjerland (2006); the exact readiness gates, recovery windows, and recommendation rules are Dofek product heuristics.

Training stress and performance

Power and curve analysis

Cycling workout metrics

prepareCyclingWorkoutMetrics resamples native power, heart-rate, and cadence streams to elapsed one-second buckets without filling dropouts. A native observation is held only to the next native timestamp when the gap is at most the bounded continuity tolerance; measured zero remains zero and missing elapsed seconds remain missing. The result reports native observation counts, covered, missing, and zero seconds, median sample interval, and largest gap independently for every stream. All resampling and power-work inputs require the caller's PowerCoveragePolicy; the package does not supply application hold or gap defaults. Dofek passes its shared application policy to these adapters.

Average power and work use covered power seconds only. The caller supplies normalized power, intensity factor, and power TSS from the canonical numerical engine through the required power-metric inputs; this module assembles those results with stream coverage and interval evidence rather than calculating another estimate. Summary-only callers can use computeCyclingPowerWork, which shares the bucket calculation and returns work and power coverage while allocating only buckets touched by native observations, independent of missing elapsed time. Intensity factor is normalized power divided by the FTP effective for that activity. Power TSS uses duration_hours × intensity_factor² × 100, following the power-stress definition; both values are unavailable rather than manufactured when FTP or normalized power is missing.

Aerobic efficiency is mean synchronized power divided by mean synchronized heart rate. Cardiac drift compares that ratio between equal elapsed-time halves as 100 × (first_half_ratio - second_half_ratio) / first_half_ratio; it requires at least 20 minutes and 90% paired coverage in each half. This is a descriptive within-workout comparison, not a causal or medical conclusion.

Recorded interval boundaries always take precedence. Without recorded intervals, the optional detector identifies at least 30 seconds whose 30-second mean is at or above 105% of the activity's effective FTP, merges interruptions shorter than 15 seconds, and exposes intervening recoveries. That detector is a Dofek heuristic. Inferred intervals never receive invented targets or completion scores.

Terrain adjustment

Grade-adjusted pace uses a bounded approximation derived from the slope-cost work of Minetti et al. (2002). It is an estimate, not a substitute for measured effort.

Activity normalization

Canonical activity types map provider-specific labels into one vocabulary. Endurance filters and weekly-volume grouping keep downstream analysis provider-neutral.

Errors and configuration

The package performs no network requests and requires no authentication or environment variables. Several calculations return zero or null when data is invalid or insufficient; callers should validate data at external boundaries and handle the nullable return types declared by each function. Training calculations are estimates and are not medical advice.

License and contributing

MIT. Source is in the Dofek repository. Please open an issue for bugs or API proposals, or submit a pull request.

Climbing strengths view migration

The strengths query negotiates responseVersion: 1 | 2, defaulting to 1. Version 1 preserves the historical panel-dimension vocabulary; version 2 includes the unified style dimension. Both repository clients explicitly request version 2. This follows the existing climbing response negotiation pattern and keeps older installed clients able to parse their responses.

The climbing-strengths-views subpath now exports CLIMBING_STRENGTHS_TABS and ClimbingStrengthsTab for fixed Styles (radar) and Progress (progress) views. The removed Grades visualization's profile value is no longer present in either the tab or renderer-view metadata above. Replace CLIMBING_STRENGTHS_PURPOSES, climbingStrengthsPurpose, and climbingStrengthsPurposeView imports with the fixed tab values; there is no alternate-format selector. The renderer-level CLIMBING_STRENGTHS_VIEWS and ClimbingStrengthsView exports remain available. This is a breaking subpath API change for package consumers; both repository clients migrate together.