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

@kvishal04/library-core

v1.0.0

Published

Reusable backend utility library with validation, encryption, sessions, and response helpers.

Readme

@kvishal04/library-core

Reusable TypeScript utility library for backend applications.

Install

npm install @kvishal04/library-core

Node Version

  • Node.js 18 or above is recommended.

Quick Start

import {
	validator,
	ResponseHandler,
	SessionManager,
	HTTP_RESPONSE_CODE,
} from '@kvishal04/library-core';

Environment Setup

Set only what your used modules need.

# Encryption
SECRET_KEY=your-secret
SECRET_IV=your-secret-iv
ENCRYPTION_METHOD=aes-256-cbc

# GeoLocation
GOOGLE_MAPS_API_KEY=your-google-api-key

# Session store location (optional)
PROJECT_ROOT=/absolute/project/path

# DB module
DB_CONFIG=[{"CONNECTION_NAME":"master","DB_TYPE":"mysql","CONFIG":{"SERVER_NAME":"localhost","PORT":3306,"USERNAME":"root","PASSWORD":"pass","DATABASE":"appdb"}}]

# Cron scheduler
CRON_JOBS=[{"JOB_NAME":"refresh-cache","CRON_EXPRESSION":"*/5 * * * *","url":"http://localhost:3000/internal/refresh","method":"POST","headers":{"authorization":"Bearer token"},"body":{}}]

Exported Features

  • Constants and enums
  • Validator
  • ResponseHandler
  • SessionManager
  • Encryption helpers
  • GeoLocation
  • ExcelUtil
  • Image resizer
  • Cron scheduler helper
  • DB module
  • Spreadsheet module
  • ConfigManager module
  • Connectors loader
  • AppConfig singleton
  • Middleware helpers (auth, multipart, system/core/app middleware, error handler)
  • System config-manager router
  • System application helpers (CORS, controller, request context, render/util)
  • Utility helpers (HttpError, throwError, validateBodyForSpecialCharacter)
  • Core response type aliases (CoreJsonResponse, CoreBufferResponse, CoreRenderResponse, CoreServiceResponse)
  • Session store alias (SessionStore)

Detailed Usage

1) Constants

import { HTTP_RESPONSE_CODE, Operators, ActionType } from '@kvishal04/library-core';

if (code === HTTP_RESPONSE_CODE.SUCCESS) {
	// success branch
}

const filter = { operator: Operators.And, action: ActionType.login };

2) Validator

import { validator } from '@kvishal04/library-core';

const schema = {
	required: ['name', 'email'],
	string: ['name'],
	email: ['email'],
	number: ['age'],
};

const payload = {
	name: 'Vishal',
	email: '[email protected]',
	age: 28,
};

validator.validate(payload, schema);

3) ResponseHandler (Express)

import { ResponseHandler } from '@kvishal04/library-core';

export function getProfile(_req: any, res: any) {
	return ResponseHandler.success(res, 200, 'Profile fetched', { id: 'u_101' });
}

export function createUser(_req: any, res: any) {
	return ResponseHandler.validationError(res, 'Validation failed', {
		email: 'Invalid email',
	});
}

4) SessionManager

import { SessionManager } from '@kvishal04/library-core';

const sessionId = SessionManager.createSession(
	'user-123',
	{
		userAgent: req.headers['user-agent'],
		acceptLanguage: req.headers['accept-language'],
		ipAddress: req.ip,
	},
	'my-app'
);

const result = SessionManager.validateSession(
	sessionId,
	{
		userAgent: req.headers['user-agent'],
		acceptLanguage: req.headers['accept-language'],
		ipAddress: req.ip,
	},
	'my-app'
);

if (!result.valid) {
	// handle invalid session
}

5) Encryption

import { encryptData, decryptData } from '@kvishal04/library-core';

const encrypted = encryptData({ userId: 'user-123' });
const decrypted = decryptData(encrypted);

6) GeoLocation

import { GeoLocation } from '@kvishal04/library-core';

const latLng = await GeoLocation.getLatLngFromAddress(
	'My Office',
	'MG Road',
	'Karnataka',
	'Bengaluru',
	'India'
);

const fullData = await GeoLocation.getGeoDataFromAddress(
	'My Office',
	'MG Road',
	'Karnataka',
	'Bengaluru',
	'India',
	process.env.MY_RUNTIME_MAP_KEY
);

7) ExcelUtil

import { ExcelUtil } from '@kvishal04/library-core';

const buffer = await ExcelUtil.createExcelBuffer([
	{ id: 1, name: 'A' },
	{ id: 2, name: 'B' },
]);

const multiBuffer = await ExcelUtil.createMultiSheetExcelBuffer([
	{ sheetName: 'Users', data: [{ id: 1, name: 'Vishal' }] },
	{ sheetName: 'Orders', data: [{ orderId: 'O1', amount: 1200 }] },
]);

8) Image Resizer

import { resizeImageFromUrl } from '@kvishal04/library-core';

const blobs = await resizeImageFromUrl({
	baseImageUrl: 'https://example.com/image.jpg',
	sizes: [64, 128, 256],
	options: {
		fit: 'contain',
		quality: 90,
		compressionLevel: 6,
	},
});

// blobs['64x64'] -> Blob

9) Cron Scheduler

import { scheduleTaskSchedulerJob } from '@kvishal04/library-core';

scheduleTaskSchedulerJob();

This reads CRON_JOBS from environment and schedules each valid cron expression.

10) DB Module

import { DB } from '@kvishal04/library-core';

const db = DB.connect('master');
const rows = await db.raw('SELECT 1 AS ok');

const health = await DB.status('master');

11) Spreadsheet Module

import { SpreadsheetService } from '@kvishal04/library-core';

const svc = new SpreadsheetService();

await svc.createFile('exports/report.xlsx', {
	sheets: [
		{
			name: 'Report',
			rows: [
				{ id: 1, name: 'A' },
				{ id: 2, name: 'B' },
			],
		},
	],
	freezeHeader: true,
	autoFilter: true,
});

const parsed = await svc.readFile('exports/report.xlsx');

If you want API routes:

import express from 'express';
import { SpreadsheetRouter } from '@kvishal04/library-core';

const app = express();
app.use(SpreadsheetRouter);

12) ConfigManager Module

import { ConfigManager, ConfigManagerApiRoutes } from '@kvishal04/library-core';

await ConfigManager.reloadConfigs();
const cfg = ConfigManager.getConfig('notify/email/gmail.config');

ConfigManager.on('config:reloaded', ({ key }) => {
	console.log('Config reloaded:', key);
});

Mount API routes:

import express from 'express';
import { ConfigManagerApiRoutes } from '@kvishal04/library-core';

const app = express();
app.use('/config-manager', ConfigManagerApiRoutes);

13) Connectors Loader

import { Connectors } from '@kvishal04/library-core';

const connector = Connectors.load('payments');

14) AppConfig Singleton

import { AppConfig } from '@kvishal04/library-core';

AppConfig.set('APP_CONFIG_ROOT', 'C:/configs');
const root = AppConfig.get<string>('APP_CONFIG_ROOT');

15) CORS Setup Helper

import express from 'express';
import { configureAppCors } from '@kvishal04/library-core';

const app = express();

app.use(
	configureAppCors({
		debug: false,
		routes: [],
		cors: {
			allowedOrigins: ['http://localhost:3000'],
			allowCredentials: true,
			maxAge: 86400,
		},
		allowedMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
		allowedHeaders: ['Content-Type', 'Authorization'],
	})
);

16) ApiController and RequestContext

import { ApiController, RequestContext } from '@kvishal04/library-core';

RequestContext.run(() => {
	RequestContext.set('requestId', 'req-123');
});

const controller = new ApiController({
	debug: true,
	routes: [],
	cors: {
		allowedOrigins: ['*'],
		allowCredentials: false,
		maxAge: 0,
	},
	allowedMethods: ['POST', 'OPTIONS'],
	allowedHeaders: ['Content-Type'],
});

17) System Response Helper

import { SystemResponse } from '@kvishal04/library-core';

return SystemResponse.JSON({ message: 'ok' }, 200);

18) System Config-Manager Router

import express from 'express';
import { SystemConfigManagerRouter } from '@kvishal04/library-core';

const app = express();
app.use(SystemConfigManagerRouter);

19) Middleware Helpers

import express from 'express';
import {
	applicationMiddleware,
	coreMiddleware,
	systemMiddleware,
	errorHandler,
	multipartAny,
	normalizeMultipartBody,
	verifyJWT,
	sessionAuth,
	generateJWT,
} from '@kvishal04/library-core';

const app = express();

app.use(applicationMiddleware);
app.use(coreMiddleware);
app.use(systemMiddleware);

app.post('/upload', multipartAny, (req, res) => {
	const body = normalizeMultipartBody(req);
	res.json({ status: true, files: body.files?.length || 0 });
});

app.get('/secure', (req, res) => {
	const user = verifyJWT(req);
	if (!sessionAuth('my-app')) {
		return res.status(401).json({ status: false, message: 'Unauthorized' });
	}
	return res.json({ status: true, user });
});

app.use(errorHandler);

const token = generateJWT({ userId: 'u_101' }, '24h');

20) Utility Helpers

import {
	HttpError,
	throwError,
	validateBodyForSpecialCharacter,
	returnDateYYYYMMDD,
} from '@learn/library-core';

const isValid = validateBodyForSpecialCharacter({ name: 'Vishal' });
if (!isValid) {
	throw new HttpError('Invalid payload', 400);
}

const today = returnDateYYYYMMDD(new Date());

21) Core Response Type Aliases

import type { CoreServiceResponse } from '@kvishal04/library-core';

const response: CoreServiceResponse = {
	kind: 'json',
	payload: { ok: true },
	statusCode: 200,
};

Build

npm run build

Publish

npm login
npm publish --access public