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

@bck-inc/nsb

v1.0.41

Published

SDK officiel pour l'API NSB (Néon Spinellia BCK) - 100 % fetch natif

Downloads

32

Readme

@bck-inc/nsb

SDK TypeScript / Node.js pour l'API NSB (Néon Spinellia BCK)

TL;DR : import { NSBCore } from '@bck-inc/nsb' → appelez votre premier endpoint en 10 lignes.


✨ Caractéristiques principales

|    |    | | :--------------------- | :------------------------------------------------------------------------------------------- | | Fetch natif | Aucun client HTTP externe — Node ≥ 18 requis (polyfill possible). | | ESM & CJS | Fonctionne avec import et require. | | Type safe | Déclarations .d.ts + type‑guards runtime. | | Cache TTL (1,5 s) | Réponses GET mises en cache pour amortir les floods. | | Rate‑limit intégré | 55 req/s (tokens valides) / 1 req/s (non autorisés). | | Errors typées | NSBError, NSBHTTPError pour des catch ciblés. | | Évènements | request, response, cacheHit, validationError, moduleStateChanged, ping, error. | | Zéro config | Instanciez, appelez : headers et baseURL gérés pour vous. |


🚀 Installation

npm i @bck-inc/nsb           # pnpm add @bck-inc/nsb / yarn add @bck-inc/nsb

Node ≥ 18 recommandé pour fetch et URL globaux. Sur Node 16 :

import fetch from 'node-fetch';
// @ts-ignore
globalThis.fetch = fetch;

⚡ Exemple rapide (TS / ESM)

import { NSBCore, NSBCodes, NSBState } from '@bck-inc/nsb';

const core = new NSBCore({
  token: process.env.NSB_TOKEN!,
  botId:  process.env.BOT_ID!,
  debug:  true,
});

core.on('cacheHit', ({ url })  => console.log('⚡ cache', url))
    .on('ping',     ({ rtt })  => console.log('ping', rtt, 'ms'))
    .on('error',    console.error);

// Active le module "welcome" sur un serveur
const res = await core.setModuleState({
  bot_id:     core['botId']!,
  server_id:  '987654321098765432',
  module_name:'welcome',
  newState:   NSBState.enabled,
});

if (res.code === NSBCodes.VALID) console.log('Module OK');

📚 API en bref

Constructeur

new NSBCore({ token, botId, baseURL?, debug? });

Méthodes

| Méthode | Effet | | ------------------------------------------- | ------------------------------------------------- | | fetchModules(query?) | GET /modules/get + cache TTL (1.5s) | | insertModule(body) / updateModule(body) | CRUD module | | setModuleState(params) | Insert ou update + événement moduleStateChanged | | enableModule(p) / disableModule(p) | Sucrage autour de setModuleState | | isStandardized(name) | Vérifie si « standard » côté API | | getStandardizedModules() | Récupère la liste complète des modules standards | | getPing(timeout?) | Retourne la latence RTT (ms) et émet ping | | connectWebSocket(options?) | Ouvre le WS NSB + gère TOGGLE/ACK | | disconnectWebSocket(code?, reason?) | Ferme le WS et stoppe la reconnexion auto |

Évènements (auto‑complétés dans VS Code)

| Event | Payload | | :------------------- | :--------------------------- | | request | { url, method } | | response | { url, status } | | cacheHit | { url, ttlLeft } | | validationError | { url, issues } | | moduleStateChanged | { module, type, newState } | | ping | { rtt } (‑1 si timeout) | | error | unknown | | wsOpen | { url } | | wsClose | { code, reason } | | wsMessage | unknown | | wsReconnect | { retryInMs } | | wsError | unknown |

Types & enums détaillés dans src/types.ts.


🔌 WebSocket NSB (conversion de ton snippet)

Le SDK intègre maintenant un client WebSocket prêt à l'emploi.

import { NSBCore } from '@bck-inc/nsb';

const core = new NSBCore({
  token: process.env.NSB_TOKEN!,
  botId: client.user!.id,
});

core.connectWebSocket({
  wsURL: 'wss://api.neon-inc.fr/nsb/ws', // optionnel (défaut identique)
  reconnectDelayMs: 5000,
  autoReconnect: true,

  onOpen: () => {
    console.log('✅ Connecté au WebSocket NSB');
  },

  onError: (error) => {
    console.error('❌ Erreur WebSocket NSB:', error);
  },

  // Équivalent du bloc TOGGLE de ton code.
  // Si cette fonction réussit: ACK success=true envoyé automatiquement.
  // Si elle throw: ACK success=false envoyé automatiquement avec error.message.
  onToggle: async (data) => {
    await client.db.execute(
      'UPDATE server_modules SET server_status = ? WHERE module_name = ? AND serverID = ?',
      [data.state, data.module_name, data.server_id]
    );
  },

  onClose: () => {
    console.warn('💥 Connexion WS fermée (reconnexion auto si activée)');
  }
});

// Plus tard (arrêt propre)
// core.disconnectWebSocket();

Exemple complet (Discord.js + DB)

import { Client, GatewayIntentBits } from 'discord.js';
import mysql from 'mysql2/promise';
import { NSBCore } from '@bck-inc/nsb';

const client = new Client({
  intents: [GatewayIntentBits.Guilds]
});

const db = await mysql.createPool({
  host: process.env.DB_HOST,
  user: process.env.DB_USER,
  password: process.env.DB_PASSWORD,
  database: process.env.DB_NAME,
});

client.once('ready', () => {
  const core = new NSBCore({
    token: process.env.NSB_TOKEN!,
    botId: client.user!.id,
    debug: true,
  });

  core.on('wsReconnect', ({ retryInMs }) => {
    console.warn(`WS reconnect dans ${retryInMs}ms`);
  });

  core.connectWebSocket({
    onToggle: async ({ state, module_name, server_id }) => {
      await db.execute(
        'UPDATE server_modules SET server_status = ? WHERE module_name = ? AND serverID = ?',
        [state, module_name, server_id]
      );
    },
    onError: (err) => {
      console.error('WS error:', err);
    }
  });

  const stop = () => {
    core.disconnectWebSocket();
    db.end();
  };

  process.on('SIGINT', stop);
  process.on('SIGTERM', stop);
});

await client.login(process.env.DISCORD_TOKEN);

🔒 Authentification & Sécurité

Toutes les requêtes requièrent deux en-têtes obligatoires :

const core = new NSBCore({
  token: process.env.NSB_TOKEN,   // Bearer token (haché SHA-256 côté serveur)
  botId:  process.env.BOT_ID,     // ID Discord du bot
  baseURL: 'https://api.neon-inc.fr/api/nsb' // Par défaut
});

Rate‑limiting :

  • ✅ Bots autorisés : 55 req/s
  • ⚠️ Tokens invalides : 1 req/s
  • ❌ Dépassement → HTTP 429 (Too Many Requests)

En cas d'erreur 401, le SDK bascule automatiquement sur la limite basse.


🧪 Tests

pnpm test        # Vitest en CI
pnpm test:watch  # watch mode

🤝 Contribuer

  1. Fork puis git checkout -b feat/ma-feature
  2. pnpm i && pnpm test
  3. PR + description claire.

Toute idée ou bug ? Ouvrez une Issue — on répond vite !


📜 Licence

MIT — © BCK Inc. 2025