open-index/open-npm huggingface dataset:
npm package: @ohfc/deferred
Description: Promise based defer-pattern, promises without the callbacks.
Author: m10rten
Latest version: 0.0.1

# `@ohfc/deferred`

A lightweight TypeScript Deferred utility class for creating promises with externally accessible `resolve` and `reject` methods, along with helpful state introspection.

---

## Installation

```
npm install @ohfc/deferred
```

---

## Usage

```ts
import { Deferred } from "@ohfc/deferred";

async function main() {
  const deferred = new Deferred<number>();

  // Somewhere else, resolve or reject:
  setTimeout(() => deferred.resolve(42), 1000);

  // Await deferred promise
  const result = await deferred.promise;
  console.log(result); // 42

  console.log("Resolved?", deferred.isResolved); // true
  console.log("Rejected?", deferred.isRejected); // false
}

main();
```

---

## API

### `class Deferred<T = void>` (export & export default)

**Properties:**

- `promise: Promise<T>`
  The underlying promise to await.

- `resolve(value: T | PromiseLike<T>): void`
  Resolves the `promise` with given value.

- `reject(reason: unknown): void`
  Rejects the `promise` with given reason.

- `isResolved: boolean` _(readonly)_
  Whether the promise has been resolved.

- `isRejected: boolean` _(readonly)_
  Whether the promise has been rejected.

- `isPending: boolean` _(readonly)_
  Whether the promise is still pending (neither resolved nor rejected).

---

## Features

- Full TypeScript support and typings.
- Externally controlled promise resolution and rejection.
- Introspect promise state for debugging or conditional logic.
- Lightweight with zero dependencies.
- Ideal for async coordination, event promisification, and deferred control flow.

---

## License

MIT License
npm package: @ohfc/once
Description: A tiny utility to ensure a function is called only once.
Author: m10rten
Latest version: 0.0.3

# @ohfc/once

A tiny utility to ensure a function is called only once. Subsequent calls return the first result. Fully typed, zero dependencies.

## 📦 Install

```bash
pnpm add @ohfc/once
# or
npm install @ohfc/once
# or
yarn add @ohfc/once
```

## 🚀 Usage

```ts
import { once } from "@ohfc/once";

const init = once(() => {
  console.log("Initialized!");
  return 42;
});

init(); // Logs 'Initialized!' and returns 42
init(); // Returns 42, does nothing
```

## 📖 API

`once(callback)`

- callback: `Function` <br>
  The function to wrap — it will only run once.
- returns: `Function` <br>
  A wrapped function that calls the original callback only once and caches its result.

## ✅ Features

- Zero dependencies
- Fully typed (TypeScript)
- Small and fast

## 📝 License

MIT
npm package: @ohfc/signal
Description: To the point reactive values anywhere with signals.
Author: m10rten
Latest version: 0.0.2

# `@ohfc/signal`

Reactive values you can read, update, and observe. Subscribe to changes and react when the value updates. Lightweight and easy to use.

## 📦 Install

```bash
pnpm add @ohfc/signal
# or
npm install @ohfc/signal
# or
yarn add @ohfc/signal
```

## 🚀 Usage

```ts
import { signal } from "@ohfc/signal";

const count = signal(0);

const unsubscribe = count.subscribe((value) => {
  console.log("Count is now:", value);
});

count.set(1); // Logs: Count is now: 1
count.set(2); // Logs: Count is now: 2

unsubscribe();
count.set(3); // No log
```

## 📖 API

### `signal(initialValue)`

- **initialValue**: `any`  
  The starting value for the signal.

- **returns**: `Signal`  
  An object with methods to interact with the reactive value.

### `Signal`

A signal instance exposes:

- `get(): T`  
  Returns the current value.

- `set(value: T): void`  
  Updates the value. Notifies all subscribers if the value changes.

- `subscribe(callback: (value: T) => void): () => void`  
  Subscribes to value changes. The callback is immediately called with the current value and again whenever the value changes. Returns an unsubscribe function.

  If a subscriber becomes unreachable (for example, if its reference goes out of scope and is garbage collected), it is automatically unsubscribed and will no longer be called on future updates.

## ✅ Features

- Reactive value container
- Subscribe to changes with unsubscribe support
- Immediate notification on subscription
- Automatic cleanup of unreachable subscribers
- No dependencies
- Typed with TypeScript

## 📝 License

MIT
npm package: @ohfc/time-ago
Description: <description>
Author: m10rten
Latest version: 0.0.1

# `@ohfc/time-ago`

A minimal, dependency-free utility to format dates and timestamps as "time ago" or "in X" strings, supporting both Node.js and browser environments.

## Installation

```bash
npm install @ohfc/time-ago
```

## Features

- Converts dates, timestamps, or ISO strings to readable relative time (e.g., `"2 days ago"`, `"in 5 minutes"`)
- Supports both **Node.js** and **browser**
- Localizable using native `Intl.RelativeTimeFormat`
- No dependencies
- Tiny footprint

## Usage

```ts
import timeAgo from "@ohfc/time-ago";

// 1 minute ago, assuming Date.now()
console.log(timeAgo(Date.now() - 60 * 1000)); // "1 minute ago"

// In 2 hours
console.log(timeAgo(Date.now() + 2 * 60 * 60 * 1000)); // "in 2 hours"

// Pass a Date or ISO string
console.log(timeAgo(new Date(Date.now() - 86400000))); // "yesterday"
console.log(timeAgo("2025-09-06T12:00:00Z")); // relative to now

// Use a different locale
console.log(timeAgo(Date.now() - 3600 * 1000, "fr")); // "il y a 1 heure"
```

## API

### `timeAgo(input, locales?)`

| Parameter | Type                              | Description                                             |
| --------- | --------------------------------- | ------------------------------------------------------- |
| `input`   | `number \| string \| Date`        | The date value: timestamp, ISO string, or `Date` object |
| `locales` | `Intl.LocalesArgument` (optional) | Optional BCP-47 locale string (defaults to `"en"`)      |

**Returns:**  
A string with the relative time, such as `"5 minutes ago"` or `"tomorrow"`.

**Throws:**  
`TypeError` if input is not provided or invalid.

---

This README enables quick installation, highlights the main features, shows how to use all API options, and documents the accepted input types and method signature—all essential for an npm package introduction.[2][4]

[1](https://spin.atomicobject.com/valuable-readme/)
[2](https://blog.bitsrc.io/writing-the-perfect-reademe-for-your-node-library-2d5f24dc1c06)
[3](https://github.com/othneildrew/Best-README-Template)
[4](https://docs.npmjs.com/about-package-readme-files/)
[5](https://www.makeareadme.com)
[6](https://stackoverflow.com/questions/28595114/how-do-i-manage-my-packages-readme-on-npmjs-com)
[7](https://snyk.io/blog/best-practices-create-modern-npm-package/)
[8](https://gist.github.com/andreasonny83/7670f4b39fe237d52636df3dec49cf3a)
[9](https://docs.npmjs.com/files/package.json/)
[10](https://www.totaltypescript.com/how-to-create-an-npm-package)
npm package: @ohfc/tiny-bus
Description: A tiny, typed event bus for in-process publish/subscribe event handling in browser and Node.js environments.
Author: m10rten
Latest version: 0.0.1

# @ohfc/tiny-bus

A tiny, typed event bus for in-process publish/subscribe event handling. Works in both browser and Node.js (within the same runtime). No cross-environment communication. Fully typed, zero dependencies.

## 📦 Install

```bash
pnpm add @ohfc/tiny-bus
# or
npm install @ohfc/tiny-bus
# or
yarn add @ohfc/tiny-bus
```

## 🚀 Usage

```ts
import { TinyBus } from "@ohfc/tiny-bus";

type AppEvents = {
  "user:login": { userId: string };
  "message:received": { from: string; content: string };
};

const bus = new TinyBus<AppEvents>();

const onLogin = (payload: { userId: string }) => {
  console.log(`User logged in: ${payload.userId}`);
};

bus.on("user:login", onLogin);

bus.emit("user:login", { userId: "abc123" });

bus.off("user:login", onLogin);

bus.clear();
```

## 📖 API

### `new TinyBus<EventMap>()`

Creates a new event bus instance.

- `EventMap`: `Record<string, unknown>`  
  An object type defining valid event names and their payload shapes.

---

### `.on(eventName, handler)`

Registers a handler for a specific event.

- `eventName`: `keyof EventMap`
- `handler`: `(payload: EventMap[eventName]) => void | Promise<void>`

The `handler` accepts a Promise, but this is not awaited for simplicity, use with caution as any error will likely cause unhandled rejections.

---

### `.off(eventName, handler)`

Removes a previously registered handler.

- `eventName`: `keyof EventMap`
- `handler`: `(payload: EventMap[eventName]) => void`

---

### `.emit(eventName, payload)`

Calls all handlers registered for the event with the provided payload.

- `eventName`: `keyof EventMap`
- `payload`: `EventMap[eventName]`

---

### `.clear(eventName?)`

Removes all handlers for a specific event, or for all events if no name is given.

- `eventName?`: `keyof EventMap`

## ✅ Features

- Zero dependencies
- Fully typed (TypeScript)
- In-process only (browser or Node.js)
- Small, fast, and simple

## 📝 License

MIT
npm package: @ohfuck/isse
Description: 用于Bun和浏览器的轻量级且灵活的EventSource/SSE库; A lightweight and flexible EventSource/SSE library for Node.js and the browser
Author: fuck_god
Latest version: 0.0.1

# @ohfuck/isse

## 介绍
    
Server-Sent Events (SSE) 是一种基于 HTTP 协议的轻量级的、可靠的、基于事件的通信协议。它允许服务器向客户端推送数据，而无需客户端发起请求。

本库提供了 SSE 协议的实现，可以方便地与其他 HTTP 服务器进行通信。可在以下环境中运行：

- Bun
- Node
- express
- 浏览器

## 安装
```bash
npm install @ohfuck/isse # or bun add @ohfuck/isse
```

## 使用
本库包含以下子包，根据情况按需从`ohfuck/isse`导入：
- `SseClient`：SSE 客户端，用于向服务器发送请求并接收数据
- `SseBunServer`：Bun 服务器端，用于处理 SSE 请求并向客户端推送数据
- `SseNodeServer`：Node 服务器端，用于处理 SSE 请求并向客户端推送数据
- `SseExpressServer`：express 服务器端，用于处理 SSE 请求并向客户端推送数据

### SseClient
客户端，在前端中使用，向服务器发送 SSE 请求并接收数据。使用方式如下：
```typescript
import { SseClient } from "@ohfuck/isse";

const sse_client = new SseClient({
    url: "http://localhost:8080/sse",
})

// 连接成功后，服务端会固定传回一个connected消息，表示连接成功，msg为客户端id
sse_client.add_listener("connected", (msg) => {
    console.log('sse connected', msg)
})

// 可监听自定义事件，接收到demo1消息时，打印消息内容
sse_client.add_listener("demo1", (msg) => {
    console.log('this is demo1', msg)
})

// 可定义msg的类型，也可以通过返回值进行取消订阅
let unsubscripe = sse_client.add_listener<string>('demo2', (msg) => {
    console.log('this is demo2, the msg type is string', msg)
    unsubscripe()
})
```

### SseBunServer
Bun 服务器端，用于处理 SSE 请求并向客户端推送数据。使用方式如下：
```typescript
import { SseBunServer } from "@ohfuck/isse";

const app = new SseNodeServer({
    port: 8080,
    prefix: '/sse'
})
```


### SseNodeServer
Node 服务器端，用于处理 SSE 请求并向客户端推送数据。使用方式如下：
```typescript
import { SseNodeServer } from "@ohfuck/isse";

const app = new SseNodeServer({
    port: 8080,
    prefix: '/sse'
})
```

### SseExpressServer
express 服务器端，用于处理 SSE 请求并向客户端推送数据。使用方式如下：
```typescript
import { SseExpressServer } from "@ohfuck/isse";
import express from "express";
    
const app = express()

app.use(new SseExpressServer({
    prefix: '/sse'
}).start)

app.get('/abc', (req, res) => {
    req['__sse__'].broadcast('connected', 'abc')
    res.send('abc')
})

app.listen(8080, () => {
    console.log('SSE server started at http://localhost:8080/sse')
})
```

**请注意：**
关于在ts中`req['__sse__']`的类型提示问题，可创建一个类型声明文件(`xxx.d.ts`)，并写入以下内容即可：
```typescript
import "@ohfuck/isse/dist/types/types/express"
```

### 实例方法
- `broadcast(type: string, data: any)`：向所有连接的客户端广播消息
- `notify(client_id: string, type: string, msg: any)`：向指定客户端发送消息
>关于`type`字段：自定义事件类型，可以自定义，建议使用英文单词，同时避免与系统事件类型冲突。

```typescript
// 向所有客户端广播一条类型为'connected'的消息
sse_client.broadcast('connected', 'this is a message')

// 向指定客户端发送一条类型为'demo1'的消息
sse_client.notify('client_id', 'demo1', 'this is a message')
```


## 二次开发

### 拉取代码
```bash
git clone https://github.com/839900146/fuck-websocket.git
```

### 安装依赖
```bash
bun install
```

### 启动前端
```bash
npm run start -w @ohfuck/isse
```

### 启动后端
请根据上面所说的文档，自行创建一个服务器进行测试

### 编译代码
```bash
npm run build -w @ohfuck/isse
```