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

@chrock-studio/code-block

v0.2.0

Published

A simple code-block wrapper to compose start blocks, body blocks, and end blocks!

Readme

@chrock-studio/code-block

A simple code-block wrapper to compose start blocks, body blocks, and end blocks!

A lightweight TypeScript library for implementing resource management patterns (similar to try-with-resources or using statements), ensuring proper resource cleanup after code execution.

📦 Installation

# Using pnpm
pnpm add @chrock-studio/code-block

# Using npm
npm install @chrock-studio/code-block

# Using yarn
yarn add @chrock-studio/code-block

🚀 Quick Start

import { createBlock } from "@chrock-studio/code-block";

// Create a file operation block
const fileBlock = createBlock(
  // Start function: open file
  (filename: string) => fs.openSync(filename, "r"),
  // End function: close file
  (fd) => fs.closeSync(fd),
);

// Use the block
const content = fileBlock((fd) => fs.readFileSync(fd, "utf-8"), "example.txt");

📖 API Documentation

block(start, end)

Creates a resource management block.

Parameters

| Parameter | Type | Description | | --------- | ---------------------------------- | ---------------------------------------------------------------- | | start | (...args: unknown[]) => unknown | Start function to initialize resources and return a cache object | | end | (cache, result?, error?) => void | Cleanup function called after the code block execution completes |

Return Value

Returns a function that accepts:

  • body: Body function that receives the cache object and returns a result
  • ...args: Arguments passed to the start function

end Function Parameters

| Parameter | Type | Description | | --------- | ------------------- | --------------------------------------------------------- | | cache | ReturnType<Start> | Resource object returned by the start function | | result | unknown | Return value of the body function (if execution succeeds) | | error | unknown | Error thrown by the body function (if execution fails) |

💡 Usage Examples

File Operations

import { createBlock } from "@chrock-studio/code-block";
import fs from "fs";

const readBlock = createBlock(
  (filename: string) => fs.openSync(filename, "r"),
  (fd) => fs.closeSync(fd),
);

const content = readBlock((fd) => fs.readFileSync(fd, "utf-8"), "example.txt");

Database Transactions

import {  createBlock } from '@chrock-studio/code-block';

const transactionBlock =  createBlock(
  // Start transaction
  () => db.beginTransaction(),
  // End transaction: commit or rollback based on result
  (tx, result, error) => {
    if (error) {
      tx.rollback();
    } else {
      tx.commit();
    }
  }
);

// Execute transaction
await transactionBlock(async (tx) => {
  await tx.query('INSERT INTO users VALUES (?)', [...]);
  await tx.query('UPDATE accounts SET balance = ?', [...]);
});

Performance Timer

import { createBlock } from "@chrock-studio/code-block";

const timerBlock = createBlock(
  // Start timing
  (label: string) => {
    console.time(label);
    return { label, start: Date.now() };
  },
  // End timing
  (cache) => {
    console.timeEnd(cache.label);
    console.log(`Duration: ${Date.now() - cache.start}ms`);
  },
);

// Use timer
timerBlock((cache) => expensiveOperation(), "operation-label");

Lock Management

import { createBlock } from "@chrock-studio/code-block";

const lockBlock = createBlock(
  // Acquire lock
  (lockName: string) => acquireLock(lockName),
  // Release lock
  (lock) => releaseLock(lock),
);

// Use lock
lockBlock((lock) => {
  // Execute code that requires synchronization
  return criticalSection();
}, "my-resource-lock");

HTTP Request Tracing

import { createBlock } from "@chrock-studio/code-block";

const requestBlock = createBlock(
  // Start tracing
  (requestId: string) => {
    console.log(`[${requestId}] Request started`);
    return { requestId, startTime: Date.now() };
  },
  // End tracing
  (cache, result, error) => {
    const duration = Date.now() - cache.startTime;
    if (error) {
      console.log(`[${cache.requestId}] Request failed in ${duration}ms`);
    } else {
      console.log(`[${cache.requestId}] Request completed in ${duration}ms`);
    }
  },
);

// Use tracing
const response = requestBlock((cache) => fetch("https://api.example.com/data"), "req-123");

Resource Pool Management

import { createBlock } from "@chrock-studio/code-block";

const poolBlock = createBlock(
  // Acquire resource from pool
  () => resourcePool.acquire(),
  // Return resource to pool
  (resource) => resourcePool.release(resource),
);

// Use resource pool
poolBlock((resource) => {
  return resource.doSomething();
});

Batch Processing

import { createBlock } from "@chrock-studio/code-block";

const batch = createBlock(startBatch, endBatch);
const count = batch(() => {
  let count = 0;
  for (const item of items) {
    if (check(item) && modify(item)) {
      count += 1;
    }
  }
  return count;
});

🔄 Execution Flow

┌─────────────────────────────────────────────────────────────┐
│                     block(start, end)                        │
│                         ↓                                   │
│              returns (body, ...args) => Result              │
│                         ↓                                   │
│  ┌──────────────────────────────────────────────────────┐  │
│  │  1. cache = start(...args)     // Initialize resource │  │
│  │  2. try {                                             │  │
│  │       result = body(cache)    // Execute body code   │  │
│  │       return result                                   │  │
│  │     } catch (err) {                                   │  │
│  │       error = err             // Capture error       │  │
│  │       throw err                                       │  │
│  │     } finally {                                       │  │
│  │       end(cache, result, error) // Cleanup resource   │  │
│  │     }                                                 │  │
│  └──────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────┘

🎯 Features

  • Type Safe: Full TypeScript type support
  • Zero Dependencies: Lightweight, no third-party dependencies
  • Resource Management: Ensures proper resource cleanup
  • Error Handling: Automatically handles exceptions
  • Flexible Composition: Supports nesting and multiple calls

📜 License

MIT License

👤 Author

JuerGenie

🏠 Homepage

https://github.com/chrock-studio/toolbox/tree/main/packages/code-block

🤝 Contributing

Contributions are welcome! Please check out the Contributing Guide.