open-index/open-npm huggingface dataset:
npm package: @rehmat-falcon/use-local-storage
Description: >
Author: RehmatFalcon
Latest version: 1.0.0

# @rehmat-falcon/use-local-storage

> 

[![NPM](https://img.shields.io/npm/v/@rehmat-falcon/use-local-storage.svg)](https://www.npmjs.com/package/@rehmat-falcon/use-local-storage) [![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)

This hook allows you to access the localstorage for a certain key.

Support for objects have been added. If your initial value is an object, it will deserialize when retrieving and serialize when saving the object.

## Install

```bash
npm install --save @rehmat-falcon/use-local-storage
```

## Usage

```jsx
import React, { Component } from 'react'

import { useLocalStorage } from '@rehmat-falcon/use-local-storage';

const Example = () => {
  const localStorageManager = useLocalStorage("key", {});
  // check if the key exists using localStorageManager.state.exists
  return (
    <div>{localStorageManager.state.value}</div>
  )
}
```

## Hook Definition
useLocalStorage(key, initialValue = "", override = false);

> key : The key in which to save the value

> initialValue : The value to use if no value is present

> override : If set to true, the initialValue will be saved into the localStorage by overriding the current value.


## License

MIT © [RehmatFalcon](https://github.com/RehmatFalcon)

---

This hook is created using [create-react-hook](https://github.com/hermanya/create-react-hook).
npm package: @rehmat-falcon/use-object-state
Description: ## This repository houses the implementation of useObjectState hook.
Author: RehmatFalcon
Latest version: 1.0.1

# @rehmat-falcon/use-object-state

## This repository houses the implementation of useObjectState hook.

useObjectState is a custom react hook developed to mimic the behavior of the old setState method while using class components.

This hook uses `useState` hook under the hood. In fact, it is just a wrapper around it to ensure that we dont have to perform destructuring operation when dealing with object state and also to ensure that we dont intruduce a data reset bug by accident; happens when we setState without specifying other values when using react hook `useState`

The implementation is simple and given below : 
```js

import { useState } from "react";

const useObjectState = (initial = {}) => {
  if(typeof initial != "object") {
    throw new Error("useObjectState can only be used with objects");
  }
  const [state, updateState] = useState(initial);

  const setState = (newStateValue) => {
    updateState({
      ...state,
      ...newStateValue
    });
  }

  return [
    state,
    setState
  ];
};

export default useObjectState;

```

You can use the above hook in your react components.

```js
  const [state, updateState] = useObjectState({
    name : "Name",
    unchangedValue : 12
  });
  const updateName = () => updateState({
    name : "New updated name"
  });
  // updateName method just updates the name. We dont have to care about the other values in the object here.
  // without it, we would have to use something like Object.assign({}, state, {name : "new name"}); or setState({...state, {name:"New name"}})
  // Our custom hook uses the latter approach under the hood.
  ```



MIT © [RehmatFalcon](https://github.com/RehmatFalcon)

---

This hook is created using [create-react-hook](https://github.com/hermanya/create-react-hook).
npm package: @rehmatalisayany/weather-mcp-server
Description: MCP Weather Service - A MCP server for weather data using Open Meteo API
Author: Rehmat Ali Sayany
Latest version: 1.0.6

# Weather MCP Server in TypeScript

A Model Context Protocol (MCP) server for fetching weather data using the Open-Meteo API. This server can be integrated with Cursor IDE to provide weather information through the MCP protocol.

## Usage

### As a CLI Tool

```bash
npx @rehmatalisayany/weather-mcp-server
```

### In Cursor IDE

Add the following configuration to your `cursor.json`:
![alt text](image.png)

```json
{
  "mcp": {
    "servers": {
      "weather": {
        "command": "@rehmatalisayany/weather-mcp-server",
        "transport": "stdio"
      }
    }
  }
}
```

### Test using MCP Client

check get-weather.ts for source code, you can run this file to connect to MCP Server

![alt text](image-1.png)

### To connect with Local MCP Server first you need to install 

### Installation

```bash
git clone https://github.com/rehmat123/weather-mcp-server.git
```

go to directory and than
### Install dependencies and build
```bash
npm i
npm build
```

### Code usage in your Agent
 ```
   const transport = new StdioClientTransport({
     command: 'node',
     args: ['dist/index.js']
   });
```

### To connect with Remote MCP Server use this, you dont need to install and compile
```
  const transport = new StdioClientTransport({
    command: 'npx',
    args: ['@rehmatalisayany/weather-mcp-server']
  });

```
## API

The server provides the following tool:

- `getWeather`: Get current weather for a location
  - Arguments:
    - `location`: String (city name or location)
  - Returns:
    - `temperature`: Current temperature in Celsius
    - `conditions`: Weather conditions description
    - `humidity`: Humidity percentage
    - `windSpeed`: Wind speed in m/s

## License

MIT
npm package: @rehookify/datepicker
Description: The ultimate tool to create a date, range and time picker in your React applications.
Latest version: 6.6.8

# @rehookify/datepicker

`@rehookify/datepicker` is an ultimate tool for creating date, range, and time pickers in your React applications.

It provides behavioral and accessibility implementations for all sorts of calendars, date and time pickers.

<p align="center">
  <a href="https://www.rehookify.com/datepicker/tutorials">Tutorials</a> |
  <a href="https://www.rehookify.com/datepicker/examples">Examples</a> |
  <a href="https://www.rehookify.com/datepicker/configuration">Configuration</a> |
  <a href="https://www.rehookify.com/datepicker/state">State</a> |
  <a href="https://www.rehookify.com/datepicker/modular-hooks">Modular Hooks</a>
</p>

## Features

- Small in size.
- No dependencies.
- [Modular design](https://www.rehookify.com/datepicker/modular-hooks): You can use as little code as possible.
- Supports single, multiple, and range date selection, as well as a time picker.
- Multiple calendar support.
- Native localization support using *.toLocaleDateString* and *.toLocaleTimeString*.
- Follows the `prop-getters` pattern, providing all the necessary props for your components.

## Motivation

By picking a date picker for you project you can get such problems:

- 🙅 your component library doesn't have the component that you need;
- ⚙️ you need to make changes to your build process;
- 💅 your styling system is different from the most popular solution;
- 🦹 it's challenging to customise a component that matches your design;
- 💰 it could cost money to get needed components;
- 🏋️ the library is heavy and doesn't have tree-shaking;
- 📚 bad documentation;
- ⛔️ no tests, no TypeScript support, no examples...

## Instalation

`@rehookify/datepicker` is available as a package in npm registry.

You can use your favarite package manager to insall it:

```bash
npm i @rehookify/datepicker
```

```bash
yarn add @rehookify/datepicker
```

```bash
pnpm add @rehookify/datepicker
```

Start with [tutorials](https://rehookify.com/datepicker/tutorials)
npm package: @rehooks/component-size
Description: React hook for component-size
Author: Fouad Matin
Latest version: 1.0.3

# `@rehooks/component-size`

> React hook for determining the size of a component

> **Note:** This is using the new [React Hooks API Proposal](https://reactjs.org/docs/hooks-intro.html)
> which is subject to change until React 16.7 final.
>
> You'll need to install `react`, `react-dom`, etc at `^16.7.0-alpha.0`

## Install

```sh
yarn add @rehooks/component-size
```

## Usage

```js
import { useRef } from 'react'
import useComponentSize from '@rehooks/component-size'

function MyComponent() {
  let ref = useRef(null)
  let size = useComponentSize(ref)
  // size == { width: 100, height: 200 }
  let { width, height } = size
  let imgUrl = `https://via.placeholder.com/${width}x${height}`

  return (
    <div style={{ width: '100%', height: '100%' }}>
      <img ref={ref} src={imgUrl} />
    </div>
  )
}
```

## ResizeObserver

[Resize Observer](https://developers.google.com/web/updates/2016/10/resizeobserver)
is the API is used to determine if an element is resized. Browser support is pretty good in Chrome, but is still missing support in other major browsers.

> [Can i use ResizeObserver?](https://caniuse.com/#feat=resizeobserver)

### Polyfill

You can import the
[polyfill](https://github.com/que-etc/resize-observer-polyfill) directly from here

```sh
yarn add resize-observer-polyfill
```

Then import it in your app:

```js
import 'resize-observer-polyfill'
```

If you are using Webpack (or similar) you could use [dynamic
imports](https://webpack.js.org/api/module-methods/#import-), to load the
Polyfill only if needed. A basic implementation could look something like this:

```js
loadPolyfills()
  .then(() => /* Render React application now that your Polyfills are ready */)

/**
* Do feature detection, to figure out which polyfills needs to be imported.
**/
function loadPolyfills() {
  const polyfills = []

  if (!supportsResizeObserver()) {
    polyfills.push(import('resize-observer-polyfill'))
  }

  return Promise.all(polyfills)
}

function supportsResizeObserver() {
  return (
    'ResizeObserver' in global &&
    'ResizeObserverEntry' in global &&
    'contentRect' in ResizeObserverEntry.prototype
  )
}
```
npm package: @rehooks/device-orientation
Description: React hook for the Device Orientation API
Author: Jake Moxey
Latest version: 1.0.0

# `@rehooks/device-orientation`

> React hook for the Device Orientation API

> **Note:** This is using the new [React Hooks API Proposal](https://reactjs.org/docs/hooks-intro.html)
> which is subject to change until React 16.7 final.
>
> You'll need to install `react`, `react-dom`, etc at `^16.7.0-alpha.0`

## Install

```sh
yarn add @rehooks/device-orientation
```

## Usage

```js
import useDeviceOrientation from '@rehooks/device-orientation';

function MyComponent() {
  let value = useDeviceOrientation();
  return (
    <div>
      <p>Absolute: {value.absolute}</p>
      <p>Alpha: {value.alpha}</p>
      <p>Beta: {value.beta}</p>
      <p>Gamma: {value.gamma}</p>
    </div>
  );
}
```
npm package: @rehooks/document-title
Description: React hook for updating document-title
Author: Amit Solanki
Latest version: 1.0.2

# `@rehooks/document-title`

> React hook for updating the document-title

> **Note:** This is using the new [React Hooks API Proposal](https://reactjs.org/docs/hooks-intro.html)
> which is subject to change until React 16.7 final.
>
> You'll need to install `react`, `react-dom`, etc at `^16.7.0-alpha.0`

## Install

```sh
yarn add @rehooks/document-title
```

## Usage

```js
import useDocumentTitle from '@rehooks/document-title';

function MyComponent() {
  useDocumentTitle('Page Title');
  return <div/>;
}
```
npm package: @rehooks/document-visibility
Description: React hook for subscribing to document visibility
Author: Jack Hanford
Latest version: 1.2.0

# `@rehooks/document-visibility`

> React hook for subscribing to document visibility

> **Note:** This is using the new [React Hooks API Proposal](https://reactjs.org/docs/hooks-intro.html)
> which is subject to change until React 16.7 final.
>
> You'll need to install `react`, `react-dom`, etc at `^16.7.0-alpha.0`

## Install

```sh
yarn add @rehooks/document-visibility
```

## Usage

```js
import useDocumentVisibility from '@rehooks/document-visibility';

function MyComponent() {
  let documentVisibility = useDocumentVisibility();
  // documentVisibility = "hidden" | "visible" | "prerender"

  // ...
}
```
npm package: @rehooks/document-visibility-hook
Description: React hook for subscribing to document visibility
Author: Jack Hanford
Latest version: 1.0.0

# `@rehooks/document-visibility-hook`

> React hook for subscribing to document visibility

> **Note:** This is using the new [React Hooks API Proposal](https://reactjs.org/docs/hooks-intro.html)
> which is subject to change until React 16.7 final.
>
> You'll need to install `react`, `react-dom`, etc at `^16.7.0-alpha.0`

## Install

```sh
yarn add document-visibility-hook
```

## Usage

```js
import useDocumentVisibility from 'document-visibility-hook';

function MyComponent() {
  let visible = useDocumentVisibility();
  // true || false

  // ...
}
```
npm package: @rehooks/input-value
Description: React hook for creating input values
Author: Jamie Kyle
Latest version: 1.0.0

# `@rehooks/input-value`

> React hook for creating input values

> **Note:** This is using the new [React Hooks API Proposal](https://reactjs.org/docs/hooks-intro.html)
> which is subject to change until React 16.7 final.
>
> You'll need to install `react`, `react-dom`, etc at `^16.7.0-alpha.0`

## Install

```sh
yarn add @rehooks/input-value
```

## Usage

```js
import useInputValue from '@rehooks/input-value';

function MyComponent() {
  let name = useInputValue('Jamie');
  // name = { value: 'Jamie', onChange: [Function] }
  return <input {...name}/>;
}
```
npm package: @rehooks/network-status
Description: React hook to track Network status
Author: Amit Solanki
Latest version: 1.0.0

# `@rehooks/network-status`

> React hook for getting network-status

> **Note:** This is using the new [React Hooks API Proposal](https://reactjs.org/docs/hooks-intro.html)
> which is subject to change until React 16.7 final.
>
> You'll need to install `react`, `react-dom`, etc at `^16.7.0-alpha.0`

## Install

```sh
yarn add @rehooks/network-status
```

## Usage

```js
import useNetworkStatus from "@rehooks/network-status";

function MyComponent() {
  let connection = useNetworkStatus();
  return (
    <div>
      <div>downlink: {connection.downlink}</div>
      <div>effectiveType: {connection.effectiveType}</div>
      <div>rtt: {connection.rtt}</div>
      <div>saveData: {connection.saveData ? "yes" : "no"}</div>
    </div>
  );
}
```
npm package: @rehooks/online-status
Description: React hook for subscribing to `online`/`offline` events and the `navigator.onLine` property to see current status
Author: @mathdroid
Latest version: 1.1.2

# `@rehooks/online-status`

> React hook for subscribing to `online`/`offline` events and the `navigator.onLine` property to see current status

> You'll need to install `react`, `react-dom`, etc at `^16.8.4`

## Install

```sh
yarn add @rehooks/online-status
```

## Usage

```js
import useOnlineStatus from '@rehooks/online-status';

function MyComponent() {
  const onlineStatus = useOnlineStatus();
  return (
    <div>
      <h1>You are {onlineStatus ? "Online" : "Offline"}</h1>
    </div>
  );
}
```
npm package: @rehooks/window-scroll-position
Description: React hook for Window scroll position
Author: Pave Prichodko
Latest version: 1.0.1

# `@rehooks/window-scroll-position`

> React hook for [Window](https://developer.mozilla.org/en-US/docs/Web/API/Window) scroll position

> **Note:** This is using the new [React Hooks API Proposal](https://reactjs.org/docs/hooks-intro.html)
> which is subject to change until React 16.7 final.
>
> You'll need to install `react`, `react-dom`, etc at `^16.7.0-alpha.0`

## Install

```sh
yarn add @rehooks/window-scroll-position
```

## Usage

```js
import useWindowScrollPosition from '@rehooks/window-scroll-position'

function MyComponent() {
  // optionally you can pass options, those are default:
  let options = {
    throttle: 100,
  }
  let position = useWindowScrollPosition(options)
  // position == { x: 0, y: 0 }
  return <div />
}
```
npm package: @rehooks/window-size
Description: React hook for subscribing to window size
Author: Jamie Kyle
Latest version: 1.0.2

# `@rehooks/window-size`

> React hook for subscribing to window size

> **Note:** This is using the new [React Hooks API Proposal](https://reactjs.org/docs/hooks-intro.html)
> which is subject to change until React 16.7 final.
>
> You'll need to install `react`, `react-dom`, etc at `^16.7.0-alpha.0`

## Install

```sh
yarn add @rehooks/window-size
```

## Usage

```js
import useWindowSize from '@rehooks/window-size';

function MyComponent() {
  let windowSize = useWindowSize();
  // {
  //   innerWidth: window.innerWidth,
  //   innerHeight: window.innerHeight,
  //   outerWidth: window.outerWidth,
  //   outerHeight: window.outerHeight,
  // }

  // ...
}
```
npm package: @rehydra/cli
Description: CLI for Rehydra PII anonymization — anonymize, rehydrate, and inspect text from the terminal
Latest version: 0.10.2

# @rehydra/cli

Command-line interface for [Rehydra](https://github.com/rehydra-ai/rehydra-sdk) PII anonymization.

## Install

```bash
npm install -g @rehydra/cli
```

## Usage

```bash
# Anonymize text
echo "Contact john@example.com" | rehydra anonymize

# Anonymize a file
rehydra anonymize input.txt -o output.txt

# Rehydrate (restore original PII)
rehydra rehydrate output.txt

# Inspect (dry-run, shows detected PII)
rehydra inspect input.txt

# Enable NER (detects names, orgs, locations)
rehydra anonymize input.txt --ner quantized

# JSON output
rehydra anonymize input.txt -f json

# Full help
rehydra --help
```

See the [main repo](https://github.com/rehydra-ai/rehydra-sdk) for full documentation.
npm package: @rehydra/opencode
Description: Rehydra plugin for OpenCode — anonymizes secrets in LLM context using native plugin hooks
Latest version: 0.10.2

# @rehydra/opencode

Prevent your coding agent from leaking secrets to LLM providers.

This plugin intercepts the conversation between [OpenCode](https://github.com/sst/opencode) and the LLM. Secrets from your `.env` files are replaced with placeholders before they leave your machine, and transparently restored before any tool (shell commands, file writes, etc.) executes locally.

The LLM never sees real secret values. Your tools run with them.

## Install

```bash
npm install @rehydra/opencode
```

Add to `opencode.json`:

```json
{
  "plugin": ["@rehydra/opencode"]
}
```

By default, the plugin reads `.env` in your project root. Secrets with values of 4+ characters are detected and scrubbed.

## Configuration

For custom settings, create `.opencode/plugins/rehydra.ts`:

```typescript
import { createRehydraPlugin } from "@rehydra/opencode";

export default createRehydraPlugin({
  // Scan multiple env files
  envFiles: [".env", ".env.local", ".env.production"],

  // Always redact these values, even if not in .env
  redactValues: ["sk-live-abc123..."],

  // Minimum value length to consider a secret (default: 4)
  minValueLength: 6,

  // Disable detection of specific PII types
  disableTypes: ["URL", "IP_ADDRESS"],
});
```

## What gets detected

- Environment variable values from `.env` files
- API keys, tokens, and credentials (pattern-based)
- AWS access keys and secret keys
- JWTs, private keys, connection strings
- Any values passed via `redactValues`

## How it works

The plugin uses five OpenCode hooks:

| Hook | What it does |
|---|---|
| `messages.transform` | Scrubs secrets from all message text before it reaches the LLM |
| `system.transform` | Tells the LLM to treat placeholders as real values |
| `tool.execute.before` | Restores real values in tool arguments before local execution |
| `tool.execute.after` | Restores real values in displayed tool output |
| `text.complete` | Restores real values in LLM response text shown to you |

Everything runs locally. No data leaves your machine except the scrubbed conversation sent to the LLM provider.

## Logging

Plugin activity is logged to OpenCode's log directory (`~/.local/share/opencode/log/`). Run with `--log-level DEBUG` for detailed output.

```
INFO service=rehydra scrubbed={"ENV_VAR_SECRET":2} messageCount=3 scrubbed 2 secret(s) from messages
INFO service=rehydra tool=bash callID=call_abc123 rehydrated PII tags in tool args
```

## Rehydra

This plugin is part of [Rehydra](https://github.com/rehydra-ai/rehydra-sdk), an open-source SDK for PII anonymization and rehydration. Rehydra combines regex-based pattern matching with NER-based detection and supports any LLM provider via fetch wrappers, proxy servers, or framework plugins.

Full documentation at [docs.rehydra.ai](https://docs.rehydra.ai).

## License

MIT
npm package: @rehype-pretty/transformers
Description: Shiki transformer that adds a copy button to code blocks
Author: https://github.com/o-az
Latest version: 0.13.2

> [!NOTE]  
> Currently in **development**.

# `@rehype-pretty/transformers`

[![JSR](https://jsr.io/badges/@rehype-pretty/transformers)](https://jsr.io/@rehype-pretty/transformers)
[![JSR](https://jsr.io/badges/@rehype-pretty/transformers/score)](https://jsr.io/@rehype-pretty/transformers)

```sh
npx jsr add @rehype-pretty/transformers
```

## Available Transformers

- [`transformerCopyButton`](./src/copy-button.ts)

## Usage

You can use this as a [`shiki` transformer](https://shiki.style/guide/transformers) in `rehype-pretty-code` by passing it to the `transformers` array.

### Options

- `visibility`: `'always' | 'hover'` (default: `'hover'`)
- `feedbackDuration`: `number` (default: `3_000`)
- `copyIcon`: `string` (default: an inline SVG of a copy icon)
- `successIcon`: `string` (default: an inline SVG of a green checkmark icon)

### Examples

#### with `rehype-pretty-code`

  ```ts
  import { unified } from 'unified'
  import remarkParse from 'remark-parse'
  import remarkRehype from 'remark-rehype'
  import rehypeStringify from 'rehype-stringify'
  import rehypePrettyCode from 'rehype-pretty-code'
  import { transformerCopyButton } from '@rehype-pretty/transformers'

  const file = await unified()
    .use(remarkParse)
    .use(remarkRehype)
    .use(rehypePrettyCode, {
      transformers: [
        transformerCopyButton({
          visibility: 'always',
          feedbackDuration: 3_000,
        }),
      ],
    })
    .use(rehypeStringify)
    .process(`\`\`\`js\nconsole.log('Hello, World!')\n\`\`\``)

  console.log(String(file))
  ```

#### with `shiki`

  ```ts
  import { codeToHtml } from 'shiki'

  const code = await codeToHtml('console.log("Hello World")', {
    lang: 'ts',
    theme: 'vitesse-light',
    transformers: [
      transformerCopyButton({
        visibility: 'always',
        feedbackDuration: 3_000,
      }),
    ]
  })
  ```
npm package: @rei-standard/amsg-client
Description: ReiStandard Active Messaging browser client SDK
Latest version: 2.0.1

# @rei-standard/amsg-client

`@rei-standard/amsg-client` 是 ReiStandard 主动消息标准的浏览器端 SDK 包，负责加密请求、解密响应和 Push 订阅。


## 安装

```bash
npm install @rei-standard/amsg-client
```

## 快速使用

```js
import { ReiClient } from '@rei-standard/amsg-client';

const client = new ReiClient({
  baseUrl: '/api/v1',
  userId: '550e8400-e29b-41d4-a716-446655440000'
});

await client.init();

await navigator.serviceWorker.register('/service-worker.js');
const registration = await navigator.serviceWorker.ready;
const subscription = await client.subscribePush(
  window.__VAPID_PUBLIC_KEY__,
  registration
);

await client.scheduleMessage({
  contactName: 'Rei',
  messageType: 'fixed',
  userMessage: '下班记得带伞～',
  firstSendTime: new Date(Date.now() + 60 * 1000).toISOString(),
  recurrenceType: 'none',
  pushSubscription: subscription.toJSON()
});
```

## 导出 API（Exports）

- `ReiClient`

`ReiClient` 主要方法：

- `init()`
- `scheduleMessage(payload)`
- `updateMessage(uuid, updates)`
- `cancelMessage(uuid)`
- `listMessages(opts)`
- `subscribePush(vapidPublicKey, registration)`

## 模块格式与类型（ESM/CJS/Types）

- ESM：`import { ReiClient } from '@rei-standard/amsg-client'`
- CJS：`const { ReiClient } = require('@rei-standard/amsg-client')`
- 类型：包内提供 `types` 入口（`dist/index.d.ts`）

## 运行环境与要求

- 浏览器环境（需 `fetch`、`crypto.subtle`）
- Push 订阅需可用 Service Worker 与 Push API
- 需要可用的 `baseUrl`（示例：`/api/v1`）
- `userId` 必须是 UUID v4

## 相关链接（绝对 URL）

- [SDK Workspace 总览](https://github.com/Tosd0/ReiStandard/blob/main/packages/rei-standard-amsg/README.md)
- [Server 包 README](https://github.com/Tosd0/ReiStandard/blob/main/packages/rei-standard-amsg/server/README.md)
- [SW 包 README](https://github.com/Tosd0/ReiStandard/blob/main/packages/rei-standard-amsg/sw/README.md)
- [Service Worker 规范](https://github.com/Tosd0/ReiStandard/blob/main/standards/service-worker-specification.md)
- [API 技术规范](https://github.com/Tosd0/ReiStandard/blob/main/standards/active-messaging-api.md)
npm package: @rei-standard/amsg-sw
Description: ReiStandard Active Messaging service worker SDK
Latest version: 2.0.1

# @rei-standard/amsg-sw

`@rei-standard/amsg-sw` 是 ReiStandard 主动消息标准的 Service Worker 插件包，目标是让推送展示和离线重试“开箱即用”。


## 功能概览

- 处理 `push` 事件：自动解析 payload 并展示通知
- 处理 `message` 事件：支持离线请求入队与主动冲刷队列
- 处理 `sync` 事件：在网络恢复后自动重试队列请求
- 使用 IndexedDB 存储待发送请求，避免页面关闭后丢失

> 注意：插件默认**不内置** `notificationclick` 逻辑，点击跳转策略由业务自行实现。

## 安装

```bash
npm install @rei-standard/amsg-sw
```

## 快速使用

```js
import { installReiSW } from '@rei-standard/amsg-sw';

installReiSW(self, {
  defaultIcon: '/icon-192x192.png',
  defaultBadge: '/badge-72x72.png'
});

// 业务侧自行实现点击跳转
self.addEventListener('notificationclick', (event) => {
  event.notification.close();
  event.waitUntil(self.clients.openWindow('/'));
});
```

离线入队（可选）：

```js
import { REI_SW_MESSAGE_TYPE } from '@rei-standard/amsg-sw';

export async function enqueueRequestToSW(requestPayload) {
  const registration = await navigator.serviceWorker.ready;
  if (!registration.active) {
    throw new Error('No active service worker');
  }

  return new Promise((resolve, reject) => {
    const channel = new MessageChannel();
    channel.port1.onmessage = (event) => {
      const result = event.data || {};
      if (result.ok) {
        resolve(result);
      } else {
        reject(new Error(result.error || 'Queue request failed'));
      }
    };

    registration.active.postMessage(
      {
        type: REI_SW_MESSAGE_TYPE.ENQUEUE_REQUEST,
        request: requestPayload
      },
      [channel.port2]
    );
  });
}
```

## 消息协议

- `REI_SW_MESSAGE_TYPE.ENQUEUE_REQUEST`：添加请求到 outbox，并立即尝试发送
- `REI_SW_MESSAGE_TYPE.FLUSH_QUEUE`：主动触发一次队列发送
- `REI_SW_MESSAGE_TYPE.QUEUE_RESULT`：SW 返回入队结果（`ok` / `error` / `queueId`）

`request` 结构示例：

```json
{
  "url": "/api/v1/schedule-message",
  "method": "POST",
  "headers": {
    "content-type": "application/json",
    "x-user-id": "550e8400-e29b-41d4-a716-446655440000",
    "x-payload-encrypted": "true",
    "x-encryption-version": "1"
  },
  "body": {
    "iv": "...",
    "authTag": "...",
    "encryptedData": "..."
  }
}
```

## 导出 API（Exports）

- `installReiSW`
- `REI_SW_MESSAGE_TYPE`

`REI_SW_MESSAGE_TYPE` 包含：

- `ENQUEUE_REQUEST`
- `FLUSH_QUEUE`
- `QUEUE_RESULT`

## 模块格式与类型（ESM/CJS/Types）

- ESM：`import { installReiSW } from '@rei-standard/amsg-sw'`
- CJS：`const { installReiSW } = require('@rei-standard/amsg-sw')`
- 类型：包内提供 `types` 入口（`dist/index.d.ts`）

## 运行环境与要求

- Service Worker 环境
- 需支持 `indexedDB`
- Background Sync 不可用时会降级为手动冲刷队列
- 建议项目可对 SW 文件做模块打包（支持包名 import）

## 常见坑

1. 本包不会自动添加 `notificationclick`，必须业务侧实现。
2. SW 文件如果不能解析包名 import，需要改走手动接入模板。
3. 请求入队 body 必须可序列化（JSON）。

## 相关链接（绝对 URL）

- [SDK Workspace 总览](https://github.com/Tosd0/ReiStandard/blob/main/packages/rei-standard-amsg/README.md)
- [Server 包 README](https://github.com/Tosd0/ReiStandard/blob/main/packages/rei-standard-amsg/server/README.md)
- [Client 包 README](https://github.com/Tosd0/ReiStandard/blob/main/packages/rei-standard-amsg/client/README.md)
- [Service Worker 规范（第 0 章）](https://github.com/Tosd0/ReiStandard/blob/main/standards/service-worker-specification.md)
npm package: @rei/cedar
Description: REI Cedar Component Library
Author: REI Software Engineering
Latest version: 16.3.1

# REI Cedar Style Framework!

[![codecov](https://codecov.io/gh/rei/rei-cedar/branch/master/graph/badge.svg)](https://codecov.io/gh/rei/rei-cedar)
[![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)

Welcome to REI's style framework! The overall goals of this project are to provide a common scaffolding for UI elements,
and a set of themes that build on this scaffolding. We started this project in 2015 as a fork of
[Bootstrap](http://getbootstrap.com/).
The project has evolved into what it is today, and will continue to grow to fit our expanding needs. Feel free to watch
the Cedar grow and learn from what we are doing, or jump in and provide some recommendations.

## Using Cedar

See the [Cedar docs](https://cedar.rei.com) for usage instructions.

## Getting Started

### Install

Clone the project.

`npm install`

### Run

`npm run dev`

Runs locally for development. Has hot reloading, and other nice things related to development.

## Testing

### Code Tests

`npm run unit`

Runs unit tests.

`npm run watch`

Runs unit tests in watch mode. This also allows you to inspect snapshot discrepancies and regenerate the snapshots if appropriate.

`npm run test:playwright`

Runs [Playwright](https://playwright.dev) end-to-end tests and Axe a11y tests.

`npm run test`

Runs both unit and e2e/accessibility tests.

## Publishing Prerelease Components

`npm run prerelease`

Publishes package to npm with a prerelease tag. You must increment the component's version manually prior to publishing. `--dry-run` flag will run the prerelease process without publishing to npm.

## Commits

This project is Commitizen friendly. To install: `npm install -g commitizen`
When creating a pull request run `git cz` rather than `git commit` and follow the prompts.

This projects Changelogs are generated.

- Generate the Changelog: `npm run changelog`

## Developer demo

The main documentation site for Cedar is our separate [Cedar docs](https://cedar.rei.com) website. With that in mind, we also have a playground for developing components and sharing ideas with others and within our team. The Cedar team produces this *developer demo* through GitHub Pages that can be accessed at [https://rei.github.io/rei-cedar/](https://rei.github.io/rei-cedar/), but we do not guarantee it will always be up to date or be an accurate representation of the Cedar library.