open-index/open-npm huggingface dataset:
npm package: @feelai/cf-worker
Description: A lightweight, type-safe wrapper for Cloudflare Workers that integrates seamlessly with `@feelai/contract`.
Latest version: 1.1.0

# @feelai/cf-worker

A lightweight, type-safe wrapper for Cloudflare Workers that integrates seamlessly with `@feelai/contract`.

## Features

- **Type Safety**: Full TypeScript support with type inference from your contracts.
- **Contract-First**: automatically validates inputs against your TypeBox schemas.
- **Middleware**: Support for `beforeRequest`, `beforeResponse`, and `beforeStream` hooks.
- **Protocols**: Easy handling of HTTP APIs, Server-Sent Events (Streams), and WebSockets.

## Installation

```bash
bun add @feelai/cf-worker
```

## Usage

### 1. Define your Contract

First, ensure you have a contract defined using `@feelai/contract`.

```typescript
// contract.ts
import { Contract, defineApiMap } from "@feelai/contract";
import { Type } from "typebox";

const api = defineApiMap({
  "/api/hello": {
    input: Type.Object({ name: Type.String() }),
    output: Type.Object({ message: Type.String() }),
  },
});

export const myContract = new Contract().api(api);
```

### 2. Initialize the Worker

Create a worker instance passing your contract.

```typescript
// worker.ts
import { CfWorker } from "@feelai/cf-worker";
import { myContract } from "./contract";

export interface Env {
  // Your Cloudflare bindings
  kv: KVNamespace;
}

export const worker = new CfWorker<typeof myContract, Env>(myContract);
```

### 3. Register Handlers

Implement the logic for your defined routes. The `input` and `output` types are automatically inferred.

```typescript
// handlers.ts
import { worker } from "./worker";

worker.fetch("/api/hello", async ({ input, env }) => {
  return {
    message: `Hello, ${input.name}!`,
  };
});
```

### 4. Export the Worker

Finally, export the `fetch` handler in your main entry file.

```typescript
// index.ts
import { worker } from "./worker";
import "./handlers"; // Import to register handlers

export default {
  fetch: (req, env, ctx) => {
    return worker.handleRequest(req, env, ctx);
  },
};
```

## Middleware

You can add middleware to intercept requests and responses, for example, to handle CORS or Authentication.

```typescript
worker
  .beforeRequest((req, env, ctx) => {
    // Check auth, CORS preflight, etc.
    if (req.method === "OPTIONS") {
      return new Response(null, { status: 204 });
    }
  })
  .beforeResponse((res, req, env, ctx) => {
    // Add CORS headers
    res.headers.set("Access-Control-Allow-Origin", "*");
    return res;
  });
```

## Stream & Socket

The worker also supports Stream and Socket handlers if your contract defines them.

```typescript
// Stream
worker.stream("streamRoute", async ({ stream, input }) => {
  stream.emit("event", { data: "foo" });
});

// Socket
worker.socket("socketRoute", async ({ req, env, ctx }) => {
  // Handle WebSocket upgrade
  // ...
});
```
npm package: @feelai/stream
Description: A utility library providing a powerful wrapper around `TypedEventEmitter`. It enhances standard event emitters with promise-based event waiting, cancellation support, and a fluent API.
Latest version: 1.1.0

# @feelai/stream

A utility library providing a powerful wrapper around `TypedEventEmitter`. It enhances standard event emitters with promise-based event waiting, cancellation support, and a fluent API.

## Features

- **Promise-based Event Handling**: Wait for specific events using `waitFor(event)`, returning a Promise so you can `await` it.
- **Cancellation**: Built-in `AbortController` support to cancel pending operations with `cancel()`.
- **Type Safety**: Built on top of `typed-emitter` for full TypeScript support.
- **Fluent API**: Chainable `on`, `off`, and `once` methods.
- **Completion Helpers**: `finish()` and `done()` methods to easily await the end of a stream.

## Usage

```typescript
import { createStream } from "@feelai/stream";
import { EventEmitter } from "events";
import TypedEventEmitter from "typed-emitter";

// Define your events
type MyEvents = {
  data: (chunk: string) => void;
  error: (err: Error) => void;
  end: () => void;
};

// Create a typed emitter
const myEmitter = new EventEmitter() as TypedEventEmitter<MyEvents>;

// Wrap it with createStream
const stream = createStream(myEmitter);

// Using standard event listeners (chainable)
stream.on("data", (chunk) => console.log("Received:", chunk)).once("end", () => console.log("Stream ended"));

// Using async/await
async function processStream() {
  try {
    // Wait for a specific event
    const [chunk] = await stream.waitFor("data");
    console.log("First chunk:", chunk);

    // Wait for stream completion
    await stream.finish();
    console.log("Done!");
  } catch (err) {
    console.error("Stream error or cancelled:", err);
  }
}

processStream();

// Cancellation
// stream.cancel(); // This will reject any pending waitFor promises
```

## API Reference

### `createStream(emitter)`

Creates a new `Stream` instance wrapping the provided `TypedEventEmitter`.

### Class `Stream<EM>`

#### Methods

- `constructor(emitter: TypedEventEmitter<EM>)`
- `on(event, listener)`: Register a listener. Returns `this`.
- `off(event, listener)`: Remove a listener. Returns `this`.
- `once(event, listener)`: Register a one-time listener. Returns `this`.
- `waitFor(event)`: Returns a `Promise` that resolves with the event arguments when the event is emitted. Rejects if the stream emits "error" or is cancelled.
- `cancel()`: Aborts the internal controller and rejects all pending `waitFor` promises.
- `finish()` / `done()`: Returns a `Promise` that resolves when the "end" event is emitted.