v1.0.10 · Release snapshot

Documentation comes from this release commit, without inheriting newer content. Commit: 63ea8c2b3d.

Hub Integration: Magic Piano × @leapgame/app-sdk

The hub (@leapgame/app-sdk) is a dependency-injection container: it defines port interfaces for subscriptions, ads, auth tokens, and tracking, but imports zero native SDKs itself. Magic Piano's src/core/sdk/hub.ts bootstraps the hub by injecting the real native implementations — react-native-purchases (via createPurchasesAdapter), AppsFlyer (via createAppsFlyerAdapter), and Firebase Auth's getIdToken callback (ads do not go through the hub: they live behind @core/ads on Google AdMob — see admob-integration.md) — at app startup. A second singleton, src/core/sdk/instance.ts, manages the @piano/sdk (game engine + analytics), injecting Firebase Analytics adapters and an MMKV-backed player-data store. The two singletons share the same Firebase anonymous uid but are otherwise independent; the hub handles money and identity while the game SDK handles gameplay, MIDI, and event tracking.


1. RevenueCat — IAP & Subscription

Status: ✅ Fully integrated

What it does: Manages subscription purchases (weekly / yearly, with 50%-off discount variant), the one-off "remove ads" IAP, individual song unlocks, restore purchases, and entitlement syncing into the local Zustand store.

How it's wired:

  • Hub port: hub.subscription (type SubscriptionService from @leapgame/app-sdk), enabled when purchasesSdk is injected into createHub.
  • Adapter: createPurchasesAdapter at src/core/sdk/adapters/purchases-adapter.ts — thin pass-through wrapping react-native-purchases' Purchases static class into the hub's PurchasesSdk interface.
  • Bootstrap: getHub() in src/core/sdk/hub.ts — dynamically imports react-native-purchases, wraps it, and passes it as purchasesSdk to createHub. RevenueCat is configured by the hub with EXPO_PUBLIC_REVENUECAT_IOS_API_KEY / EXPO_PUBLIC_REVENUECAT_ANDROID_API_KEY and the entitlement id "VIP".
  • appUserId: After anon sign-in, the Firebase uid is read and passed as appUserId so RevenueCat links the subscriber record to the Firebase identity.
  • Entitlement sync call path:
    1. At startup: getCustomerInfo() → resolveEntitlements() → syncEntitlementsFromRC().
    2. On purchase: PaywallHost calls hub.subscription.purchase(pkg) → result carries customerInfo → syncEntitlementsFromRC().
    3. On restore: hub.subscription.restore() → same syncEntitlementsFromRC() path.
    4. On guest re-login (sign out → sign in again): refreshEntitlements() at src/features/monetization/refresh-entitlements.ts re-pulls Purchases.getCustomerInfo() to restore a returning subscriber's flags without a full relaunch.
  • Entitlement resolution: src/features/monetization/resolve-entitlements.ts — checks info.entitlements.active["VIP"]?.isActive for isPremium; checks allPurchasedProductIdentifiers for com.piano.noadspack for isNoAds.
  • Entitlement storage: MMKV-persisted Zustand store at src/features/songs/entitlements-store.ts holds isPremium and adsRemoved. setPremiumEntitlement() in entitlements-actions.ts also calls library.setSubscription() and sdk.player.setVip() to propagate the flag into the game engine.

Key code:

// src/core/sdk/hub.ts — adapter injection
const PurchasesMod = await import("react-native-purchases");
const purchasesSdk: PurchasesSdk = createPurchasesAdapter(PurchasesMod.default);
const hub = createHub({ ..., revenueCat: { iosKey, androidKey, entitlementId: "VIP" }, storeIds: {} }, { ..., appUserId, purchasesSdk });

// PaywallHost.tsx — purchase flow
const result = await hub.subscription?.purchase(pkg);
if (result?.customerInfo) await syncEntitlementsFromRC(result.customerInfo as CustomerInfo);

Product catalog (src/features/monetization/catalog.ts):

  • com.piano.weekly / com.piano.yearly (RC offering default)
  • com.piano.weekly50 / com.piano.yearly50 (RC offering discount — the 50%-off variant)
  • com.piano.noadspack (RC offering iap_noads)
  • Per-song IAP: com.piano.songdeal1 (Rush E), com.piano.songdeal2 (Passo Bem Solto)

Gaps / TODOs:

  • storeIds: {} is an empty object — if the hub uses this field for store product id validation, no ids are registered (no functional impact observed yet, but worth confirming with the hub's internals).
  • android ad unit ids are absent from the ads config block (only ios keys are set); no Android build is currently targeted so this is latent.
  • isPremiumCached is a module-level boolean only set on first getCustomerInfo() — it is not refreshed after a mid-session restore (the entitlements store gets updated, but the ad-gate flag in hub.ts does not re-read it until the next app launch). Low risk while iOS-only.
  • The no_ads entitlement is checked via allPurchasedProductIdentifiers (product id match), not via an RC entitlement name — a future RC dashboard restructuring could break this check.

2. AppsFlyer

Status: 🟡 Partial — adapter and event schema fully designed; SDK not yet installed or wired

What it does (design intent): Sends custom conversion events (af_inters_displayed, af_rewarded_displayed, af_song_click) to AppsFlyer for attribution and ROAS measurement. Auto-SDK events (af_ad_revenue, af_purchase, first_open, session_start) are expected to be emitted by the AppsFlyer SDK itself.

How it's wired (design):

  • Adapter: AppsFlyerAnalyticsAdapter at packages/analytics/src/adapters/appsflyer.ts — implements IAnalyticsAdapter, accepts an injected AppsFlyerClient interface (avoids importing react-native-appsflyer at package scope so the analytics package stays test-friendly).
  • Event routing: packages/analytics/src/event-routing.ts defines eventProviders — af_inters_displayed and af_rewarded_displayed route to ["appsflyer"] only; song_click routes to ["firebase"] with a name override { appsflyer: "af_song_click" }.
  • Auto-SDK guard: AUTO_SDK_EVENTS set excludes af_ad_revenue, af_purchase, first_open, session_start from the dispatcher so they are never double-counted.
  • What is NOT yet done:
    • react-native-appsflyer is not in package.json and not in node_modules.
    • AppsFlyerAnalyticsAdapter is not instantiated anywhere in src/core/sdk/instance.ts's buildAnalyticsAdapters() — only Firebase and console adapters are active.
    • No AppsFlyer SDK init call (no app key, no appsFlyer.initSdk()) exists anywhere in the app source.

Key code (design layer — not yet wired):

// packages/analytics/src/adapters/appsflyer.ts
export class AppsFlyerAnalyticsAdapter implements IAnalyticsAdapter {
  readonly name = "appsflyer";
  constructor(private readonly client: AppsFlyerClient) {}
  logEvent(name: string, params?: AnalyticsParams): void {
    void this.client.logEvent(name, params ?? {});
  }
}

// packages/analytics/src/event-routing.ts
af_inters_displayed: ["appsflyer"],
af_rewarded_displayed: ["appsflyer"],
song_click: ["firebase"],  // with override: { appsflyer: "af_song_click" }

Gaps / TODOs:

  • Install react-native-appsflyer and run a native rebuild.
  • In src/core/sdk/instance.ts buildAnalyticsAdapters(), wrap the RN AppsFlyer SDK in an AppsFlyerClient shim and push new AppsFlyerAnalyticsAdapter(shim) into the adapters array.
  • Add AppsFlyer SDK init (app key, dev key) — likely in hub.ts or app/_layout.tsx.
  • The appsflyerid param defined in ad_impression / ad_impression_ama event schemas (packages/analytics/src/event-schemas.ts) has nowhere to be populated until the SDK is live and returns the AppsFlyer ID.

3. Events / Analytics

Status: ✅ Fully integrated (Firebase sink); 🟡 AppsFlyer sink pending (see Feature 2)

What it does: All in-app behavioural events flow through a typed AnalyticsDispatcher in @piano/analytics, which validates params via valibot schemas, applies per-provider name overrides, and fans out to one or more adapters. Currently the live sink is Firebase Analytics only.

How it's wired:

  • Package: packages/analytics/ — contains AnalyticsDispatcher, FirebaseAnalyticsAdapter, AppsFlyerAnalyticsAdapter, ConsoleAnalyticsAdapter, DebugBridgeAnalyticsAdapter, and Valibot event schemas.
  • Adapter injection: buildAnalyticsAdapters() in src/core/sdk/instance.ts creates FirebaseAnalyticsAdapter (injecting the RNFB modular logEvent/setUserProperty calls so the analytics package never imports React Native), plus ConsoleAnalyticsAdapter in dev, plus an optional WebSocket debug bridge for the analytics visualizer.
  • SDK wiring: createPianoSdk({ analytics: buildAnalyticsAdapters() }) passes the adapter array to the game SDK, which wraps them in AnalyticsDispatcher and exposes sdk.analytics.track(event, params).
  • trackEvent() call path: src/core/sdk/analytics.ts exposes the app-wide trackEvent<E>(event, params) helper. It calls getSdkSync() for synchronous dispatch when the SDK is already resolved, or falls back to getSdk().then(s => s.analytics.track(...)) for pre-init events (which the dispatcher queues until initAll() completes).
  • Hub tracking sink: hub.tracking.addSink({ name: "firebase", log: logEvent(...) }) in hub.ts — a separate Firebase sink for hub-internal events (e.g. subscription lifecycle). This is distinct from sdk.analytics (game events) — the hub does not use the @piano/analytics dispatcher.
  • Event schemas: ~79 events defined as Valibot schemas in packages/analytics/src/event-schemas.ts; types derive via v.InferOutput. The full human-readable tracking sheet lives at docs/analytics/Piano-Tracking-Events.xlsx.
  • Event categories:
    • FTUE / onboarding: fn_loading_start, fn_after_splash_screen, fn_intro_*, fn_training_*, fn_tutorial_*
    • Song funnel: song_impression → song_click → song_load → song_start → me_start → song_end → song_result
    • Ads: fullads_*, videoads_*, bannerads_*, openads_*, ad_impression
    • Subscription: sub_offer_show, sub_offer_click, sub_offer_close, sub_offer_cancel, user_subscription
    • IAP: iap_offer_show, iap_offer_click, iap_offer_success, iap_offer_fail, iap_offer_reward
    • Navigation: screen_view (fired automatically by useScreenViewTracking hook)

Key code:

// src/core/sdk/analytics.ts — fire-and-forget typed dispatch
export function trackEvent<E extends AnalyticsEventName>(event: E, params: AnalyticsEventMap[E]): void {
  const sdk = getSdkSync();
  if (sdk) { sdk.analytics.track(event, params); return; }
  void getSdk().then((s) => s.analytics.track(event, params));
}

// src/core/sdk/hub.ts — separate hub-internal Firebase sink
hub.tracking.addSink({
  name: "firebase",
  log: (event, params) => logEvent(getAnalytics(getApp()), event, params as Record<string, unknown>),
});

Gaps / TODOs:

  • The af_inters_displayed and af_rewarded_displayed events are routed to the appsflyer provider in event-routing.ts, but will silently be a no-op until AppsFlyerAnalyticsAdapter is added to buildAnalyticsAdapters().
  • ad_impression_ama routes to firebase_only_ama — a provider type declared in the type union but not mapped to any concrete adapter; it will currently be swallowed by the dispatcher (no adapter with name "firebase_only_ama" exists). Needs clarification on whether it should route to the same Firebase adapter under a different event name.
  • Song-session correlation (song_session_id) is maintained in a module-level singleton in src/core/sdk/analytics.ts — it is not persisted and resets on app restart or resetSdk().

4. Auth

Status: 🟡 Partial — Firebase anonymous auth fully integrated; named account auth (email/password) gated off pending Firebase linkWithCredential implementation

What it does: Signs in anonymously via Firebase Auth on first launch, producing an uid that is reused as the RevenueCat App User ID, the player-data storage key, and the guest session identity. Real email/password sign-in routes are declared but intentionally suspended.

How it's wired:

  • firebase-auth.ts: ensureAnonUid() at src/core/sdk/firebase-auth.ts — calls signInAnonymously(getAuth(getApp())), which is idempotent (RNFB reuses the cached anon user from the iOS Keychain across launches). Returns the uid, or null if offline with no cached user.
  • Hub seam: makeFirebaseGetIdToken() in src/core/sdk/hub.ts — signs in anonymously, then returns a () => Promise<string | null> closure that calls user.getIdToken() on demand. This closure is passed as getIdToken to createHub, and the hub calls it before every authenticated backend request.
  • appUserId: After makeFirebaseGetIdToken() resolves, getAuth().currentUser?.uid is read and passed as appUserId to createHub — linking RevenueCat to the same Firebase identity.
  • Guest session: ensureGuestSession() at src/features/auth/guest.ts calls getGuestIdentity() (which awaits getHub() to guarantee anon sign-in is complete), then writes a Session object into useAuthStore with the Firebase uid as user.id. On every guest login it also calls refreshEntitlements() to restore a returning subscriber's flags.
  • AUTH_ENABLED flag: app/_layout.tsx line 29 — const AUTH_ENABLED = false. The (auth) route group (Stack.Protected guard={AUTH_ENABLED && hasCompleted}) is permanently blocked. src/features/auth/api.ts additionally rejects all sign-in / sign-up calls with an explicit error message directing to 11.FIRESTORE-INTEGRATION.md §11.
  • Sign-out: performSignOut() at src/features/auth/signOut.ts — wipes useAuthStore, useEntitlementsStore, useTracksStore, usePianoUiStore, useOnboardingStore, queryClient, and calls wipePlayerDataForUid(uid) + wipeLibraryForUser(uid) so a fresh guest session starts clean.
  • SDK init: getSdk() in instance.ts awaits ensureAnonUid() before creating createPianoSdk, scoping the MMKV MmkvPlayerDataStorage to the uid.

Key code:

// src/core/sdk/firebase-auth.ts
export async function ensureAnonUid(): Promise<string | null> {
  try {
    const credential = await signInAnonymously(getAuth(getApp()));
    return credential.user?.uid ?? getAuth(getApp()).currentUser?.uid ?? null;
  } catch {
    return getAuth(getApp()).currentUser?.uid ?? null;
  }
}

// src/core/sdk/hub.ts — getIdToken seam
async function makeFirebaseGetIdToken(): Promise<() => Promise<string | null>> {
  await signInAnonymously(getAuth(getApp()));
  return async () => {
    const user = getAuth(getApp()).currentUser;
    return user ? await user.getIdToken() : null;
  };
}

// app/_layout.tsx
const AUTH_ENABLED = false;
// ...
<Stack.Protected guard={AUTH_ENABLED && hasCompleted}>
  <Stack.Screen name="(auth)" />
</Stack.Protected>

Gaps / TODOs:

  • Named account auth (email / password + linkWithCredential) is fully suspended. Re-enabling requires wiring real Firebase Auth sign-in and linking the anonymous credential to a named account before surfacing the (auth) routes.
  • GUEST_CLOUD_SYNC flag in guest.ts (defaults to the value exported from @core/services/library) gates whether the anon uid partition is synced to users/{uid}/library on Firestore — check the current value to confirm if cloud library sync is live.
  • Token TTL in guest.ts (GUEST_TOKEN_TTL_MS = 1h) reflects Firebase ID token lifetime. There is no automatic refresh loop in the guest session; expired tokens are only refreshed when the hub re-calls getIdToken() on a new backend request (RNFB handles refresh under the hood via getIdToken()).

Summary Table

FeatureStatusHub Port / AdapterKey Files
RevenueCat — IAP & Subscription✅ Fully integratedhub.subscription / createPurchasesAdapter → PurchasesSdksrc/core/sdk/hub.ts, src/core/sdk/adapters/purchases-adapter.ts, src/features/monetization/resolve-entitlements.ts, src/features/monetization/syncEntitlementsFromRC.ts, src/features/monetization/catalog.ts, src/features/songs/entitlements-store.ts, src/features/paywall/components/PaywallHost.tsx
AppsFlyer🟡 Adapter built, SDK not installedsdk.analytics dispatcher / AppsFlyerAnalyticsAdapter (not yet instantiated)packages/analytics/src/adapters/appsflyer.ts, packages/analytics/src/event-routing.ts
Events / Analytics✅ Firebase live; 🟡 AppsFlyer pendingsdk.analytics (AnalyticsDispatcher) + hub.tracking.addSink (hub-internal)src/core/sdk/analytics.ts, src/core/sdk/instance.ts, packages/analytics/src/adapters/firebase.ts, packages/analytics/src/dispatcher.ts, packages/analytics/src/event-schemas.ts, docs/analytics/Piano-Tracking-Events.xlsx
Auth🟡 Anon auth live; named account gated offgetIdToken callback injected into createHub / makeFirebaseGetIdTokensrc/core/sdk/firebase-auth.ts, src/core/sdk/hub.ts, src/features/auth/guest.ts, src/features/auth/signOut.ts, app/_layout.tsx