open-index/open-npm huggingface dataset:
npm package: @ko-developerhong/react-native-crypto-rsa
Description: crypto library for rsa
Author: ko-devHong
Latest version: 0.1.22

# @ko-developerhong/react-native-crypto-rsa

## introduce
>`@ko-developerhong/react-native-crypto-rsa` The library provides RSA encryption and decryption in React Native applications, which allow you to generate public and private keys, and encrypt or decrypt messages.

## Installation

```sh
npm install @ko-developerhong/react-native-crypto-rsa
```

## iOS
1. Add the following lines to the Podfile.
```Podfile
pod 'react-native-crypto-rsa', :path => '../node_modules/react-native-crypto-rsa'
```
2. From the terminal, go to the root directory of the project and issue the `pod install` command.
```shell
cd ios
pod install
# OR
npx pod-install ios
```
### Manual Installation
> Open `Xcode`, click Project Files, and add `libreact-native-crypto-rsa.a` to the `Link Binary With Libraries` section on the `Build Phases` tab.

## Usage

### Generating public and private keys
- The `publicKey` value is returned in the form of a `pemString`.
```tsx
import RNCryptoRsa from '@ko-developerhong/react-native-crypto-rsa';

// keySize: An integer value representing the size of the key to be generated. The default is 2048.
const keySize = 2048
const { publicKey } = await RNCryptoRsa.init(keySize);
const publicKeyPemString = await RNCryptoRsa.getPublicKey();
```

### Encrypt and decrypt messages
```tsx
import RNCryptoRsa from '@ko-developerhong/react-native-crypto-rsa';

const encryptedMessage = await RNCryptoRsa.encrypt('Hello, World!', publicKey);
const decryptedMessage = await RNCryptoRsa.decrypt(encryptedMessage); // Hello, World!
```

### SHA512 hash generation
```tsx
import RNCryptoRsa from '@ko-developerhong/react-native-crypto-rsa';

const { publicKey } = await RNCryptoRsa.init(keySize);
const sha512Text = await RNCryptoRsa.getSHA512Text(publicKey); // hashText
```

## Precautions
> RSA encryption and decryption are CPU and memory intensive, which can affect performance when handling large amounts of data.
> Public and private keys are critical to security, so they should be stored in a secure place and deleted if unnecessary.
> The public key is used to encrypt the message, and the private key is used to decrypt the encrypted message.

## Example
```shell
yarn example start

yarn example android
# OR
yarn example ios
```

## Contributing

See the [contributing guide](CONTRIBUTING.md) to learn how to contribute to the repository and the development workflow.

## License

MIT

---

Made with [create-react-native-library](https://github.com/callstack/react-native-builder-bob)
npm package: @ko-yelie/kgl
Description: Minimal WebGL library
Author: Ko.Yelie
Latest version: 0.6.2

# KGL

Minimal WebGL library

## Pros and Cons

### Pros

- Lightweight
- Can write with less code.
- Automates calculations to fit WebGL and DOM sizes.
- Support TypeScript.

### Cons

- Fragment shaders must always be written by you.
- Cannot use complex 3D models.
- Cannot use lighting.
- Not support WebGL2 yet.

## Documentation

- [API](https://ko-yelie.github.io/kgl/api/)

## Usage

### Installation

#### ES Modules

[npm](https://www.npmjs.com/package/@ko-yelie/kgl)

```sh
npm i @ko-yelie/kgl
```

```js
// Kgl
import Kgl from '@ko-yelie/kgl'

// KglAuto
import { KglAuto } from '@ko-yelie/kgl'

// Import only KGL (ignore KglAuto and effects)
import Kgl from '@ko-yelie/kgl/dist/kgl.es.js'
```

#### CDN

[unpkg](https://unpkg.com/@ko-yelie/kgl)

```html
<script src="https://unpkg.com/@ko-yelie/kgl"></script>
```

```js
// Kgl
Kgl.default

// KglAuto
const { KglAuto } = Kgl
```

### `Kgl`

#### HTML

```html
<script type="x-shader/x-fragment" id="fs">
  precision highp float;

  uniform vec2 uResolution; // window size (auto added)
  uniform float uTime;

  void main() {
    float alpha = 1. - length(gl_FragCoord.xy / uResolution) * (sin(uTime) * 0.5 + 0.5);
    gl_FragColor = vec4(vec3(0.), alpha);
  }
</script>
```

#### JS

```js
import Kgl from '@ko-yelie/kgl'

const kgl = new Kgl()

/**
 * program
 */
const program = kgl.createProgram({
  fragmentShaderId: 'fs',
  uniforms: {
    uTime: 0,
  },
  isAutoAdd: true,
})

/**
 * resize
 */
function resize() {
  kgl.resize()
}
resize()
window.addEventListener('resize', resize)

/**
 * tick
 */
function tick(time) {
  program.uniforms.uTime = time * 0.001

  kgl.draw()

  requestAnimationFrame(tick)
}
requestAnimationFrame(tick)
```

### `KglAuto`

#### JS

```js
import { KglAuto } from '@ko-yelie/kgl'

new KglAuto({
  programs: {
    main: {
      fragmentShaderId: 'fs',
      uniforms: {
        uTime: 0,
      },
    },
  },
  tick: (kgl, time) => {
    kgl.programs.main.uniforms.uTime = time
    kgl.draw()
  },
})
```

## Examples

https://ko-yelie.github.io/kgl/
npm package: @ko_kr/id
Description: Korean id number(jumin) library
Author: Changwan Jun
Latest version: 0.2.1
Deprecated: package rename to @kokr/id

# ko_KR - id

## 설치방법

```bash
npm install @ko_kr/id
```

```typescript
import { analyze, validate } from '@ko_kr/id'

// 주민번호 분석
analyze('000101-1000002')
/*
{
  valid: true, // 올바른 주민번호 여부
  parity: 2, // 주민번호 맨 뒤 검증코드
  gender: 'M', // 성별
  foreigner: false, // 외국인여부
  birth: '1900-01-01', // 생일 (2003-02-29와 같이 존재하지 않는 경우 null 반환)
  age: 121, // 만나이
  krAge: 122, // 한국나이
}
*/

// 주민번호 분석 (now에는 기준 날짜. age, krAge 계산할 때 기준)
analyze('000101-1000002', { now: '2021-06-01' })


// 일반 주민등록번호 (외국인 등록번호 미포함)
validate('010101 - 0010101')

// 외국인 등록번호 포함
validate('010101-5010105', { enableForeigner: true })
validate('010101-6010108', { enableForeigner: true })
validate('010101-7010101', { enableForeigner: true })
validate('010101-8010103', { enableForeigner: true })
```
npm package: @ko_kr/phone
Description: Korean phone number library
Author: Changwan Jun
Latest version: 0.2.1
Deprecated: package rename to @kokr/phone

# ko_KR - phone

## 설치방법

```bash
npm install @ko_kr/phone
```

```typescript
import { format } from '@ko_kr/id'

// 전화번호 포맷
format('0212341234') // '02-1234-1234'
format('021231234') // '02-123-1234'
```
npm package: @ko_kr/text
Description: Library to find josa using template literal
Author: Changwan Jun
Latest version: 0.2.0
Deprecated: package rename to @kokr/text

# ko_KR - text

## 설치방법

```bash
npm install @ko_kr/text
```

```typescript
import text from '@ko_kr/text'

let name = '완두'

// 은/는
console.log(text`${name}는 코딩을 합니다.`) // 완두는 코딩을 합니다.
console.log(text`${name}은 코딩을 합니다.`) // 완두는 코딩을 합니다.

// 이/가
console.log(text`${name}가 코딩을 했습니다.`) // 완두가 코딩을 했습니다.
console.log(text`${name}이 코딩을 했습니다.`) // 완두가 코딩을 했습니다.

// 을/를
console.log(text`${name}을 가르쳤습니다.`) // 완두를 가르쳤습니다.
console.log(text`${name}를 가르쳤습니다.`) // 완두를 가르쳤습니다.

// 와/과
console.log(text`${name}와 코딩을 했습니다.`) // 완두와 코딩을 했습니다.
console.log(text`${name}과 코딩을 했습니다.`) // 완두와 코딩을 했습니다.

// 아/야
console.log(text`${name}아!`) // 완두야!
console.log(text`${name}야!`) // 완두야!

// 이어요/여요
console.log(text`${name}이어요.`) // 완두여요.
console.log(text`${name}여요.`) // 완두여요.

// 이었/였
console.log(text`${name}이었어요.`) // 완두였어요.
console.log(text`${name}였어요.`) // 완두였어요.

// 이에요/예요
console.log(text`${name}이에요.`) // 완두예요.
console.log(text`${name}예요.`) // 완두예요.

// 로/으로
let place = '대구'
console.log(text`${place}으로 갑시다.`) // 대구로 갑시다.
console.log(text`${place}로 갑시다.`) // 대구로 갑시다.

place = '부산'
console.log(text`${place}으로 갑시다.`) // 부산으로 갑시다.
console.log(text`${place}로 갑시다.`) // 부산으로 갑시다.

place = '서울' // 예외케이스
console.log(text`${place}으로 갑시다.`) // 서울로 갑시다.
console.log(text`${place}로 갑시다.`) // 서울로 갑시다.
```
npm package: @koa-boot/server
Description: A SpringBoot-like lightweight web framework based on Koa.
Author: mokuo
Latest version: 0.1.5

# koa-boot-server

[![Actions Status](https://github.com/SUCHMOKUO/node-worker-threads-pool/workflows/Workflow/badge.svg)](https://github.com/SUCHMOKUO/koa-boot-server/actions)
[![](https://img.shields.io/npm/v/@koa-boot/server.svg)](https://www.npmjs.com/package/@koa-boot/server)

A SpringBoot-like lightweight web framework based on Koa.

_TODO_

- [ ] Add document
npm package: @koa-framework/koa-bodyparser
Description: koa-bodyparser for @koa-framework/koa-framework
Author: luobotang
Latest version: 0.3.0

# bodyparser

## 安装

```
npm i @luobotang/koa-bodyparser
```

## 配置

```js
module.exports = {
  bodyparser: {
    // options for 'koa-bodyparser'
  }
}
```

## 使用

```js
router.use(middlewares.bodyparser)
```
npm package: @koa-framework/koa-compress
Description: compress plugin for @koa-framework/koa-framework
Author: luobotang
Latest version: 0.3.0

# compress

## 安装

```
npm i @luobotang/koa-compress
```

## 配置

```js
module.exports = {
  compress: {
    // options to '[koa-compress](https://www.npmjs.com/package/koa-compress)'
  }
}
```

## 使用

```js
router.use(middlewares.compress)
```
npm package: @koa-framework/koa-favicon
Description: koa-favicon for @koa-framework/koa-framework
Author: luobotang
Latest version: 0.3.0

# favicon

## 安装

```
npm i @luobotang/koa-favicon
```

## 配置

```js
module.exports = {
  favicon: '/path/to/favicon.ico'
}
```

## 使用

```js
router.use(middlewares.favicon)
```
npm package: @koa-framework/koa-fetch
Description: node-fetch plugin for @koa-framework/koa-framework
Author: luobotang
Latest version: 0.3.0

# @luobotang/koa-fetch

## API

- ```app.fetch()```: 直接暴露 ```node-fetch``` 的 ```fetch()```
- ```app.fetch_get(url, params)```: 发送 GET 请求
- ```app.fetch_post(url, data)```: POST 发送 JSON 格式数据
npm package: @koa-framework/koa-mount
Description: router extension for @koa-framework/koa-framework
Author: luobotang
Latest version: 0.3.1

# mount

## 安装

```js
npm i @luobotang/koa-mount
```

## API

- ```app.router.mount(path, ...middlewares)```：匹配 - 改写路径 - 执行 - 恢复路径
- ```app.rourer.match(path, middleware)```：匹配 - 执行
npm package: @koa-framework/koa-multer
Description: multer plugin for @koa-framework/koa-framework
Author: luobotang
Latest version: 0.3.0

# @luobotang/koa-multer

## 安装

```
npm i @luobotang/koa-multer
```

## 配置

```js
module.exports = {
  multer: {
    // options pass to 'multer'
  }
}
```

## 使用

路由：

```js
router.post('/form', interceptor.multer.single('file'), controller.foo.form)
```

Controller：

```js
exports.form = async (ctx) => {
  const { originalname, size, mimetype } = ctx.file
  ctx.body = `${originalname} ${size} ${mimetype}`
}
```
npm package: @koa-framework/koa-mysql
Description: mysql plugin for @koa-framework/koa-framework
Author: luobotang
Latest version: 0.3.1

# @luobotang/koa-mysql

## 配置

```app.config.mysql```

参考：[mysqljs/mysql](https://github.com/mysqljs/mysql#connection-options)

## API

- ```app.db.escape(val)```: 内部调用 ```mysql.escape(val)```
- ```app.db.query(sql, params)```: 基础查询方法，返回 Promise，成功数据为 { results, fields }，失败数据为错误信息。
- ```async app.db.select(sql, params)```: 返回 results
- ```async app.db.select_one(sql, params)```: 返回 results[0]
- ```async app.db.insert(sql, params)```: 返回 results.affectedRows
- ```async app.db.insert_one(sql, params)```: 返回 results.affectedRows[0]
- ```async app.db.insert_id(sql, params)```: 返回 results.insertId
- ```async app.db.update(sql, params)```: 返回 results.changedRows
- ```async app.db.update_one(sql, params)```: 返回 results.changedRows[0]
- ```async app.db.delete(sql, params)```: 返回 results.affectedRows
- ```async app.db.delete_one(sql, params)```: 返回 results.affectedRows[0]
npm package: @koa-framework/koa-nos
Description: NOS client plugin for @koa-framework/koa-framework
Author: luobotang
Latest version: 0.3.0

# nos

## 安装

```
npm i @luobotang/koa-nos
```

## 配置

```js
module.exports = {
  nos: {
    accessKey: 'your-access-key',
    accessSecret: 'your-access-secret',
    endpoint: 'http://nos.netease.com',
    defaultBucket: 'nos-test'
  }
}
```

## 使用

```js
exports.download = async (ctx) => {
  const { filename } = ctx.query
  ctx.response.attachment(filename)
  ctx.body = await ctx.nos.get(filename)
}

exports.upload = async (ctx) => {
  const { originalname, buffer } = ctx.file // @koa/multer
  await ctx.nos.put(originalname, require('streamifier').createReadStream(buffer))
  ctx.body = 'OK'
}

exports.delete = async (ctx) => {
  const { filename } = ctx.query
  await ctx.nos.del(filename)
  ctx.body = 'OK'
}
```
npm package: @koa-framework/koa-redis
Description: ioredis plugin for @koa-framework/koa-framework
Author: luobotang
Latest version: 0.3.1

# @luobotang/koa-redis

## 配置

```app.config.redis```

## API

- ```app.redis.xxx()```: 方法与 ioredis 的实例对象一致
npm package: @koa-framework/koa-redis-cache
Description: redis cache plugin for @koa-framework/koa-framework
Author: luobotang
Latest version: 0.3.0

# redis-cache

借助 redis 缓存数据

## 使用

### 配置

示例：

```js
module.exports = {
  cache: {
    prefix: 'my-app'
  }
}
```

配置项说明：

- ```prefix```: 在 redis 中统一添加该前缀添加到传入 key，例如 ```app.cache.set('foo', {name: 'luobotang'})```` 实际 redis 的 key 为 ``my-app__foo```

### 插件

在 controller 使用：

```js
exports.foo = async (ctx) => {
  const data = await ctx.cache.get('bar')
  if (data) {
    ctx.body = data
    return
  }
  const new_data = await ctx.service.xxx.getData()
  await ctx.cache.set('bar', new_data)
  ctx.body = new_data
}
```

上面例子也可以简化为：

```js
exports.foo = async (ctx) => {
  ctx.body = await ctx.cache.getOrSet('bar', async () => await ctx.service.xxx.getData())
}
```

### 拦截器

在 router 中使用：

```js
router.get('/user', interceptor.cache.get('user', 'user_id'), controller.user.get)
router.post('/user', interceptor.cache.del('user', 'user_id'), controller.user.post)
router.delete('/user', interceptor.cache.del('user', 'user_id'), controller.user.delete)
```
npm package: @koa-framework/koa-static
Description: static plugin for @koa-framework/koa-framework
Author: luobotang
Latest version: 0.3.0

# static

## 安装

```
npm i @luobotang/koa-static
```

## 配置

```js
module.exports = {
  static: {
    root: '/static/root/path',
    // other options to '[koa-static](https://www.npmjs.com/package/koa-static)'
  }
}
```

## 使用

```js
router.use(middlewares.static)
```
npm package: @koa-framework/koa-validator
Description: data validator plugin for @koa-framework/koa-framework
Author: luobotang
Latest version: 0.3.1

# validator

数据校验插件

## 使用

应用配置：

```js
module.exports = {
  plugins: [
    '@luobotang/koa-validator'
  ]
}
```

校验配置，放在应用根目录下的 validator 中，以文件名加载到 app.validator 上。

示例，```validator/user.js```：

```js
module.exports = ({ defineValidation, defineObjectValidation }) => ({
  user_id: defineValidation('user_id', ['id', 4, 20]),
  user_name: defineValidation('user_name', 'notempty', 'string', ['length', 2, 20]),
  default: defineObjectValidation('用户', 'user_id', 'user_name')
})
```

在 router.js 中使用，示例：

```js
module.exports = ({ router, interceptor, controller }) => {
  const { validate } = interceptor
  router.get('/user/byId', validate(['user_id']), controller.user.byId)
  router.post('/user/create', validate('user'), controller.user.create)
}
```

## API

- ```app.base_validators```
- ```app.validators```
- ```app.defineValidation(key, ...rules)```
- ```app.defineObjectValidation(name, ...validations)```
- ```app.interceptor.validate()```
npm package: @koa-framework/mysql
Description: mysql plugin for @koa-framework/koa-framework
Author: luobotang
Latest version: 0.3.2

# @luobotang/koa-mysql

## 配置

```app.config.mysql```

参考：[mysqljs/mysql](https://github.com/mysqljs/mysql#connection-options)

## API

`MySqlDb`:

- ```db.escape(val)```: 内部调用 ```mysql.escape(val)```
- ```db.query(sql, params)```: 基础查询方法，返回 Promise，成功数据为 { results, fields }，失败数据为错误信息。
- ```async db.select(sql, params)```: 返回 results
- ```async db.select_one(sql, params)```: 返回 results[0]
- ```async db.insert(sql, params)```: 返回 results.affectedRows
- ```async db.insert_one(sql, params)```: 返回 results.affectedRows[0]
- ```async db.insert_id(sql, params)```: 返回 results.insertId
- ```async db.update(sql, params)```: 返回 results.changedRows
- ```async db.update_one(sql, params)```: 返回 results.changedRows[0]
- ```async db.delete(sql, params)```: 返回 results.affectedRows
- ```async db.delete_one(sql, params)```: 返回 results.affectedRows[0]

作为插件自动安装后，即添加 `app.db` 和 `app.context.db`，值为 `MySqlDb` 类型。

也可以手动创建：

```js
const { createMySqlDb } = require('@luobotang/koa-mysql')

const db = createMySqlDb(
  { /* mysql config */ },
  logger /* log4js logger */
)
```
npm package: @koa-framework/sql-builder
Description: Sql builder for @koa-framework/koa-framework
Author: luobotang
Latest version: 0.3.2

用于在 Service 中构建 SQL 并执行查询，例如：

```js
// service/user.js
module.exports = (app) => {
  return {
    queryById(user_id) {
      return app.sql()
        .select('user_id', 'user_name', 'create_time')
        .from('TB_USER')
        .where(`user_id = ${app.db.escape(user_id)}`)
        .execOne()
    }
  }
}
```

支持的 SQL 类型：
- select：
  ```js
  sql()
    .select('name', 'id')
    .from('TB_USER')
    .where('create_time > "2019-12-31"')
    .orderBy('create_time DESC')
  ```
- insert：
  ```js
  sql()
    .insert('name', 'id')
    .into('TB_USER')
    .value('张三', 123)
    .value('李四', 456)
  ```
- update：
  ```js
  sql()
    .update('TB_USER')
    .set({name: '张三'})
    .where('id = 123')
  ```
- delete：
  ```js
  sql()
    .delete()
    .from('TB_USER')
    .where('id = 1')
  ```

执行模式：
- 只生成 SQL：
  ```js
  sql.sql()
  ```
- 执行，返回结果数组：
  ```js
  sql.exec()
  ```
- 执行，只返回第一个返回结果：
  ```js
  sql.execOne()
  ```
npm package: @koa-lite/controller
Description: integrated koa-router and joi, support api docs generated
Author: luckcoding
Latest version: 0.4.1

# @koa-lite/controller

[![npm package](https://img.shields.io/npm/v/@koa-lite/controller/latest.svg)](https://www.npmjs.com/package/@koa-lite/controller)

## install

`$ yarn add @koa-lite/controller`

## use

```js
// controller.ts
import { Prefix, Tag, Get, Summary, Query } from '@koa-lite/controller'
@Prefix('/ucenter')
export default class User {
  @Tag('User')
  @Get('/user') // or request.get('/user'), request('get', '/user')
  @Summary('User list')
  @Query(Joi.object({
    name: Joi.string().required().description('name'),
  })) // check.query()
  async sms(ctx: BaseContext) {
    ctx.body = {}
  }
}

// router.ts
import { Controller, InjectHandle } from '@koa-lite/controller'
import User from './controller.ts'

// 包装函数
InjectHandle(({ fn }) => fn)

const router = new Controller({
  prefix: '/v1',
  docs: {
    title: '接口文档 - 客户端',
    version: 'v1',
    description: '业务接口文档 - by Hotchcms',
    securities: [{
      type: 'headers',
      key: 'Authorization', // 自动注入token等信息
      value: function (data) {
        var ret = (data instanceof Object) && data.ret
        return /^Bearer\s/.test(ret) ? ret : ''
      },
    }, {
      type: 'headers',
      key: 'x-device-id',
      value: '10001',
    }],
  }})
  .controllers([ User ])
  .get('/', ctx => { ctx.body = 'API V1' })

// app.ts
app.use(router.routes())
```

## api

* `Prefix()`
* `Get()`
* `Post()`
* `Put()`
* `Delete()`
* `Body`
* `Query`
* `Params`
* `Headers`
* `Middle([])`
* `Summary()`
* `Tag()`
npm package: @koa/access-log
Description: Middleware for common log format access logs
Author: Christoffer Hallas
Latest version: 1.0.0

# [Accesslog](https://github.com/koajs/accesslog)

Output [Common Log Format](http://en.wikipedia.org/wiki/Common_Log_Format) access logs to any stream. Defaults to `process.stdout`.

> Notice: We recommend using `@koa/access-log` for installation, as both `koa-accesslog` and `@koa/access-log` refer to the same module. However, in our next major version bump (v2), we will deprecate `koa-accesslog` and only maintain `@koa/access-log`.

## Install

```bash
# npm ..
npm i koa-accesslog
# yarn ..
yarn add koa-accesslog
```

or

```bash
# npm ..
npm i @koa/access-log
# yarn ..
yarn add @koa/access-log
```

## Usage

```js
const Koa = require('koa');
const accesslog = require('koa-accesslog');
// or
// const accesslog = require('@koa/access-log');
const app = new Koa();

app.use(accesslog());
```

## Output

```
127.0.0.1 - - [19/Nov/2014:13:47:37 +0100] "GET / HTTP/1.X" 404 -
```

## Configure

You may configure Accesslog to use any writable stream such as an
instance of `stream.PassThrough` as seen below.

```js
const log = new stream.PassThrough();
app.use(accesslog(log));
```

## License

[MIT](LICENSE)
npm package: @koa/body-parsers
Description: Koa body parsers collection
Author: Jonathan Ong
Latest version: 6.0.1

# [**@koa/body-parsers**](https://github.com/koajs/body-parsers)

[![NPM version][npm-image]][npm-url]

A more functional version of body parsing.
Use this module if you want to "lazily" parse the body.
Other middleware automatically parse the body in the middleware chain, which might not be ideal as business logic like authentication, authorization, and routing are not done prior to body parsing.

Includes a `json` and `urlencoded` parsers.

## API

Initialization:

```js
// import withBodyParsers from '@koa/body-parsers'
import { withBodyParsers } from "@koa/body-parsers";
import Koa from "koa";

const app = new Koa();
withBodyParsers(app);

// example usage
app.use(async (ctx) => {
  const currentUser = UserService.getCurrentUser(ctx);
  ctx.assert(currentUser, 401);

  ctx.assert(ctx.request.is("json"), 415);
  const body = await ctx.request.json("100kb");
  ctx.body = body;
});
```

Because this module is a plugin for the `context`, the API signature is different.

### Expect: 100-continue and ctx.response.writeContinue()

`Expect: 100-continue` is automatically supported as long as you use `app.listen()`.
Otherwise, create your server like this:

```js
const fn = app.callback();
const server = http.createServer(); // or whatever server you use
server.on("request", fn); // regular requests
server.on("checkContinue", function (req, res) {
  // tag requests with `Expect: 100-continue`
  req.checkContinue = true;
  fn(req, res);
});
```

If `Expect: 100-continue` was sent to the client,
this will automatically response with a "100-continue".
Use this right before parsing the body.
Automatically called by all following body parsers,
but you would still have to call it if you're doing something like:

```js
app.use(async (ctx) => {
  if (ctx.request.is("image/*")) {
    ctx.response.writeContinue();
    const buffer = await ctx.request.buffer();
  }
});
```

### const body = await ctx.request.json([limit])

Get the JSON body of the request, if any.
`limit` defaults to `100kb`.

### const body = await ctx.request.urlencoded([limit])

Get the traditional form body of the request, if any,
`limit` defaults to `100kb`.

### const text = await ctx.request.text([limit])

Get the body of the request as a single `text` string.
`limit` defaults to `100kb`.
You could use this to create your own request body parser of some sort.

### const buffer = await ctx.request.buffer([limit])

Get the body of the request as a single `Buffer` instance.
`limit` defaults to `1mb`.

[npm-image]: https://img.shields.io/npm/v/@koa/body-parsers.svg?style=flat-square
[npm-url]: https://npmjs.org/package/@koa/body-parsers
npm package: @koa/ejs
Description: ejs render middleware for Koa.js
Author: dead_horse
Latest version: 5.1.0

# @koa/ejs

> Koa ejs view render middleware. support all feature of [ejs](https://github.com/mde/ejs).

[![Build Status](https://secure.travis-ci.org/koajs/ejs.svg)](http://travis-ci.org/koajs/ejs)

[![NPM](https://nodei.co/npm/@koa/ejs.png?downloads=true)](https://nodei.co/npm/@koa/ejs/)

## Usage

### Example

```js
const Koa = require("koa");
const render = require("@koa/ejs");
const path = require("path");

const app = new Koa();
render(app, {
  root: path.join(__dirname, "view"),
  layout: "template",
  viewExt: "html",
  cache: false,
  debug: true,
});

app.use(async function (ctx) {
  await ctx.render("user");
});

app.listen(7001);
```

Or you can checkout the [example](https://github.com/koajs/ejs/tree/master/example).

### Settings

- root: view root directory.
- fs: file system module with same Node.js fs interface (default `Node.js fs module`).
- layout: global layout file, default is `layout`, set `false` to disable layout.
- viewExt: view file extension (default `html`).
- cache: cache compiled templates (default `true`).
- debug: debug flag (default `false`).
- delimiter: character to use with angle brackets for open / close (default `%`).
- async: When true, EJS will use an async function for rendering. Depends on async/await support in the JS runtime.
- outputFunctionName: Set to a string (e.g., 'echo' or 'print') for a function to print output inside scriptlet tags.

### Layouts

`@koa/ejs` supports layouts. The default layout file is `layout`. If you want to change default layout file, use `settings.layout`. Also you can specify layout by `options.layout` in `await ctx.render`.
Also you can set `layout = false` to disable the layout.

```
<html>
  <head>
    <title>koa ejs</title>
  </head>
  <body>
    <h3>koa ejs</h3>
    <%- body %>
  </body>
</html>
```

### Include

Supports ejs includes.

```
<div>
  <%- include ('user.html') -%>
</div>
```

### State

Support [`ctx.state` in koa](https://github.com/koajs/koa/blob/master/docs/api/context.md#ctxstate).


### TypeScript

If you're project based on TypeScript, we recommend using [`@types/koa-ejs`](https://www.npmjs.com/package/@types/koa-ejs) until we start supporting it in the upcoming releases.

## Licences

[(The MIT License)](LICENSE)
npm package: @koa/etag
Description: Koa ETag support middleware
Latest version: 5.0.2

# @koa/etag

[![NPM version][npm-image]][npm-url]
[![Test coverage][coveralls-image]][coveralls-url]
[![Dependency Status][david-image]][david-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]

Etag support for Koa responses using [etag](https://github.com/jshttp/etag).

## Installation

```bash
# npm
$ npm install @koa/etag
# yarn
$ yarn add @koa/etag
```

## Example

```js

const Koa = require('koa');
const etag = require('@koa/etag');
const conditional = require('koa-conditional-get');
const compress = require('koa-compress');

const app = new Koa();

// must be used before `conditional` and `etag`
app.use(compress());

// etag works together with conditional-get
app.use(conditional());
app.use(etag());

app.use(function (ctx) {
  ctx.body = 'Hello World';
});

app.listen(3000);

console.log('listening on port 3000');
```

## License

[MIT](LICENSE)

[npm-image]: https://img.shields.io/npm/v/koa-etag.svg?style=flat-square
[npm-url]: https://npmjs.org/package/@koa/etag
[github-tag]: http://img.shields.io/github/tag/koajs/etag.svg?style=flat-square
[github-url]: https://github.com/koajs/etag/tags
[coveralls-image]: https://img.shields.io/coveralls/koajs/etag.svg?style=flat-square
[coveralls-url]: https://coveralls.io/r/koajs/etag?branch=master
[david-image]: http://img.shields.io/david/koajs/etag.svg?style=flat-square
[david-url]: https://david-dm.org/koajs/etag
[license-image]: http://img.shields.io/npm/l/koa-etag.svg?style=flat-square
[license-url]: LICENSE
[downloads-image]: http://img.shields.io/npm/dm/koa-etag.svg?style=flat-square
[downloads-url]: https://npmjs.org/package/koa-etag
[gittip-image]: https://img.shields.io/gittip/jonathanong.svg?style=flat-square
[gittip-url]: https://www.gittip.com/jonathanong/
npm package: @koa/json-async-iterator
Description: Koa JSON response body streaming for async iterators
Author: Jonathan Ong
Latest version: 1.0.0

# @koa/json-async-iterator

Koa JSON response body streaming for async iterators

## Usage

```js
const jsonAsyncIterator = require('@koa/json-async-iterator')
const app = new Koa()

app.use(jsonAsyncIterator())

app.use(async ctx => {
  const iterator = async function* () {
    yield Promise.resolve({ foo: 'bar' })
    yield Promise.resolve({ baz: 'qux' })
  }
  ctx.body = iterator()
})
```

Output:

```json
[
{"foo":"bar"}
,
{"baz":"qux"}
]
```

Example with PostgreSQL:

```js
import QueryStream from 'pg-query-stream'
import pg from 'pg'

const client = new pg.Client()
await client.connect()

// later in your middleware
app.use(async (ctx) => {
    // stream all the rows from the database to the client
    ctx.body = client.query(new QueryStream(`
        SELECT * 
        FROM posts
        ORDER BY id ASC
    `))
})
```

## Options

### `before`

The string to write before the first value in the iterator.

Default: `'[\n'`

### `separator`

The string to write between each value in the iterator.

Default: `'\n,\n'`

### `after`

The string to write after the last value in the iterator.

Default: `'\n]'`

### `formatError`

A function that takes an error and returns a value to be stringified.

Default: `(err) => ({ error: { message: err.message } })`

### `pretty`

Whether to pretty-print the JSON.

Default: `false`

### `spaces`

The number of spaces to use for pretty-printing.

Default: `2`

## License

MIT
npm package: @koa/json-filter
Description: Middleware allowing the client to filter the response to only what they need
Latest version: 1.0.0

# koa-json-filter

Middleware allowing the client to filter the response to only what they need,
reducing the amount of traffic over the wire using the `?filter=foo,bar,baz` querystring parameter.

JSONSelect would also be great for this but I find it's a little too complicated for the average use-case,
so this is just a simple key filter.

## Installation

```
$ npm install @koa/json-filter
```

Please note that if you're using an earlier version of koa 2 with function generator you need to install the older version `0.0.1`

```
$ npm install koa-json-filter@0.0.1
```

## Options

* `name` querystring param defaulting to "filter"

## Filtering customization

You may also set `ctx.filter` to an array of names to filter on,
for example by using a header field `X-Filter: name,email`.

## Example

### Object responses

Script:

```js
const Koa = require('koa');
const filter = require('@koa/json-filter');

const app = new Koa();

app.use(filter());

app.use(async ctx => {
  ctx.body = {
    name: 'tobi',
    email: 'tobi@segment.io',
    packages: 5,
    friends: ['abby', 'loki', 'jane']
  };
});

app.listen(3000);
console.log('app listening on port 3000');
```

Response:

```
$ GET /?filter=name
{
  "name": "tobi"
}
```

### Array responses

Script:

```js
const Koa = require('koa');
const filter = require('@koa/json-filter');

const app = new Koa();

app.use(filter());

app.use(async ctx => {
  ctx.body = [
    {
      name: 'tobi',
      email: 'tobi@segment.io',
      packages: 5,
      friends: ['abby', 'loki', 'jane']
    },
    {
      name: 'loki',
      email: 'loki@segment.io',
      packages: 2,
      friends: ['loki', 'jane']
    },
    {
      name: 'jane',
      email: 'jane@segment.io',
      packages: 2,
      friends: []
    },
    {
      name: 'ewald',
      email: 'ewald@segment.io',
      packages: 2,
      friends: ['tobi']
    }
  ];
});

app.listen(3000);
console.log('app listening on port 3000');
```

Response:

```
$ GET /?filter=name,email
[
  {
    "name": "tobi",
    "email": "tobi@segment.io"
  },
  {
    "name": "loki",
    "email": "loki@segment.io"
  },
  {
    "name": "jane",
    "email": "jane@segment.io"
  },
  {
    "name": "ewald",
    "email": "ewald@segment.io"
  }
]
```

# License

MIT
npm package: @koa/multer
Description: Route middleware for Koa that handles `multipart/form-data` using multer
Author: Fangdun Cai
Latest version: 4.0.0

# [**@koa/multer**](https://github.com/koajs/multer)

> Route middleware for Koa that handles `multipart/form-data` using [multer][]

[![NPM version][npm-img]][npm-url]
[![NPM Downloads][downloads-image]][npm-url]
[![Build status][actions-img]][actions-url]
[![Test coverage][coveralls-img]][coveralls-url]
[![Dependency status][david-img]][david-url]
[![License][license-img]][license-url]


## Call for Maintainers

This module is a fork of [koa-multer][], the most widely used multer middleware in the koa community.  Due to lack of maintenance, it was forked to the official Koa organization and is available under `@koa/multer` package name.


## Install

> Note that you must install either `multer@1.x` (Buffer) or `multer@2.x` (Streams):

```sh
npm install --save @koa/multer multer
```


## Usage

```js
const Koa = require('koa');
const Router = require('@koa/router');
const multer = require('@koa/multer');

const app = new Koa();
const router = new Router();
const upload = multer(); // note you can pass `multer` options here

// add a route for uploading multiple files
router.post(
  '/upload-multiple-files',
  upload.fields([
    {
      name: 'avatar',
      maxCount: 1
    },
    {
      name: 'boop',
      maxCount: 2
    }
  ]),
  ctx => {
    console.log('ctx.request.files', ctx.request.files);
    console.log('ctx.files', ctx.files);
    console.log('ctx.request.body', ctx.request.body);
    ctx.body = 'done';
  }
);

// add a route for uploading single files
router.post(
  '/upload-single-file',
  upload.single('avatar'),
  ctx => {
    console.log('ctx.request.file', ctx.request.file);
    console.log('ctx.file', ctx.file);
    console.log('ctx.request.body', ctx.request.body);
    ctx.body = 'done';
  }
);

// add the router to our app
app.use(router.routes());
app.use(router.allowedMethods());

// start the server
app.listen(3000);
```


## Contributors

| Name            | Website                         |
| --------------- | ------------------------------- |
| **Nick Baugh**  | <http://niftylettuce.com/>      |
| **Imed Jaberi** | <https://www.3imed-jaberi.com/> |


## License

[MIT](LICENSE) © Fangdun Cai


##

[npm-img]: https://img.shields.io/npm/v/@koa/multer.svg?style=flat-square

[npm-url]: https://npmjs.org/package/@koa/multer

[actions-img]: https://github.com/koajs/multer/actions/workflows/unit-tests.yaml/badge.svg

[actions-url]: https://github.com/koajs/multer/actions

[coveralls-img]: https://img.shields.io/coveralls/koajs/multer.svg?style=flat-square

[coveralls-url]: https://coveralls.io/r/koajs/multer?branch=master

[license-img]: https://img.shields.io/badge/license-MIT-green.svg?style=flat-square

[license-url]: LICENSE

[david-img]: https://img.shields.io/david/koajs/multer.svg?style=flat-square

[david-url]: https://david-dm.org/koajs/multer

[downloads-image]: https://img.shields.io/npm/dm/@koa/multer.svg?style=flat-square

[multer]: https://github.com/expressjs/multer

[koa-multer]: https://github.com/koa-modules/multer
npm package: @koa_web/boot
Description: ne front end basic module
Latest version: 2.0.9

# @koa_web/boot
![](https://img.shields.io/badge/version-1.4.1-green.svg?)
[![](https://img.shields.io/badge/nodejs->=8.0-green.svg?)](https://nodejs.org/en/)
[![](https://img.shields.io/badge/npm->=5.4-blue.svg)](https://www.npmjs.com/)
![](https://img.shields.io/badge/license-MIT-000000.svg)

## 简介
> ne 前端基础工程

## 安装&配置

全局安装该模块 `$ npm install @koa_web/boot -g` 或 `$ npm install @koa_web/boot -g --production`

## 使用
### 1 获取使用帮助
通过`ne -h`或`ne --help`查看使用帮助

```bash
$ ne -h
Usage: ne run [command] [option]

Options:

  -v, --version    output the version number
  -e --env [env]   what env do you want set
  --senv [senv]    what egg environment do you want
  -h, --help       output usage information

Commands:

  dev [options]    run project in dev mode
  build [options]  Only effective in dashboard or h5.
  lint             lint project code follow your eslint file
  packageName      echo project name
  packageVersion   echo project version
  startup:docker   startup. Only effective in docker container
  test             Only effective in service(egg.js)
  cov              Only effective in service(egg.js)
  ci               Only effective in service(egg.js)
```

### 2 获取版本号
通过`ne -v`或`ne --version`查看版本号
```bash
$ ne-create-project -v

 v1.4.1
```

### 3 指令说明
#### 3.1 dev
开发模式启动当前工程
```bash
$ ne run dev
```

#### 3.2 build
编译当前工程
```bash
$ ne run build
```

#### 3.3 lint
对当前工程进行语法检测
```bash
$ ne run lint
```

#### 3.4 packageName
输出当前工程的名称
```bash
$ ne run packageName
```
#### 3.5 packageVersion
输出当前工程的版本号
```bash
$ ne run packageVersion
```
#### 3.6 startup:docker
容器中启动该工程的命令
```bash
$ ne run startup:docker
```
#### 3.7 test
对当前工程进行单元测试，只在eggjs为基础的后端工程中有效
```bash
$ ne run test
```
#### 3.8 cov
生成当前工程的测试覆盖率报告，只在eggjs为基础的后端工程中有效
```bash
$ ne run cov
```
#### 3.9 ci
对当前工程进行语法检测并生成当前工程的测试覆盖率报告，只在eggjs为基础的后端工程中有效
```bash
$ ne run ci
```
### 4 设置环境变量
优先读取第一种方式设定的环境变量
#### 4.1 运行时注入
##### 4.1.1 -e --env
注入环境变量，可以用 process.env.k1 获取到
```bash
$ ne run dev -e k1=v1,k2=v2
$ ne run dev --env k1=v1,k2=v2
```
##### 4.1.2 senv
注入eggjs启动参数，只在eggjs为基础的后端工程中有效
```bash
$ ne run dev --senv port=7002
```
#### 4.2 在当前工程的package.json中写入
在当前工程的package.json中写入，格式为
默认在`dev`指令中注入了`NODE_ENV=development`
```bash
  "ne-env-[command]": {
    "k1": "v1",
    "k2": "v2"
  },
  "ne-senv-[command]": {
    "k1": "v1",
    "k2": "v2"
  }
```
其中 `ne-senv-[command]` 只在以eggjs为基础的后端工程中有效 \
例如
```bash
  "ne-env-dev": {
    "NODE_SYS": "dealer"
  },
  "ne-senv-dev": {
    "port": "7002"
  }
```

## 本地安装

工程目类下安装该模块 `$ npm install @koa_web/boot --save-dev` \
提供基于githook的相关语法检查与commit信息检查

相关功能基于[yorkie](https://github.com/yyx990803/yorkie)和[lint-staged](https://github.com/okonet/lint-staged)进行修改

## 测试相关
请参照[yorkie](https://github.com/yyx990803/yorkie)和[lint-staged](https://github.com/okonet/lint-staged)
npm package: @koa_web/koa-cache
Description: koa entry middleware for xosyun
Author: xosyun
Latest version: 2.0.7

### 简介

用到的依赖有dayjs，koa-compose，koa-send，koa-static-cache，winston

### 安装&配置

```bash
$ npm i @koa_web/koa-entry -s
```

### 使用

- 基础用法

```js
const koaEntry = require('ne-koa-entry');

const staticPath = [ dir1, dir2 ];
app.use(koaEntry(
    staticPath // 需要映射静态资源的文件夹列表
));
```

- 使用prefix

```js
const staticPath = [ dir1, { path: dir2, prefix: '/template' }];
app.use(koaEntry(
    staticPath // 需要映射静态资源的文件夹列表
));
```

- 使用koa-webpack
```js
app.use(koaEntry(
    staticPath, // 需要映射静态资源的文件夹列表
    webpackConfig // webpack配置
));
```

- 使用回调函数
```js
app.use(koaEntry(
    staticPath, // 需要映射静态资源的文件夹列表
    webpackConfig, // webpack配置
    ctx => {
        console.log(ctx);
        ctx.body = '无权限访问';
    } // 回调函数，可以拿到ctx, 可以自定义页面内容
));
```
npm package: @koa_web/koa-proxy
Description: ### 简介 [koa2](https://github.com/koajs/koa)的中间件，主要实现http的代理
Author: yun.jin
Latest version: 2.0.6

# @koa_web/koa-nginx

### 简介
[koa2](https://github.com/koajs/koa)的中间件，主要实现http的代理

### 安装&配置说明
$ npm i @koa_web/koa-nginx --save

### 使用
```
const Koa = require('koa');
const Proxy = require('@koa_web/koa-nginx');
const app = new Koa();
const Nginx = Proxy.proxy({
  proxies: [
    {
      host: 'http://localhost:3333/',
      context: 'nginx'
    },
  ]
});
app.use(Nginx);
app.listen(3000);
    
```
- `proxyTimeout`
请求的超时时间, 单位毫秒,default 30000

- `rewrite`
路径重写选项,Funtion, 默认 `path.replace(context, '')`, 即去除设置的context路径

- `handleReq`
当数据经过代理前的钩子函数, 参数为一个对象. 包括`proxyReq`,`req`,`res`,`options`
```js
const Nginx = Proxy.proxy({
  proxies: ...,
  handleReq: proxyObj => {
    { proxyReq, req, res, options } = proxyObj;
  }
});
```

- `handleRes`
请求代理后的钩子函数, 包括 `proxyRes`,`req`,`res`

- `error`
请求代理错误的钩子函数,包括 `err`,`req`,`res`

- `proxies`
koa-nginx 的主要参数，数组形式。主要包含如下参数。
  * `target` 需要被代理到的地址
  * `context` 代理前缀，只有满足代理前缀的地址才能被代理。
  * `rewrite` 路径重写.
  * `proxyTimeout` 单独的代理配置的超时。
npm package: @koa_web/webpack
Description: wepback config for xosyun
Author: xosyun
Latest version: 2.0.43

### 简介

webpack4配置（已含babel-loader以及babel-polyfill，postcss-loader，eslint-loader等）

### 安装&配置

```bash
$ npm i @koa_web/webpack --save-dev
```

### 使用
#### config配置js对象

```js
const { vue_dashboard_dev, vue_dashboard_prod, vue_h5_dev, vue_h5_prod } = require('@koa_web/webpack');
```

#### 支持扩展webpack配置
在项目执行目录下新建webpack.config.js
```js
module.exports = {
  module: {
    ...
  },
  rule: {
    ...
  },
};
```

#### 示例

- 开发模式，和ne-koa-entry结合使用，详情查看[ne-koa-entry文档](http://git.nx-code.com/ne-fe/koa/ne-koa-entry)

server/index.js

```js
app.use(koaEntry(
  [ webRoot ],
  process.env.NODE_ENV === 'development' ? require('@koa_web/webpack').vue_dashboard_dev : ''
));
```

package.json

```json
{
    "scripts":{
        "dev":"cross-env NODE_ENV=development node server/server.js"
    }
}
```

- 生产模式

package.json
```json
{
    "scripts":{
        "build":"ne-webpack -c vue_dashboard"
    }
}
```
npm package: @koab/react-use-static
Description: A react hook which can keep static state between functional components.
Author: Cem Sorgun
Latest version: 1.0.7

# react-use-static
 A react hook which can keep static/shared state between functional components.

 [Live Demo](https://codesandbox.io/s/react-use-static-demo-9h10o?file=/src/ExampleComponent.js:109-158)
 
# Install

```npm install @koab/react-use-static``` or ```yarn add @koab/react-use-static```
 
# Example usage

Basically you need to assign an unique key to separate states between component types via second parameter. The third parameter is for persisting data even after each instance of component is unmounted.

```
import useStatic from 'react-use-static';

const Component = ({ defaultValue }) => {
 const persistDataEvenAfterUnmount = false;
 const uniqueComponentKey = 'ComponentKey';
 ...
 const [state, setValue] = useStatic(defaultValue, uniqueComponentKey, persistDataEvenAfterUnmount);
 ...
};
```