open-index/open-npm huggingface dataset:
npm package: @sntran/html-rewriter
Description: HTMLRewriter for all platforms.
Author: Trần Nguyễn Sơn
Latest version: 0.3.0

# HTMLRewriter

Provides the same HTMLRewriter for all platforms.

## Examples

Rewrite URL links in HTML:

```js
import { HTMLRewriter } from "@sntran/html-rewriter";

export default {
  async fetch(request) {
    const OLD_URL = "developer.mozilla.org";
    const NEW_URL = "mynewdomain.com";

    class AttributeRewriter {
      constructor(attributeName) {
        this.attributeName = attributeName;
      }
      element(element) {
        const attribute = element.getAttribute(this.attributeName);
        if (attribute) {
          element.setAttribute(
            this.attributeName,
            attribute.replace(OLD_URL, NEW_URL),
          );
        }
      }
    }

    const rewriter = new HTMLRewriter()
      .on("a", new AttributeRewriter("href"))
      .on("img", new AttributeRewriter("src"));

    const res = await fetch(request);
    const contentType = res.headers.get("Content-Type");

    // If the response is HTML, it can be transformed with
    // HTMLRewriter -- otherwise, it should pass through
    if (contentType.startsWith("text/html")) {
      return rewriter.transform(res);
    } else {
      return res;
    }
  },
};
```
npm package: @sntran/lol-html
Description: Streaming HTML rewriter/parser with CSS selector-based API
Latest version: 2.7.1

# LOL HTML JavaScript API

## Example

```js
'use strict';

const { HTMLRewriter } = require('lol-html'); // path/to/lol-html.js

const chunks = [];
const rewriter = new HTMLRewriter('utf8', (chunk) => {
  chunks.push(chunk);
});

rewriter.on('a[href]', {
  element(el) {
    const href = el
      .getAttribute('href')
      .replace('http:', 'https:');
    el.setAttribute('href', href);

    el.onEndTag((tag)=> {
      console.log(`Tag ended: ${tag.name}`);
    });
  },
});

[
  '<div><a href=',
  'http://example.com>',
  '</a></div>',
].forEach((part) => {
  rewriter.write(Buffer.from(part));
});

rewriter.end();

const output = Buffer.concat(chunks).toString('utf8');
console.log(output);
```

## Building

```bash
rustup update # https://rustup.rs
cargo install wasm-pack

wasm-pack build --target nodejs --release
```
npm package: @sntran/serve
Description: Cross-runtime HTTP server
Author: Trần Nguyễn Sơn
Latest version: 0.0.3

# serve

Provides a common HTTP server API for all runtimes. Currently supports Node.js,
Deno, Bun, and Cloudflare Workers (no-op).

## Why?

Different runtimes have different APIs for creating HTTP servers. For Node.js,
`http.createServer` takes a handler with its own incoming and outgoing message
objects. `Deno.serve` takes a handler with web standard `Request` and `Response`
objects. `Bun.serve` takes an object with a `fetch` method, similar to
Cloudflare Workers. Workers, however, handle the serving.

This library takes the most common denominator of these APIs and provides a
`serve` API that can be used across all runtimes. Similar to Bun and Cloudflare
Workers, it takes an object with `fetch` function. The abstration across
runtimes are handled by conditional exports defined in `package.json`.

The default uses Node.js's `http.createServer` and normalizes the incoming and
outgoing messages to web standard `Request` and `Response` objects, and let
`Deno` polyfill to `Deno.serve`.

A separate export for `Bun` to explicitly use `Bun.serve`.

For Cloudflare Workers, it's a no-op, provided to avoid runtime errors. To
re-use codebase, it is recommend to export the handler object in the `default`
export.

## Examples

```js
import { serve } from "@sntran/serve";

const abortController = new AbortController();

const handler = {
  fetch(request) {
    return new Response("Hello, world!");
  },
  hostname: "0.0.0.0",
  port: 8080,
  signal: abortController.signal,
  onListen({ hostname, port }) {
    console.log(`Server running at http://${hostname}:${port}`);
  },
  // Other options are passed to the underlying server.
  // For Node.js, it's passed to `http.createServer`.
  keepAlive: true,
  keepAliveTimeout: 5000, // milliseconds
  // For Bun, it's passed to `Bun.serve`.
  idleTimeout: 5, // seconds
};

export default handler;

const server = serve(handler);

// To stop the server
abortController.abort();
```
npm package: @sntran/socket
Description: Cross runtime Socket API
Author: Trần Nguyễn Sơn
Latest version: 0.3.0

# @sntran/socket

Cross runtime implementation of the proposed
[Socket API](https://sockets-api.proposal.wintercg.org/).

On Node, a custom implementation on top of `node:net` and `node:tls` is used.
Deno uses the same implementation with buit-in polyfills. On Cloudflare Workers,
`cloudflare:sockets` is used.

## Usage

See [examples](./examples/gopher.js) for more detailed usage.

```js
import { connect } from "@sntran/socket";

export default {
  async fetch(request) {
    const gopherAddr = { hostname: "gopher.floodgap.com", port: 70 };
    const url = new URL(req.url);

    try {
      const socket = connect(gopherAddr);

      const writer = socket.writable.getWriter();
      const encoder = new TextEncoder();
      const encoded = encoder.encode(url.pathname + "\r\n");
      await writer.write(encoded);

      return new Response(socket.readable, {
        headers: { "Content-Type": "text/plain" },
      });
    } catch (error) {
      return new Response("Socket connection failed: " + error, {
        status: 500,
      });
    }
  },
};
```