v1.0.13 · Release snapshot

Documentation comes from this release commit, without inheriting newer content. Commit: 371ee4692c.

Monorepo

Magic Piano is a Bun + Turborepo monorepo. The Expo app stays at the repo root; reusable piano logic lives in packages/* as @piano/* workspace packages plus the instrument-agnostic @rhythm/engine rhythm-game core, all built with tsup and orchestrated by turbo.

Why a monorepo

  • The piano engines are reusable. Audio, MIDI, gameplay, progression, catalog, ads, and analytics are domain logic that has nothing to do with React Native. Putting them under packages/* lets the same code ship to a future web build, a CLI, or a unit-test runner without dragging Expo with them.
  • The app stays thin. app/ and src/ only contain UI, navigation, and React Query glue. All gameplay state machines live in @piano/gameplay-{learn,magic,zen}.
  • One install, one lockfile. Bun's hoisted workspaces share a single bun.lock and node_modules, so React, RN, and Reanimated cannot be duplicated across packages — the #1 cause of "Invalid hook call" errors in RN monorepos.

Repo layout

magic_piano/
├── app/                       # expo-router routes (host)
├── src/                       # Expo app source (host)
├── packages/                  # Bun workspaces, all named @piano/*
│   ├── types/                 # leaf — domain types for game / midi / player
│   ├── keyboard/              # piano key model + layout math
│   ├── core/                  # cross-cutting engine primitives
│   ├── network/               # MIDI repository contracts
│   ├── analytics/             # adapter + dispatcher (+ visualizer/ browser tool)
│   ├── ads/                   # provider contract
│   ├── midi/                  # MIDI parser (midi-parser-js wrapper)
│   ├── progression/           # XP / level service
│   ├── player-data/           # PlayerDataManager (Zod-validated)
│   ├── user-library/          # Owned songs + subscription ledger (cloud-ready)
│   ├── catalog/               # SongCatalog (songs + moods)
│   ├── rhythm-engine/         # @rhythm/engine — instrument-agnostic rhythm core
│   ├── soundfont/             # @piano/soundfont — pure SF2 parse / ADSR / voice-plan (+ browser lab)
│   ├── gameplay-learn/        # legacy practice-mode engine (predates src/features/learn)
│   ├── gameplay-magic/        # magic-mode engine (thin shim re-exports from @rhythm/engine, slated for removal once Learn + Zen migrate)
│   ├── gameplay-zen/          # zen-mode engine
│   └── sdk/                   # public facade — createPianoSdk()
├── tools/                     # optional non-workspace tools (e.g. `piano-devtool-desktop` — the Piano DevTool Electron app, see [devtool.md](devtool.md))
├── modules/                   # local Expo modules (host-native bridges, autolinked on prebuild)
│   ├── screen-gesture-defer/  # iOS app-wide bottom-edge system gesture deferral
│   ├── perf-hud/              # iOS SwiftUI overlay — UI FPS / DRAW FPS / JANK / RAM / CPU (always-on)
│   └── sdk-crash-guards/      # iOS load-time guards against third-party SDK faults (no JS facade)
├── android/                   # Expo prebuild output
├── ios/                       # Expo prebuild output
├── package.json               # workspaces: ['packages/*']
├── turbo.json                 # build / typecheck / test / lint / dev pipeline
├── tsconfig.base.json         # shared compiler options for packages
├── tsup.config.base.ts        # shared bundler config for packages
├── bunfig.toml                # bun: hoisted linker, exact installs
└── metro.config.js            # watchFolders + nodeModulesPaths for packages

modules/ holds local Expo modules — host-native bridges autolinked on expo prebuild (Swift/Kotlin + expo-module.config.json). They are not Bun workspace packages: no package.json, no tsup build, not imported as @piano/*. The app imports them via relative paths from src/ (e.g. system-gesture-defer.ts → modules/screen-gesture-defer, perf-hud.ts → modules/perf-hud). See architecture.md § Local Expo modules.

Workspace dependency graph

@piano/types is the leaf; @piano/sdk is the facade. Every other package sits between them.

Topological build order (what turbo run build walks):

LayerPackages
L0types, ads, keyboard, network, analytics, progression, audio-engine
L1midi, rhythm-engine
L2core (re-exports from rhythm-engine)
L3player-data, user-library, gameplay-learn, gameplay-magic (re-exports from rhythm-engine), gameplay-zen
L4catalog
L5sdk

Deprecation track: @piano/midi, @piano/gameplay-magic (the judgement module), and parts of @piano/core (event-bus, state-machine, tick-clock) are now thin re-exports from @rhythm/engine. They stay for backward compatibility with @piano/gameplay-learn and @piano/gameplay-zen until those packages migrate; track full removal in the rhythm-engine package README.

Package responsibilities

PackageContainsExternal deps
@piano/typesDomain types for game / midi / player—
@piano/keyboardPiano key model, octave math, layout helpers—
@piano/midiMIDI byte → event parsermidi-parser-js
@piano/coreCross-cutting engine primitives (event buses, clocks, base classes)—
@piano/networkIMidiRepository contract for fetching songs—
@piano/analyticsValibot schema-driven typed track() + IAnalyticsAdapter fan-out (docs); browser visualizer under visualizer/ (bun run analytics:viz)valibot
@piano/adsIAdsProvider contract—
@piano/progressionXP table + LevelServicevalibot
@piano/player-dataPlayerDataManager (XP, unlocks) + IPlayerDataStoragevalibot
@piano/user-libraryUserLibraryManager (owned songs, snapshots) + ILibraryStoragevalibot, @piano/core
@piano/catalogSongCatalog (songs + moods)valibot
@rhythm/engineInstrument-agnostic rhythm core: chart parser, bitmask cursor, judgement, scoring, PlayController, optional React bindings. Single source of truth for tile/highlight/judgement on the UI thread.react-native-reanimated (peer, optional via ./react), midi-parser-js
@piano/audio-enginePlatform-agnostic piano audio contracts (PianoAudioEngine, instrument / clock / effects / settings / diagnostics / preset) + shared pure helpers (velocity curves, resolveAudioBackend). Imported directly by src/core/audio/engine/ (docs).—
@piano/soundfontPure SF2 parse, region merge, ADSR convert, sample voice-plan (no AudioContext). Used by app adapters + browser lab (bun run soundfont:lab / soundfont:lab:build).—
@piano/gameplay-learnLearn-mode engine + scoring—
@piano/gameplay-magicMagic-mode shim (judgement re-exports from @rhythm/engine; judgement-queue + engine retained for legacy consumers, removal scheduled after Learn + Zen migrate)—
@piano/gameplay-zenZen-mode engine + scoring—
@piano/sdkcreatePianoSdk(config) — single entry point for the Expo appre-exports everything

The Expo app only imports @piano/sdk (and re-exported types from it). Reaching past the SDK into a sub-package directly works but defeats the facade — keep that for tests or scripts.

Per-package layout

Every package is identical:

packages/<name>/
├── src/
│   └── index.ts        # the only entry point
├── tests/              # bun test
├── dist/               # tsup output (gitignored)
├── package.json        # name = "@piano/<name>"
├── tsconfig.json       # extends ../../tsconfig.base.json
├── tsup.config.ts      # imports baseConfig from ../../tsup.config.base.ts
└── README.md

package.json is uniform too:

{
  "name": "@piano/<name>",
  "version": "0.0.0",
  "type": "module",
  "main": "./src/index.ts",
  "module": "./src/index.ts",
  "types": "./src/index.ts",
  "exports": {
    ".": {
      "types": "./src/index.ts",
      "default": "./src/index.ts"
    }
  },
  "files": ["src"],
  "scripts": {
    "build": "tsup",
    "test": "bun test",
    "typecheck": "tsc --noEmit",
    "clean": "rm -rf dist .turbo"
  }
}

Workspace deps use "@piano/<dep>": "workspace:*". Runtime/peer deps go under dependencies. Build tooling (tsup, typescript, @types/bun) goes under devDependencies.

Shared configs

tsconfig.base.json

Strict, ES2022, declaration emit + sourcemaps + incremental builds. Extended by every package's tsconfig.json:

{
  "extends": "../../tsconfig.base.json",
  "compilerOptions": {
    "outDir": "./dist",
    "rootDir": "./src"
  },
  "include": ["src/**/*"],
  "exclude": ["dist", "node_modules", "tests"]
}

The Expo app's tsconfig.json does not extend this file — it extends expo/tsconfig.base because Expo needs different jsx, lib, and types settings. The two tsconfigs intentionally diverge: packages target plain ES2022, the app targets RN.

tsup.config.base.ts

Dual ESM + CJS output, declaration files, sourcemaps, no code splitting (each package ships a single index.{js,cjs,d.ts}). Extended by every package's tsup.config.ts:

import { defineConfig } from 'tsup';
import { baseConfig } from '../../tsup.config.base';

export default defineConfig(baseConfig);

If a package needs entry-point overrides (multiple subpath exports, side-effects flag, externals), it can spread baseConfig and add its own keys.

bunfig.toml

[install]
exact = true       # pin every install to an exact version
linker = "hoisted" # hoist deps to root node_modules (required for Metro)

The hoisted linker is what lets Metro resolve a single copy of react / react-native / react-native-reanimated across the app and packages. Don't switch to isolated — RN cannot tolerate duplicate copies of those modules.

The [test] table also sets pathIgnorePatterns = ["build/**", "ios/**", "android/**", "node_modules/**"]. bun test keeps a directory fd open for every folder it walks while discovering tests; a local simulator build under build/ios-sim (~15k folders) plus ios/Pods (~10k) made each shard hold ~30k fds, and the nine //#test:app:* shards that Turbo runs together exhausted the system file table (ENFILE / SystemFdQuotaExceeded, shards failing at random). Keep native build output out of the test walk.

turbo.json

{
  "tasks": {
    "build":     { "dependsOn": ["^build"], "outputs": ["dist/**"] },
    "test":      { "dependsOn": ["^build"], "outputs": [] },
    "typecheck": { "dependsOn": ["^build"], "outputs": [] },
    "dev":       { "cache": false, "dependsOn": ["^build"], "outputs": [], "persistent": true },
    "clean":     { "cache": false, "outputs": [] }
  }
}

^build means "build dependencies first" — turbo walks the workspace graph in topological order. So bunx turbo run typecheck rebuilds dependent dist/ outputs before typechecking each package, which guarantees @piano/sdk typechecks against fresh declaration files of @piano/types etc.

How the Expo app consumes packages

Three pieces make this work:

  1. Bun workspaces (package.json workspaces: ["packages/*"]) symlink each @piano/* into node_modules/@piano/.
  2. Metro watchFolders (metro.config.js) point at packages/, so editing a file in packages/midi/src/parser.ts triggers Fast Refresh in the running app.
  3. disableHierarchicalLookup: true (metro.config.js) prevents Metro from walking up into nested node_modules, which is what would otherwise pull in a duplicate react.
  4. DEDUPE_SINGLETONS resolver forces react-native-reanimated and react-native-worklets to always resolve from the root node_modules — a nested copy in packages/*/node_modules causes frame-callback id collisions and release crashes. Agent rule: .cursor/rules/monorepo-metro.mdc. After editing metro.config.js, run expo start --clear.

The Reanimated and Unistyles babel plugins both live in the root babel.config.js, and autoProcessPaths is ['app', 'packages'] — so worklets and styled components inside packages/* get the same codegen the app sources do.

Common commands

CommandEffect
bun installInstall root + all workspaces, refresh symlinks
bun run startStart Metro for the Expo app (consumes packages by symlink)
bun run ios / bun run androidBuild + launch the native app
bun run typecheckTypecheck the Expo app only (tsc --noEmit at root)
bun run typecheck:allTypecheck every workspace package via turbo run typecheck
bun run build:packagesBuild all @piano/* (turbo run build, topologically ordered)
bun run lint:allRun each workspace's lint script
bunx turbo run build --filter=@piano/midiBuild a single package and its dependencies
bunx turbo run dev --filter=@piano/midiWatch-mode tsup --watch for one package
bun run clean (per package)rm -rf dist .turbo inside that package

Adding / removing a package

See adding-a-package.md for the full recipe. TL;DR:

  1. Copy an existing leaf package (packages/types/ is a good template).
  2. Rename it in package.json (@piano/<new-name>).
  3. Add "@piano/<dep>": "workspace:*" for any workspace deps.
  4. Run bun install from the repo root — the symlink appears under node_modules/@piano/.
  5. Add it to @piano/sdk's dependencies and src/index.ts re-export if it should be part of the public surface.

Things to watch for

  • Don't ship react/react-native from a package. RN packages only — the engines under @piano/* are pure TS and must stay that way. If you need RN, write a thin adapter in src/features/<x>/ instead.
  • Peer deps for the host app. When a package eventually does want a peer (e.g. expo-asset for sample loading), declare it as peerDependencies in the package and ensure the same exact version is in the root package.json.
  • workspace:* pins are protocol-only. bun install rewrites them to actual versions in the published artifact, but inside this repo they always resolve to the live source.
  • turbo run build caches per package. If you bypass turbo and run tsup directly in one package, turbo will still see clean inputs next time and skip — that's intentional. To force a rebuild, bun run clean in that package or bunx turbo run build --force.