### Install and Run Commands Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/examples/vite/README.md Standard commands for installing dependencies, starting the development server, and building the project. ```bash pnpm install ``` ```bash pnpm dev ``` ```bash pnpm build ``` -------------------------------- ### Setup local toolchains Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/CONTRIBUTING.md Commands to enable pnpm and install project dependencies. ```bash corepack enable pnpm pnpm install --frozen-lockfile ``` -------------------------------- ### Install Dependencies with Package Managers Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/examples/nextjs/README.md Installs project dependencies using common package managers like pnpm, npm, yarn, or bun. Ensure you have Node.js 18+ or Bun installed. ```bash pnpm install # or npm install # or yarn install # or bun install ``` -------------------------------- ### Start Development Server Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/examples/nextjs/README.md Starts the Next.js development server to run the FSRS optimizer example locally. Access the application at http://localhost:3000. ```bash pnpm dev # or npm run dev # or yarn dev # or bun dev ``` -------------------------------- ### Install @open-spaced-repetition/binding Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/packages/binding/README.md Commands to install the package using various Node.js package managers. ```bash npm install @open-spaced-repetition/binding pnpm install @open-spaced-repetition/binding yarn add @open-spaced-repetition/binding bun add @open-spaced-repetition/binding ``` -------------------------------- ### Install @open-spaced-repetition/binding Package Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/README.md Install this package if you need parameter optimization from review logs, CSV conversion, and timezone handling. ```bash pnpm add @open-spaced-repetition/binding ``` -------------------------------- ### Full Example: Customizing ts-fsrs Strategies Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/7-strategies.md Demonstrates how to create and register custom scheduler, learning steps, and seed strategies. This example shows advanced customization for the FSRS algorithm. ```typescript import { fsrs, StrategyMode, State, Rating, createEmptyCard, BasicScheduler, type TSchedulerStrategy, type TLearningStepsStrategy, type TSeedStrategy, } from 'ts-fsrs' // 1. Custom scheduler class class VerboseScheduler extends BasicScheduler { review(grade) { console.log(`[Scheduler] Reviewing grade ${grade}`) return super.review(grade) } } // 2. Custom learning steps const customSteps: TLearningStepsStrategy = (params, state, curStep) => { if (state === State.Learning) { return { [Rating.Good]: { scheduled_minutes: 60, next_step: curStep + 1 }, } } return {} } // 3. Custom seed const customSeed: TSeedStrategy = function() { return `seed-${this.review_time.getTime()}` } // 4. Register strategies const scheduler = fsrs({ enable_fuzz: true, enable_short_term: true }) .useStrategy(StrategyMode.SCHEDULER, VerboseScheduler) .useStrategy(StrategyMode.LEARNING_STEPS, customSteps) .useStrategy(StrategyMode.SEED, customSeed) // 5. Use scheduler normally const card = createEmptyCard() const result = scheduler.next(card, new Date(), Rating.Good) // Console output: // [Scheduler] Reviewing grade 3 ``` -------------------------------- ### Install ts-fsrs Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/9-quick-start-reference.md Install the ts-fsrs library using npm. For parameter optimization, also install the @open-spaced-repetition/binding package. ```bash npm install ts-fsrs # For parameter optimization npm install @open-spaced-repetition/binding ``` -------------------------------- ### Install WASI Asset Package Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/packages/binding/README.md Manually install the WASI asset package using pnpm before proceeding with dynamic WASI initialization. ```bash pnpm add @open-spaced-repetition/binding-wasm32-wasi ``` -------------------------------- ### Install @open-spaced-repetition/binding Package Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/INDEX.md Install the @open-spaced-repetition/binding package using npm. This package offers a high-performance FSRS parameter optimizer and CSV converter. ```bash npm install @open-spaced-repetition/binding ``` -------------------------------- ### Initialize WASI Optimizer in Vite Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/packages/binding/README.md Load WASM and worker assets using Vite's `?url` and `?worker` imports, then initialize the optimizer dynamically. Ensure `@open-spaced-repetition/binding-wasm32-wasi` is installed explicitly for this Vite setup. ```typescript import { initOptimizer } from '@open-spaced-repetition/binding/dynamic-wasi' import wasmUrl from '@open-spaced-repetition/binding-wasm32-wasi/fsrs-binding.wasm32-wasi.wasm?url' import WasiWorker from '@open-spaced-repetition/binding-wasm32-wasi/wasi-worker-browser.mjs?worker' const binding = await initOptimizer({ wasm: wasmUrl, worker: () => new WasiWorker(), }) const item = new binding.FSRSBindingItem([ new binding.FSRSBindingReview(3, 0), new binding.FSRSBindingReview(4, 1), ]) const parameters = await binding.computeParameters([item], { enableShortTerm: true, numRelearningSteps: 1, }) console.log(parameters) ``` -------------------------------- ### Iterate Through Grades - TypeScript Example Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/5-utility-functions.md This example demonstrates how to iterate through the exported Grades constant and log each grade value. Ensure Grades and Rating are imported. ```typescript import { Grades, Rating } from 'ts-fsrs' for (const grade of Grades) { console.log(grade) // 1, 2, 3, 4 } ``` -------------------------------- ### Install ts-fsrs Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/packages/fsrs/README.md Install the ts-fsrs package using npm, yarn, pnpm, or bun. Node.js version 20.0.0 or higher is required. ```bash npm install ts-fsrs yarn add ts-fsrs pnpm install ts-fsrs bun add ts-fsrs ``` -------------------------------- ### Example Usage of CardInput Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/4-types.md Demonstrates how to create and use the CardInput interface with the ts-fsrs scheduler. Requires importing necessary functions and types. ```typescript import { createEmptyCard, Rating } from 'ts-fsrs' const input: CardInput = { due: '2024-12-25', state: 'Learning', stability: 2.0, difficulty: 5.0, elapsed_days: 0, scheduled_days: 1, learning_steps: 1, reps: 1, lapses: 0, last_review: Date.now(), } const scheduler = fsrs() const result = scheduler.next(input, new Date(), Rating.Good) ``` -------------------------------- ### Install ts-fsrs Package Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/README.md Use this command to add the ts-fsrs package to your project for scheduling reviews. ```bash pnpm add ts-fsrs ``` -------------------------------- ### FSRS Learning Steps Examples Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/4-types.md Illustrates different ways to define learning step sequences. An empty array lets FSRS manage intervals, while custom arrays define specific durations. ```typescript // Immediate 1m, then 10m learning_steps: ['1m', '10m'] // No explicit steps; FSRS determines intervals learning_steps: [] // Custom multi-step sequence learning_steps: ['1m', '5m', '30m', '2h', '1d'] ``` -------------------------------- ### Example Usage of RecordLog Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/4-types.md Demonstrates how to access the results for each possible rating (Again, Hard, Good, Easy) from a RecordLog object returned by the scheduler's repeat function. ```typescript const preview = scheduler.repeat(card, new Date()) preview[Rating.Again] // { card: ..., log: ... } preview[Rating.Hard] // { card: ..., log: ... } preview[Rating.Good] // { card: ..., log: ... } preview[Rating.Easy] // { card: ..., log: ... } ``` -------------------------------- ### Configure pnpm for WebAssembly Support Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/examples/nextjs/README.md Configures pnpm to support the 'wasm32' CPU architecture, which is necessary for downloading WebAssembly dependencies like '@open-spaced-repetition/binding'. This ensures correct dependency resolution. ```json { "pnpm": { "supportedArchitectures": { "cpu": [ "current", "wasm32" ] } } } ``` -------------------------------- ### Custom Learning Steps Strategy Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/9-quick-start-reference.md Implements a custom learning steps strategy for the FSRS scheduler. This example defines a specific schedule for the 'Good' rating, setting the next scheduled minutes and step increment. ```typescript import { fsrs, StrategyMode, State, Rating, type TLearningStepsStrategy, } from 'ts-fsrs' const customSteps: TLearningStepsStrategy = (params, state, curStep) => { return { [Rating.Good]: { scheduled_minutes: 60, next_step: curStep + 1 }, } } const scheduler = fsrs() scheduler.useStrategy(StrategyMode.LEARNING_STEPS, customSteps) ``` -------------------------------- ### Apply a Specific Rating and Get Next State Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/packages/fsrs/README.md Use the `next` method to apply a specific user rating (e.g., `Rating.Good`) to a card and get the updated card state and review log. ```typescript const result = scheduler.next(card, new Date(), Rating.Good) console.log(result.card) console.log(result.log) ``` -------------------------------- ### Install ts-fsrs Package Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/INDEX.md Install the ts-fsrs package using npm. This package provides the TypeScript scheduler for FSRS-6 algorithm. ```bash npm install ts-fsrs ``` -------------------------------- ### Catch FSRSError Example Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/6-errors.md Demonstrates how to catch and handle the base FSRSError in a try-catch block. ```typescript import { FSRSError } from 'ts-fsrs' try { // Some FSRS operation } catch (err) { if (err instanceof FSRSError) { console.error('FSRS error:', err.message) } } ``` -------------------------------- ### Initialize TS-FSRS Library Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/example/example.html Demonstrates how to import the TS-FSRS library into a browser environment. It includes options for production via CDN and local development paths, attaching the library to the window object for global access. ```javascript // Production import import * as tsFsrs from 'https://cdn.jsdelivr.net/npm/ts-fsrs@latest/+esm'; // Development import (requires build) // import * as tsFsrs from '../dist/index.mjs'; window.tsfsrs = tsFsrs; ``` -------------------------------- ### Apply Rating and Get Result with `next` Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/packages/fsrs/README.md The `next` method applies a specific user rating to a card and returns the updated card state and review log. ```typescript const result = scheduler.next(card, new Date(), Rating.Good) ``` -------------------------------- ### Card State Transitions Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/9-quick-start-reference.md Illustrates the flow of card states based on user ratings (e.g., 'Again', 'Good/Easy'). This visual guide helps understand how reviews affect card progression. ```text New ──Good/Easy──> Learning ──Good/Easy──> Review │ └─Again─────────> Relearning Learning ──Again──> Relearning ──Good/Easy──> Review Review ──Again───> Relearning ``` -------------------------------- ### Card Rating Enumeration and Example Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/2-card-operations.md Defines the possible ratings a user can give a card and demonstrates how to use the 'Good' rating with the scheduler. The 'Manual' rating is reserved for specific internal operations. ```typescript enum Rating { Manual = 0, Again = 1, Hard = 2, Good = 3, Easy = 4, } type RatingType = 'Manual' | 'Again' | 'Hard' | 'Good' | 'Easy' type Grade = Exclude ``` ```typescript import { fsrs, Rating, createEmptyCard } from 'ts-fsrs' const scheduler = fsrs() const card = createEmptyCard() const result = scheduler.next(card, new Date(), Rating.Good) // Scheduling outcome for a Good rating ``` -------------------------------- ### Configure Next.js Server External Packages Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/examples/nextjs/README.md Specifies that the '@open-spaced-repetition/binding' package should not be bundled during Next.js server-side compilation. This prevents build errors related to native or WebAssembly modules. ```typescript serverExternalPackages: [ '@open-spaced-repetition/binding' ] ``` -------------------------------- ### Run common repository commands Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/CONTRIBUTING.md Standard commands for checking, testing, and building the project from the root directory. ```bash pnpm check pnpm test pnpm test:coverage pnpm build pnpm docs ``` -------------------------------- ### Recommend Learning Steps Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/packages/binding/README.md Compute optimal learning and relearning steps based on review history and target decay or parameters. ```typescript import { readFileSync } from 'node:fs' import { computeOptimalSteps } from '@open-spaced-repetition/binding' const csvBuffer = readFileSync('./revlog.csv') const stepStats = computeOptimalSteps(csvBuffer, 0.9, 0.5) console.log(stepStats.recommendedLearningSteps) console.log(stepStats.recommendedRelearningSteps) ``` -------------------------------- ### Configure Learning Steps Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/9-quick-start-reference.md Define custom learning steps for new cards using the 'learning_steps' option. An empty array allows FSRS to manage timing automatically. ```typescript // Default: new cards spend 1m, then 10m in learning const scheduler = fsrs({ learning_steps: ['1m', '10m'], }) // Custom: longer learning for difficult material const slow = fsrs({ learning_steps: ['1m', '5m', '30m'], }) // No explicit steps (FSRS determines timing) const fsrsManaged = fsrs({ learning_steps: [], }) ``` -------------------------------- ### Basic ts-fsrs Usage for Scheduling Reviews Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/README.md Demonstrates how to initialize the FSRS scheduler, create a new card, preview review outcomes, and apply a final rating to update the card. ```typescript import { createEmptyCard, fsrs, Rating } from 'ts-fsrs' const scheduler = fsrs() const card = createEmptyCard() // Preview all four possible outcomes before the user answers. const preview = scheduler.repeat(card, new Date()) // Apply the final rating after the user has already answered. const result = scheduler.next(card, new Date(), Rating.Good) console.log(preview[Rating.Good].card) console.log(result.card) console.log(result.log) ``` -------------------------------- ### createEmptyCard() Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/2-card-operations.md Create a new flashcard with initial (empty) state. The card is ready for its first review. ```APIDOC ## createEmptyCard() ### Description Create a new flashcard with initial (empty) state. The card is ready for its first review. ### Method ```typescript export function createEmptyCard( now?: DateInput, afterHandler?: (card: Card) => R ): R ``` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **now** (`DateInput`, Optional): Due date for the new card. Can be Date, ISO string, or milliseconds. Defaults to current date. - **afterHandler** (`(card: Card) => R`, Optional): Optional transform function applied to the card before returning. ### Returns - `Card` — A new card with default (empty) state if no `afterHandler`. - `R` — Result of `afterHandler` if provided. ### Card state ```typescript { due: now or Date.now(), stability: 0, difficulty: 0, elapsed_days: 0, scheduled_days: 0, reps: 0, lapses: 0, learning_steps: 0, state: State.New, last_review: undefined } ``` ### Example ```typescript import { createEmptyCard } from 'ts-fsrs' const card = createEmptyCard() // Card is due now, state is New const cardWithCustomDue = createEmptyCard(new Date(2024, 11, 25)) // Card is due on Dec 25, 2024 ``` ### Example with afterHandler ```typescript interface CustomCard extends Card { id: string } const card = createEmptyCard( new Date(), (card) => ({ ...card, id: 'card-001', }) ) console.log(card.id) // 'card-001' ``` ``` -------------------------------- ### Configure PNPM for WebAssembly Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/examples/vite/README.md Adds support for WebAssembly binaries in the package.json file. ```json { "pnpm": { "supportedArchitectures": { "cpu": ["current", "wasm32"] } } } ``` -------------------------------- ### Get Card Retrievability (Formatted) Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/1-fsrs-scheduler.md Calculate and retrieve the card's retrievability probability as a formatted percentage string. ```typescript const card = result.card // from previous next() const retrievability = scheduler.get_retrievability(card, new Date(), true) console.log(retrievability) // "92.45%" ``` -------------------------------- ### Get Card Retrievability (Decimal) Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/1-fsrs-scheduler.md Calculate and retrieve the card's retrievability probability as a decimal value between 0 and 1. ```typescript const card = result.card // from previous next() const decimal = scheduler.get_retrievability(card, new Date(), false) console.log(decimal) // 0.9245 ``` -------------------------------- ### Compute Optimal Learning Steps Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/8-binding-optimizer.md Calculates recommended learning and relearning steps based on review history, target retention, and decay parameters. Requires review data as a CSV buffer. ```typescript export function computeOptimalSteps( csvBuffer: Buffer | Uint8Array, requestRetention: number, decayOrParams: number | number[] ): StepStats ``` ```typescript interface StepStats { recommendedLearningSteps: string[] // e.g., ['1m', '10m'] recommendedRelearningSteps: string[] // e.g., ['10m'] } ``` ```typescript import { readFileSync } from 'node:fs' import { computeOptimalSteps } from '@open-spaced-repetition/binding' const csvBuffer = readFileSync('./revlog.csv') const stats = computeOptimalSteps(csvBuffer, 0.9, 0.5) console.log('Learning steps:', stats.recommendedLearningSteps) console.log('Relearning steps:', stats.recommendedRelearningSteps) ``` -------------------------------- ### Handle Out-of-Range Parameter Validation Error Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/6-errors.md Example showing how to catch an FSRSValidationError when a parameter like 'request_retention' is set outside its valid range. ```typescript import { fsrs, Rating, FSRSValidationError, createEmptyCard } from 'ts-fsrs' const scheduler = fsrs() const card = createEmptyCard() try { scheduler.parameters = { request_retention: 1.5 } // Out of range } catch (err) { if (err instanceof FSRSValidationError) { console.error(err.message) // Output: "Requested retention rate should be in the range (0,1]" } } ``` -------------------------------- ### Chain Multiple Reviews Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/9-quick-start-reference.md Simulate chaining multiple reviews for a card, updating the card's state after each review. This demonstrates how to handle sequential reviews. ```typescript let card = createEmptyCard() // First review: Good let result = scheduler.next(card, new Date(), Rating.Good) card = result.card // Second review: Easy (3 days later) const nextReviewDate = new Date() nextReviewDate.setDate(nextReviewDate.getDate() + 3) result = scheduler.next(card, nextReviewDate, Rating.Easy) card = result.card console.log(card.due) // Next scheduled date ``` -------------------------------- ### parameters (property) Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/1-fsrs-scheduler.md Allows getting the current FSRS scheduler parameters or updating them at runtime. Updating parameters triggers recomputation of derived values. ```APIDOC ## parameters (property) ### Description Get or update scheduler parameters at runtime. ### Getter - Returns the current `FSRSParameters` object. ### Setter - Accepts a partial object and triggers recomputation of derived values (interval modifier, forgetting curve, etc.). ### Parameters #### Request Body - **request_retention** (number) - Optional - Target recall probability (0 < retention ≤ 1). Default: 0.9. - **maximum_interval** (number) - Optional - Maximum review interval in days. Default: 36500 (100 years). - **w** (number[]) - Optional - 21 FSRS algorithm weights. - **enable_fuzz** (boolean) - Optional - Apply randomness to intervals. Default: false. - **enable_short_term** (boolean) - Optional - Enable short-term stability calculation. Default: true. - **learning_steps** (Steps) - Optional - Learning step durations (e.g., ['1m', '10m']). - **relearning_steps** (Steps) - Optional - Relearning step durations (e.g., ['10m']). ### Example ```typescript scheduler.parameters = { request_retention: 0.85, maximum_interval: 20000, } console.log(scheduler.parameters.request_retention) // 0.85 ``` ``` -------------------------------- ### Handling FSRSValidationError Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/1-fsrs-scheduler.md Example of how to catch and handle FSRSValidationError, which is thrown for various invalid inputs or states during scheduler operations. This snippet shows how to log the error message. ```typescript try { scheduler.next(card, new Date(), 0) // Invalid grade } catch (err) { if (err instanceof FSRSValidationError) { console.error('Invalid grade:', err.message) } } ``` -------------------------------- ### Math Helper Functions Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/9-quick-start-reference.md Utilize math utility functions from `ts-fsrs` for clamping values within a range and rounding numbers. Examples demonstrate `clamp` and `roundTo`. ```typescript import { clamp, roundTo } from 'ts-fsrs' clamp(5, 1, 10) // 5 clamp(0, 1, 10) // 1 clamp(15, 1, 10) // 10 roundTo(3.14159, 2) // 3.14 ``` -------------------------------- ### Configure Relearning Steps Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/9-quick-start-reference.md Specify custom relearning steps for failed cards using the 'relearning_steps' option. The default is ['10m']. ```typescript // Default: failed cards spend 10m relearning const scheduler = fsrs({ relearning_steps: ['10m'], }) // Custom: longer relearning const deep = fsrs({ relearning_steps: ['10m', '1d'], }) ``` -------------------------------- ### Create FSRSBindingItem with Reviews Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/8-binding-optimizer.md Represents a card's review history. Initialize with an array of `FSRSBindingReview` objects in chronological order. ```typescript export class FSRSBindingItem { constructor(reviews: FSRSBindingReview[]) } ``` ```typescript const reviews = [ new FSRSBindingReview(3, 0), // Good on day 0 new FSRSBindingReview(4, 1), // Easy on day 1 new FSRSBindingReview(3, 5), // Good on day 5 ] const item = new FSRSBindingItem(reviews) ``` -------------------------------- ### Apply Mean Reversion to Difficulty Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/3-algorithm.md Blends the current difficulty with an initial difficulty value. Use this to prevent difficulty from drifting too far from its starting point over time. ```typescript mean_reversion(init: number, current: number): number ``` -------------------------------- ### Define Learning and Relearning Steps Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/2-card-operations.md Configure the timings for new cards and failed cards using string-based step units. The FSRS algorithm manages timing when an empty array is provided. ```typescript type StepUnit = `${number}${TimeUnit}` type TimeUnit = 'm' | 'h' | 'd' type Steps = StepUnit[] | readonly StepUnit[] ``` ```typescript import { fsrs } from 'ts-fsrs' const scheduler = fsrs({ learning_steps: ['1m', '10m'], // New card: 1m, then 10m relearning_steps: ['10m'], // Failed card: 10m }) ``` -------------------------------- ### Get Retrievability Percentage Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/9-quick-start-reference.md Calculates and displays the current retrievability (recall probability) of a card. Use `true` for a formatted percentage string, or `false` for a decimal value. ```typescript const r = scheduler.get_retrievability(card, new Date(), true) console.log(r) // "92.45%" const decimal = scheduler.get_retrievability(card, new Date(), false) console.log(decimal) // 0.9245 ``` -------------------------------- ### Handle Invalid Grade Validation Error Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/6-errors.md Example demonstrating how to catch an FSRSValidationError when an invalid grade (outside the 1-4 range) is provided to the scheduler's next method. ```typescript import { fsrs, Rating, FSRSValidationError, createEmptyCard } from 'ts-fsrs' const scheduler = fsrs() const card = createEmptyCard() try { scheduler.next(card, new Date(), 0) // Invalid grade } catch (err) { if (err instanceof FSRSValidationError) { console.error('Validation failed:', err.message) // Output: "Validation failed: Invalid grade \"0\",expected 1-4" } } ``` -------------------------------- ### Accessing and Updating FSRS Parameters Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/3-algorithm.md Demonstrates how to get the current FSRS parameters and how to update them. Updating parameters can trigger recomputation of dependent values like the interval modifier. ```typescript const algo = fsrs() algo.parameters = { request_retention: 0.85 } console.log(algo.interval_modifier) // Recomputed const current = algo.parameters console.log(current.enable_short_term) // true ``` -------------------------------- ### Date Helper Functions Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/9-quick-start-reference.md Perform date calculations using `ts-fsrs` utility functions. Examples include adding days to a date, calculating the difference between dates, and formatting dates. ```typescript import { date_scheduler, date_diff, formatDate } from 'ts-fsrs' // Add 10 days to a date const future = date_scheduler(new Date(), 10, true) // Calculate days between dates const days = date_diff(new Date(), new Date('2024-12-25'), 'days') // Format date const str = formatDate(new Date()) // "2024-12-25 14:30:45" ``` -------------------------------- ### Map `next` Result with `afterHandler` Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/packages/fsrs/README.md Use the `afterHandler` option with the `next` method to transform the resulting card and log objects, for example, to convert Date objects to timestamps for storage. ```typescript const saved = scheduler.next(card, new Date(), Rating.Good, ({ card, log }) => ({ card: { ...card, due: card.due.getTime(), last_review: card.last_review?.getTime() ?? null, }, log: { ...log, due: log.due.getTime(), review: log.review.getTime(), }, })) ``` -------------------------------- ### computeOptimalSteps Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/8-binding-optimizer.md Recommends optimal learning and relearning step timings based on review history. It takes a CSV buffer of reviews, a target retention rate, and either a decay value or full FSRS parameters to calculate the best step durations. ```APIDOC ## computeOptimalSteps() ### Description Recommends optimal learning/relearning step timings based on review history. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **csvBuffer** (`Buffer | Uint8Array`) - Required - Review CSV export. - **requestRetention** (`number`) - Required - Target retention (0 < r ≤ 1). - **decayOrParams** (`number | number[]`) - Required - Decay value (0.1–0.8) or full parameter array (21 elements). ### Returns `StepStats` - An object containing recommended learning and relearning steps. ```typescript interface StepStats { recommendedLearningSteps: string[] // e.g., ['1m', '10m'] recommendedRelearningSteps: string[] // e.g., ['10m'] } ``` ### Example ```typescript import { readFileSync } from 'node:fs' import { computeOptimalSteps } from '@open-spaced-repetition/binding' const csvBuffer = readFileSync('./revlog.csv') const stats = computeOptimalSteps(csvBuffer, 0.9, 0.5) console.log('Learning steps:', stats.recommendedLearningSteps) console.log('Relearning steps:', stats.recommendedRelearningSteps) ``` ``` -------------------------------- ### Run Biome Linting Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/examples/vite/README.md Commands for checking and automatically fixing code style issues using Biome. ```bash # Check code pnpm lint # Fix issues automatically pnpm lint:fix ``` -------------------------------- ### mean_reversion() Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/3-algorithm.md Blends the initial difficulty with the current difficulty, applying mean reversion towards the initial value. This method helps to prevent difficulty from drifting too far from its starting point. ```APIDOC ## mean_reversion() ### Description Blend initial difficulty with current difficulty, applying mean reversion toward initial value. ### Method `mean_reversion(init: number, current: number): number` ### Parameters #### Path Parameters - `init` (number) - Required - Initial difficulty (e.g., from init_difficulty). - `current` (number) - Required - Current/proposed difficulty. ### Returns `number` — Mean-reverted difficulty (8 decimals). ``` -------------------------------- ### FSRSAlgorithm Class Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/3-algorithm.md The FSRSAlgorithm class provides the core logic for calculating memory dynamics and scheduling intervals. Its mathematical computation methods are publicly accessible. ```APIDOC ## FSRSAlgorithm ### Description Base class for FSRS scheduling logic. All mathematical computation methods are public and can be used independently. ### Methods - `constructor(params: Partial)` - `parameters: FSRSParameters` (Get/set algorithm parameters) - `interval_modifier: number` (Computed interval scaling factor) - `seed: string` (Random seed for fuzz) - `forgetting_curve: (t: number, s: number) => number` (Retrievability function) ``` -------------------------------- ### Create a Scheduler and Empty Card Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/9-quick-start-reference.md Initialize the FSRS scheduler and create an empty card object to begin scheduling reviews. ```typescript import { fsrs, Rating, createEmptyCard } from 'ts-fsrs' const scheduler = fsrs() const card = createEmptyCard() ``` -------------------------------- ### initOptimizer Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/8-binding-optimizer.md Dynamically initialize the optimizer with externally provided WASM and worker resources. This is useful for custom bundlers, edge runtimes, or pipelines where WASM/worker paths differ. ```APIDOC ## initOptimizer() ### Description Dynamically initialize the optimizer with externally provided WASM and worker resources. ### Method `initOptimizer` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options.wasm** (ArrayBuffer | Uint8Array | string | URL | Response) - Required - WASM binary: ArrayBuffer, Buffer, file path, URL, or fetch Response. - **options.worker** (() => Worker) | string | URL - Required - Worker factory function or path/URL to worker script. - **options.errorEvent** (boolean) - Optional - Emit custom events for worker errors (browser only). ### Request Example ```typescript import { initOptimizer } from '@open-spaced-repetition/binding/dynamic-wasi' import wasmUrl from '@open-spaced-repetition/binding-wasm32-wasi/fsrs-binding.wasm32-wasi.wasm?url' import WasiWorker from '@open-spaced-repetition/binding-wasm32-wasi/wasi-worker-browser.mjs?worker' const binding = await initOptimizer({ wasm: wasmUrl, worker: () => new WasiWorker() }) // Use as normal const item = new binding.FSRSBindingItem([ new binding.FSRSBindingReview(3, 0) ]) const params = await binding.computeParameters([item]) ``` ### Response #### Success Response - **binding** (typeof binding) - Initialized binding module with same API. #### Response Example ```typescript // Example response is the initialized binding module itself // const binding = ... ``` ``` -------------------------------- ### Algorithm Methods Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/INDEX.md Core methods that implement the FSRS algorithm's state transition logic. ```APIDOC ## Algorithm Methods ### `init_stability()` **Description**: Calculates the initial stability of a card based on a given rating. **Formula**: $S_0(G) = w_{G-1}$ ### `init_difficulty()` **Description**: Calculates the initial difficulty of a card based on a given rating. **Formula**: $D_0(G) = w_4 - e^{(G-1) \cdot w_5} + 1$ ### `next_difficulty()` **Description**: Updates the card's difficulty based on the review outcome, incorporating mean reversion and linear damping. ### `next_recall_stability()` **Description**: Calculates the stability of a card after a successful recall. **Formula**: Uses an exponential growth formula. ### `next_forget_stability()` **Description**: Calculates the stability of a card after a failed recall. **Formula**: Uses a power law decay. ### `next_short_term_stability()` **Description**: Calculates the stability for same-day reviews. **Formula**: $S' = S \cdot e^{w_{17} \cdot (g - 3 + w_{18})}$ ### `next_interval()` **Description**: Determines the next review interval based on the card's stability, interval modifier, and fuzz factor. ### `next_state()` **Description**: Computes the next state of the card, routing to either recall or forget logic. ### `forgetting_curve()` **Description**: Calculates the retrievability of a card at a specific time 't' given its stability 'S'. **Formula**: $R(t,S) = (1 + \text{FACTOR} \times \frac{t}{9S})^{\text{DECAY}}$ ``` -------------------------------- ### Configure Next.js Cross-Origin Isolation Headers Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/examples/nextjs/README.md Sets 'Cross-Origin-Opener-Policy' and 'Cross-Origin-Embedder-Policy' headers to enable cross-origin isolation. This is required for client-side WebAssembly training that relies on 'SharedArrayBuffer'. ```typescript async headers() { return [ { source: '/:path*', headers: [ { key: 'Cross-Origin-Opener-Policy', value: 'same-origin', }, { key: 'Cross-Origin-Embedder-Policy', value: 'require-corp', }, ], }, ]; } ``` -------------------------------- ### Default Parameters Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/9-quick-start-reference.md Import and log the default parameters for FSRS. These include retention, interval, learning/relearning steps, and weights. ```typescript import { default_request_retention, default_maximum_interval, default_learning_steps, default_relearning_steps, default_w, } from 'ts-fsrs' console.log(default_request_retention) // 0.9 console.log(default_maximum_interval) // 36500 console.log(default_learning_steps) // ['1m', '10m'] console.log(default_relearning_steps) // ['10m'] console.log(default_w.length) // 21 ``` -------------------------------- ### Add a changeset Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/CONTRIBUTING.md Command to generate a changeset for tracking changes in published packages. ```bash pnpm changeset ``` -------------------------------- ### Algorithm Imports Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/INDEX.md Import FSRSAlgorithm and related functions for decay factor computation. Essential for understanding and manipulating the core FSRS algorithm. ```typescript // Algorithm import { FSRSAlgorithm, forgetting_curve, computeDecayFactor, } from 'ts-fsrs' ``` -------------------------------- ### Initialize the FSRS Scheduler Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/packages/fsrs/README.md Import and initialize the FSRS scheduler. This sets up the default parameters for the spaced repetition algorithm. ```typescript import { createEmptyCard, fsrs, Rating } from 'ts-fsrs' const scheduler = fsrs() ``` -------------------------------- ### repeat() Method Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/1-fsrs-scheduler.md Previews the scheduling outcomes for all four possible ratings (Again, Hard, Good, Easy) without altering the card's state. It takes the card and current time as input and can optionally accept a handler to transform the output. ```APIDOC ## repeat() ### Description Preview all four possible scheduling outcomes (Again, Hard, Good, Easy) without committing a rating. ### Method `repeat(card: CardInput | Card, now: DateInput): IPreview` `repeat(card: CardInput | Card, now: DateInput, afterHandler: (recordLog: IPreview) => R): R` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **card** (`CardInput | Card`) - Required - The card to preview. - **now** (`DateInput`) - Required - Current date/time (Date, ISO string, or milliseconds). - **afterHandler** (`(recordLog: IPreview) => R`) - Optional - Transform the result. ### Request Example ```typescript const card = createEmptyCard() const preview = scheduler.repeat(card, new Date()) console.log(preview[Rating.Again]) // Card state if user rates Again console.log(preview[Rating.Good]) // Card state if user rates Good ``` ### Response #### Success Response (200) - **IPreview** (`object`) - Preview outcomes for each grade (Again, Hard, Good, Easy), each containing updated `card` and `log`. - **R** (`any`) - Result of `afterHandler` if provided. #### Response Example ```json { "Again": { "card": { ... }, "log": { ... } }, "Hard": { "card": { ... }, "log": { ... } }, "Good": { "card": { ... }, "log": { ... } }, "Easy": { "card": { ... }, "log": { ... } } } ``` ### Throws - `FSRSValidationError` — if card or date is invalid ``` -------------------------------- ### Run package-scoped commands Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/CONTRIBUTING.md Commands to execute tasks for specific packages within the monorepo. ```bash pnpm --filter ts-fsrs test pnpm --filter ts-fsrs build pnpm --filter @open-spaced-repetition/binding check ``` -------------------------------- ### Initialize Scheduler with Custom Parameters Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/packages/fsrs/README.md Initialize the FSRS scheduler with custom parameters to fine-tune its behavior, such as request retention, maximum interval, and fuzzing. ```typescript import { fsrs } from 'ts-fsrs' const scheduler = fsrs({ request_retention: 0.9, maximum_interval: 36500, enable_fuzz: true, enable_short_term: true, learning_steps: ['1m', '10m'], relearning_steps: ['10m'], }) ``` -------------------------------- ### Schedule Card Review with Rating Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/1-fsrs-scheduler.md Use the next() method to schedule a card review based on the user's rating (Again, Hard, Good, or Easy). This updates the card's scheduling state. ```typescript const card = createEmptyCard() const result = scheduler.next(card, new Date(), Rating.Good) console.log(result.card) // Updated card with new due date, stability, difficulty console.log(result.log) // Review history entry ``` -------------------------------- ### Create an empty flashcard with afterHandler Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/2-card-operations.md Demonstrates using the `afterHandler` option with `createEmptyCard` to add custom properties or perform transformations on the newly created card. ```typescript interface CustomCard extends Card { id: string } const card = createEmptyCard( new Date(), (card) => ({ ...card, id: 'card-001', }) ) console.log(card.id) // 'card-001' ``` -------------------------------- ### next() Method Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/1-fsrs-scheduler.md Schedules a card based on the user's provided rating (Again, Hard, Good, or Easy). This method updates the card's state and returns the updated card and a log item for the review. It also supports an optional handler for result transformation. ```APIDOC ## next() ### Description Schedule the card with a user-provided rating (Again, Hard, Good, or Easy). ### Method `next(card: CardInput | Card, now: DateInput, grade: Grade): RecordLogItem` `next(card: CardInput | Card, now: DateInput, grade: Grade, afterHandler: (recordLog: RecordLogItem) => R): R` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **card** (`CardInput | Card`) - Required - The card being reviewed. - **now** (`DateInput`) - Required - Review date/time. - **grade** (`Grade`) - Required - User's rating: 1=Again, 2=Hard, 3=Good, 4=Easy. - **afterHandler** (`(recordLog: RecordLogItem) => R`) - Optional - Transform the result. ### Request Example ```typescript const card = createEmptyCard() const result = scheduler.next(card, new Date(), Rating.Good) console.log(result.card) // Updated card with new due date, stability, difficulty console.log(result.log) // Review history entry ``` ### Response #### Success Response (200) - **RecordLogItem** (`object`) - Updated card and review log. - **R** (`any`) - Result of `afterHandler` if provided. #### Response Example ```json { "card": { "due": "2023-10-27T10:00:00.000Z", "stability": 7.1, "difficulty": 5.5, "elapsed_days": 1, "scheduled_days": 10, "reps": 2, "lapses": 0, "memories": 0, "ப்பை": 0.9 }, "log": { "i": 2, "r": 1, "m": 0, "s": 7.1, "h": 5.5, "t": 10, "due": "2023-10-27T10:00:00.000Z", "elapsed": 1 } } ``` ### Throws - `FSRSValidationError` — if grade is not 1–4, or if card/date is invalid ``` -------------------------------- ### TypeScript Types and Usage Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/9-quick-start-reference.md Demonstrates importing various fully typed exports from ts-fsrs, including FSRS parameters, card types, and preview interfaces. ```typescript import { fsrs, createEmptyCard, Rating, State, Card, CardInput, ReviewLog, RecordLogItem, FSRSParameters, type IPreview, } from 'ts-fsrs' // Types available for import const params: FSRSParameters = { /* ... */ } const card: Card = createEmptyCard() const preview: IPreview = scheduler.repeat(card, new Date()) ``` -------------------------------- ### Configure Short-Term Stability Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/9-quick-start-reference.md Enable or disable short-term stability adjustments using 'enable_short_term'. The default is true, which optimizes same-day learning. ```typescript // Default: true (enables same-day learning optimization) const scheduler = fsrs({ enable_short_term: true, }) // Set to false for traditional FSRS (no same-day adjustments) const longTermOnly = fsrs({ enable_short_term: false, }) ``` -------------------------------- ### Create an empty flashcard Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/2-card-operations.md Initializes a new flashcard with default state, ready for its first review. An optional `afterHandler` can transform the card before it's returned. ```typescript import { createEmptyCard } from 'ts-fsrs' const card = createEmptyCard() // Card is due now, state is New const cardWithCustomDue = createEmptyCard(new Date(2024, 11, 25)) // Card is due on Dec 25, 2024 ``` -------------------------------- ### Custom Learning Steps Strategy Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/7-strategies.md Defines custom delays for learning step transitions. This strategy overrides the default calculation of when a card should be reviewed next during the learning phase. It applies when enable_short_term is true. ```typescript import { fsrs, StrategyMode, State, Rating, type TLearningStepsStrategy, } from 'ts-fsrs' // Custom learning steps: longer delays const customSteps: TLearningStepsStrategy = (params, state, curStep) => { return { [Rating.Good]: { scheduled_minutes: 30, // 30 minutes next_step: curStep + 1, }, } } const scheduler = fsrs() scheduler.useStrategy(StrategyMode.LEARNING_STEPS, customSteps) ``` -------------------------------- ### FSRSBinding Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/_autodocs/8-binding-optimizer.md Provides a direct interface to compute next memory states for advanced usage. It allows calculating the difficulty and stability of a card after a review, given the previous state, target retention, and time elapsed. ```APIDOC ## FSRSBinding ### Description Direct interface to compute next memory states (advanced usage). ### Constructor `constructor()` ### Methods #### nextStates `nextStates(memoryState: { difficulty: number, stability: number } | null, requestRetention: number, deltaT: number): Array<{ difficulty: number, stability: number }>` Computes the next memory states for a card. ### Parameters - **memoryState** (`{ difficulty: number, stability: number } | null`) - Optional - The current memory state of the card. If null, it assumes the card is new. - **requestRetention** (`number`) - Required - The desired retention rate (0 < r ≤ 1). - **deltaT** (`number`) - Required - The time elapsed in days since the last review. ### Returns `Array<{ difficulty: number, stability: number }>` - An array containing the next memory states for each possible rating (Again, Hard, Good, Easy). ### Example ```typescript import { FSRSBinding } from '@open-spaced-repetition/binding' const binding = new FSRSBinding() // Compute state transitions for all 4 grades const nextStates = binding.nextStates(null, 0.9, 0) // Returns array of 4 states [Again, Hard, Good, Easy] ``` ``` -------------------------------- ### Preview All Outcomes with `repeat` Source: https://github.com/open-spaced-repetition/ts-fsrs/blob/main/packages/fsrs/README.md The `repeat` method is used to preview all four possible scheduling outcomes for a card without modifying its state. ```typescript const preview = scheduler.repeat(card, new Date()) ```