open-index/open-npm huggingface dataset:
npm package: @luobotang/koa-bodyparser
Description: koa-bodyparser for @luobotang/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: @luobotang/koa-compress
Description: compress plugin for @luobotang/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: @luobotang/koa-favicon
Description: koa-favicon for @luobotang/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: @luobotang/koa-fetch
Description: node-fetch plugin for @luobotang/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: @luobotang/koa-mount
Description: router extension for @luobotang/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: @luobotang/koa-multer
Description: multer plugin for @luobotang/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: @luobotang/koa-mysql
Description: mysql plugin for @luobotang/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: @luobotang/koa-nos
Description: NOS client plugin for @luobotang/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: @luobotang/koa-redis
Description: ioredis plugin for @luobotang/koa-framework
Author: luobotang
Latest version: 0.3.0

# @luobotang/koa-redis

## 配置

```app.config.redis```

## API

- ```app.redis.xxx()```: 方法与 ioredis 的实例对象一致
npm package: @luobotang/koa-redis-cache
Description: redis cache plugin for @luobotang/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: @luobotang/koa-static
Description: static plugin for @luobotang/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: @luobotang/koa-validator
Description: data validator plugin for @luobotang/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: @luodexun/wallet-api
Description: Public API
Author: luodexun
Latest version: 0.0.8

# ARK Core - Public API

<p align="center">
    <img src="https://raw.githubusercontent.com/ARKEcosystem/core/master/banner.png" />
</p>

## Documentation

You can find installation instructions and detailed instructions on how to use this package at the [dedicated documentation site](https://docs.ark.io/guidebook/core/plugins/optional/core-api.html).

## Security

If you discover a security vulnerability within this package, please send an e-mail to security@ark.io. All security vulnerabilities will be promptly addressed.

## Credits

This project exists thanks to all the people who [contribute](../../../../contributors).

## License

[MIT](LICENSE) © [ARK Ecosystem](https://ark.io)
npm package: @luogu-dev/markdown-it-katex
Description: Fast math support for markdown-it with KaTeX
Author: Takahiro Ethan Ikeuchi @iktakahiro
Latest version: 0.0.1

# Changes done by the Luogu Dev Team

As we use slightly different LaTeX standards, we modified the parser a bit, especially the part that checks if the LaTeX `$` delimeter is valid, to suit our standards.

# markdown-it-katex

Add Math to your Markdown

[KaTeX](https://github.com/Khan/KaTeX) is a faster alternative to MathJax. This plugin makes it easy to support in your markdown.

Need convincing?

* Check out the comparative benchmark: [KaTeX vs MathJax](https://jsperf.com/katex-vs-mathjax/42)

## Usage
Install markdown-it
```
npm install markdown-it
```

Install the plugin

```
npm install @iktakahiro/markdown-it-katex
```

Use it in your javascript

```javascript
var md = require('markdown-it')(),
    mk = require('@iktakahiro/markdown-it-katex');

md.use(mk);

// double backslash is required for javascript strings, but not html input
var result = md.render('# Math Rulez! \n  $\\sqrt{3x-1}+(1+x)^2$');
```

Include the KaTeX stylesheet in your html:
```html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/KaTeX/0.9.0/katex.min.css">
```

If you're using the default markdown-it parser, I also recommend the [github stylesheet](https://github.com/sindresorhus/github-markdown-css):
```html
<link rel="stylesheet" href="https://cdn.jsdelivr.net/github-markdown-css/2.2.1/github-markdown.css"/>
```

`KaTeX` options can be supplied with the second argument to use.
```javascript
md.use(mk, {"throwOnError" : false, "errorColor" : " #cc0000"});
```

## Examples

### Inline
Surround your LaTeX with a single `$` on each side for inline rendering.
```
$\sqrt{3x-1}+(1+x)^2$
```

### Block
Use two (`$$`) for block rendering. This mode uses bigger symbols and centers
the result.

```
$$\begin{array}{c}

\nabla \times \vec{\mathbf{B}} -\, \frac1c\, \frac{\partial\vec{\mathbf{E}}}{\partial t} &
= \frac{4\pi}{c}\vec{\mathbf{j}}    \nabla \cdot \vec{\mathbf{E}} & = 4 \pi \rho \\

\nabla \times \vec{\mathbf{E}}\, +\, \frac1c\, \frac{\partial\vec{\mathbf{B}}}{\partial t} & = \vec{\mathbf{0}} \\

\nabla \cdot \vec{\mathbf{B}} & = 0

\end{array}$$
```

## Syntax

Math parsing in markdown is designed to agree with the conventions set by pandoc:

    Anything between two $ characters will be treated as TeX math. The opening $ must
    have a non-space character immediately to its right, while the closing $ must
    have a non-space character immediately to its left, and must not be followed
    immediately by a digit. Thus, $20,000 and $30,000 won’t parse as math. If for some
    reason you need to enclose text in literal $ characters, backslash-escape them and
    they won’t be treated as math delimiters.

## Math Syntax Support

KaTeX is based on TeX and LaTeX. Support for both is growing. Here's a list of
currently supported functions:

[Function Support in KaTeX](https://github.com/Khan/KaTeX/wiki/Function-Support-in-KaTeX)
npm package: @luohc92/vue-image-viewer
Description: a image viewer for vue
Author: luohc92
Latest version: 0.1.5

# vue-image-viewer

A image viewer for vue2.x

## Install

```
npm i @luohc92/vue-image-viewer
```

## Usage

```
import ImageViewer from "@luohc92/vue-image-viewer";
Vue.use(ImagePreview)
```

```
  this.$imageViewer({
    images: images,
    curIndex: 0,
    zIndex: 2000,
    showDownload: true,
    showThumbnail: true,
    handlePosition: "bottom",
    maskBgColor: "rgba(0,0,0,0.7)",
    onClose: () => {
      console.log("close");
    },
  });
```

### Props

| Name           | Type                | Required | Description                                       | Default         |
| -------------- | ------------------- | -------- | ------------------------------------------------- | --------------- |
| images         | Array               | true     | images source 图片源                              | []              |
| curIndex       | Number              | false    | default display image 默认显示图片                | 0               |
| zIndex         | Number              | false    | set image viewer z-index 设置图片查看器的 z-index | 2000            |
| showDownload   | Boolean             | false    | show download button 显示下载按钮                 | false           |
| showThumbnail  | Boolean             | false    | show images thumbnail 显示图片缩略图              | false           |
| handlePosition | String [top,bottom] | false    | set handle position 设置操作柄显示位置            | bottom          |
| maskBgColor    | String              | false    | set mask background color 设置遮罩背景颜色        | rgba(0,0,0,0.7) |
| onClose        | Function            | false    | close function callback 关闭方法回调              | null            |
| onDownload     | Function            | false    | download image function callback 关闭方法回调     | null            |

### Keyboard Shortcuts

| Keyboard    | Action                                                                          |
| ----------- | ------------------------------------------------------------------------------- |
| arrow-left  | prev 上一张                                                                     |
| arrow-right | next 下一张                                                                     |
| arrow-up    | zoomIn 放大                                                                     |
| arrow-down  | zoomOut 缩小                                                                    |
| alt         | clockwise rotation 顺时针旋转                                                   |
| ctrl        | mirror 镜像翻转                                                                 |
| space       | toggle image size mode [contain,original] 图片显示大小模式[自适应大小,原始大小] |
| esc         | close 关闭                                                                      |

## Demo

[![Demo Image](https://github.com/luohc92/vue-image-viewer/blob/main/examples/assets/demo.png)]
npm package: @luohx/my-ui-vue
Description: ## Project setup ``` npm install ```
Author: lhx
Latest version: 0.0.1

# my-ui-vue

## Project setup
```
npm install
```

### Compiles and hot-reloads for development
```
npm run serve
```

### Compiles and minifies for production
```
npm run build
```

### Lints and fixes files
```
npm run lint
```

### Customize configuration
See [Configuration Reference](https://cli.vuejs.org/config/).
npm package: @luojia/browser-filedownloader
Description: file downloader for browser
Author: luojia@luojia.me
Latest version: 1.0.4

# browser-FileDownloader

File downloader for browser

## Feature

This downloader will try resume the progress at the breakpoint if available.

Note: This downloader uses `fetch()` to fetch content, resources from other domains must have correct CORS headers.

## Get

### 1. Directly use `dist/FileDownloader.js`

Just load `FileDownloader.js` by script tag and the `FileDownloader` is the class object.

### 2. Install from npm

```shell
npm i @luojia/browser-filedownloader
```
Then in your javascript code:

```javascript
import FileDownloader from '@luojia/browser-filedownloader'
```

## Usage

```javascript
const downloader=new FileDownloader(url,{
	//should it start downloading after the instance created.
	autoStart:true,

	autoRetry:10,//retry times

	//if you don't want to process the result, set this to true and the result will be saved to you device.
	autoSave:false,

	//when autoSavem is true, you can set the filename here.
	//the file extension is not required, the browser will add it automatically based on file mime type.
	fileName:`name`,

	fetchOptions:{},//options for fetch()

	//retry if stream stucked. If there is no byte received in 1 second, it is treated as stucked.
	retryWhenStuck:true,

	//a function for progress events
	progress(loaded,total){
		console.log('downloaded:',loaded,'of',total,'bytes');
	},

	//a function for loaded result
	load(blob,objectURL){
		//you don't need to set this function if autoSave is true

		//here is what autoSave does
		let a = document.createElement('a');
		a.href=objectURL;
		a.download = encodeURIComponent(this.opts.filename);
		a.click();
	},

	//a function for download error
	error(err){
		console.error(err);
		//if an error occurred, the downloader will stop the task
		//when retry times reach the limit, an error will emit too
	}
});

//start downloading, you don't need to call this if autoStart is true
downloader.start();

//abort the downloader
downloader.abort();

//close the downloader and clear buffers
downloader.close();
```
npm package: @luolapeikko/auth-header
Description: Typescript/Javascript http auth header utils
Author: mharj
Latest version: 0.0.1

# @luolapeikko/auth-header

Typescript/Javascript http auth header class and parser.

## Package includes:

- Function and Type: [AuthHeader](./src/AuthHeader.ts) - this function returns AuthHeader class as a Result instance when parse http auth header.
- Function: [isAuthHeaderString](./src/isAuthHeader.ts) - this function check if string value is valid auth header string.
- Function: [isAuthHeaderInstance](./src/AuthHeader.ts) - this type guard function to check if value is AuthHeader class instance.
- Class: [AuthHeaderError](./src/AuthHeaderError.ts) - Common error class for when the Authorization header is missing or invalid.
- Type: [AuthorizationSchemeType](./src/types/index.ts) - Authorization scheme type.
- Const: [authorizationSchemeTypes](./src/types/index.ts) - Authorization scheme types array.
- Interface: [IAuthHeader](./src/types/IAuthHeader.ts) - Interface type for base auth header instance.

## examples

Handle both raw jwt token string and http bearer jwt token string  

```typescript
import {AuthHeader, isAuthHeader} from '@luolapeikko/auth-header';

function handleBearerToken(rawTokenOrAuthBearer: string): void {
	const bearerAuthOrString: string | AuthHeader<'BEARER'> = isAuthHeader(rawTokenOrAuthBearer) ? AuthHeader(rawTokenOrAuthBearer, ['BEARER']).unwrap() : rawTokenOrAuthBearer;
	const token = typeof bearerAuthOrString === 'string' ? bearerAuthOrString : bearerAuthOrString.getCredentials();
	// validate Bearer value
}
```

Handle basic auth credentials

```typescript
function handleBasicAuth(authHeader: string | null | undefined): void {
	const basicAuth: AuthHeader<'BASIC'> = AuthHeader(authHeader, ['BASIC']).unwrap();
	// get and validate credentials
	const username = basicAuth.getUsername();
	const password = basicAuth.getPassword();
}
```
npm package: @luolapeikko/cache-types
Description: Typescript cache interfaces
Author: mharj
Latest version: 0.0.10

# @luolapeikko/cache-types

Typescript Cache interfaces.

Cache interface is a simple Map like key-value interface with basic operations like `get`, `set`, `has`, `delete` and `clear` with cache related options like "set" method to add entry ttl to the cache and "expires" method to get current entry ttl.

## Example

```typescript
import {type ICache} from '@luolapeikko/cache-types';

function foo(cache: ICache<string>) {
	const value = cache.get('key');
	cache.set('key', 'value' /*, ttl: Date */);
	cache.has('key'); // true
	cache.expires('key'); // Date or undefined
	cache.delete('key');
	cache.clear();
	cache.size(); // 0
}
```

## [Full Documentation](https://luolapeikko.github.io/cache-types/)

- [ICache](https://luolapeikko.github.io/cache-types/interfaces/ICache.html)
- [IAsyncCache](https://luolapeikko.github.io/cache-types/interfaces/IAsyncCache.html)
npm package: @luolapeikko/core-ts-array
Description: Type-safe array validation, assertions, and predicates for TypeScript
Author: mharj
Latest version: 0.0.4

# Core TypeScript Array (@luolapeikko/core-ts-array)

Array type guards, assertions, and predicates for TypeScript applications.

## Features

- Type guards for array validation
- Assertion functions that throw TypeError
- Predicate functions for functional programming
- Support for empty arrays, non-empty arrays, and element validation

## Installation

```bash
npm install @luolapeikko/core-ts-array
```

## Full documentation

See https://luolapeikko.github.io/core-ts/ for detailed API documentation and usage examples for each package.

## Usage

```typescript
import {
  ArrayCore,
  ArrayAssert,
  ArrayPredicate,
} from "@luolapeikko/core-ts-array";

// Type guards
const value: unknown = [1, 2, 3];

if (ArrayCore.is(value)) {
  console.log(`Array length: ${value.length}`); // value is typed as unknown[] | readonly unknown[]
}

// Assertions
function processArray(input: unknown): string[] {
  ArrayAssert.assert(input);
  return input.map((item) => String(item)); // input is now typed as unknown[] | readonly unknown[]
}
const data: unknown = ["hello", "world"];
const result: string[] = processArray(data);

// Core utilities - checking array contents
const numbers: number[] = [1, 2, 3, 4, 5];
ArrayCore.oneOf(numbers, 2); // true
ArrayCore.anyOf(numbers, [2, 4]); // true
ArrayCore.allOf(numbers, [1, 2, 3, 4, 5]); // true

// Predicates for filtering arrays
numbers.filter(ArrayPredicate.oneOf(1)); // [1]
numbers.filter(ArrayPredicate.anyOf([2, 4])); // [2, 4]
```
npm package: @luolapeikko/core-ts-async-iterable
Description: Type-safe async iterable validation, assertions, and predicates for TypeScript
Author: mharj
Latest version: 0.0.4

# Core TypeScript Async Iterable (@luolapeikko/core-ts-async-iterable)

Async iterable type guards, assertions, and predicates for TypeScript applications.

## Features

- Type guards for async iterable validation
- Assertion functions that throw TypeError
- Predicate functions for functional programming
- Support for async iteration, element validation, and collection operations

## Installation

```bash
npm install @luolapeikko/core-ts-async-iterable
```

## Full documentation

See https://luolapeikko.github.io/core-ts/ for detailed API documentation and usage examples for each package.

## Usage

```typescript
import {
  AsyncIterableCore,
  AsyncIterableAssert,
  AsyncIterablePredicate,
} from "@luolapeikko/core-ts-async-iterable";

const undefinedValue: unknown = undefined;
// Type guard
if (AsyncIterCore.is(undefinedValue)) {
  console.log("Value is async iterable"); // value is typed as AsyncIterable<unknown>
}
// Assertion
AsyncIterAssert.assert(undefinedValue); // type asserted as AsyncIterable<unknown>

// Collection operations
const asyncNumbers = (async function* () {
  yield 1;
  yield 2;
  yield 3;
  yield 4;
  yield 5;
})();
await AsyncIterCore.anyOf(asyncNumbers, [2, 4]); // true

// Predicate usage
const asyncGen = (async function* () {
  yield "hello";
  yield "world";
})();

// Convert async iterable to array or set
await AsyncIterCore.asArray(asyncGen); // Promise<['hello', 'world']>
await AsyncIterCore.asSet(asyncGen); // Promise<Set<'hello' | 'world'>>

// Filtering with predicate
for await (const value of AsyncIterCore.filter(
  asyncGen,
  AsyncIterPredicate.oneOf("hello")
)) {
  console.log(`Filtered value: ${value}`); // Outputs 'hello'
}
```
npm package: @luolapeikko/core-ts-error
Description: Error handling utilities and type-safe error building for TypeScript
Author: mharj
Latest version: 0.0.4

# Core TypeScript Error (@luolapeikko/core-ts-error)

Error handling utilities and type-safe error building for TypeScript applications.

## Features

- Error building utilities for consistent error messages
- Assertion functions that throw TypeError
- Support for value error construction and unknown error handling
- Foundation package for other @luolapeikko/core-ts modules

## Installation

```bash
npm install @luolapeikko/core-ts-error
```

## Full documentation

See https://luolapeikko.github.io/core-ts/ for detailed API documentation and usage examples for each package.

## Usage

```typescript
import { ErrorCore, ErrorAssert, ErrorCast } from '@luolapeikko/core-ts-error';

// Type guards for Error objects
if (ErrorCore.is(value)) {
  console.log(`Error message: ${value.message}`); // value is typed as Error
}

// Assertions
function processError(input: unknown) {
  ErrorAssert.assert(input);
  return input.stack; // input is now typed as Error
}

// Casting unknown errors
try {
  throw new Error('Something went wrong');
} catch (error) {
  const typedError = ErrorCast.from(error); // Error object
  console.log(typedError.message);
}

```
npm package: @luolapeikko/core-ts-iterable
Description: Type-safe iterable validation, assertions, and predicates for TypeScript
Author: mharj
Latest version: 0.0.4

# Core TypeScript Iterable (@luolapeikko/core-ts-iterable)

Iterable type guards, assertions, and predicates for TypeScript applications.

## Features

- Type guards for iterable validation
- Assertion functions that throw TypeError
- Predicate functions for functional programming
- Support for empty iterables, element validation, and collection operations

## Installation

```bash
npm install @luolapeikko/core-ts-iterable
```

## Full documentation

See https://luolapeikko.github.io/core-ts/ for detailed API documentation and usage examples for each package.

## Usage

```typescript
import {
  IterableCore,
  IterableAssert,
  IterablePredicate,
} from "@luolapeikko/core-ts-iterable";

// Type guards
if (IterableCore.is(value)) {
  console.log("Value is iterable"); // value is typed as Iterable<unknown>
}

// Assertions
function processIterable(input: unknown) {
  IterableAssert.assert(input);
  for (const item of input) {
    // input is now typed as non-empty iterable
    console.log(item);
  }
}

// Collection operations
const numbers = [1, 2, 3, 4, 5];
const hasEven = IterableCore.anyOf(numbers, [2, 4]); // true
const allPositive = IterableCore.allOf(numbers, [1, 2, 3, 4, 5]); // true
```
npm package: @luolapeikko/core-ts-loadable
Description: Loadable type functions for TypeScript
Author: mharj
Latest version: 0.0.4

# Core TypeScript String (@luolapeikko/core-ts-loadable)

Loadable type functions for TypeScript applications.

## Features

- Resolver to handle argument as "value", () => "value", Promise<"value"> or () => Promise<"value">

## Installation

```bash
npm install @luolapeikko/core-ts-loadable
```

## Full documentation

See https://luolapeikko.github.io/core-ts/ for detailed API documentation and usage examples for each package.

## Usage

```typescript
import type {Loadable} from '@luolapeikko/core-ts-type';
import {LoadableCore} from '@luolapeikko/core-ts-loadable';

// example resolving a Loadable string
async function demo(loadable: Loadable<string>) {
	const value: string = await LoadableCore.resolve(loadable);
}

// example usage
async function example() {
	const directValue: string = await LoadableCore.resolve('hello');
	const functionValue: string = await LoadableCore.resolve(() => 'hello');
	const promiseValue: string = await LoadableCore.resolve(Promise.resolve('hello'));
	const asyncFunctionValue: string = await LoadableCore.resolve(() => Promise.resolve('hello'));
}
```
npm package: @luolapeikko/core-ts-nullish
Description: Type-safe null/undefined validation and assertions for TypeScript
Author: mharj
Latest version: 0.0.4

# Core TypeScript Nullish (@luolapeikko/core-ts-nullish)

Null/undefined type guards and assertions for TypeScript applications.

## Features

- Type guards for null/undefined validation
- Assertion functions that throw TypeError
- Support for nullish value detection and non-nullish validation

## Installation

```bash
npm install @luolapeikko/core-ts-nullish
```

## Full documentation

See https://luolapeikko.github.io/core-ts/ for detailed API documentation and usage examples for each package.

## Usage

```typescript
import { NullishCore, NullishAssert } from "@luolapeikko/core-ts-nullish";

// Type guards
if (NullishCore.is(value)) {
  console.log("Value is null or undefined"); // value is typed as null | undefined
}

if (NullishCore.isNot(value)) {
  console.log(`Value: ${value}`); // value is typed as NonNullish<typeof value>
}

// Assertions
function processValue(input: unknown) {
  NullishAssert.assertNot(input);
  return input.toString(); // input is now typed as non-nullish
}

// Practical examples
const userInput: string | null | undefined = getUserInput();

if (NullishCore.isNot(userInput)) {
  // userInput is now typed as string
  console.log(`Processing: ${userInput.toUpperCase()}`);
}

// Safe processing
function safeProcess(value: unknown) {
  if (NullishCore.isNot(value)) {
    // Value is guaranteed to be non-nullish
    return String(value).length;
  }
  return 0;
}
```
npm package: @luolapeikko/core-ts-number
Description: Type-safe number validation, assertions, and casting utilities for TypeScript
Author: mharj
Latest version: 0.0.4

# Core TypeScript Number (@luolapeikko/core-ts-number)

Number type guards, assertions, casting, and predicates for TypeScript applications.

## Features

- Type guards for number validation
- Assertion functions that throw TypeError
- Casting functions for safe number conversion
- Support for integers, finite numbers, and range validation

## Installation

```bash
npm install @luolapeikko/core-ts-number
```

## Full documentation

See https://luolapeikko.github.io/core-ts/ for detailed API documentation and usage examples for each package.

## Usage

```typescript
import {
  NumberCore,
  NumberAssert,
  NumberCast,
} from "@luolapeikko/core-ts-number";

// Type guards
const value: unknown = 42;

if (NumberCore.isNumber(value)) {
  console.log(`Number: ${value.toFixed(2)}`); // value is typed as number
}

if (NumberCore.isInt(value)) {
  console.log(`Integer: ${value}`); // value is typed as Integer
}

// Assertions
function processNumber(input: unknown) {
  NumberAssert.assertFinite(input);
  return input * 2; // input is now a finite number
}

// Casting
const userInput = "42";
const numValue = NumberCast.intFrom(userInput); // 42 as Integer
const floatValue = NumberCast.numberFrom("3.14"); // 3.14 as number

// Example usage
const testNumber = 123;
const result = processNumber(testNumber);
console.log("Processed number:", result);
```
npm package: @luolapeikko/core-ts-record
Description: Type-safe record/object validation, assertions, and mapping utilities for TypeScript
Author: mharj
Latest version: 0.0.4

# Core TypeScript Record (@luolapeikko/core-ts-record)

Record/object type guards, assertions, mapping utilities, and predicates for TypeScript applications.

## Features

- Type guards for record/object validation
- Assertion functions that throw TypeError
- Mapping utilities for object transformation
- Predicate functions for functional programming
- Support for empty objects, key validation, and property checking

## Installation

```bash
npm install @luolapeikko/core-ts-record
```

## Full documentation

See https://luolapeikko.github.io/core-ts/ for detailed API documentation and usage examples for each package.

## Usage

```typescript
import {
  RecordAssert,
  RecordCore,
  RecordMapper,
  RecordPredicate,
} from "@luolapeikko/core-ts-record";

// Type guards
const value: unknown = { name: "John", age: 30 };

if (RecordCore.is(value)) {
  console.log(`Object keys: ${RecordCore.keys(value)}`); // value is typed as Record<string, unknown>
}

// Assertions
function processRecord(input: unknown) {
  RecordAssert.assert(input);
  return RecordCore.values(input); // input is now typed as record, get values safely
}

// Core utilities
const data = { a: 1, b: 2, c: 3 };
const keys = RecordCore.keys(data); // ['a', 'b', 'c']
const values = RecordCore.values(data); // [1, 2, 3]
const picked = RecordCore.pick(["a", "c"], data); // { a: 1, c: 3 }
const omitted = RecordCore.omit(["b"], data); // { a: 1, c: 3 }

// Mapping utilities
const pickMapper = RecordMapper.pick(["a", "c"]); // Function to pick keys
const propMapper = RecordMapper.prop("name"); // Function to get property
const mappedData = pickMapper(data); // Apply the pick mapper
const testObj = { name: "Test", value: 42 };
const nameValue = propMapper(testObj); // Apply the prop mapper

// Predicates for filtering
const objects = [{ name: "John" }, { name: "Jane" }, { age: 30 }];
const johnObjects = objects.filter(RecordPredicate.propEq("name", "John")); // [{ name: 'John' }]

// Example usage
const testRecord = { foo: "bar", baz: 42 };
const result = processRecord(testRecord);
```
npm package: @luolapeikko/core-ts-string
Description: Type-safe string validation, assertions, and predicates for TypeScript
Author: mharj
Latest version: 0.0.4

# Core TypeScript String (@luolapeikko/core-ts-string)

String type guards, assertions, and predicates for TypeScript applications.

## Features

- Type guards for string validation
- Assertion functions that throw TypeError
- Predicate functions for functional programming
- Support for empty strings, case validation, and prefix/suffix checking

## Installation

```bash
npm install @luolapeikko/core-ts-string
```

## Full documentation

See https://luolapeikko.github.io/core-ts/ for detailed API documentation and usage examples for each package.

## Usage

```typescript
import {
  StringCore,
  StringAssert,
  StringPredicate,
} from "@luolapeikko/core-ts-string";

// Type guards
const value: unknown = "hello world";

if (StringCore.is(value)) {
  console.log(value.toUpperCase()); // value is typed as string
}

const emptyValue: unknown = "";
if (StringCore.isEmpty(emptyValue)) {
  console.log("Empty string"); // value is typed as EmptyString (or '')
}

// Predicates for filtering
const files = ["readme.md", "package.json", "src/index.ts"];
const markdownFiles = files.filter(StringPredicate.endsWith(".md")); // ['readme.md']

// Assertions
function processString(input: unknown) {
  StringAssert.assert(input); // First assert it's a string
  StringAssert.assertNotEmpty(input); // Then assert it's not empty
  return input.trim(); // input is now typed as non-empty string
}

// Example usage
const testInput = "test string";
const result = processString(testInput);
console.log("Processed string:", result);
```
npm package: @luolapeikko/core-ts-type
Description: Common TypeScript types for @luolapeikko/core-ts packages
Author: mharj
Latest version: 0.0.4

# Core TypeScript Types (@luolapeikko/core-ts-type)

A collection of foundational TypeScript types and utilities for building robust applications.

## Features

- Type definitions for @luolapeikko/core-ts packages

## Installation

```bash
npm install @luolapeikko/core-ts-type
```

## Full documentation

See https://luolapeikko.github.io/core-ts/ for detailed API documentation and usage examples for each package.

## Usage

```typescript
import type { Nullish } from "@luolapeikko/core-ts-type";

function processInput(input: Nullish<string>) {
  if (!input) {
    console.log("Input is null or undefined");
  } else {
    console.log(`Input value: ${input}`);
  }
}
```
npm package: @luolapeikko/graph-entity
Description: Graph Entity service to track linked service nodes and node change events
Author: mharj
Latest version: 0.0.6

# graph-entity

Graph Entity service to track linked services and change events, idea is loosely based on Graph Database but more Entity and event driven.

## Overview

Service is designed to track linked service nodes and their change events (by adding/removing nodes and edges and nodes emitting change events).
This allow tracking changes as example NodeJS => Express => Logins: [User1, User2, User3] / Logouts. Or track other services like Redis, MongoDB, etc. and those relations and events.

## Example

```typescript
import {EventEmitter} from 'events';
import type {type GraphNodeEventMapping, type IGraphBaseEntityNode, type IGraphEventEntityNode} from '@luolapeikko/graph-entity-types';
import {GraphManager} from '@luolapeikko/graph-entity';

export const GraphTypeEnum = {
	NodeJS: 0,
	Express: 10,
	ExpressRouter: 11,
	MognoDB: 20,
	Redis: 30,
} as const;

const manager = new GraphManager<ExpressJs | NodeJsNode>();

type NodeJsNode = IGraphBaseEntityNode<typeof GraphTypeEnum.NodeJS, {version: string}>;
export const rootNodejsGraphNode: NodeJsNode = {
	nodeType: GraphTypeEnum.NodeJS,
	getNodeId: () => 'nodejs',
	getNodeProps: () => ({version: process.versions.node}),
};
manager.addNode(rootNodejsGraphNode); // add nodejs node to manager

export class ExpressJs
	extends EventEmitter<GraphNodeEventMapping>
	implements IGraphEventEntityNode<typeof GraphTypeEnum.Express, {port: string | number | undefined; status?: 'running' | 'stopped'}>
{
	public nodeType = GraphTypeEnum.Express;
	public getNodeId = () => 'express';
	private port: string;
	private status: 'running' | 'stopped' = 'stopped';
	public constructor(port: string) {
		super();
		this.port = port;
		manager.addEdge(rootNodejsGraphNode, this); // here constructor work easy way to add edge to nodejs root node
		// after start server, set status to running and notify with this.emit('nodeUpdated') event
	}
	public getNodeProps() {
		return {
			port: this.port,
			status: this.status,
		};
	}
}

// hook to manager events and output the node hierarchy structure
manager.on('graphUpdate', async (node) => {
	console.log(await manager.getNodeStructure(node));
});
```
npm package: @luolapeikko/graph-entity-types
Description: Typess for Graph Entity module
Author: mharj
Latest version: 0.0.10

# graph-entity

Graph Entity service to track linked services and change events, idea is loosely based on Graph Database but more Entity and event driven.

## Overview

Service is designed to track linked service nodes and their change events (by adding/removing nodes and edges and nodes emitting change events).
This allow tracking changes as example NodeJS => Express => Logins: [User1, User2, User3] / Logouts. Or track other services like Redis, MongoDB, etc. and those relations and events.

## Example

```typescript
import {EventEmitter} from 'events';
import {GraphManager, type GraphNodeEventMapping, type IGraphBaseEntityNode, type IGraphEventEntityNode} from '.';

export const GraphTypeEnum = {
	NodeJS: 0,
	Express: 10,
	ExpressRouter: 11,
	MognoDB: 20,
	Redis: 30,
} as const;

const manager = new GraphManager<ExpressJs | NodeJsNode>();

type NodeJsNode = IGraphBaseEntityNode<typeof GraphTypeEnum.NodeJS, {version: string}>;
export const rootNodejsGraphNode: NodeJsNode = {
	nodeType: GraphTypeEnum.NodeJS,
	getNodeId: () => 'nodejs',
	getNodeProps: () => ({version: process.versions.node}),
};
manager.addNode(rootNodejsGraphNode); // add nodejs node to manager

export class ExpressJs
	extends EventEmitter<GraphNodeEventMapping>
	implements IGraphEventEntityNode<typeof GraphTypeEnum.Express, {port: string | number | undefined; status?: 'running' | 'stopped'}>
{
	public nodeType = GraphTypeEnum.Express;
	public getNodeId = () => 'express';
	private port: string;
	private status: 'running' | 'stopped' = 'stopped';
	public constructor(port: string) {
		super();
		this.port = port;
		manager.addEdge(rootNodejsGraphNode, this); // here constructor work easy way to add edge to nodejs root node
		// after start server, set status to running and notify with this.emit('nodeUpdated') event
	}
	public getNodeProps() {
		return {
			port: this.port,
			status: this.status,
		};
	}
}

// hook to manager events and output the node hierarchy structure
manager.on('graphUpdate', async (node) => {
	console.log(await manager.getNodeStructure(node));
});
```
npm package: @luolapeikko/memcached
Description: Javascript memcached server
Author: mharj
Latest version: 0.0.1

# @luolapeikko/memcached

Javascript memcached server (loosley based on https://github.com/alexfernandez/nodecached).
This is quite minimalistic implementation, but it should be enough for simple use cases and unit testing.
Currently only supports TCP protocol and have only in-memory storage.

## Usage

### CLI

```bash
npm install -g @luolapeikko/memcached
memcached
```

### API

```typescript
import { MemcachedServer } from "@luolapeikko/memcached";

const server = new MemcachedServer({
  port: 11211,
  store: new InMemoryStore(),
  logger: console,
});
await server.start();

await server.stop();
```
npm package: @luolapeikko/odata-query-filter
Description: OData $filter string parser and evaluator
Author: mharj
Latest version: 0.0.4

# @luolapeikko/odata-query-filter

[![TypeScript](https://badges.frapsoft.com/typescript/code/typescript.svg?v=101)](https://github.com/ellerbrock/typescript-badges/)
[![Maintainability](https://qlty.sh/gh/luolapeikko/projects/odata-query-filter/maintainability.svg)](https://qlty.sh/gh/luolapeikko/projects/odata-query-filter)
[![Code Coverage](https://qlty.sh/gh/luolapeikko/projects/odata-query-filter/coverage.svg)](https://qlty.sh/gh/luolapeikko/projects/odata-query-filter)
[![CI/CD](https://github.com/luolapeikko/odata-query-filter/actions/workflows/main.yml/badge.svg)](https://github.com/luolapeikko/odata-query-filter/actions/workflows/main.yml)

## Builds a data filter based on $filter query values.

Handles most OData query comparison operators (`eq` | `ne` | `gt` | `ge` | `lt` | `le`), logical operators (`and` | `or` | `not`), array lambda operators (`any` | `all`), and functions (`contains` | `startswith` | `endswith` | `tolower` | `toupper` | `trim` | `length` | `concat` | `indexof` | `substring`).
Automatic ISO DateTime string / Date handling, and uses `toString()` for custom objects in comparisons.

## Usage examples

```typescript
interface Person {
  name: string;
}
const personList = [{ name: "John" }, { name: "Mary" }];
const personFilter = createODataFilter<Person>("name eq 'John'");
console.log(personList.filter(personFilter)); // [{name: 'John'}]
```

```typescript
import { createODataFilter } from "@luolapeikko/odata-query-filter";

const handleRequest = (req, res, next) => {
  const dataArray: DataType[] = await getSomeData();
  const queryFilter = req.query.$filter;
  if (typeof queryFilter === "string") {
    const filterCallback = createODataFilter<DataType>(queryFilter);
    res.json(dataArray.filter(filterCallback));
  }
};
```
npm package: @luolapeikko/oidc-jwt-verify-tachyon
Description: Tachyon Drive cache adapters for oidc-jwt-verify
Author: mharj
Latest version: 0.0.2

# @luolapeikko/oidc-jwt-verify-tachyon

[![TypeScript](https://badges.frapsoft.com/typescript/code/typescript.svg?v=101)](https://github.com/ellerbrock/typescript-badges/)
[![npm version](https://badge.fury.io/js/@luolapeikko%2Foidc-jwt-verify-tachyon.svg)](https://badge.fury.io/js/@luolapeikko%2Foidc-jwt-verify-tachyon)
[![Maintainability](https://qlty.sh/gh/luolapeikko/projects/oidc-jwt-verify/maintainability.svg)](https://qlty.sh/gh/luolapeikko/projects/oidc-jwt-verify)
[![Code Coverage](https://qlty.sh/gh/luolapeikko/projects/oidc-jwt-verify/coverage.svg)](https://qlty.sh/gh/luolapeikko/projects/oidc-jwt-verify)
[![CI/CD](https://github.com/luolapeikko/oidc-jwt-verify/actions/workflows/oidc-jwt-verify-tachyon.yml/badge.svg)](https://github.com/luolapeikko/oidc-jwt-verify/actions/workflows/oidc-jwt-verify-tachyon.yml)

## Tachyon drivers for @luolapeikko/oidc-jwt-verify caches

- Tachyon storage driver can be used as public ssl cert caching.
- Tachyon storage driver can be used as validated token caching.

## Enable public cert file caching

```typescript
const certCacheSchema = z.object({certs: z.record(z.string(), z.record(z.string(), z.string())), _ts: z.number()}) satisfies StandardSchemaV1<
	unknown,
	CertRecords
>;

// with Tachyon file storage driver
await useCache(new TachyonCertCache(new FileStorageDriver({name: 'FileCertCacheDriver', fileName: './unitTestCache.json'}, certCacheBufferSerializer(certCacheSchema))));
```

## Enable verified token persist caching (Tachyon storage driver with encryption)

```typescript
import {
  isRawJwtToken,
  type RawJwtToken,
  setTokenCache,
} from "@luolapeikko/oidc-jwt-verify";
import { buildTokenCacheBufferSerializer } from "@luolapeikko/oidc-jwt-verify-tachyon";
import {
  CryptoBufferProcessor,
  FileStorageDriver,
} from "tachyon-drive-node-fs";
import { TachyonExpireCache } from "tachyon-expire-cache";
import { z } from "zod";

const tokenBodySchema = z.object({}).loose(); // or build token payload schema
const tokenCacheMapSchema = z.map(
  z.string().refine(isRawJwtToken),
  z.object({ expires: z.number(), data: tokenBodySchema }),
);
const bufferSerializer = buildTokenCacheBufferSerializer(tokenCacheMapSchema);
// const stringSerializer = buildTokenCacheStringSerializer<TokenPayload>(tokenCacheMapSchema); // if using string based Tachyon drivers
const processor = new CryptoBufferProcessor(Buffer.from("some-secret-key"));
const driver = new FileStorageDriver(
  { name: "TokenStorageDriver", fileName: "./tokenCache.aes" },
  bufferSerializer,
  processor,
);
const cache = new TachyonExpireCache<
  z.infer<typeof tokenBodySchema>,
  RawJwtToken
>({ name: "TachyonExpireCache" }, driver);
setTokenCache(cache);
```
npm package: @luolapeikko/result-option
Description: Rust style Result for TypeScript/Javascript
Author: mharj
Latest version: 2.2.1

# @luolapeikko/result-option

[![TypeScript](https://badges.frapsoft.com/typescript/code/typescript.svg?v=101)](https://github.com/ellerbrock/typescript-badges/)
[![npm version](https://badge.fury.io/js/@luolapeikko%2Fresult-option.svg)](https://badge.fury.io/js/@luolapeikko%2Fresult-option)
[![Maintainability](https://qlty.sh/gh/luolapeikko/projects/result-option/maintainability.svg)](https://qlty.sh/gh/luolapeikko/projects/result-option)
[![Code Coverage](https://qlty.sh/gh/luolapeikko/projects/result-option/coverage.svg)](https://qlty.sh/gh/luolapeikko/projects/result-option)
![example workflow](https://github.com/luolapeikko/result-option/actions/workflows/main.yml/badge.svg)

A lightweight library for representing the Rust style Result and Option classes for function callback or promise in TypeScript/JavaScript.

## install

```bash
npm install @luolapeikko/result-option
```

## [Documentation](https://luolapeikko.github.io/result-option/)
- [Result](https://luolapeikko.github.io/result-option/types/IResult.html)
- [Option](https://luolapeikko.github.io/result-option/types/IOption.html)
npm package: @luolapeikko/ts-common
Description: Typescript common utils and types
Author: mharj
Latest version: 1.1.4

# ts-common

Collection of common TS utility types, interfaces and utils.

[![TypeScript](https://badges.frapsoft.com/typescript/code/typescript.svg?v=101)](https://github.com/ellerbrock/typescript-badges/)
[![npm version](https://badge.fury.io/js/@luolapeikko%2Fts-common.svg)](https://badge.fury.io/js/@luolapeikko%2Fts-common)
![github action](https://github.com/luolapeikko/ts-common/actions/workflows/main.yml/badge.svg?branch=main)

## Install

```bash
npm install @luolapeikko/ts-common
```

### Documentation

- `Loadable` type to handle loadable value (e.g. value, value Promise, callback function returning value).
- Array utility types like `NonEmptyArray` and `NonEmptyReadonlyArray`.
- Object utility conditional types like `RecordHaveReadonlyKeys` and `RecordHaveWritableKeys`.
- `OneOf` type to handle one of types (non-union way).
- Helper interfaces like `IToString`, `IToJSON`.
- new Core helper class namespaced functions under [`ArrayCore`, `ErrorCore`, `IterCore`, `LoadableCore`, `NumberCore`, `RecordCore`, `UndefCore`] for easier access.

### "Core" function usage examples

```typescript
import {NumberCore as N} from '@luolapeikko/ts-common';
N.isInteger(1); // true
N.isFloat(1); // false

import {RecordCore as R} from '@luolapeikko/ts-common';
const data: Data = {demo: 'hello', value: null};
const output: Pick<Data, 'value'> = R.pick(['value'], data);
const dataArray: Data[] = [{demo: 'hello', value: null}];
const output: Pick<Data, 'demo'>[] = dataArray.map(R.pick(['demo']));

import {UndefCore as U} from '@luolapeikko/ts-common';
U.isUndef(null); // true
U.isNull(null); // true
U.isNullish(null); // true
U.assertNull('test'); // throws
```

See more features on [Package documentation](https://luolapeikko.github.io/ts-common/)