New:Introducing Socket Scanning for VS Code Marketplace Extensions.Learn more →
Get Started

@time-provider/core

Package Overview
Dependencies
Maintainers
1
Versions
17
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@time-provider/core

Inject time. Control it in tests.

latest
Source
npmnpm
Version
4.1.0
Version published
Weekly downloads
6
-76.92%
Maintainers
1
Weekly downloads
 
Created
Source

Time-Provider

npm jsr jsr score types Node.js ^18.18 || >=20.4 Deno ~1.39.1 || >=1.43 module ESM + CJS CodeQL check codecov tests npm downloads dependencies unpacked-size minified size openssf best practices license

Time-Provider

🌳 Tree-shakable | 📦 Zero runtime dependencies | 🧪 No global monkey-patching | 🛡️ Type-safe | ⏱️ Deterministic timers | 🕓 Four clock strategies | 🌍 Real timezone support (when applicable) | 🔌 Bring your own date library | 🧩 Modular & Extensible

Time is a dependency

Code coupled to the native Date object, Temporal objects, any specific date library, or the environment's timers has an implicit dependency on the system clock. That's what pushes teams toward global fake-timer libraries for testing - patching Date/timers process-wide, which affects unrelated code and makes tests harder to reason about.

vs. jest.useFakeTimers() / sinon.useFakeTimers(): scoped per call site, no global patch, no restore/cleanup step.

time-provider makes time an explicit, injectable dependency instead: a single object exposing a clock, a converter, a scheduler, and timings, swappable per call site.
Note: Non baseline or additional features are available as addons.

Features

  • Four clock strategies: system (real time), fixed, manual (move time explicitly), sequential (predefined instants) - same API for production and tests.
  • Wall clock steps: move a manual clock as elapsed time (flow), a host sleep (sleep) or a wall correction (snap), and step from timer to timer with moveTo("nextTimer")/moveUntil("noTimers").
  • Deterministic timers: driven by the clock strategy, not the real event loop, so manual/sequential/fixed runs are synchronous and don't depend on wall-clock time.
  • Bring your own date library: adapters for Temporal, Day.js, Luxon, Moment.js, Moment.js + moment-timezone, and native Date. Your code keeps working with the date type it already uses.
  • Real timezone support where the underlying library allows it (native Date, plain Moment.js are UTC-only - see ARCHITECTURE.md) - withTimezone(...) plus localNow()/utcNow().
  • Tree-shakable: no deterministic runtimes bundled when not imported.
  • Zero runtime dependencies in @time-provider/core.

Install

npm install @time-provider/core @time-provider/plugin-native

Swap plugin-native for plugin-dayjs, plugin-luxon, plugin-moment, plugin-moment-timezone, or plugin-temporal depending on the date library you use.

Usage

// production: import the default production runtime
import { createTimeProvider } from "@time-provider/core";
import { plugin } from "@time-provider/plugin-native";

// create a production runtime
const timeProvider = createTimeProvider.for(plugin).create();

class UserService {
  constructor(private readonly timeProvider: ITimeProvider<Date>) {}

  createUser() {
    return { createdAt: this.timeProvider.clock.utcNow() };
  }
}
// test: import the deterministic runtime
import { createTimeProvider } from "@time-provider/core/deterministic";
import { plugin } from "@time-provider/plugin-native/deterministic";

// create a deterministic runtime
{
  using timeProvider = createTimeProvider
    .for(plugin)
    .asManual()
    .withInitialTime("2026-01-01T00:00:00.000Z")
    .create();

  let retries = 0;
  {
    //timers are cleared when disposing their handles
    using timerHandle = timeProvider.scheduler.timers.every({ seconds: 1 }, () => retries++);
    timeProvider.clock.moveBy({ seconds: 3 });
  }

  expect(retries).toBe(3);
}

Same idea, closer to a real service - a retry/backoff loop injected with the time provider, unaware of which strategy backs it:

// production: a retry/backoff service, injected with the real time provider
class RetryingOperation {
  constructor(private readonly timeProvider: ITimeProvider<Date>) {}

  run(operation: () => boolean, onGiveUp: () => void, maxAttempts = 3) {
    let attempt = 0;
    this.timeProvider.scheduler.timers.recurring(() => {
      attempt++;
      if (operation()) return false; // succeeded, stop retrying
      if (attempt >= maxAttempts) {
        onGiveUp();
        return false;
      }
      return { seconds: attempt }; // back off: 1s, 2s, 3s...
    });
  }
}

new RetryingOperation(timeProvider).run(sendRequest, pageOnCallEngineer);
// test: same service, injected with a manual provider instead - no real waiting
using timeProvider = createTimeProvider.for(plugin).asManual().withInitialTime(0).create();

let attempts = 0;
let gaveUp = false;
new RetryingOperation(timeProvider).run(
  () => ++attempts === 3, // succeeds on the 3rd try
  () => (gaveUp = true),
);

timeProvider.clock.moveBy({ seconds: 1 }); // 2nd attempt
timeProvider.clock.moveBy({ seconds: 2 }); // 3rd attempt, succeeds

expect(attempts).toBe(3);
expect(gaveUp).toBe(false);

Every time provider exposes the same four-part surface:

interface ITimeProvider<TDate> extends IHasAbortSignal, IDisposable {
  clock: IClock<TDate>; // localNow, utcNow, timestampNow, monotonicNow, withTimezone
  converter: IConverter<TDate>; // convertToUtc, convertToLocal
  scheduler: IScheduler; // timers (once, every, recurring, wait), microtasks
  timings: ITimings; // mark, measure, entries, clear
}

scheduler is where everything that schedules a callback to run later sits, so the scheduling addons extend that facet rather than the root. Animation-Frame comes with its addon that extends ITimeProvider with:

interface ITimeProvider<TDate> {
  scheduler: { animation: IAnimationFrameApi }; //scheduleFrame
}

Clock strategies

StrategyBehaviorTypical use
SystemReal time, real timersProduction
FixedAlways the same instantDeterministic single-instant tests
ManualAdvances only when told toSimulations, timer/retry logic tests
SequentialReturns a predefined instant sequenceTests asserting on changing timestamps
createTimeProvider.for(plugin).asFixed().withFixedTime("2026-01-01T00:00Z").create();
createTimeProvider.for(plugin).asManual().withInitialTime("2026-01-01T00:00Z").create();
createTimeProvider
  .for(plugin)
  .asSequential()
  .withSequentialTime("2026-01-01T00:01Z")
  .withSequentialTime("2026-01-01T00:02Z")
  .create();

Manual and sequential clocks run synchronously. A due timer callback fires in-line, as a direct side effect of the call that made it due (moveBy(), moveTo(), moveUntil(), or localNow()/utcNow() on sequential clocks) - not on a real event-loop tick. This is what makes them deterministic without await, but it means call ordering can differ subtly from a real async run. Use timestampNow() instead when you only need a value to compute with - it never triggers any timer on sequential clocks or advances time.

Addons vs. Plugins

Within the scope of this library, these two terms refer to different concepts.

  • A plugin, is essentially an adapter. It allows you to connect your preferred date library (e.g. Luxon, Temporal, etc.) to the Time Provider core library without adding any new functionality. Its sole purpose is to bridge the two libraries (e.g. the dayjs plugin).
  • An addon, as the name suggests, extends the library by introducing new functionality or enhancing existing facades (e.g. the animation-frame API addon)

Available addons

  • Animation-frame API addon - access browser-specific animation frame timers
  • Compat addon - keep calling native-style setTimeout/setInterval/queueMicrotask/performance while you migrate
  • Cron addon - schedule recurring callbacks with the cron syntax or a JSON-friendlier one
  • ETA addon - get the ETA (estimated time of arrival) for a task by notifying its progression
  • Idle addon - run callbacks when the host reports itself idle, drained on demand on a deterministic clock

Learn more

  • Guide - Read the guide
  • API - Browse the library API
  • ARCHITECTURE.md - how the packages fit together, the plugin/adapter model, why native Date and plain Moment.js are UTC-only.
  • CONTRIBUTING.md - development setup, workflow, reporting bugs/features.
  • BENCHMARK.md - faster than jest/sinon fake timers.
  • Per-package README (packages/<name>/README.md) for adapter-specific notes.
  • CHANGELOG.md - changes log from the core library and all plugins.

License

MIT

Keywords

clock

FAQs

Package last updated on 28 Sep 2026

Related posts