GitHub Packages docs for v0.4.0

@shnwazdeveloper @shnwaz developer /shnwazdev

A dependency-free JavaScript toolkit for realtime state, events, polling, safer logs, guarded fetch calls, rate limiting, and circuit-breaker recovery.

Package: @shnwazdeveloper/shnwazdev Registry: npm.pkg.github.com License: MIT
24

Exports

Realtime, timing, safety, and resilience helpers.

0

Runtime dependencies

Simple ESM. No runtime dependencies.

Safe

Publish path

Secret scan, tests, and dry-run before release.

Install

Install from GitHub Packages

The package is scoped to `@shnwazdeveloper`, so npm must use GitHub Packages for that scope.

User or project .npmrc
@shnwazdeveloper:registry=https://npm.pkg.github.com
Authenticate npm
gh auth refresh -h github.com -s read:packages
$token = gh auth token
npm config set "//npm.pkg.github.com/:_authToken" "$token" --location=user
Install latest
npm install @shnwazdeveloper/shnwazdev@0.4.0

Quick start

Use the main tools together

Combine state, events, safe logging, rate limiting, and guarded fetch calls in app code, bots, dashboards, workers, and APIs.

Example
import {
  createEventBus,
  createRateLimiter,
  createRealtimeStore,
  createSafeLogger,
  safeFetch
} from "@shnwazdeveloper/shnwazdev";

const store = createRealtimeStore({ online: false });
const bus = createEventBus();
const logger = createSafeLogger(console);
const limiter = createRateLimiter({ limit: 10, interval: 60000 });

limiter.assert("user:shnwazdeveloper");
store.setState({ online: true });
bus.emit("status", store.getState());

const result = await safeFetch("https://api.github.com", {
  allowedOrigins: ["https://api.github.com"],
  timeout: 3000
});

logger.info("request finished", result.safeRequest);

API reference

Everything exported by the package

Filter by area to scan the package quickly. Every API is dependency-free and exported from the package root.

createEventBus

Local publish/subscribe events with `on`, `once`, `off`, `emit`, and `emitAsync`.

createRealtimeStore

Small state container with subscriptions, selectors, updates, and `waitFor`.

createPoller

Repeated async work with `onData`, `onError`, `runOnce`, `until`, and backoff.

createHeartbeat

Live beat signals for bots, dashboards, workers, and connection monitors.

sleep

Abortable async delay that cleans up abort listeners on resolve and abort.

timeout

Wrap a promise and reject with `TimeoutError` if it takes too long.

retry

Retry unstable async work with delay, backoff factor, and custom retry logic.

debounce

Delay frequent calls until input settles. Useful for search and resize events.

throttle

Limit high-frequency calls from scroll, pointer, and progress events.

redactSensitiveData

Replace sensitive keys and token-like strings with `[REDACTED]`.

detectSecrets

Find sensitive values and return masked previews without exposing the raw value.

assertNoSecrets

Throw `SensitiveDataError` when a payload contains sensitive data.

safeJsonStringify

Stringify circular data safely while redacting secrets.

createSafeLogger

Console-style logger that redacts every argument before writing.

maskSecret

Create masked secret previews with no raw characters shown by default.

createSecureId

Generate crypto-safe request IDs, trace IDs, and session-safe identifiers.

constantTimeEqual

Compare strings without returning early at the first different character.

sanitizeHeaders

Prepare request or response headers for logs by redacting private fields.

sanitizeUrl

Redact query params, credentials, and token-like values before logging URLs.

createRateLimiter

In-memory rate limiting by key with `consume`, `assert`, `reset`, and snapshots.

createCircuitBreaker

Open after repeated failures and recover through a half-open test call.

safeFetch

Origin-guarded fetch with timeout support and redacted request metadata.

Realtime

State, events, polling, and heartbeat

The realtime helpers are meant for dashboards, bots, small services, worker loops, browser apps, and local tools that need live updates without a heavy framework.

Recommended use

  • Use `createRealtimeStore` for shared state.
  • Use `createEventBus` for app messages.
  • Use `createPoller` for repeated async checks.
  • Use `createHeartbeat` for liveness signals.

Timing

Control async work and frequent input

Timing helpers keep small apps predictable: abort delays, cap slow work, retry unstable operations, and reduce noisy UI event handlers.

Timing helpers
await sleep(500);
await timeout(fetch("https://api.github.com"), 3000);
await retry(loadData, { retries: 3, delay: 500, factor: 2 });

Safety

Redact first, then log

Safety helpers are built around one rule: keep structure, remove secrets. They protect common keys like `token`, `password`, `authorization`, `cookie`, `secret`, `apiKey`, and private key fields.

Safe logger
const logger = createSafeLogger(console);

logger.info("request", {
  user: "shnwazdeveloper",
  token: "private-token"
});

Repo safety checks

  • `npm run secret:check` scans source and docs.
  • `npm run safe:check` runs secret scan, tests, and pack dry-run.
  • CI runs safety checks on pushes and pull requests.
  • The publish workflow checks secrets before `npm publish`.

Resilience

Safer calls under pressure

These helpers reduce repeated abuse, stop retry storms, and keep request logs useful without exposing tokens or private headers.

safeFetch
const result = await safeFetch("https://api.github.com", {
  allowedOrigins: ["https://api.github.com"],
  timeout: 3000
});

logger.info("request", result.safeRequest);
Rate limit and circuit breaker
const limiter = createRateLimiter({ limit: 5, interval: 60000 });
limiter.assert("user:shnwazdeveloper");

const breaker = createCircuitBreaker(loadData, {
  failureThreshold: 3,
  recoveryTime: 30000
});

await breaker.execute();

Publishing

Release to GitHub Packages

New versions publish when a version tag is pushed. The workflow installs, checks for secrets, runs tests, and publishes with GitHub's package token.

  1. Edit code or docs.
  2. Update `version` in `package.json`.
  3. Run `npm run safe:check`.
  4. Commit and push `main`.
  5. Push a tag like `v0.4.0`.
  6. GitHub Actions publishes the package.

Troubleshooting

Common install and publish issues

npm 404 from registry.npmjs.org

npm is using the wrong registry. Set the GitHub Packages scope registry.

npm config set "@shnwazdeveloper:registry" "https://npm.pkg.github.com" --location=user
npm 401 Unauthorized

npm needs a GitHub token with `read:packages`.

gh auth refresh -h github.com -s read:packages
$token = gh auth token
npm config set "//npm.pkg.github.com/:_authToken" "$token" --location=user
Package version already exists

GitHub Packages does not republish the same version. Increase `package.json` and push a matching new tag.

Secret check fails

Remove the secret from source/docs. Use placeholders that do not look like real tokens, then run `npm run safe:check` again.