npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

funnisdk

v1.0.0

Published

[![npm version](https://img.shields.io/npm/v/funnisdk.svg)](https://www.npmjs.com/package/funnisdk) [![License: ISC](https://img.shields.io/badge/License-ISC-blue.svg)](https://opensource.org/licenses/ISC)

Readme

FunniGames SDK

npm version License: ISC

A lightweight, type-safe TypeScript/JavaScript SDK for seamless integration with the FunniGames platform. Built with modern web standards, this SDK enables your game to communicate with the FunniGames host environment via secure postMessage API.

🎮 Features

  • 🔒 Secure Communication - Built on postMessage API for safe cross-origin communication
  • 📦 Lightweight - Minimal bundle size with zero dependencies
  • 🎯 TypeScript First - Full TypeScript support with comprehensive type definitions
  • 🚀 Easy Integration - Simple initialization and intuitive API
  • 👤 User Profiles - Access and manage player profiles
  • 🏆 Leaderboard Support - Built-in leaderboard functionality
  • 🎲 Game Lifecycle - Manage game saves

📦 Installation

npm install funnisdk

🚀 Quick Start

import FunniGamesSDK from 'funnisdk';

async function initializeGame() {
// Initialize SDK with required features
    const initialized = await FunniGamesSDK.initialize({
        leaderboard: true,
        gameplay: true,
    });

    if (!initialized) {
        console.error('Failed to initialize SDK');
        return;
    }

// Start game session
    await FunniGamesSDK.gameplay.start();

// Get user profile
    const profile = await FunniGamesSDK.profile.getProfile();
    console.log('Player:', profile.data.full_name);
    console.log('Coins:', profile.data.totalCoins);

// Add score to leaderboard
    await FunniGamesSDK.leaderboard.addScore(1000);

// Save game progress
    await FunniGamesSDK.profile.saveData('progress', JSON.stringify({
        level: 5,
        score: 1000,
        completedAt: new Date().toISOString()
    }));
}

initializeGame().catch(console.error);

📚 Table of Contents

🎯 Initialization

initialize(config: InitConfig): Promise<boolean>

Initialize the SDK with the features your game needs. This must be called before using any other SDK features.

Parameters:

interface InitConfig {
    leaderboard?: boolean;  // Enable leaderboard functionality
    gameplay?: boolean;     // Enable gameplay state management
}

Returns: Promise<boolean> - Returns true if initialization succeeded, false otherwise.

Example:

const success = await FunniGamesSDK.initialize({
    leaderboard: true,
    gameplay: true
});

if (success) {
    console.log('SDK initialized successfully');
} else {
    console.error('SDK initialization failed');
}

Note: The Profile component is always initialized by default, regardless of the config.

📖 API Reference

Profile API

Manage user profiles, coins, and save/load game data.

getProfile(): Promise<ResponseModel & { data: UserProfile }>

Retrieve the current user's profile information.

Response:

{
    status: boolean;
    message: string | null;
    version: number;
    data: {
        account_id: string;
        full_name: string;
        totalPoints: number;
        totalCoins: number;
        timeWallet: {
            freeTimeRemaining: number;
            todayTimeRemaining: number;
            totalTimeRemaining: number;
            eligiblePlay: boolean;
            todayUsedTime: number;
        }
        ;
        moneyWalletBalance: number;
        images: {
            proAvatar: string | null;
            avatar: string;
        }
        ;
        pro: {
            startedDate: string;
            expirationDate: string;
        }
        ;
        isGuest: boolean;
        isActive: boolean;
    }
}

Example:

const profile = await FunniGamesSDK.profile.getProfile();
console.log(`Welcome ${profile.data.full_name}!`);
console.log(`You have ${profile.data.totalCoins} coins`);

addPoint(amount: number): Promise<ResponseModel & { data: AddPointInterface }>

Add coins to the user's account.

Parameters:

  • amount (number) - Number of coins to add (must be positive)

Example:

await FunniGamesSDK.profile.addPoint(50);
console.log('Added 50 coins to user account');

saveData(key: string, data: string): Promise<ResponseModel & { data: SaveData }>

Save custom game data associated with a key.

Parameters:

  • key (string) - Unique identifier for the data
  • data (string) - Data to save (must be a string, use JSON.stringify for objects)

Example:

const gameData = {
    level: 5,
    health: 100,
    inventory: ['sword', 'shield']
};

await FunniGamesSDK.profile.saveData(
    'player_progress',
    JSON.stringify(gameData)
);

getData(key: string): Promise<ResponseModel & { data: GetData }>

Retrieve previously saved game data.

Parameters:

  • key (string) - The key used when saving the data

Example:

const response = await FunniGamesSDK.profile.getData('player_progress');
if (response.status) {
    const gameData = JSON.parse(response.data);
    console.log('Current level:', gameData.level);
}

Leaderboard API

Manage game scores and retrieve leaderboard rankings.

addScore(score: number): Promise<ResponseModel>

Submit a score to the leaderboard.

Parameters:

  • score (number) - The score to submit

Example:

await FunniGamesSDK.leaderboard.addScore(1500);
console.log('Score submitted successfully');

getLeaderboard(): Promise<ResponseModel & { data: LeaderboardInterface }>

Retrieve the current leaderboard standings.

Response:

{
    status: boolean;
    message: string | null;
    version: number;
    data: {
        leaderboard: [
            {
                userId: string;
                userName: string;
                totalPoints: number;
                rank: number;
                images? : {
                    avatar? : string;
                    proAvatar? : string;
                };
                uniqueId: string;
                isPro: boolean;
            }
        ];
        userRecord: {
            _id: string;
            name ? : string;
            registrationId: string;
            images ? : {
                avatar? : string;
                proAvatar? : string;
            };
            uniqueId: string;
            pro: {
                startedDate ? : Date | null;
                expirationDate ? : Date | null;
            }
        }
    }
}

Example:

const leaderboard = await FunniGamesSDK.leaderboard.getLeaderboard();
console.log('Top player:', leaderboard.data.leaderboard[0]);
console.log('Your rank:', leaderboard.data.userRecord);

📝 Type Definitions

ResponseModel

interface ResponseModel {
    status: boolean;
    message: string | null;
    version: number;
    data?: any;
}

InitConfig

interface InitConfig {
    leaderboard?: boolean;
    gameplay?: boolean;
}

UserProfile

interface UserProfile {
    account_id: string;
    full_name: string;
    totalPoints: number;
    totalCoins: number;
    timeWallet: TimeWallet;
    moneyWalletBalance: number;
    images: Images;
    pro: Pro;
    isGuest: boolean;
    isActive: boolean;
}

For complete type definitions, see the TypeScript declarations included in the package.


⚠️ Error Handling

All SDK methods return promises and may throw errors. Always use try-catch blocks or .catch() handlers.

Common error scenarios:

  • SDK not initialized (call initialize() first)
  • Parent window not available (game not embedded in FunniGames platform)
  • Network/communication failures
  • Invalid parameters

Example:

try {
    const profile = await FunniGamesSDK.profile.getProfile();
    console.log('Profile loaded:', profile.data);
} catch (error) {
    console.error('Failed to load profile:', error.message);
    // Handle error appropriately (show message to user, retry, etc.)
}

🌍 Environment Requirements

  • Platform: Must be embedded in an iframe within the FunniGames platform
  • Parent Window: Parent window must implement required postMessage handlers
  • Browser: Modern browser with ES2018+ support
  • Node: >=14.0.0 (for development)

🛠️ Build & Development

Development Setup

# Clone the repository
git clone <repository-url>

# Navigate to the SDK directory
cd jsSDK

# Install dependencies
npm install

# Start development build with watch mode
npm run dev

Building

# Clean build artifacts
npm run clean

# Build the SDK
npm run build

# Prepare for publishing
npm run prepare-publish

Build Output

The SDK is built in multiple formats:

  • ESM (dist/index.js) - ES Module format
  • CommonJS (dist/index.cjs) - CommonJS format
  • IIFE (dist/game-platform.min.js) - Browser-ready bundle
  • Types (dist/index.d.ts) - TypeScript type definitions

💡 Examples

Complete Game Integration

import FunniGamesSDK from 'funnisdk';
import {FlowType, ProgressionStatus} from 'funnisdk';

class Game {
    async init() {
        // Initialize SDK
        const success = await FunniGamesSDK.initialize({
            leaderboard: true,
            gameplay: true
        });

        if (!success) {
            throw new Error('Failed to initialize FunniGames SDK');
        }

        // Get player info
        const profile = await FunniGamesSDK.profile.getProfile();
        this.displayPlayerInfo(profile.data);

        // Load saved progress
        try {
            const savedData = await FunniGamesSDK.profile.getData('game_progress');
            this.loadProgress(JSON.parse(savedData.data));
        } catch (error) {
            // No saved data, start fresh
            this.startNewGame();
        }
    }

    async startLevel(level: number) {
        // Signal game start
        await FunniGamesSDK.gameplay.start();

        // Track level start
        await FunniGamesSDK.analytics.progressionEvent(
            ProgressionStatus.Start,
            `Level${level}`,
            '',
            ''
        );
    }

    async completeLevel(level: number, score: number, coinsEarned: number) {
        // Submit score
        await FunniGamesSDK.leaderboard.addScore(score);

        // Add coins
        await FunniGamesSDK.profile.addPoint(coinsEarned);

        // Track resource gain
        await FunniGamesSDK.analytics.resourceEvent(
            FlowType.Source,
            'currency',
            'coins',
            coinsEarned,
            'coins'
        );

        // Track progression
        await FunniGamesSDK.analytics.progressionEvent(
            ProgressionStatus.Complete,
            `Level${level}`,
            '',
            '',
            score
        );

        // Save progress
        await this.saveProgress();
    }

    async purchaseItem(itemId: string, cost: number) {
        try {
            const transaction = await FunniGamesSDK.wallet.spendFunniCoin(itemId, cost);

            // Deliver item to player
            this.giveItemToPlayer(itemId);

            // Consume transaction
            await FunniGamesSDK.wallet.consume(transaction.Transaction.TransactionId);

            // Track spending
            await FunniGamesSDK.analytics.resourceEvent(
                FlowType.Sink,
                'item',
                itemId,
                cost,
                'coins'
            );

            return true;
        } catch (error) {
            console.error('Purchase failed:', error);
            return false;
        }
    }

    async saveProgress() {
        const progress = {
            level: this.currentLevel,
            score: this.totalScore,
            inventory: this.inventory,
            savedAt: new Date().toISOString()
        };

        await FunniGamesSDK.profile.saveData(
            'game_progress',
            JSON.stringify(progress)
        );
    }

    async endGame() {
        await this.saveProgress();
        await FunniGamesSDK.gameplay.stop();
    }
}

📄 License

Proprietary License - see the LICENSE file for details.


📞 Support


🔄 Changelog

v1.0.0 (Current)

  • Initial release
  • Profile management
  • Leaderboard integration
  • Game save management

Made with ❤️ by the FunniGames Team