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

@natiwo/core

v0.1.0

Published

NATIWO Core - Types, utils e constantes compartilhadas

Readme

@natiwo/core

Core utilities, types, and error handling for TypeScript applications

npm version License: MIT

Installation

pnpm add @natiwo/core
# or
npm install @natiwo/core
# or
yarn add @natiwo/core

Features

  • 🎯 Result Pattern - Type-safe error handling without exceptions
  • Validation - Schema validation with Zod integration
  • 🛡️ Enhanced Errors - Rich error classes with context
  • 🔧 Utilities - 130+ utility functions (strings, arrays, objects, dates)
  • 📝 Types - Common TypeScript types and utilities

Quick Start

Result Pattern

import { Result } from '@natiwo/core';

// Wrap async operations
const result = await Result.from(
  fetch('https://api.example.com/users')
);

if (result.isOk()) {
  const data = result.unwrap();
  console.log(data);
} else {
  const error = result.unwrapErr();
  console.error(error);
}

// Chain operations
const processed = await Result.from(getUserById(id))
  .map(user => user.name)
  .mapErr(err => new CustomError('User fetch failed', err));

Validation

import { validate, schemas } from '@natiwo/core';
import { z } from 'zod';

const UserSchema = z.object({
  email: z.string().email(),
  age: z.number().min(18),
});

const result = validate(UserSchema, {
  email: '[email protected]',
  age: 25,
});

if (result.isOk()) {
  const user = result.unwrap(); // Type-safe!
}

Utility Functions

import { sleep, retry, chunk, pick, omit } from '@natiwo/core';

// Async utilities
await sleep(1000);
const data = await retry(() => fetchData(), { retries: 3 });

// Array utilities
const chunks = chunk([1, 2, 3, 4, 5], 2); // [[1,2], [3,4], [5]]

// Object utilities
const subset = pick(user, ['id', 'name']);
const filtered = omit(user, ['password']);

Enhanced Errors

import { 
  ApplicationError, 
  ValidationError, 
  NotFoundError 
} from '@natiwo/core/errors';

throw new NotFoundError('User not found', { userId: '123' });

throw new ValidationError('Invalid email', {
  field: 'email',
  value: 'invalid',
});

API Reference

Result<T, E>

Type-safe wrapper for operations that may fail.

Methods:

  • isOk(): boolean - Check if result is successful
  • isErr(): boolean - Check if result is error
  • unwrap(): T - Get value (throws if error)
  • unwrapErr(): E - Get error (throws if ok)
  • unwrapOr(defaultValue: T): T - Get value or default
  • map<U>(fn: (value: T) => U): Result<U, E> - Transform value
  • mapErr<F>(fn: (error: E) => F): Result<T, F> - Transform error

Static Methods:

  • Result.ok<T>(value: T) - Create success result
  • Result.err<E>(error: E) - Create error result
  • Result.from<T>(promise: Promise<T>) - Wrap async operation

Utilities

String:

  • capitalize(str) - Capitalize first letter
  • slugify(str) - Convert to URL-safe slug
  • truncate(str, length) - Truncate with ellipsis
  • camelCase(str), snakeCase(str), kebabCase(str) - Case conversion

Array:

  • chunk(array, size) - Split into chunks
  • unique(array) - Remove duplicates
  • groupBy(array, key) - Group by property
  • shuffle(array) - Randomize order

Object:

  • pick(obj, keys) - Select properties
  • omit(obj, keys) - Exclude properties
  • deepMerge(obj1, obj2) - Deep merge objects
  • isEmpty(obj) - Check if empty

Date:

  • formatDate(date, format) - Format date
  • addDays(date, days) - Add days
  • diffDays(date1, date2) - Difference in days

Async:

  • sleep(ms) - Async delay
  • retry(fn, options) - Retry with backoff
  • timeout(promise, ms) - Add timeout to promise

Validation

import { validate, ValidationError } from '@natiwo/core';

const result = validate(schema, data);
// Returns Result<T, ValidationError>

Brazilian Utilities

import { validateCPF, validateCNPJ, formatCPF } from '@natiwo/core';

const isValid = validateCPF('123.456.789-00');
const formatted = formatCPF('12345678900'); // '123.456.789-00'

TypeScript Types

import type { 
  DeepPartial,
  DeepRequired,
  Prettify,
  Constructor,
  AsyncFunction,
  Nullable
} from '@natiwo/core/types';

type User = {
  id: string;
  profile: {
    name: string;
    email: string;
  };
};

type PartialUser = DeepPartial<User>;
// All properties optional, recursively

Best Practices

  1. Always use Result for operations that may fail

    // ❌ Bad
    async function getUser(id: string) {
      return await db.user.findUnique({ where: { id } });
    }
    
    // ✅ Good
    async function getUser(id: string) {
      return await Result.from(
        db.user.findUnique({ where: { id } })
      );
    }
  2. Validate user input

    const result = validate(CreateUserSchema, req.body);
    if (result.isErr()) {
      return res.status(400).json({ error: result.unwrapErr() });
    }
  3. Use utility functions to avoid reinventing the wheel

    // ❌ Bad
    const names = users.map(u => u.name).filter((n, i, a) => a.indexOf(n) === i);
    
    // ✅ Good
    const names = unique(users.map(u => u.name));

License

MIT © NATIWO Sistemas