open-index/open-npm huggingface dataset:
npm package: @kognitivedev/deployer-docker
Description: Docker deployment file generator for Kognitive
Latest version: 0.2.22

# @kognitivedev/deployer-docker

> Generate Docker deployment files for Kognitive projects.

## Usage

```typescript
import { generateDockerFiles } from "@kognitivedev/deployer-docker";

generateDockerFiles("./", {
  backendPort: 3001,
  dashboardPort: 3002,
  includeRedis: true,
  includeQdrant: true,
});
```

Generates: `Dockerfile`, `docker-compose.prod.yml`, `.dockerignore`, `.env.example`

The Dockerfile includes a non-root user, health check against `/api/runtime/info`, and optimized layer caching.

## CI/CD with GitHub Actions

```typescript
import { generateGitHubActionsDocker } from "@kognitivedev/deployer-docker";

generateGitHubActionsDocker("./", {
  registry: "ghcr.io",        // or "docker.io"
  imageName: "my-app",
  triggerBranch: "main",
});
// Generates: .github/workflows/docker-deploy.yml
```

## Deployment Script

```typescript
import { generateDeployScript } from "@kognitivedev/deployer-docker";

generateDeployScript("./");
// Generates: deploy.sh (docker compose up + health check + rollback on failure)
```
npm package: @kognitivedev/deployer-vercel
Description: Vercel deployment config generator for Kognitive
Latest version: 0.2.22

# @kognitivedev/deployer-vercel

> Generate Vercel deployment configuration for Kognitive projects.

## Usage

```typescript
import { generateVercelConfig } from "@kognitivedev/deployer-vercel";

generateVercelConfig("./", {
  framework: "nextjs",
  regions: ["iad1"],
});
```

Generates: `vercel.json` (with CORS headers for runtime API) and `.env.example`.

## CI/CD with GitHub Actions

```typescript
import { generateGitHubActionsVercel } from "@kognitivedev/deployer-vercel";

generateGitHubActionsVercel("./", {
  triggerBranch: "main",
});
// Generates: .github/workflows/vercel-deploy.yml
// - Preview deploys on pull requests
// - Production deploy on merge to main
```
npm package: @kognitivedev/documents
Description: Document parsing and OCR pipeline for Kognitive
Latest version: 0.2.22

# @kognitivedev/documents

> Document parsing and OCR pipeline for Kognitive.

## Installation

```bash
bun add @kognitivedev/documents ai
```

## Quick Start

```typescript
import { createOpenAI } from "@ai-sdk/openai";
import {
  AISDKVisionOCRProvider,
  DocumentProcessor,
  LibreOfficeConverter,
  toRagDocuments,
} from "@kognitivedev/documents";
import {
  AISDKEmbeddingProvider,
  DocumentPipeline,
  InMemoryVectorStore,
  RecursiveTextChunker,
} from "@kognitivedev/rag";

const openai = createOpenAI({ apiKey: process.env.OPENAI_API_KEY });

const processor = new DocumentProcessor({
  ocrProvider: new AISDKVisionOCRProvider({
    model: openai("gpt-4o-mini"),
    providerName: "openai",
    modelName: "gpt-4o-mini",
  }),
  officeConverter: new LibreOfficeConverter(),
});

const processed = await processor.process({
  path: "./contract.pdf",
});

const ragDocs = toRagDocuments(processed, { mode: "page" });

const pipeline = new DocumentPipeline({
  chunker: new RecursiveTextChunker({ chunkSize: 1000, overlap: 200 }),
  embedder: new AISDKEmbeddingProvider({
    model: openai.embedding("text-embedding-3-small"),
  }),
  vectorStore: new InMemoryVectorStore(),
});

await pipeline.ingest(ragDocs);
```

## Supported Inputs

- `pdf`: native text extraction with OCR fallback on sparse pages
- `docx`: native extraction via Mammoth
- `txt`, `md`, `html`, `json`: direct UTF-8 parsing
- `png`, `jpg`, `jpeg`, `webp`, `tiff`: OCR
- `doc`, `odt`, `ppt`, `pptx`, `xls`, `xlsx`: optional LibreOffice conversion to PDF, then PDF processing

## Using with Agents

Use `createFileProcessor()` to create a callback compatible with `@kognitivedev/agents` file processing:

```typescript
import { createFileProcessor, AISDKVisionOCRProvider } from "@kognitivedev/documents";
import { createAgent } from "@kognitivedev/agents";
import { openai } from "@ai-sdk/openai";

const agent = createAgent({
  name: "doc-reader",
  instructions: "Analyze documents and answer questions.",
  model: openai("gpt-4o"),
  fileProcessing: {
    processFile: createFileProcessor({
      ocrProvider: new AISDKVisionOCRProvider({ model: openai("gpt-4o-mini") }),
    }),
  },
});
```

## Public API

- `DocumentProcessor`
- `ProcessorFactory`
- `OCRProvider`
- `AISDKVisionOCRProvider`
- `LibreOfficeConverter`
- `toRagDocuments`
- `createFileProcessor`
npm package: @kognitivedev/evals
Description: Evaluation framework with model-graded and rule-based scorers
Latest version: 0.2.22

# @kognitivedev/evals

> Evaluation framework with model-graded, rule-based, and composite scorers.

## Installation

```bash
bun add @kognitivedev/evals ai zod
```

## Quick Start

```typescript
import { runEvals, ruleBased, modelGradedScorer, EvalDatasetBuilder } from "@kognitivedev/evals";

const report = await runEvals({
  generateResponse: async (messages) => {
    const result = await generateText({ model: openai("gpt-4o-mini"), messages });
    return result.text;
  },
  dataset: EvalDatasetBuilder.fromArray([
    { input: [{ role: "user", content: "Hello" }] },
  ]),
  scorers: [
    ruleBased.containsKeyword("hello"),
    modelGradedScorer({ model: openai("gpt-4o-mini"), criteria: "Is this helpful?" }),
  ],
});

console.log(report.summary.avgScore);
```

## Scorers

- `modelGradedScorer` — LLM-as-judge via AI SDK `generateObject`
- `ruleBased.containsKeyword`, `.matchesRegex`, `.exactMatch`, `.lengthRange`
- `compositeScorer` — weighted average of multiple scorers
npm package: @kognitivedev/mcp
Description: MCP client and server with AI SDK tool conversion
Latest version: 0.2.22

# @kognitivedev/mcp

> MCP client and server with AI SDK tool conversion and stdio transport.

## Installation

```bash
bun add @kognitivedev/mcp ai zod
```

## MCPClient

```typescript
import { MCPClient } from "@kognitivedev/mcp";

const client = new MCPClient({ transport: { type: "http", url: "http://localhost:8080/mcp" } });
await client.connect();
const tools = client.toAISDKTools(); // Use in streamText
```

## MCPServer

```typescript
import { MCPServer } from "@kognitivedev/mcp";

const server = new MCPServer({ name: "my-server", version: "1.0" });
server.registerTool({ name: "search", execute: async (args) => searchDb(args.query) });
const response = await server.handleRequest(jsonRpcRequest);
```

## StdioTransport

Communicate with MCP servers via child process stdin/stdout for CLI tools.
npm package: @kognitivedev/rag
Description: RAG pipeline with chunkers, vector stores, and AI SDK tool output
Latest version: 0.2.22

# @kognitivedev/rag

> RAG pipeline with 6 chunkers, 3 vector stores, and AI SDK tool output.

## Installation

```bash
bun add @kognitivedev/rag ai zod
```

## Quick Start

```typescript
import { DocumentPipeline, RecursiveTextChunker, InMemoryVectorStore, AISDKEmbeddingProvider } from "@kognitivedev/rag";
import { openai } from "@ai-sdk/openai";

const pipeline = new DocumentPipeline({
  chunker: new RecursiveTextChunker({ chunkSize: 1000 }),
  embedder: new AISDKEmbeddingProvider({ model: openai.embedding("text-embedding-3-small") }),
  vectorStore: new InMemoryVectorStore(),
});

await pipeline.ingest([{ content: "Your documents here" }]);
const results = await pipeline.search("query", { topK: 5 });
const tool = pipeline.asAISDKTool(); // Use in streamText
```

For PDFs, DOCX, images, and OCR-backed ingestion, preprocess files with `@kognitivedev/documents` and then pass the resulting text documents into `pipeline.ingest()`.

## Chunkers

RecursiveTextChunker, MarkdownChunker, TokenChunker, HTMLChunker, JSONChunker, SentenceChunker

## Vector Stores

InMemoryVectorStore (dev), PgVectorStore (PostgreSQL), QdrantVectorStore (Qdrant)
npm package: @kognitivedev/shared
Description: Foundation utilities for the Kognitive AI framework
Latest version: 0.2.22

# @kognitivedev/shared

> Foundation utilities for the Kognitive AI framework — EventBus, Cache, Logger, Errors, Retry, and OpenTelemetry integration.

## Installation

```bash
bun add @kognitivedev/shared
```

## Exports

### Events
- `InMemoryEventBus` — typed pub/sub: `emit()`, `on()`, `once()`, `removeAll()`

### Cache
- `InMemoryCacheAdapter` — TTL-based cache: `get()`, `set()`, `delete()`, `clear()`

### Logger
- `ConsoleLogger` — structured logging with prefix
- `NoopLogger` — silent logger for testing

### Errors
- `KognitiveError`, `RetryableError`, `ValidationError`, `TimeoutError`, `NotFoundError`, `ApprovalDeniedError`

### Utilities
- `withRetry(fn, options)` — exponential backoff retry
- `generateId()` — UUID generation

### Telemetry
- `withSpan(name, fn, attributes?)` — OpenTelemetry span wrapper (no-op if OTEL not installed)
- `createSpan()`, `endSpan()` — manual span control

### Streaming
- `StreamMode` — `"values" | "updates" | "messages" | "custom" | "debug"`
- `StreamEvent` — `{ event: string; data: unknown }`
- `parseStreamModes(input)` — validate and parse comma-separated mode string
- `createSSEEncoder()` — `TransformStream<StreamEvent, Uint8Array>` for SSE wire format
- `sseHeaders()` — standard SSE response headers

### Types
- `ResourceId` — `{ organizationId?, userId?, sessionId? }`
- `Result<T, E>` — discriminated union with `ok()` / `err()` helpers
npm package: @kognitivedev/storage
Description: Multi-backend storage abstraction for the Kognitive platform
Latest version: 0.2.22

# @kognitivedev/storage

> Multi-backend storage abstraction with InMemory and Composite implementations.

## Installation

```bash
bun add @kognitivedev/storage
```

## Quick Start

```typescript
import { InMemoryStorageBackend, CompositeStorage } from "@kognitivedev/storage";

const store = new InMemoryStorageBackend();
const record = await store.create("users", { name: "Alice" });
const found = await store.get("users", record.id);
const list = await store.list("users", { where: { name: "Alice" } });
```

## StorageBackend Interface

`get()`, `list()`, `create()`, `update()`, `delete()`, `transaction()`, `capabilities()`

## Implementations

- **InMemoryStorageBackend** — Map-based, for development/testing
- **CompositeStorage** — routes different collections to different backends
npm package: @kognitivedev/tools
Description: Tool system with approval workflows and AI SDK conversion
Latest version: 0.2.22

# @kognitivedev/tools

> Tool system for Kognitive agents — createTool, ToolRegistry, approval workflows, and AI SDK conversion.

## Installation

```bash
bun add @kognitivedev/tools
```

## Quick Start

```typescript
import { createTool, ToolRegistry } from "@kognitivedev/tools";
import { z } from "zod";
import { streamText } from "ai";

const searchTool = createTool({
  id: "search",
  description: "Search documentation",
  inputSchema: z.object({ query: z.string() }),
  execute: async (input) => ({ results: [`Result for: ${input.query}`] }),
});

const registry = new ToolRegistry();
registry.register(searchTool);

const result = await streamText({
  model: openai("gpt-4o"),
  tools: registry.toAISDKTools(),
  messages,
});
```

## Features

- **createTool** — typed tool factory with Zod schemas
- **ToolRegistry** — named collection with `toAISDKTools()` conversion
- **Approval** — `requireApproval` (boolean or conditional function)
- **AI SDK native** — converts directly to AI SDK `tool()` format
npm package: @kognity/vue-yellow-marker
Description: Adds a text selection and highlighting functionality to your Vue components
Author: Kognity
Latest version: 2.7.2

# Vue Yellow Marker
Adds a text selection and highlighting functionality to your VUE components.

[![Build Status](https://travis-ci.org/Kognity/vue-yellow-marker.svg?branch=master)](https://travis-ci.org/Kognity/vue-yellow-marker)

![Example](https://github.com/Kognity/vue-yellow-marker/raw/master/doc/vue-yellow-marker-screen.png)

## Installation

```
npm install @kognity/vue-yellow-marker --save
```

## Usage



```javascript
import { HighlightMixin } from "@kognity/vue-yellow-marker";

export default {
  name: "MyComponent",
  mixins: [
    HighlightMixin,
  ],
  ...
  ...
}
```

## Live demo

See [live examples in codesandbox](https://codesandbox.io/s/github/harabchuk/vue-yellow-marker-examples/tree/master/)

## License

MIT
npm package: @koha-community/prettier-plugin-template-toolkit
Description: Prettier plugin for formatting Template::Toolkit templates.
Author: Jonathan Druart
Latest version: 2.0.2

# prettier-plugin-template-toolkit

Formatter plugin for Template::Toolkit template files.

This is a fork of [prettier-plugin-jinja-template](https://github.com/davidodenwald/prettier-plugin-jinja-template), we are very grateful to the original author!

## Install

```bash
npm install --save-dev prettier prettier-plugin-template-toolkit
```

Add the plugin to your `.prettierrc`:
```json
{
  "plugins": ["prettier-plugin-template-toolkit"]
}
```

## Use

To format basic .html files, you'll have to override the used parser inside your `.prettierrc`:
```json
{
  "overrides": [
    {
      "files": ["*.html"],
      "options": {
        "parser": "template-toolkit"
      }
    }
  ]
}
```

Run it on all HTML files in your project:
```bash
npx prettier --write **/*.html
```

If you don't have a prettier config you can run the plugin with this command:
```bash
npx prettier --plugin=prettier-plugin-template-toolkit --parser=template-toolkit --write **/*.html
```

### Ignoring Code

Using range ignores is the best way to tell prettier to ignore part of files. Most of the time this is necessary for Template::Toolkit tags inside `script` or `style` tags:

```html
<!-- prettier-ignore-start -->
  <script>
    window.someData = [% data %]
  </script>
<!-- prettier-ignore-end -->

<!-- prettier-ignore-start -->
  <style>
    :root { --accent-color: [% theme_accent_color %] }
  </style>
<!-- prettier-ignore-end -->
```

Or using Template::Toolkit comments:
```tt
[%# prettier-ignore-start %]
  <script>
    window.someData = [% data %]
  </script>
[%# prettier-ignore-end %]

[%# prettier-ignore-start %]
  <style>
    :root { --accent-color: [% theme_accent_color %] }
  </style>
[%# prettier-ignore-end %]}
```
npm package: @kohaku-eth/railgun
Description: Simplified Railgun TS utils
Latest version: 0.0.1-alpha.12

# @kohaku-eth/railgun

Cross-platform Railgun Typescript SDK with support for kohaku's standard interfaces.  The SDK is designed to interface with railgun's on-chain contracts, facilitating state syncing, transaction construction, proof generation, transaction submission via broadcasters, and proof submission.

## Installation

```sh
pnpm add @kohaku-eth/railgun
```

## Quick Start

See the [tests](./tests/) for more examples.

## Development

Get your nix environment and env vars as explained in the root readme.

Run tests with this command (from root dir):

```shell
cd packages/railgun && just integration
```
npm package: @kohaku/hexo-renderer-markdown-it
Description: A faster and CommonMark compliant alternative for Hexo.
Author: Nanami
Latest version: 0.0.3

# Hexo Renderer Markdown-it

Modified from [markdown-it-katex](https://github.com/iktakahiro/markdown-it-katex/tree/fd03d2d21dbc02c73c8e651abd5386af076a1440) and [hexo-renderer-markdown-it-plus](https://github.com/CHENXCHEN/hexo-renderer-markdown-it-plus/tree/c94ed9305c1d5ddb9b1c305d7e2e53a1d84d76ce). For better KaTeX writing experience. You can find the original README file in `doc`.

> Local Git: lilyknight/hexo-related/hexo-renderer-markdown-it  
> Github: https://github.com/ymd45921/hexo-renderer-markdown-it-plus  
> NPM: `@kohaku/hexo-renderer-markdown-it`

## Usage

Recommend use it with `hexo-theme-ymd45921`.

You should remove your previous Markdown renderer before install this.

```bash
yarn remove hexo-renderer-marked
yarn add @kohaku/hexo-renderer-markdown-it
```

## Options

You can configure this renderer by adding a section to your hexo main `_config.yml` file like below. Of course, do-nothing is also recommend.

```yml
ymd45921:
  markdown_it:
    highlight: true
    html: true
    xhtmlOut: true
    breaks: true
    langPrefix:
    linkify: true
    typographer:
    quotes: “”‘’
    plugins:
      - plugin:
          name: markdown-it-mark
          enable: false
    katex:
      throwOnError: false
      errorColor: '#c00'
      strict: ignore          # ignore | warn | error
      output:                 # mathml | html | htmlAndMathml
      leqno: false
      fleqn: false
      macros: 
        "\\and": "\\mathbb{∧}"
```

The `plugins` object contains all plugins to markdown-it you want to add. If you want to add a plugin named as `markdown-it-something`, you should install it as a dependency first, and add it to the `plugins` object as provided format.

The `katex` object contains options that directly apply to KaTeX. Some options' meaning is as follows:

- `throwOnError`: when error occurred in KaTeX parsing, renderer will return the TeX formula if it set to `true`, or try to continue the parse by ignoring the part of the parse that went wrong.
- `errorColor`: while `throwOnError` set to `false`, renderer will set the ignored part to this color.
- `output`: determines the markup language of the output. Valid choices includes MathML, HTML and both.

 You can also check the [KaTeX official doc](https://katex.org/docs/options.html) to see what other key does in the example above.

## Some notes

If you set katex output format to `HTML`, you should import KaTeX's stylesheet in your webpage to ensure rendered block displays correctly in browsers. 

```html
<link rel="stylesheet" href="https://unpkg.com/katex@0.16.7/dist/katex.min.css">
```

Alternatively, if you set `MathML` as output, which will place rendered results to `<math>` blocks that have long been supported by Firefox long, and are supported by most modern browsers today.
npm package: @kohaku/hexo-theme-ymd45921
Description: A self-use Hexo theme, designed and modified based on volantis.
Latest version: 1.0.0

<h1 align="center">Hexo-theme-ymd45921</h1>

<p align="center">
  一个修改自 hexo-theme-volantis 的主题。用于自己的博客使用。
</p>
<p align="center">
  A Hexo theme forked from hexo-theme-volantis. Modified for self-use.
</p>
<br>

<p align="center">
  <a href="https://volantis.js.org">Volantis Official Website</a>
</p>

目前的默认分支是 2023 年基于 Volantis 的 `6.0-pjax` 分支重新修改而成。旧版本仍然可以通过 `legacy` 分支取得，Commit ID = 16a166d31866538ca107db2e7a45bd6ec3668000.
npm package: @kohaku/yidm-v3
Description: Some key functions used by Yidm Android APP.
Author: Nanami
Latest version: 0.0.4

# Yidm V3

An attempt to reverse engineer an Android React Native APP.

While in theory you could inject your own JS code and debug it dynamically, this is almost entirely static analysis.

## usage

Install this package by `yarn add @kohaku/yidm-v3` and use it to construct params in request sent to yidm.

It is now possible to construct device id randomly from strings.

Support `commonjs`, some issue still in `module`.
npm package: @kohana/mvc
Description: The mvc inspired from PHP's Kohana framework's pattern.
Author: Kojin Nakana
Latest version: 1.0.1

# KohanaJS core-mvc
The mvc inspired from PHP's Kohana framework's pattern.

## The core mvc defines MVC classes
### Model
Model is simple Javascript Object. Define it for future extension.

### View
View is Adapter for different template engine.
User store data in view.data, then render it to get text.

### Controller
Controller is the class accept request and return response from a client.
It provides 3 stages to execute a request.
1. before()
2. action_XXX()
3. after()

### ControllerMixin
Decorator for Controllers to perform additional functionality
npm package: @kohanajs/core-mvc
Description: The MVC classes inspired from Kohana framework's pattern
Author: Kojin Nakana
Latest version: 3.5.0

# KohanaJS core-mvc
The mvc inspired from PHP's Kohana framework's pattern.

## The core mvc defines MVC classes
### Model
Model is simple Javascript Object. Define it for future extension.

### View
View is Adapter for different template engine.
User store data in view.data, then render it to get text.

### Controller
Controller is the class accept request and return response from a client.
It provides 3 stages to execute a request.
1. before()
2. action_XXX()
3. after()

### ControllerMixin
Decorator for Controllers to perform additional functionality
npm package: @kohanajs/esm-mvc
Description: The MVC classes inspired from Kohana framework's pattern
Author: Kojin Nakana
Latest version: 1.0.0

# KohanaJS core-mvc
The mvc inspired from PHP's Kohana framework's pattern.

## The core mvc defines MVC classes
### Model
Model is simple Javascript Object. Define it for future extension.

### View
View is Adapter for different template engine.
User store data in view.data, then render it to get text.

### Controller
Controller is the class accept request and return response from a client.
It provides 3 stages to execute a request.
1. before()
2. action_XXX()
3. after()

### ControllerMixin
Decorator for Controllers to perform additional functionality
npm package: @kohanajs/mod-mail
Description: KohanaJS Transactional Email Module
Author: Kojin Nakana
Latest version: 8.0.2

# kohanajs-mod-mail

Module for Transactional email

##install
```npm i @kohanajs/mod-mail```

this will install Mail Object with default adapter for preview

add ```require("@kohanajs/mod-mail");``` to application/require.js to load default config file and default routes.

##usage
```
const {Mail} = require('@kohanajs/mod-mail');

const mail = new Mail({
  domain:'localhost',
  ip:'127.0.0.1'
});
await mail.send('this is subject', 'this is body text', 'sender@kohanajs.com', 'recipient@example.com')
```

###templates
```
const mail = new Mail({
  domain:'localhost',
  ip:'127.0.0.1'
  templateFolder: `${__dirname}/edm`
});

const result = await mail.send('subject', 'test.txt', 'TEST', '20221234', {
  html:'test.html',
  tokens: {'message': 'hello world'},
});

//result.payload.text
//result.payload.html
```

###only html template
```
const mail = new Mail({
  domain:'localhost',
  ip:'127.0.0.1'
  templateFolder: new Map([
    ['html', `${__dirname}/edm`]
  ])
});

const result = await mail.send('subject', 'hello {{@message}}', 'TEST', '20221234', {
  html:'test.html',
  tokens: {'message': 'hello world'},
});

//result.payload.text
//result.payload.html
```

###template use handle (WIP)
```
const mail = new Mail({
  domain:'localhost',
  ip:'127.0.0.1'
  templateFolder: '@edm'
});

const result = await mail.send('subject', 'test::text', 'TEST', '20221234', {
  html:'test::html',
  tokens: {'message': 'hello world'},
});
```
npm package: @kohapi/generator
Description: A auto code generator.
Author: kohai
Latest version: 0.0.1-alpha.14

# @kohapi/generator

> 开发中

一个自动生成代码文件的工具

## 使用说明

```bash
# 全局安装
npm install -g @kohapi/generator

# 局部安装（推荐）
npm install -D @kohapi/generator

# 查看帮助信息
kohapi-generator

# 初始化配置文件
kohapi-generator init

# 生成 yapi 对应的前端文件
kohapi-generator yapi-client-ts

# 生成 yapi 对应的 hapi 文件
kohapi-generator yapi-hapi-ts

# 指定配置文件名称，路径相对于项目根目录
kohapi-generator yapi-client-ts -c ./config/kohapi.config.js

# 其他待开发
```
npm package: @koharakazuya/nextjs-component-catalog
Description: CLI to generate component catalog for Next.js (App Router)
Author: KoharaKazuya
Latest version: 0.4.0

# Next.js Component Catalog

Next.js (App Router) アプリケーション開発でコンポーネントカタログを提供します。

## 使い方

**1. ソースコード中の任意の箇所にカタログファイルを作成する**

ファイル名は `*.catalog.jsx` や `*.catalog.tsx` である必要があります。

推奨: コンポーネントの実装ファイルの隣に配置することを推奨します。

例:

```
Example/
  index.ts
  Example.tsx
  Example.catalog.tsx
```

**2. カタログファイルにコンポーネントの使用例を実装し、名前付きでエクスポートする**

エクスポートで使用した名前はパスとして使用されます。

特定のコンテナサイズや背景色、中央揃えなどのレイアウトでコンポーネントを動かしたい場合はここで調整してください。

例:

```tsx
import Example from "./Example";

export function Default() {
  return <Example />;
}

export function Checked() {
  return <Example checked />;
}
```

**3. ビルドを実行してページを生成する**

```console
$ npx nextjs-component-catalog build
```

を実行してください。ソースコード中のカタログファイルの定義から app/ ディレクトリ以下に Next.js のルート定義ファイルが生成されます。

Next.js を起動し、カタログのページ (デフォルトでは `/dev/catalog`) にアクセスするとカタログを確認できます。

```console
$ npx nextjs-component-catalog build --watch
```

で監視モードで起動することもできます。

プロジェクトルートに `.nextjs-component-catalogrc` という JSON ファイルを作成すると設定を変更することができます。詳細は <./src/generator.ts> の `Options` を参照してください。

## 仕組み

このツールのコア部分の大まかな仕組みは以下の通りです。

- 特定ディレクトリ以下の `*.catalog.tsx` などを監視
- カタログファイルを見つけたら、ファイル内容をパースし、export 構文からシンボルを取得
- カタログファイルに対応するパスとなるよう app/ 以下にファイルを生成 (ファイルの内容はカタログファイルを読み込み表示するだけのページコンポーネント)

## Storybook との比較

コンポーネントカタログツールが必要な場合、基本的には [Storybook](https://storybook.js.org/) を使用することを推奨します。

以下の観点で Storybook が適さずこのツールが必要になる場合があります。

- Storybook が Next.js とは別のビルドチェーンを持っていることにより、セットアップの手間が大きすぎるもしくは一部のビルド機能が再現できない
- アプリケーション全体で設定している機能 (共通の認証や React Context など) を Next.js 側と Storybook 側で多重に管理したくない
- コンポーネントカタログをアプリケーションに埋め込みたい
- もっとシンプルにしたい
- もっとビルドを速くしたい

このような観点がない場合、Storybook は多数の非常に洗練された機能を持つためデフォルトで便利です。
npm package: @koharakazuya/typescript-i18n
Description: 国際化対応 (i18n) するとき TypeScript においてシンプルかつ便利な方法を提供する
Author: KoharaKazuya
Latest version: 0.1.0

# `@koharakazuya/typescript-i18n`

国際化対応 (i18n) するとき TypeScript においてシンプルかつ便利な方法を提供する npm パッケージ。

## 特徴

- 翻訳データは非プログラマが扱うこともあるので JSON のような単純な形式で定義できる
- 翻訳データの構造、パラメーターについて TypeScript の型推論機能で抜け漏れのチェックや自動補完ができる
- 翻訳データの各項目は使用箇所を追跡できる

## インストール

```console
$ npm install @koharakazuya/typescript-i18n
```

前提として TypeScript 最新バージョン、Compiler Option の `strict: true` 環境を想定しています。

## 使い方

サンプル

```typescript
import {
  checkSchemaParams,
  i18n,
  type Dictionary,
  type DictionarySchema,
} from "@koharakazuya/typescript-i18n";

// 翻訳データは `{ system: { title: "タイトル" } }` のように JSON のような形式で
// 構造で定義します。末端が文字列となっていれば自由にネストできます。
// また、`"年齢は{{age}}です。"` のように `{{変数名}}` で変数を埋め込むことができます。
// ここでは翻訳データの構造を定義します。データの構造とパラメーターについて定義してください。
// `extends DictionarySchema` は必須です。
interface MyDictionarySchema extends DictionarySchema {
  title: { brand: string; year: number };
  message: {
    submit: {};
    error: { amount: number };
    ok: {
      alert: {};
    };
  };
}

// 各言語ごとの翻訳データを定義します。翻訳データの構造に沿って定義してください。
// 変数自体に型は宣言せず、`as const satisfies Dictionary<MyDictionarySchema>`
// をつけなければならないことに注意してください。
const ja = {
  title: "{{brand}} from {{year}}",
  message: {
    submit: "送信しました",
    error: "エラーが発生しました: {{amount}}",
    ok: { alert: "OK" },
  },
} as const satisfies Dictionary<MyDictionarySchema>;
// 翻訳データ中で使ったパラメーターがデータ構造中に存在するかチェックします。
// 不足しているとコンパイルエラーになります。関数の中身は空なので実行時は何も実行しません。
checkSchemaParams<typeof ja, MyDictionarySchema>();

// 各言語ごとに翻訳関数を定義します。
const t = i18n<MyDictionarySchema>(ja);

// 翻訳関数を使って翻訳した文字列を取得します。
// どのデータを使用するか第一引数で指定します。このときエディタの補完機能が使えます。
// また、間違ったデータを指定した場合はコンパイルエラーになります。
// 第二引数には翻訳データのパラメーターを指定します。同様にエディタの補完機能が使えます。
const s1 = t((x) => x.message.error, { amount: 100 });
const s2 = t((x) => x.message.submit, {});
const s3 = t((x) => x.title, { brand: "Example", year: 2023 });

console.log({ s1, s2, s3 });
```
npm package: @kohicorp/wizard
Description: Setup wizard for Kohi API monitoring
Author: KohiCorp
Latest version: 0.0.2

# @kohicorp/wizard

Setup wizard for Kohi API monitoring.

## Usage

```bash
npx @kohicorp/wizard
```

## What it does

1. Detects your framework from project files
2. Prompts for your Kohi project key and secret key
3. Installs the SDK
4. Configures environment variables (`.env` for Node/Python, `export` commands for Go)
5. Shows the integration code (copied to clipboard)

## Supported Frameworks

| Framework | Language | SDK |
|-----------|----------|-----|
| Next.js | Node.js | kohi-node |
| Express | Node.js | kohi-node |
| net/http | Go | kohi-go |
| fasthttp | Go | kohi-go |
| FastAPI | Python | kohi-python |
| Flask | Python | kohi-python |
npm package: @kohlarnhin/mcp-server-postgres
Description: MCP server for interacting with PostgreSQL databases based on Node
Latest version: 1.0.0

# MCP Server for PostgreSQL

这是一个基于Node.js的MCP（Model Context Protocol）服务器，用于与PostgreSQL数据库交互。它允许AI模型通过MCP协议查询和操作PostgreSQL数据库。

## 功能特点

- 支持基本的SQL查询操作
- 可配置的写操作权限（INSERT、UPDATE、DELETE、DDL）
- 多数据库模式支持
- 基于模式的细粒度权限控制
- 安全的事务管理
- 查询结果以JSON格式返回

## 安装

```bash
# 全局安装
npm install -g @kohlarnhin/mcp-server-postgres

# 本地安装
npm install @kohlarnhin/mcp-server-postgres
```

## 配置

环境变量可以通过`.env`文件或直接在运行环境中设置：

```
POSTGRES_HOST=127.0.0.1
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASS=your_password
POSTGRES_DB=your_database

# 日志设置
ENABLE_LOGGING=true

# 写操作权限（全局）
ALLOW_INSERT_OPERATION=true
ALLOW_UPDATE_OPERATION=true
ALLOW_DELETE_OPERATION=false
ALLOW_DDL_OPERATION=false

# 基于特定模式的权限（可选）
# 格式: "schema1:true,schema2:false"
SCHEMA_INSERT_PERMISSIONS="public:true,private:false"
SCHEMA_UPDATE_PERMISSIONS="public:true,private:false"
SCHEMA_DELETE_PERMISSIONS="public:false,private:false"
SCHEMA_DDL_PERMISSIONS="public:false,private:false"

# 多数据库模式（可选）
# 当POSTGRES_DB为空时启用
MULTI_DB_WRITE_MODE=false
```

## 使用方法

### 本地开发

```bash
npm run dev
```

### 生产环境

```bash
npm run build
npm start
```

### 以stdio模式运行（用于MCP集成）

```bash
npm run stdio
```

## MCP集成

在`~/.cursor/mcp.json`中添加以下配置，将其集成到支持MCP的环境中：

```json
{
  "mcpServers": {
    "Postgres": {
      "command": "npx",
      "args": [
        "mcprunner",
        "POSTGRES_HOST=127.0.0.1",
        "POSTGRES_PORT=5432",
        "POSTGRES_USER=postgres",
        "POSTGRES_PASS=123456",
        "POSTGRES_DB=your_database",
        "ALLOW_INSERT_OPERATION=true",
        "ALLOW_UPDATE_OPERATION=true",
        "ALLOW_DELETE_OPERATION=false",
        "--",
        "npx",
        "-y",
        "@kohlarnhin/mcp-server-postgres"
      ]
    }
  }
}
```

## 查询示例

通过MCP协议，可以执行如下SQL查询：

```sql
-- 查询表列表
SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'

-- 查询特定表的结构
SELECT column_name, data_type FROM information_schema.columns WHERE table_name = 'your_table' AND table_schema = 'public'

-- 查询数据
SELECT * FROM your_table WHERE condition

-- 插入数据（如果启用了INSERT权限）
INSERT INTO your_table (column1, column2) VALUES ('value1', 'value2')

-- 更新数据（如果启用了UPDATE权限）
UPDATE your_table SET column1 = 'new_value' WHERE condition

-- 删除数据（如果启用了DELETE权限）
DELETE FROM your_table WHERE condition

-- DDL操作（如果启用了DDL权限）
CREATE TABLE new_table (id SERIAL PRIMARY KEY, name VARCHAR(100))
```

## 许可证

MIT
npm package: @kohlmannj/css-to-object
Description: Convert flat CSS rule to JavaScript style object
Author: Joseph Kohlmann
Latest version: 1.2.1


# @kohlmannj/css-to-object

Convert flat CSS rules to JavaScript style objects

Useful for css-in-js libraries

```sh
npm i css-to-object
```

```js
const cssToObject = require('css-to-object')

const style = cssToObject(`
  color: tomato;
  padding: 16px;
  @media (min-width: 40em) {
    paddingLeft: 32px;
    paddingRight: 32px;
  }
  &:hover: {
    color: black;
  }
  & h1 {
    font-size: 48px;
  }
`, {
  camelCase: true,
  numbers: true
})

// {
//   color: 'tomato',
//   padding: 16,
//   '@media (min-width: 40em)': {
//     paddingLeft: 32,
//     paddingRight: 32,
//   },
//   ':hover': {
//     color: 'black'
//   },
//   h1: {
//     fontSize: 48
//   }
// }
```

## Options

- `ampersands`: preserves `&` in nested selectors
  - For use with JSS / [jss-nested](http://cssinjs.org/jss-nested/?v=v6.0.1) and other CSS-in-JS solutions that support the `&` reference selector
- `numbers`: Converts px values to numbers
- `camelCase`: converts CSS properties to camelCased keys

## Differences from the Original
This is a fork of [jxnblk/css-to-object](https://github.com/jxnblk/css-to-object) / [`css-to-object` on NPM](https://www.npmjs.com/package/css-to-object) with the following changes:

- Add `ampersands` option (see above)
- Import [`css.parse()`](https://github.com/reworkcss/css#cssparsecode-options) directly, thereby enabling **usage in web browsers**
  - The [`css` module]() exports both its `parse()` and `stringify()` methods
  - `css.stringify()`'s [source map support](https://github.com/reworkcss/css/blob/master/lib/stringify/source-map-support.js) depends on [Node `fs`](https://www.nodejs.org/api/fs.html) module, which can't be used in-browser
  - Therefore, despite only using `css.parse()`, the original `css-to-object` module cannot be bundled with Webpack or used client-side
- Incorporate @meyer's shorthand bugfix ([jxnblk/css-to-object#3](https://github.com/jxnblk/css-to-object/pull/3))

[MIT License](LICENSE.md)
npm package: @kohlmannj/opml-generator
Description: opml generator for node.js
Author: Joseph Kohlmann
Latest version: 2.0.0-alpha.1

# opml-generator.js [![Build Status](https://travis-ci.org/azu/opml-generator.svg)](https://travis-ci.org/azu/opml-generator)

Generate opml from object.

## Installation

```sh
npm install opml-generator
```

## Usage

``` js
var header = {
    "title": "title-text",
    "dateCreated": new Date(2014, 2, 9),
    "ownerName": "azu"
};
var outlines = [
    {
        text: "txt",
        title: "title-text",
        type: "rss",
        "xmlUrl": "http://example.com/rss",
        "htmlUrl": "http://example.com/"
    },
    {
        text: "txt",
        title: "title-text",
        type: "rss",
        "xmlUrl": "http://example.com/rss",
        "htmlUrl": "http://example.com/"
    }
];
opml(header, outlines);// => XML
```

## Contributing

1. Fork it!
2. Create your feature branch: `git checkout -b my-new-feature`
3. Commit your changes: `git commit -am 'Add some feature'`
4. Push to the branch: `git push origin my-new-feature`
5. Submit a pull request :D

## License

MIT
npm package: @kohoz/claudy
Description: Claude Code Workspace Manager - Launch Claude with pre-configured workspaces
Author: Koho Zheng
Latest version: 1.0.1

# Claudy

Claude Code Workspace Manager - Launch Claude with pre-configured workspaces.

```
 ▐▛███▜▌  ▐▛███▜▌  ▐▛███▜▌
▝▜█████▛▘▝▜█████▛▘▝▜█████▛▘
  ▘▘ ▝▝    ▘▘ ▝▝    ▘▘ ▝▝
```

## Features

- Save and manage multiple Claude Code workspaces
- Quick launch with pre-configured working directories
- Support for additional directories (`--add-dir`)
- Interactive TUI for workspace selection
- CLI commands for automation

## Requirements

- [Bun](https://bun.sh) >= 1.0.0
- [Claude Code](https://docs.anthropic.com/en/docs/claude-code) CLI installed

## Installation

```bash
bun add -g @kohoz/claudy
```

## Usage

### Interactive Mode

Simply run `claudy` to open the interactive workspace selector:

```bash
claudy
```

### Add a Workspace

```bash
# Add current directory interactively
claudy add

# Add current directory with a name
claudy add myapp

# Add a specific directory
claudy add myapp ~/projects/myapp

# Add with additional directories
claudy add myapp ~/projects/myapp ~/projects/shared-lib
```

### Launch a Workspace

```bash
claudy myapp
```

### Manage Workspaces

```bash
# List all workspaces
claudy ls

# Edit a workspace
claudy edit myapp

# Delete a workspace
claudy rm myapp
```

## Commands

| Command | Description |
|---------|-------------|
| `claudy` | Interactive workspace selector |
| `claudy <name>` | Launch workspace directly |
| `claudy add [name] [cwd] [dirs...]` | Add a new workspace |
| `claudy edit [name]` | Edit an existing workspace |
| `claudy rm [name]` | Remove a workspace |
| `claudy ls` | List all workspaces |
| `claudy help` | Show help |
| `claudy --version` | Show version |

## Configuration

Workspaces are stored in `~/.config/claudy/workspaces.json`:

```json
{
  "workspaces": [
    {
      "name": "myapp",
      "description": "My awesome app",
      "cwd": "/path/to/myapp",
      "addDirs": ["/path/to/shared-lib"]
    }
  ]
}
```

## How It Works

Claudy is a wrapper around Claude Code that:

1. Stores workspace configurations (working directory + additional directories)
2. Launches Claude Code with the correct `cwd` and `--add-dir` flags
3. Provides a nice TUI for selecting workspaces

When you run `claudy myapp`, it executes:

```bash
cd /path/to/myapp && claude --add-dir /path/to/shared-lib
```

## License

MIT
npm package: @koi-br/web-ai-chat
Description: 一个轻量级的网页AI聊天窗口组件
Author: Your Name
Latest version: 1.0.7

# Web AI Chat Window

一个轻量级的网页AI聊天窗口组件，支持页面数据展示和实时对话功能。

## 安装

### NPM
```bash
npm install @koi-br/web-ai-chat
```

### Yarn
```bash
yarn add @koi-br/web-ai-chat
```

### CDN
```html
<!-- 引入样式和脚本 -->
<link rel="stylesheet" href="https://unpkg.com/@koi-br/web-ai-chat@latest/dist/styles.css">
<script src="https://unpkg.com/@koi-br/web-ai-chat@latest/dist/index.umd.js"></script>
```

## API密钥获取

要使用Web AI Chat，您需要一个有效的API密钥。您可以通过以下方式获取：

1. 访问 [OpenAI平台](https://platform.openai.com/account/api-keys)
2. 注册或登录您的OpenAI账户
3. 在API密钥页面点击"Create new secret key"
4. 复制生成的密钥并妥善保管

注意：
- API密钥属于敏感信息，请勿直接在前端代码中暴露
- 建议通过后端服务器中转API请求，保护您的密钥安全
- 首次使用需要绑定支付方式，API调用会产生相应费用

## 使用方法

### ES Module
```javascript
import { WebAIChat } from '@koi-br/web-ai-chat';
import '@koi-br/web-ai-chat/dist/styles.css';

const chat = new WebAIChat({
  container: '#chat-container',
  apiKey: 'your-api-key'
});

await chat.init();
```

### CommonJS
```javascript
const { WebAIChat } = require('@koi-br/web-ai-chat');
require('@koi-br/web-ai-chat/dist/styles.css');

const chat = new WebAIChat({
  container: '#chat-container',
  apiKey: 'your-api-key'
});

chat.init();
```

### UMD (浏览器直接使用)
```html
<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="https://unpkg.com/@koi-br/web-ai-chat@latest/dist/styles.css">
</head>
<body>
  <div id="chat-container"></div>
  <script src="https://unpkg.com/@koi-br/web-ai-chat@latest/dist/index.umd.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', async () => {
      try {
        // 使用 WebAIChatModule.WebAIChat 构造函数
        const chat = new WebAIChatModule.WebAIChat({
          container: '#chat-container',
          apiKey: 'your-api-key'
        });
        
        await chat.init();
      } catch (error) {
        console.error('Chat initialization failed:', error);
      }
    });
  </script>
</body>
</html>
```

## 配置选项

```typescript
interface ChatConfig {
  container: string;        // 容器选择器（必需）
  apiKey: string;          // API密钥（必需）
  height?: number;         // 聊天窗口高度，默认 500
  width?: number;          // 聊天窗口宽度，默认 350
  theme?: 'light'|'dark';  // 主题，默认 'light'
}
```

## 方法

### init()
初始化聊天窗口。

### send(message: string)
发送消息。

### clear()
清空聊天记录。

### setTheme(theme: 'light' | 'dark')
切换主题。

## 事件监听

```javascript
// 监听消息事件
chat.on('message', (message) => {
  console.log('New message:', message);
});

// 监听错误事件
chat.on('error', (error) => {
  console.error('Error:', error);
});
```

## 许可证

MIT
npm package: @koi-br/web-tracker-simple
Description: A lightweight web tracking SDK
Author: dekun.tang
Latest version: 1.2.3

# Web Tracker Simple

一个简单的 Web 埋点工具，支持页面访问、点击事件等基础埋点功能。

## 功能特点

- 📊 页面访问（PV）统计
- 👆 点击事件跟踪
- 📱 设备信息收集
- 👤 用户行为分析
- 📝 自定义数据上报
- 📌 自定义页面标题
- 🛣 路由变化监听
- 🔄 防重复上报

## 安装

```bash
npm install @koi-br/web-tracker-simple
```

## 使用示例

### 基础配置

```typescript
import Tracker from '@koi-br/web-tracker-simple';

const tracker = Tracker({
  appId: 'your-app-id',
  endpoint: 'your-endpoint',
  debug: true
});
```

### 使用子类

如果需要直接访问各个子类：

```typescript
import Tracker from '@koi-br/web-tracker-simple';

// 获取子类引用
const { PageTracker, ClickTracker } = Tracker;

// 使用工厂函数创建跟踪器实例
const tracker = Tracker({
  appId: 'your-app-id',
  endpoint: 'your-endpoint'
});
```

### 动态设置自定义数据

```typescript
// 设置自定义数据
tracker.setCustomData({
  userId: '123',
  userType: 'vip',
  customField: 'customValue'
});

// 获取当前自定义数据
const currentData = tracker.getCustomData();
```

### 动态设置页面标题

```typescript
// 设置自定义页面标题
tracker.setCustomTitle('自定义页面标题');

// 获取当前自定义标题
const currentTitle = tracker.getCustomTitle();
```

### 设置用户ID

```typescript
tracker.setUserId('user-123');
```

### 初始化路由（Vue Router）

```typescript
import { createRouter } from 'vue-router';

const router = createRouter({
  // 你的路由配置
});

tracker.initRouter(router);
```

### 点击事件跟踪

在 HTML 元素上添加 `data-track-id` 属性来跟踪点击事件：

```html
<button data-track-id="submit-button">提交</button>
```

可以添加自定义数据属性：

```html
<button 
  data-track-id="submit-button"
  data-custom-user-type="vip"
  data-custom-action="submit"
>
  提交
</button>
```

## 配置选项

```typescript
interface TrackerConfig {
  appId: string;         // 应用ID（必填）
  endpoint?: string;     // 上报地址
  debug?: boolean;       // 是否开启调试模式
  sampleRate?: number;   // 采样率 0-1
  maxBatchSize?: number; // 批量上报大小
  maxWaitTime?: number;  // 最大等待时间(ms)
  customData?: Record<string, any>;  // 自定义数据
  customTitle?: string;  // 自定义页面标题
}
```

## 事件数据格式

### 页面访问事件

```typescript
interface PageViewData {
  title: string;         // 页面标题
  url: string;          // 页面URL
  referrer: string;     // 来源页面
  timestamp: number;    // 时间戳
  pageKey: string;      // 页面标识
  isFirst: boolean;     // 是否首次访问
}
```

### 点击事件

```typescript
interface ClickEventData {
  trackId: string;      // 跟踪ID
  elementType: string;  // 元素类型
  elementText: string;  // 元素文本
  title: string;        // 页面标题
  url: string;         // 页面URL
  pageKey: string;     // 页面标识
  // ... 其他自定义数据
}
```

## 注意事项

1. 确保在使用前设置正确的 `appId` 和 `endpoint`
2. 建议在开发环境开启 `debug` 模式以便调试
3. 自定义数据属性名需要使用 `data-custom-` 前缀
4. 页面标题获取优先级：路由 meta > 自定义标题 > document.title
5. 设备ID会在本地存储中保存，用于用户识别

## License

MIT

## Author

dekun.tang
npm package: @koi-br/web-tracking
Description: 前端埋点SDK
Latest version: 1.0.2

# Web Tracking SDK

一个轻量级的前端埋点SDK，专注于页面访问、用户行为和性能数据的采集。支持自动采样、节流控制和SPA应用。

## 核心功能

### 1. 自动数据采集
- 🔄 页面访问统计 (PV/UV)
  - 页面进入/离开事件
  - 访客身份识别
  - 访问次数统计
  - 停留时长记录

- 🖱️ 用户交互追踪
  - 按钮点击事件
  - 链接点击事件
  - 页面滚动深度
  - 点击位置热图

- 📊 性能监控
  - 页面加载时间
  - 首次渲染时间
  - DOM就绪时间

### 2. 智能采集策略
- ⚡ 事件节流 (2秒间隔)
- 🌊 滚动防抖 (500ms)
- 📦 批量数据上报
- 🎯 可配置采样率

## 安装

```bash
npm install @koi-br/web-tracking
```

## 快速开始

```typescript
import { initTracker } from '@koi-br/web-tracking';

const tracker = initTracker({
  appId: 'your-app-id',
  uploadUrl: 'https://your-api.com/collect',
  autoTrack: true,
  uploadInterval: 5000,
  maxCache: 50,
  sampling: {
    ratio: 0.5,                    // 采样率50%
    eventTypes: ['button_click']   // 指定采样事件类型
  }
});
```

## 配置项

| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| appId | string | - | 应用标识 |
| uploadUrl | string | - | 数据上报地址 |
| autoTrack | boolean | false | 开启自动采集 |
| uploadInterval | number | 5000 | 上报间隔(ms) |
| maxCache | number | 50 | 本地缓存上限 |
| sampling.ratio | number | 1 | 采样比例(0-1) |
| sampling.eventTypes | string[] | - | 采样事件类型 |

## 采集数据结构

```typescript
interface TrackEvent {
  // 基础信息
  type: 'page_enter' | 'page_leave' | 'button_click' | 'link_click' | 'page_scroll' | 'uv';
  timestamp: number;
  url: string;
  title: string;

  // 访客信息
  visitorId: string;     // 访客ID
  isNewVisitor: boolean; // 是否新访客
  visitCount: number;    // 访问次数
  sessionId: string;     // 会话ID
  
  // 环境信息
  userAgent: string;     // 浏览器信息
  deviceType: string;    // 设备类型
  screenSize: string;    // 屏幕尺寸
  language: string;      // 用户语言
  timezone: string;      // 时区
  referrer: string;      // 来源页面

  // 交互数据
  duration?: number;     // 停留时长
  scrollDepth?: number;  // 滚动深度
  buttonText?: string;   // 按钮文本
  buttonId?: string;     // 按钮ID
  linkText?: string;     // 链接文本
  linkHref?: string;     // 链接地址
  clickPosition?: {      // 点击位置
    x: number;
    y: number;
    elementPath: string;
  };

  // 性能数据
  performance?: {
    loadTime: number;    // 加载耗时
    firstPaint: number;  // 首次渲染
    domReady: number;    // DOM就绪
  };
}
```

## 性能优化

1. 数据采集优化
   - 事件节流控制，避免高频触发
   - 滚动事件防抖处理
   - 可配置采样率，降低数据量

2. 数据上报优化
   - 批量上报机制
   - 本地数据缓存
   - 上报失败自动重试
   - 页面关闭前确保数据发送

## 浏览器支持

- 支持所有现代浏览器
- 支持移动端浏览器
- 依赖 localStorage 和 Performance API

## 开发构建

```bash
# 安装依赖
npm install

# 开发构建
npm run dev

# 生产构建
npm run build
```

## License

MIT
npm package: @koi-br/web-tracking-sdk
Description: web-watch
Author: BR
Latest version: 1.1.1

# Web Tracking SDK

一个轻量级的前端埋点SDK，专注于页面访问、用户行为和性能数据的采集。支持自动采样、SPA应用和表单监控。

## 核心功能

### 1. 页面访问统计
- 🔄 PV/UV 统计
  - 页面浏览/进入/离开事件
  - 访客身份识别与追踪
  - 会话管理
  - 页面停留时长

### 2. 用户行为追踪
- 🖱️ 点击事件追踪
  - 重要按钮点击（提交、保存、删除等）
  - 外部链接点击
  - 可追踪元素点击
  - 点击位置与元素路径
- 📝 表单行为监控
  - 表单提交事件
  - 表单基础信息采集

### 3. 性能监控
- ⚡ 核心性能指标
  - First Contentful Paint (FCP)
  - Largest Contentful Paint (LCP)
  - 页面加载性能
  - DOM 准备时间

### 4. 智能采集策略
- 🎯 灵活的采样配置
- 🔍 重要行为优先采集
- 🌟 SPA 路由变化监听
- 🛡️ 防止重复采集

## 安装

```bash
npm install @koi-br/web-tracking-sdk
```

## 快速开始

```typescript
import { initTracker } from '@koi-br/web-tracking-sdk';

const tracker = initTracker({
  appId: 'your-app-id',
  uploadUrl: 'https://your-api.com/collect',
  autoTrack: true,
  uploadInterval: 5000,
  projectId: 'your-project-id',
  maxCache: 50,
  sampling: {
    ratio: 0.5,                    // 采样率50%
    eventTypes: ['click_button']   // 指定采样事件类型
  }
});
```

## 事件类型

```typescript
type EventType = 
  // 页面相关
  | 'page_view'      // 页面浏览
  | 'page_enter'     // 页面进入
  | 'page_leave'     // 页面离开
  | 'page_scroll'    // 页面滚动
  // 交互相关
  | 'click_button'   // 按钮点击
  | 'click_link'     // 链接点击
  | 'click_element'  // 元素点击
  | 'form_submit'    // 表单提交
  // 性能相关
  | 'performance'    // 性能数据
  // 用户相关
  | 'user_visit'     // 用户访问
  | 'user_engage'    // 用户参与
  | 'custom_event';  // 自定义事件
```

## 配置选项

| 参数 | 类型 | 默认值 | 说明 |
|------|------|--------|------|
| appId | string | - | 应用标识 |
| uploadUrl | string | - | 数据上报地址 |
| autoTrack | boolean | false | 开启自动采集 |
| uploadInterval | number | 5000 | 上报间隔(ms) |
| maxCache | number | 50 | 本地缓存上限 |
| sampling.ratio | number | 1 | 采样比例(0-1) |
| sampling.eventTypes | string[] | - | 采样事件类型 |

## 特色功能

### 1. 智能按钮识别
- 支持通过文本内容识别重要按钮（如：提交、保存、删除等）
- 支持 role="button" 属性识别
- 支持自定义 data-track 属性标记

### 2. 链接点击过滤
- 自动过滤无效链接
- 排除锚点链接
- 支持 no-track 类名排除

### 3. SPA 支持
- 自动监听路由变化
- 准确记录页面切换
- 支持 History API

### 4. 访客追踪
- 唯一访客标识
- 新老访客区分
- 访问次数统计
- 会话管理

## 浏览器支持

- 现代浏览器 (Chrome, Firefox, Safari, Edge)
- 移动端浏览器
- 依赖 API: localStorage, MutationObserver, PerformanceObserver

## License

MIT