Eve library

Meditation Developer Guide

Guide

Revision 1

On this page

Comprehensive development guide for the Meditation (Shared Meditation) domain libraries.

This guide covers local development setup, building, testing, debugging, and common development tasks for all 6 Meditation libraries.


Prerequisites#

Required Software#

Tool Version Purpose
Node.js >= 20.0 JavaScript runtime
pnpm >= 10.0 Package manager
Nx (via pnpm) Monorepo task runner

Installation#

bash
# From the repository root
pnpm install

No databases or external services are required. All meditation libraries are pure TypeScript with eventemitter3 as their only runtime dependency (plus optional react peer dependency for hook factories).


Project Structure#

All Meditation libraries live under libs/meditation/:

text
libs/meditation/
  timer/       @oshun/meditation-timer       Meditation timer engine
  player/      @oshun/meditation-player      Audio player engine
  breathing/   @oshun/meditation-breathing   Breathing exercise engine
  session/     @oshun/meditation-session     Session lifecycle management
  progress/    @oshun/meditation-progress    Progress and achievement tracking
  offline/     @oshun/meditation-offline     Offline content management
  core/        (placeholder - .gitkeep only)
  analytics/   (placeholder - .gitkeep only)

The core/ and analytics/ directories are reservations for future libraries and do not contain source code.

Library Independence#

Unlike most domains where libraries form a dependency hierarchy, the 6 meditation libraries are fully independent at the package level. They share no inter-library dependencies. Integration happens at the application layer in the Tara domain (apps/tara/web, apps/tara/mobile).

Each library can be developed, built, and tested in complete isolation.

Per-Library File Layout#

text
libs/meditation/{library}/
  src/
    index.ts               Public API barrel export (comprehensive)
    types.ts               All type definitions
    {feature}.ts           Feature implementation
    {feature}.spec.ts      Feature tests
    hooks.ts               React hook factories
  package.json
  project.json
  tsconfig.json
  tsconfig.lib.json
  tsconfig.spec.json
  vitest.config.ts

Package Name Convention#

  • NPM scope: @oshun/meditation-*
  • Nx project name: @oshun/meditation-{library}
  • Example: @oshun/meditation-timer

Building Libraries#

Build a Single Library#

bash
pnpm nx build @oshun/meditation-timer
pnpm nx build @oshun/meditation-player
pnpm nx build @oshun/meditation-breathing
pnpm nx build @oshun/meditation-session
pnpm nx build @oshun/meditation-progress
pnpm nx build @oshun/meditation-offline

Build All Meditation Libraries#

Project tags are not fully consistent across libraries. Some use scope:meditation, others use domain:meditation. Run both tag filters:

bash
pnpm nx run-many --target=build --projects=tag:scope:meditation
pnpm nx run-many --target=build --projects=tag:domain:meditation

Build Configuration#

Most libraries use @nx/js:tsc, but session uses @nx/esbuild:esbuild:

Library Executor Output Format
timer @nx/js:tsc ESM
player @nx/js:tsc ESM
breathing @nx/js:tsc ESM
session @nx/esbuild:esbuild ESM + CJS dual
progress @nx/js:tsc ESM
offline @nx/js:tsc ESM

The session library uses esbuild with dual ESM+CJS output format and generatePackageJson: true for broader compatibility.

Tag Reference#

Library Tags
timer scope:meditation, layer:core, type:lib
player scope:meditation, layer:core, type:lib
breathing scope:meditation, layer:core, type:lib
session scope:shared, type:lib, domain:meditation
progress domain:meditation, type:library
offline scope:shared, type:lib, domain:meditation

Testing#

Run Tests for a Single Library#

bash
pnpm nx test @oshun/meditation-timer
pnpm nx test @oshun/meditation-player
pnpm nx test @oshun/meditation-breathing
pnpm nx test @oshun/meditation-session
pnpm nx test @oshun/meditation-progress
pnpm nx test @oshun/meditation-offline

Run All Meditation Tests#

bash
pnpm nx run-many --target=test --projects=tag:scope:meditation
pnpm nx run-many --target=test --projects=tag:domain:meditation

Test Configuration#

Libraries use Vitest via the @nx/vite:test executor:

typescript
import { defineConfig } from 'vitest/config';
import path from 'path';

export default defineConfig({
  test: {
    globals: true,
    environment: 'node',
    root: path.resolve(__dirname),
    include: ['src/**/*.{test,spec}.ts'],
    coverage: {
      provider: 'v8',
      reporter: ['text', 'json', 'html'],
      include: ['src/**/*.ts'],
      exclude: ['src/**/*.{test,spec}.ts', 'src/index.ts'],
    },
  },
});

The coverage configuration excludes test files and the barrel index.ts from coverage measurement.

Test Count by Library#

Library Test Files Coverage Areas
player 2 Core playback, queue operations
timer 1 Timer lifecycle, phases, events
breathing 1 Exercise lifecycle, pattern execution
session 8 Session lifecycle, storage, analytics, scheduler CRUD/iCal/recurrence
progress 1 Progress recording, streak calculation
offline 5 Manager, download queue, storage, suggestions, versioning

Total: 18 test files across the domain.

Running Tests with Coverage#

bash
pnpm nx test @oshun/meditation-timer -- --coverage

Writing Tests#

Meditation tests typically test event-driven behavior. Use Vitest's fake timers for time-dependent code:

typescript
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { MeditationTimer } from './timer.js';

describe('MeditationTimer', () => {
  beforeEach(() => {
    vi.useFakeTimers();
  });

  afterEach(() => {
    vi.useRealTimers();
  });

  it('should emit tick events at configured intervals', () => {
    const timer = new MeditationTimer();
    const tickHandler = vi.fn();
    timer.on('tick', tickHandler);

    timer.loadPreset(PRESET_5_MINUTES);
    timer.start();

    vi.advanceTimersByTime(3000);
    expect(tickHandler).toHaveBeenCalled();
  });

  it('should emit complete event when timer finishes', () => {
    const timer = new MeditationTimer();
    const completeHandler = vi.fn();
    timer.on('complete', completeHandler);

    timer.loadPreset(PRESET_1_MINUTE);
    timer.start();

    vi.advanceTimersByTime(60000);
    expect(completeHandler).toHaveBeenCalledOnce();
  });
});

Testing Storage Backends#

All libraries with persistence offer in-memory storage for testing:

typescript
import { InMemorySessionStorage } from '@oshun/meditation-session';

describe('Session persistence', () => {
  it('should save and retrieve sessions', async () => {
    const storage = new InMemorySessionStorage();
    // Use in-memory storage instead of localStorage or IndexedDB
  });
});

Linting#

bash
# Lint a single library
pnpm nx lint @oshun/meditation-timer

# Lint all meditation libraries
pnpm nx run-many --target=lint --projects=tag:scope:meditation
pnpm nx run-many --target=lint --projects=tag:domain:meditation

Common Development Tasks#

Adding a New Feature to an Existing Library#

For example, adding a new soundscape feature to @oshun/meditation-player:

  1. Create libs/meditation/player/src/soundscape.ts with the implementation
  2. Create libs/meditation/player/src/soundscape.spec.ts with tests
  3. Export from libs/meditation/player/src/index.ts:
typescript
export {
  SoundscapeManager,
  createSoundscapeManager,
  type SoundscapeConfig,
  type SoundscapeEvents,
} from './soundscape.js';
  1. If the feature needs React integration, add hook factories in hooks.ts
  2. Verify:
bash
pnpm nx build @oshun/meditation-player
pnpm nx test @oshun/meditation-player
pnpm nx lint @oshun/meditation-player

Adding a New Meditation Library#

  1. Create directory structure under libs/meditation/{new-lib}/
  2. Create project.json:
json
{
  "name": "@oshun/meditation-{new-lib}",
  "$schema": "../../../node_modules/nx/schemas/project-schema.json",
  "sourceRoot": "libs/meditation/{new-lib}/src",
  "projectType": "library",
  "tags": ["scope:meditation", "layer:core", "type:lib"],
  "targets": {
    "build": {
      "executor": "@nx/js:tsc",
      "outputs": ["{options.outputPath}"],
      "options": {
        "outputPath": "dist/libs/meditation/{new-lib}",
        "tsConfig": "libs/meditation/{new-lib}/tsconfig.lib.json",
        "main": "libs/meditation/{new-lib}/src/index.ts",
        "assets": ["libs/meditation/{new-lib}/*.md"]
      }
    },
    "lint": {
      "executor": "@nx/eslint:lint",
      "options": {
        "lintFilePatterns": ["libs/meditation/{new-lib}/**/*.ts"]
      }
    },
    "test": {
      "executor": "@nx/vite:test",
      "outputs": ["{workspaceRoot}/coverage/libs/meditation/{new-lib}"],
      "options": {
        "config": "libs/meditation/{new-lib}/vitest.config.ts"
      }
    }
  }
}
  1. Create package.json:
json
{
  "name": "@oshun/meditation-{new-lib}",
  "version": "0.1.0",
  "private": true,
  "type": "module",
  "main": "./src/index.ts",
  "types": "./src/index.ts",
  "dependencies": {
    "eventemitter3": "^5.0.1"
  },
  "peerDependencies": {
    "react": "^18.0.0"
  },
  "peerDependenciesMeta": {
    "react": { "optional": true }
  },
  "devDependencies": {
    "vitest": "catalog:"
  }
}
  1. Run pnpm install.

Integrating with the Tara Domain#

Meditation libraries are consumed by the Tara domain:

  • apps/tara/web - Next.js web app, imports hooks and types
  • apps/tara/mobile - React Native app, imports hooks and types
  • libs/tara/ui - UI components that wrap meditation hooks

In Tara applications, React hooks are initialized with the setReactHooks pattern:

typescript
// In Tara app initialization
import { setTimerReactHooks } from '@oshun/meditation-timer';
import { setReactHooks } from '@oshun/meditation-player';
import { useState, useEffect, useCallback, useRef } from 'react';

setTimerReactHooks({ useState, useEffect, useCallback, useRef });
setReactHooks({ useState, useEffect, useCallback, useRef });

Key Patterns and Conventions#

Event-Driven Core Classes#

Every library's primary class extends or wraps eventemitter3 for typed event emission. Events use discriminated union types:

typescript
type TimerEvents = {
  tick: TickEventData;
  stateChange: StateChangeEventData;
  phaseChange: PhaseChangeEventData;
  complete: CompleteEventData;
  error: TimerErrorEventData;
};

When adding new event types, define specific data payloads for each event type.

Platform Abstraction (Three-Tier Pattern)#

Libraries that interact with platform APIs provide three implementations:

  1. Abstract base class - defines the interface
  2. Web implementation - uses browser APIs (Web Audio, navigator, etc.)
  3. Noop implementation - for testing or unsupported platforms

Plus a factory function that selects the right implementation:

typescript
// Example from timer
export abstract class TimerBackgroundHandler {
  /* ... */
}
export class WebTimerBackgroundHandler extends TimerBackgroundHandler {
  /* ... */
}
export class NoopTimerBackgroundHandler extends TimerBackgroundHandler {
  /* ... */
}
export function createTimerBackgroundHandler(): TimerBackgroundHandler {
  /* ... */
}

Storage Backends#

Libraries needing persistence provide interchangeable backends:

Backend Use Case
InMemory* Testing and server-side rendering
LocalStorage Simple browser persistence
IndexedDB* Larger datasets, structured queries

Always use InMemory* backends in tests for isolation and speed.

React Hook Factories (createUse* Pattern)#

All libraries export factory functions rather than direct React hooks. This avoids a hard React dependency:

typescript
// Library exports factory
export function createUseMeditationTimer(hooks: ReactHooks) {
  return function useMeditationTimer(
    config?: TimerConfig
  ): UseMeditationTimerReturn {
    const [state, setState] = hooks.useState<TimerState>('idle');
    // ...
  };
}

The consuming application calls setReactHooks() once, then uses the convenience hooks or creates hooks from factories.

Branded Types#

Type safety is enforced through branded types that prevent mixing up plain strings and numbers:

typescript
type SessionId = string & { readonly __brand: 'SessionId' };
type DurationSeconds = number & { readonly __brand: 'DurationSeconds' };
type Timestamp = number & { readonly __brand: 'Timestamp' };
type Percentage = number & { readonly __brand: 'Percentage' };

When creating new types, follow this branding pattern for IDs, durations, timestamps, and any numeric type that could be accidentally mixed up.

Default Configs#

Every configurable feature exports a DEFAULT_*_CONFIG constant:

typescript
export const DEFAULT_TIMER_CONFIG: TimerConfig = {
  /* ... */
};
export const DEFAULT_PLAYER_CONFIG: PlayerConfig = {
  /* ... */
};
export const DEFAULT_CACHE_CONFIG: AudioCacheConfig = {
  /* ... */
};

New features should follow this convention.


Debugging Tips#

Event Listener Debugging#

If events are not firing as expected, check:

  1. The event name matches exactly (TypeScript should enforce this)
  2. The listener was registered before the event was emitted
  3. The emitter instance is the same one you registered on

Add a wildcard listener for debugging:

typescript
// eventemitter3 does not support '*', so log specific events:
timer.on('tick', (data) => console.log('tick:', data));
timer.on('stateChange', (data) => console.log('state:', data));

Fake Timers and Async Code#

When using vi.useFakeTimers(), be aware that Promises still need to be flushed. If your code uses await, you may need to combine vi.advanceTimersByTime() with await vi.runAllTimersAsync():

typescript
vi.useFakeTimers();
const promise = timer.start(); // Starts async operation
vi.advanceTimersByTime(60000);
await vi.runAllTimersAsync();
await promise;

Storage Backend Differences#

If behavior differs between InMemory and LocalStorage/IndexedDB backends, check:

  1. Serialization: localStorage stringifies everything, which can change types
  2. Async vs sync: IndexedDB operations are async; InMemory may be sync
  3. Storage limits: localStorage has ~5MB limit per origin

React Hook Registration Errors#

If hooks throw "React hooks not initialized" errors:

  1. Verify setReactHooks() was called before any hook is used
  2. Verify the hooks object includes all required React functions: useState, useEffect, useCallback, useRef
  3. In tests, mock React hooks:
typescript
import { setTimerReactHooks } from '@oshun/meditation-timer';

setTimerReactHooks({
  useState: vi.fn(),
  useEffect: vi.fn(),
  useCallback: vi.fn((fn) => fn),
  useRef: vi.fn(() => ({ current: null })),
});

Build Order#

Since meditation libraries are independent, build order does not matter. You can build any single library without building others first:

bash
pnpm nx build @oshun/meditation-offline  # Works without building timer, player, etc.

Project Configuration Reference#

Dependencies#

Dependency Type Purpose
eventemitter3 Runtime Event emission (all libraries)
react Optional React hooks (all libraries)
@types/react Dev React type definitions
@types/node Dev Node.js type definitions
vitest Dev Test framework

Subpath Exports#

@oshun/meditation-player provides granular subpath exports:

typescript
import { MeditationPlayer } from '@oshun/meditation-player'; // Full API
import { MeditationPlayer } from '@oshun/meditation-player/player'; // Player only
import { PlaybackQueue } from '@oshun/meditation-player/queue'; // Queue only
import { AudioMixer } from '@oshun/meditation-player/mixer'; // Mixer only
import { createUsePlayer } from '@oshun/meditation-player/hooks'; // Hooks only

This allows tree-shaking and selective imports in applications.