open-index/open-npm huggingface dataset:
npm package: @sigeco/tools
Description: Tools for sigeco
Author: Juan Manuel Abanto Mera
Latest version: 1.0.3

# @sigeco/tools
[![npm downloads](https://img.shields.io/npm/dt/@sigeco/tools.svg?maxAge=2592000)](http://npmjs.com/package/@sigeco/tools)
[![gzip size](https://img.badgesize.io/https:/npmcdn.com/@sigeco/tools/dist/sigeco-tools.umd.min.js?compression=gzip)]()
[![version](https://img.shields.io/npm/v/@sigeco/tools.svg)]()

additional tools in react

## Installation

Sigeco Tools is available as an [npm package](https://www.npmjs.com/package/@sigeco/tools).

Note that this package requires `@material-ui/core` **v4**, `react-draggable` **v4** and `react-virtualized` **v9**.

**[Stable channel v1]**

```sh
// with npm
npm install @sigeco/tools

// with yarn
yarn add @sigeco/tools
```

**[With UMD]**

You can also use a global-friendly UMD build:

```html
https://cdn.jsdelivr.net/npm/@sigeco/tools@1.0.1/dist/sigeco-tools.umd.js

https://cdn.jsdelivr.net/npm/@sigeco/tools@1.0.1/dist/sigeco-tools.umd.min.js
```

### ActionField API

### FieldSet API

### Table API
npm package: @sigex-kz/asn1.js-rfc5652
Description: RFC5652 definitions for https://github.com/indutny/asn1.js/
Author: sigex-kz
Latest version: 1.0.9

# asn1.js-rfc5652

Incomplete RFC5652 definitions for https://github.com/indutny/asn1.js/

See sources to identify what's implemented and tests for basic examples.

## Install

```
npm install @sigex-kz/asn1.js-rfc5652
```

## Usage

```js
const cms = rfc5652.ContentInfo.decode(cmsPemString, 'pem', { label: 'CMS' });

console.log(cms.content.version);
console.log(cms.contentType);
console.log(cms.content.encapContentInfo.eContent);

const newCmsPemString = rfc5652.ContentInfo.encode(cms, 'pem', { label: 'CMS' });
```

## Test data generation
```
cd test/fixtures/

openssl genpkey -genparam -algorithm ec -pkeyopt ec_paramgen_curve:P-256 -pkeyopt ec_param_enc:named_curve -out ec-keygenparams.temp.pem
openssl req -x509 -newkey ec:ec-keygenparams.temp.pem -keyout ec-key.temp.pem -out ec-cert.temp.pem -days 365 -nodes -subj '/CN=test-ec'
openssl cms -sign -binary -in ec-cert.temp.pem -signer ec-cert.temp.pem -inkey ec-key.temp.pem -outform PEM -out ec-cms.pem
openssl cms -sign -binary -in ec-cert.temp.pem -signer ec-cert.temp.pem -inkey ec-key.temp.pem -outform PEM -out ec-cms-embedded.pem -nodetach

openssl req -x509 -newkey rsa:2048 -keyout rsa-key.temp.pem -out rsa-cert.temp.pem -days 365 -nodes -subj '/CN=test-rsa'
openssl cms -sign -binary -in rsa-cert.temp.pem -signer rsa-cert.temp.pem -inkey rsa-key.temp.pem -outform PEM -out rsa-cms.pem
openssl cms -sign -binary -in rsa-cert.temp.pem -signer rsa-cert.temp.pem -inkey rsa-key.temp.pem -outform PEM -out rsa-cms-embedded.pem -nodetach

rm *.temp.pem
```
npm package: @sigfox/eslint-config-react
Description: Eslint config for React projects used @ Sigfox
Latest version: 0.3.1

# @sigfox/eslint-config-react

[![npm version](https://badge.fury.io/js/%40sigfox%2Feslint-config-react.svg)](https://www.npmjs.com/package/@sigfox/eslint-config-react)

This is the shared Eslint configuration used for React based projects at [Sigfox](https://www.sigfox.com).

It is meant to be used with Prettier (all rules handled by Prettier are turned off).

> ---
>
> ⚠️ Work in progress
>
> This package is still at its early stages, and radical changes may occur.
>
> ---

## Installation

### Yarn

If you use yarn, run `npm info "@sigfox/eslint-config-react@latest" peerDependencies` to list the peer dependencies and versions, then run `yarn add --dev <dependency>@<version>` for each listed peer dependency.

### npm 5+

```sh
npx install-peerdeps --dev @sigfox/eslint-config-react
```

## Usage

Here is our typical `.eslintrc` file:

```json
// .eslintrc
{
  "extends": "@sigfox/eslint-config-react",
  "parser": "babel-eslint",
  "env": {
    "browser": true,
    "node": true,
    "es6": true
  },
  "rules": {}
}
```

We use the [babel-eslint](https://github.com/babel/babel-eslint/). It's not mandatory, but if you are using babel (including babel-loader in your webpack or other flavors), you should use this parser to avoid false positives.

## Meant to be used with [Prettier](https://prettier.io/)

All rules that are unnecessary or might conflict with Prettier are turned off.

This is the Prettier config we use:

```json
// .prettierrc

{
  "printWidth": 80,
  "tabWidth": 2,
  "tabs": false,
  "semi": true,
  "singleQuote": true,
  "trailingComma": "none",
  "bracketSpacing": true,
  "jsxBracketSameLine": false,
  "arrowParens": "avoid",
  "proseWrap": "preserve"
}
```

Please refer to the [Prettier documentation](https://prettier.io/docs/en/install.html) to integrate it in your environment and [editor/IDE](https://prettier.io/docs/en/editors.html). Don't forget to consider [prettier-eslint](https://github.com/prettier/prettier-eslint).

## Troubeshooting

If you are migrating from a previous eslint version or configuration, or just did an upgrade of this package or dependencies, follow these steps after installation and configuration:

- destroy your node_modules directory
- if you are using yarn, clean its cache: `yarn cache clean`
- `yarn` or `npm install`
- reboot your editor / IDE

## Contributing

Don't hesitate to open issues, submit pull requests, and to start a debate.

Still, you have to keep in mind that this is the configuration we use at Sigfox, and that we might decline change requests because they don't comply with our internal choices, and not because they are stupid.

Feel free to fork, change, rename and pubish your own package based on this one.

## Licence and credits

MIT

Big thanks to Airbnb for publishing their [eslint config packages](https://github.com/airbnb/javascript/tree/master/packages), which we used and tuned for a time before deciding to make our own package. Most of the code here is still simple copy/paste of it.
npm package: @sigfox/joi-phone
Description: Joi extension for phone validation
Author: Sigfox developers
Latest version: 1.0.1

# joi-phone - Joi extension for phone validation

## This is a fork of [joi-phone-validator](https://github.com/oystparis/joi-phone-validator).

All credits go to the original creators, we forked it in order to export an extension instead of a validator.

## Features

Joi extension for phone number validation.

- [Joi](#joi)
  - [`phone`](#phone)
  - [`mobile`](#mobile)
  - [`validate`](#validate)

## When use it?

This module can be used if you need to extend your Joi instance with a phone/mobile number validator.

## Install

```bash
npm install @sigfox/joi-phone
```

## Usage

#### `phone`

Generates a joi schema that matches any phone number.

#### `mobile`

Joi rule for mobile number matching.

#### `validate`

Joi rule for E.164 international format matching.

```javascript
const joi = require('joi');
const joiPhone = require('@sigfox/joi-phone');

const joiExtended = joi.extend(joiPhone);

const phoneSchema = joiExtended
  .phone()
  .validate();

const mobileSchema = joiExtended
  .phone()
  .mobile();

joiExtended.validate('+33123456789', phoneSchema); // success
joiExtended.validate('0000123456789', phoneSchema); // error

joiExtended.validate('+1403 306-0485', mobileSchema); // success
joiExtended.validate('+33123456789', mobileSchema); // error
```

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/joi-query
Description: Joi helpers for url query validation
Author: Sigfox developers
Latest version: 1.0.1

# joi-query - Joi helpers for url query validation

## Features

- [Joi](https://github.com/hapijs/joi)
  - [`queryFilter`](https://github.com/sigfox/javascript/packages/joi-query/lib/filter.js)
  - [`queryOrder`](https://github.com/sigfox/javascript/packages/joi-query/lib/order.js)
  - [`queryLimit`](https://github.com/sigfox/javascript/packages/joi-query/lib/limit.js)
  - [`queryOffset`](https://github.com/sigfox/javascript/packages/joi-query/lib/offset.js)
  - [`queryFields`](https://github.com/sigfox/javascript/packages/joi-query/lib/fields.js)
  - [`queryEmbed`](https://github.com/sigfox/javascript/packages/joi-query/lib/embed.js)
  - [`queryBoolOperators`](https://github.com/sigfox/javascript/packages/joi-query/lib/bool-operators.js)
  - [`queryAltInOperator`](https://github.com/sigfox/javascript/packages/joi-query/lib/alt-in-operator.js)
  - [`queryAltRangeOperators`](https://github.com/sigfox/javascript/packages/joi-query/lib/alt-range-operators.js)
  - [`queryAndOperator`](https://github.com/sigfox/javascript/packages/joi-query/lib/alt-operator.js)
  - [`queryOrOperator`](https://github.com/sigfox/javascript/packages/joi-query/lib/or-operator.js)
  - [`queryAltExistsOperator`](https://github.com/sigfox/javascript/packages/joi-query/lib/alt-exists-operator.js)

## When use it?

This module can be used if you need to validate url queries using Joi

## Install

```bash
npm install @sigfox/joi-query
```

## Usage

```javascript
const joi = require('joi');

// This adds the helpers to the joi instance
require('./joi-query')(joi);
```

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/koa-acl
Description: Koa middleware for ACL handling.
Author: Sigfox developers
Latest version: 1.0.3

# koa-acl

Koa middleware for ACL handling.

## When use it?

This module can be used if you need to handle authorizations on your koa app.

## Features

- Returns boom error if the user doesn't have the right roles.

## Install

```bash
npm install @sigfox/koa-acl
```

## Usage

- `roles` (`Array[String]`): These are the roles that the middleware will search for in `ctx.state` (`ctx.state.user.roles` or directly `ctx.state.roles`)

- `query` (`Function`): A function taking ctx as a parameter. If falsy, the middleware will deny access.

```javascript
const Koa = require('koa');
const Router = require('koa-router');
const aclMiddleware = require('@sigfox/koa-acl');
const controller = require('hypothetical-controller');

const ADMIN_ROLE = 'admin';

// ctx.state must be populated by user or roles
const addUser = (ctx, next) => {
  // Both of those are working, user.roles has priority though.
  ctx.state.user = {
    roles: [ADMIN_ROLE]
  };
  ctx.state.roles = [ADMIN_ROLE];
  return next();
};

const addAdmin = (ctx, next) => {
  ctx.state.user = {
    isAdmin: true
  };
  return next();
};

// Just provide the allowed roles and/or a query, this will generate middlewares that you can use together or separately
const { roles: hasAdminRole, query: isAdmin } = aclMiddleware({
  roles: [ADMIN_ROLE],
  query: ctx => !!(ctx.state.user && ctx.state.user.isAdmin)
});

const getRoutes = () => {
  const router = new Router();

  // This will reach the controller
  router.get('/data/1', controller);

  // This will reach the controller
  router.get('/data/2', addUser, hasAdminRole, controller);

  // This will return 403 because no user is provided
  router.get('/data/3', hasAdminRole, controller);

  // This will return 403 because no user is provided
  router.get('/data/4', isAdmin, controller);

  // This will reach the controller
  router.get('/data/5', addAdmin, isAdmin, controller);

  return router.routes();
};

const app = new Koa().use(getRoutes()).listen();
```

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/koa-error-handler
Description: Koa middleware handling errors.
Author: Sigfox developers
Latest version: 1.1.0

# koa-error-handler

Koa middleware for Error Handling

## When use it?

This module can be used if you need an Error Handler for your Koa App.

## Features

Mount an Error Handler to your Koa app. If an error is caught, a JSON body will be used as response by default:

```json
{
  "statusCode": 500,
  "error": "Internal Server Error",
  "message": "An internal server error occurred"
}
```

If an HTML response is preferred when the "Accept" header is set to prefer HTML response, the middleware
can be configured with html and renderHTML parameters to send an HTML response instead of the default JSON response.

## Install

```bash
npm install @sigfox/koa-error-handler
```

## Usage

**errorHandler({ renderHtml, html })**

- `renderHTML` (`Function`) (`optional`): An asynchronous function returning a Promise resulting to a string representing an HTML page

- `html` (`String`) (`optional`): A string representing an HTML page, used as fallback if renderHTML Promise is rejected or an error is thrown by renderHTML function.

```javascript
const Koa = require('koa');
const errorHandler = require('@sigfox/koa-error-handler');

const html = '<!DOCTYPE html><html lang="en"><body></body></html>';

const app = new Koa()
  .use(
    errorHandler({
      renderHTML: () => Promise.resolve(html),
      html
    })
  )
  .listen();
```

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/koa-health-check
Description: Koa middleware mounting the GET /health route returning the app status depending on ctx.isShutdown existence.
Author: Sigfox developers
Latest version: 1.0.1

# koa-health-check

Koa middleware mounting the route GET /health.

## When use it?

You can use this module if you need a route returning the health status of your Koa app.

## Features

Mount GET /health to your Koa app, this route verifies the existence of a field in the Koa's context,
and will set the status to 503 if that field exists, otherwise 200.

## Install

```bash
npm install @sigfox/koa-health-check
```

## Usage

- `fieldToVerify` (`String`) (`default: "isShutdown"`): The name of the field in the ctx that /health will search for, if that field exists and is truthy, a 503 status will be responded.

```javascript
const Koa = require('koa');
const healthCheck = require('@sigfox/koa-health-check');

const HEALTH_CHECK_DELAY = 2000;

const app = new Koa().use(healthCheck());

const server = app.listen();

process.on('SIGTERM', () => {
  app.context.isShutdown = true;
  console.warn(`Received SIGTERM signal, respecting health check delay ${HEALTH_CHECK_DELAY}ms...`);
  setTimeout(() => server.close(), HEALTH_CHECK_DELAY);
});
```

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/koa-joi-validate
Description: Joi validation middleware for Koa.
Author: Sigfox developers
Latest version: 1.1.0

# koa-joi-validate

[![npm version](https://img.shields.io/npm/v/@sigfox/koa-joi-validate.svg?style=flat)](https://www.npmjs.com/package/@sigfox/koa-joi-validate)
[![code style](https://img.shields.io/badge/code_style-prettier-ff69b4.svg)](https://prettier.io)
[![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/sigfox/javascript/blob/master/LICENSE)

[Joi](https://github.com/hapijs/joi) validation middleware for [Koa](https://koajs.com) using [Boom](https://github.com/hapijs/boom) to format errors.

## Features

- Allows **easy** and **declarative** validation of request's `body`, `headers`, `params` and `query`
- Uses [Joi](https://github.com/hapijs/joi), a **robust** and **popular** validation library
- Formats errors using [Boom](https://github.com/hapijs/boom) to format errors. together with [@sigfox/koa-boom](https://github.com/sigfox/javascript/tree/master/packages/koa-boom).

## Install

```bash
npm install @sigfox/koa-joi-validate
```

## Usage

**koaJoiValidate(schemasOrFunc, joiValidateOptions)**

- `schemasOrFunc` (`Object | Function`) (`mandatory`)
  - ***Object***: The Joi schemas that will be passed to Joi.validate
  - ***Function***: A custom function taking ctx as a parameter. Use this is you want to build the schema from the context

- `joiValidateOptions` (`Object`) (`default: {}`): Additonal options that will be spread as Joi.validate() options.

```javascript
const Joi = require('joi');
const Koa = require('koa');
const koaJoiValidate = require('@sigfox/koa-joi-validate');

const app = new Koa()
  .use(
    koaJoiValidate({
      body: Joi.object().keys({
        firstname: Joi.string(),
        lastname: Joi.string()
      })
    })
  )
  .use(
    koaJoiValidate(ctx => ({
      query: ctx.state.joiSchema
    }))
  )
  .listen();
```

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/koa-k8s-ops-app
Description: Instantiates a Koa app with default OPS middlewares.
Author: Sigfox developers
Latest version: 1.1.1

# koa-k8s-ops-app

Instantiates a **Koa app** with default **OPS middlewares**.

## Features

Creates an OPS-specific Koa application with already mounted middlewares.

## Install

```bash
npm install @sigfox/koa-k8s-ops-app
```

## Usage

```javascript
const KoaOps = require('@sigfox/koa-k8s-ops-app');

const app = new KoaOps();
const server = app.listen();
```

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/koa-k8s-probes
Description: Koa middleware mounting customizable Kubernetes probes for readiness and liveness checks.
Author: Sigfox developers
Latest version: 1.0.0

# koa-k8s-probes

Koa middleware mounting customizable probes for **readiness** and **liveness** checks, especially useful in a **Kubernetes runtime context**.

## Features

Mount GET **/liveness** and **/readiness** routes to your Koa application. By default, these routes will always return a `200` HTTP status code.

You can customize each route check by setting the `livenessProbe` or `readinessProbe` attributes when mounting middleware. These custom checks would
have to **return a Promise**. If _resolved_, a `200` HTTP status code will be returned, otherwise it will be a `503`.

## Install

```bash
npm install @sigfox/koa-k8s-probes
```

## Usage

```javascript
const k8sProbes = require('@sigfox/koa-k8s-probes');
const Koa = require('koa');

async function readinessProbe(ctx) {
  const { mongodbClient, redisClient, otherClient } = ctx.services;
  await Promise.all([
    mongodbClient.db.command({ ping: 1 }),
    redisClient.ping(),
    otherClient.someCheck()
  ]);
}

const app = new Koa().use(k8sProbes()); // always return 200 with default configuration
const app = new Koa().use(k8sProbes({ readinessProbe })); // customize readiness route and return 503 when promise is rejected

const server = app.listen();
```

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/koa-maintenance
Description: Koa middleware to manage maintenance.
Author: Sigfox developers
Latest version: 1.0.0

# koa-maintenance

Koa middleware to manage maintenance mode.

## When use it?

You can use this module if you need to manage the maintenance mode of your Koa app.

## Features

Switch on or off at startup the maintenance mode of your Koa app, if on it will send a 503 status to all incoming requests, if off it will go through the maintenance middleware without modifications of the incoming request. The HTTP status code and the body's response can be customised via the `options` parameter.

## Install

```bash
npm install @sigfox/koa-maintenance
```

## Usage

- `isOn` (`Boolean`) (`default: "false"`): The flag to indicate if the maintenance is on or off, default is off.
- `options` (`Object`) (`default`: "{ status: 503, message: "We are currently down for maintenance." }"): The options to customise status code and body's response.

```javascript
const Koa = require('koa');
const maintenance = require('@sigfox/koa-maintenance');

const app = new Koa();
app.use(
  maintenance(process.env.MAINTENANCE === 'true', {
    status: 503,
    message: 'Something amazing is coming, bear with us'
  })
);

const server = app.listen();
```

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/koa-mongoose-model-stream-export
Description: Mongoose schema to CSV/JSON
Author: Sigfox developers
Latest version: 1.0.1

# koa-mongoose-model-stream-export

Koa middleware mounting routes in order to export Mongoose schema to CSV/JSON.

## When use it?

This module can be used if you need a route returning the schema of a Mongoose Model using CSV or JSON format.

## Features

- Formats a mongoose Model to CSV/JSON and adds it to Koa's context.
- Select the fields you want in the export adding EXPORT_FIELDS to the Model.
- Tranforms the data by adding the method .transformForExport() to the model.

## Install

```bash
npm install @sigfox/koa-mongoose-model-stream-export
```

## Usage

```javascript
const Koa = require('koa');
const mongoose = require('mongoose');
const Router = require('koa-router');
const mongooseModelStreamExport = require('@sigfox/koa-mongoose-model-stream-export');

const { Company, User } = require('./hypothetical-models');

// EXPORT_FIELDS can be defined in the model if you want to specify the fields to export
// Warning: Those are the fields that will be in the CSV, all the other fields will be removed
Company.statics.EXPORT_FIELDS = ['name', 'email', 'phoneNumber'];
// transformForExport can be defined in the model if you want to transform the data before formatting it for export
User.statics.transformForExport = user => ({
  name: `${user.firstname} ${user.lastname}`,
  email: user.email
});

const getRoutes = () => {
  const router = new Router();

  router.get('company-schema', mongooseModelStreamExport(Company));
  router.get('user-schema', mongooseModelStreamExport(User));

  return router.routes();
};

const app = new Koa().use(getRoutes()).listen();
```

### Options

- JSON (default)

- CSV: If you want the route to return the data using CSV format, you can set `Content-Type=text/csv` or add ?format=csv in the request's query.

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/koa-multipart-form
Description: Koa middleware handling multipart/form-data
Author: Sigfox developers
Latest version: 1.0.1

# koa-multipart-form

Koa middleware handling multipart/form-data.

## When use it?

You can use this module if you need your Koa app to parse 'multipart/form-data'.

## Features

Parses requests having type: 'multipart/form-data' and set ctx.body with the parsed stream.

## Install

```bash
npm install @sigfox/koa-multipart-form
```

## Usage

**koaMultipartForm(options)**

- `options` (`Object`) (`default: {}`) You can either decide to pass an object that will be used as options for formidable.IncomingForm or the instance of it directly:
  - ***Object***: The options that will be passed to IncomingForm.
  - ***instance of formidable.IncomingForm***: The instance of IncomingForm that will be used for multipart processing.

```javascript
const Koa = require('koa');
const koaMultipartForm = require('koa-multipart-form');

const app = new Koa().use(koaMultipartForm()).listen();
```

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/koa-prometheus
Description: Koa middleware exposing Prometheus metrics.
Author: Sigfox developers
Latest version: 1.1.0

# koa-prometheus

Koa middleware exposing **Prometheus metrics**.

## Features

Mount route providing **metrics** formatted for **Prometheus**, as _text_ or _JSON_. Metrics _collection interval_ is **customizable**, as well as the _endpoint URL_ and metric attribute name _prefix_.

## Install

```bash
npm install @sigfox/koa-prometheus
```

## Usage

```javascript
const prometheus = require('@sigfox/koa-prometheus');
const Koa = require('koa');

const app = new Koa().use(prometheus());
const server = app.listen();
```

## Response format

Default response format is **Prometheus-formatted** text.

To receive it as a **JSON-formatted** response, set request's _Accept_ header to **application/json**.

## Configuration

|          |  Type  | Default  | Description                                 |
| -------- | :----: | :------: | ------------------------------------------- |
| interval | number |  10000   | The interval at which metrics are collected |
| prefix   | string |   none   | Prefix to add to each metric attribute name |
| url      | string | /metrics | API endpoint URL configuration              |

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/koa-prometheus-http-metrics
Description: Koa middleware registering Prometheus HTTP metrics.
Author: Sigfox developers
Latest version: 2.1.0

# koa-prometheus-http-metrics

Koa middleware registering **Prometheus HTTP metrics**.

## Features

Mount a middleware that registers **HTTP metrics** in the _prom-client_ singleton and then can be easily exposed with the _@sigfox/koa-prometheus_ package.

## Install

```bash
npm install @sigfox/koa-prometheus-http-metrics
```

## Usage

```javascript
const promHttpMetrics = require('@sigfox/koa-prometheus-http-metrics');
const Koa = require('koa');

const app = new Koa().use(
  promHttpMetrics({
    filter: path => !path.includes('/admin') // remove admin routes from prometheus monitoring
  })
);
const server = app.listen();
```

By default the label used is the `ctx.path` given by Koa, if `@koa-router` is used `ctx.routerPath` will be used to group requests going to the same route. For example GET /users/1 and GET /users/2 requests matching the route /users/:id will be grouped using the label `/users/:id`.

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/koa-query-fields
Description: Koa middleware selecting fields from ctx.body depending on ctx.query.fields.
Author: Sigfox developers
Latest version: 1.0.1

# koa-query-fields

Koa middleware selecting fields from ctx.body depending on ctx.query.fields.

## When use it?

This module can be used if you need to select fields from the response body of a koa request depending on ctx.query.fields

## Features

Select response body fields, the middleware expects to find state.query.fields.

## Install

```bash
npm install @sigfox/koa-query-fields
```

## Usage

```javascript
const Koa = require('koa');
const Router = require('koa-router');
const { asyncGetPublicData } = require('hypothetical-async-getters');
const queryFields = require('@sigfox/koa-query-fields');

const getRoutes = () => {
  const router = new Router();

  router.get('data', queryFields, async ctx => {
    const data = await asyncGetPublicData();
    ctx.body = data;
  });

  return router.routes();
};

const app = new Koa().use(getRoutes()).listen();
```

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/koa-visibility
Description: Koa middleware hiding fields from ctx.body depending on user roles.
Author: Sigfox developers
Latest version: 1.0.1

# koa-visibility

Koa middleware hiding fields from ctx.body depending on user roles.

## When use it?

This module can be used if you need to hide fields from the response body of a koa request depending of the role of the user requesting.

## Features

Hide response body fields, the middleware expects to find state.user.roles or state.roles

## Install

```bash
npm install @sigfox/koa-visibility
```

## Usage

**visibility(config)**

- `config` (`Object`) (`mandatory`): Object containing roles as keys, associated with the fields (`Array[String]`) that they can read.

```javascript
const Koa = require('koa');
const Router = require('koa-router');
const { asyncGetUsers, asyncGetPublicData } = require('hypothetical-async-getters');
const visibility = require('@sigfox/koa-visibility');

const PUBLIC_FIELDS = ['firstname', 'lastname'];
const USER_FIELDS = ['company', 'email'];
const ADMIN_FIELDS = ['phoneNumber', 'address'];

// ctx.state must be populated by user or roles
const addUser = (ctx, next) => {
  // Both of those are working, user.roles has priority though.
  ctx.state.user = {
    roles: ['admin']
  };
  ctx.state.roles = ['admin'];
  return next();
};

const visibilityMiddleware = visibility({
  public: PUBLIC_FIELDS,
  user: [...PUBLIC_FIELDS, ...USER_FIELDS],
  admin: [...PUBLIC_FIELDS, ...USER_FIELDS, ...ADMIN_FIELDS]
});

const getRoutes = () => {
  const router = new Router();

  // No visibility here since data is already public
  router.get('/users', addUser, visibilityMiddleware, async ctx => {
    const users = await asyncGetUsers();
    ctx.body = users;
  });

  // No visibility here since data is already public
  router.get('/data', async ctx => {
    const data = await asyncGetPublicData();
    ctx.body = data;
  });

  return router.routes();
};

const app = new Koa().use(getRoutes()).listen();
```

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/monganym
Description: Anonymize mongodb database.
Author: Sigfox developers
Latest version: 1.1.1

# mongoanym

Anonymize mongodb database using declarative configuration backed by Chance.js to generate deterministic suite of anonymous data.

## Install

```
npm i @sigfox/mongoanym
```

## Usage

### CLI

```
npx mongoanym mongodb://192.168.0.5/foo --config examples/config.json
```

### As a module

```
const mongoanym = require('mongoanym');

await mongoanym(url, config);
```

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/mongoose-archive
Description: Mongoose plugin adding the method .archive() to your resource Model
Author: Sigfox developers
Latest version: 1.0.1

# mongoose-archive - Mongoose plugin adding the method .archive() to your documents schemas

## When use it?

This module can be used if you need to archive some Mongo resources.

## Features

- Adds .archive() method to your schema: set archivedAt: new Date() & isArchived: true.
- Adds .restore() method to your schema: set archivedAt: undefined & isArchived: false.
- On methods .find(), .findOne(), .findOneAndRemove() & .findOneAndUpdate(), archived documents will not be found anymore.

## Install

```bash
npm install @sigfox/mongoose-archive
```

## Usage

Schema declaration

```javascript
const mongoose = require('mongoose');
const mongooseArchive = require('@sigfox/mongoose-archive');

const { Schema, mongo } = mongoose;

const userSchema = new Schema({
  firstName: { type: String, required: true },
  lastName: { type: String, required: true },
  email: { type: String, required: true }
});

userSchema.plugin(mongooseArchive);
```

Archive resource

```javascript
const archiveUser = async UserModel => {
  const user = await UserModel.findOne({ email: 'foobar@mail.com' });
  await user.archive();
  ctx.status = 204;
};
```

Restore resource

```javascript
const restoreUser = async user => {
  await user.restore();
};
```

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/redux-api-maintenance-middleware
Description: Redux middleware to catch maintenance window.
Author: Sigfox developers
Latest version: 1.0.0

# redux-api-maintenance-middleware

Redux middleware to catch maintenance window.

## Features

The middleware checks if the `API_FAILURE` action from '@sigfox/redux-api-middleware' is dispatched with a status and error corresponding to a maintenance window, if such action is dispatched the middleware will dispatch an `API_MAINTENANCE` action.

## Install

```bash
npm install @sigfox/redux-api-maintenance-middleware
```

## Usage

```javascript
import { applyMiddleware, createStore } from 'redux';
import axios from 'axios';
import apiMiddleware from '@sigfox/redux-api-middleware';
import apiMaintenanceMiddleware, {
  API_MAINTENANCE
} from '@sigfox/redux-api-maintenance-middleware';

const initialState = { payload: null, error: null, maintenance: false };
const reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'SUCCESS':
      return { payload: action.payload, maintenance: false, error: null };
    case 'FAILURE':
      return { error: action.error, payload: null, maintenance: action.maintenance };
    case API_MAINTENANCE:
      return { ...state, maintenance: true };
    default:
      return state;
  }
};

const store = createStore(
  reducer,
  applyMiddleware([
    apiMiddleware(axios.create()),
    apiMaintenanceMiddleware({ status: 503, error: { error: 'maintenance' } })
  ])
);

store.dispatch({
  type: 'api',
  types: ['REQUEST', 'SUCCESS', 'FAILURE'],
  promise: client => client.request({ url: 'http://localhost:3000/data', method: 'get' })
});
```

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/redux-api-middleware
Description: Redux API middleware.
Author: Sigfox developers
Latest version: 1.2.0

# redux-api-middleware

Redux middleware handling api calls.

## Features

Send api request calling a custom promise.

Depending on the api response, an action will be dispatched containing response data or error.

## Install

```bash
npm install @sigfox/redux-api-middleware
```

## Usage

- Provide a http client to the middleware, this client will be given to you in order to build your request.

- "type: 'api'" is necessary, otherwise, the action will go directly to the next middleware

- "types" must be an array of three elements of format: [request, success, failure], correponding action will be dispatched depending on the status of the api call.

- "reject: true" means that in the case of an error, the error will be thrown

```javascript
const axios = require('axios');
const apiMiddleware = require('@sigfox/redux-api-middleware');

const reducer = (state = {}, action) => {
  switch (action.type) {
    case 'SUCCESS':
      return action;
    case 'FAILURE':
      return action;
    default:
      return state;
  }
};

// Provide an api client to the middleware
const store = createStore(reducer, applyMiddleware(apiMiddleware(axios.create())));

store.dispatch({
  type: 'api',
  types: ['REQUEST', 'SUCCESS', 'FAILURE'],
  promise: client => client.request({ url: 'http://localhost:3000/data', method: 'get' })
});

// Example using dispatch + getState in the promise.
store.dispatch({
  type: 'api',
  types: ['REQUEST', 'SUCCESS', 'FAILURE'],
  promise: async (client, dispatch, getState) => {
    const state = getState();
    if (!state.isLoading) {
      dispatch({ type: 'START_LOADER' });
    }
    return client.request({ url: 'http://localhost:3000/data', method: 'get' });
  },
  // In the case of an error, this option will throw the error instead of just dispatching an action.
  reject: true
});
```

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/redux-router-transitions-middleware
Description: Redux router transitions middleware.
Author: Sigfox developers
Latest version: 1.1.3

# redux-router-transitions-middleware

Redux middleware for [@sigfox/redux-router](https://github.com/sigfox/redux-router) handling API calls during routes transitions

## Features

When the route changes ([@sigfox/redux-router](https://github.com/sigfox/redux-router)), the middleware checks if the React component associated to the new route has static method "fetchDataDeferred" and calls it.

## Install

```bash
npm install @sigfox/redux-router-transitions-middleware
```

## Usage

```javascript
import React from 'react';
import { createStore, combineReducers, compose, applyMiddleware } from 'redux';
import createHistory from 'history/lib/createMemoryHistory';

import { Route } from '@sigfox/react-router';
import { reduxReactRouter, routerStateReducer, push } from '@sigfox/redux-router';
import transitionsMiddleware from '@sigfox/redux-router-transitions-middleware';

const INIT_COMPONENT = 'INIT_COMPONENT';

class FirstComponent extends React.Component {
  static fetchDataDeferred = ({ dispatch }) =>
    dispatch({
      type: INIT_COMPONENT,
      data: 1
    });

  render = () => <div>First component</div>;
}

const routes = (
  <Route path="/">
    <Route path="first" component={FirstComponent} />
  </Route>
);

const componentReducer = (state = {}, action) => {
  switch (action.type) {
    case INIT_COMPONENT:
      return { data: action.data };
    default:
      return state;
  }
};

const reducer = combineReducers({
  router: routerStateReducer,
  component: componentReducer
});

const store = compose(
  reduxReactRouter({
    routes,
    createHistory
  }),
  applyMiddleware(transitionsMiddleware)
)(createStore)(reducer);

// This will trigger a rerouting to /first, since the component has the method "fetchDataDeferred", the
// action 'INIT_COMPONENT' will be dispatched and the value of data in the component reducer will change.
store.dispatch(push({ pathname: '/first' }));
```

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @sigfox/universal-api-client
Description: Universal API client.
Author: Sigfox developers
Latest version: 1.0.1

# universal-api-client

Simple promisified http client to send requests

## Features

Send http request:

- POST
- GET
- PUT
- PATCH
- DELETE
- HEAD
- OPTIONS

## Install

```bash
npm install @sigfox/universal-api-client
```

## Usage

```javascript
const ApiClient = require('@sigfox/universal-api-client');

const apiClient = new ApiClient({ baseURL: '/api' });

const getData = client => client.get('/data');

const postData = (client, data) => client.post('/data', data);

getData(client).then(response => {
  // use response here
});

postData(client, { lifePurpose: 42 }).then(response => {
  // use response here
});

// and so on...
```

## Test

```bash
npm test
```

## Licence

This project is licensed under the MIT License - see the [LICENSE](https://github.com/sigfox/javascript/blob/master/LICENSE) file for details.
npm package: @siggame/colisee-lib
Description: A collection of JavaScript & TypeScript modules common between many colisee services.
Author: siggame@mst.edu
Latest version: 0.3.1

# siggame/colisee-lib

A collection of JavaScript & TypeScript modules common between many colisee services.

[![Travis](https://img.shields.io/travis/siggame/colisee-lib.svg?style=flat-square)](https://travis-ci.org/siggame/colisee-lib)
[![Dependencies](https://img.shields.io/david/siggame/colisee-lib.svg?style=flat-square)](https://github.com/siggame/colisee-lib)
[![NPM Version](https://img.shields.io/npm/v/@siggame/colisee-lib.svg?style=flat-square)](https://www.npmjs.com/package/@siggame/colisee-lib)
[![NPM Total Downloads](https://img.shields.io/npm/dt/@siggame/colisee-lib.svg?style=flat-square)](https://www.npmjs.com/package/@siggame/colisee-lib)

## Table Of Contents
- [Description](#description)
- [Getting Started](#getting-started)
- [Usage](#usage)
- [Contributors](#contributors)
- [Change Log](#change-log)
- [License](#license)
- [Contributing](#contributing)

## Description

This is a collection of modules that will be common between many colisee services. This includes loggers, middlewares, database utilities, etc.

## Getting Started
To save the repo to your package.json dependencies:
```
npm install --save @siggame/colisee
```

Importing the code:
```typescript
import * as coliseeLib from "@siggame/colissee-lib";
```

## Usage

TODO

## Contributors
- [Russley Shaw](https://github.com/russleyshaw)
- [user404d](https://github.com/user404d)
- [Hannah Reinbolt](https://github.com/LoneGalaxy)
- [Matthew Qualls](https://github.com/MatthewQualls)

## Change Log

View our [CHANGELOG.md](https://github.com/siggame/colisee-lib/blob/master/CHANGELOG.md)

## License

View our [LICENSE.md](https://github.com/siggame/colisee/blob/master/LICENSE.md)

## Contributing

View our [CONTRIBUTING.md](https://github.com/siggame/colisee/blob/master/CONTRIBUTING.md)
npm package: @siggame/colisee-tslint
Description: The official tslint config for ACM SIG-Game's Colisee
Author: Russley Shaw
Latest version: 1.0.4

# siggame/colisee-tslint

The official tslint config for ACM SIG-Game's Colisee

[![Dependencies](https://img.shields.io/david/siggame/colisee-tslint.svg)](https://github.com/siggame/colisee-tslint)
[![NPM Version](https://img.shields.io/npm/@siggame/colisee-tslint.svg?style=flat-square)](https://www.npmjs.com/package/@siggame/colisee-tslint)
[![NPM Total Downloads](https://img.shields.io/npm/dt/@siggame/colisee-tslint.svg?style=flat-square)](https://www.npmjs.com/package/@siggame/colisee-tslint)

## Table Of Contents
- [Description](#description)
- [Getting Started](#getting-started)
- [Usage](#usage)
- [Contributors](#contributors)
- [License](#license)
- [Contributing](#contributing)

## Description

A long description of the project.

## Getting Started
```
npm install --save-dev tslint @siggame/colisee-tslint
```

Add the following `tslint.json`
```json
{
    "extends": "@siggame/colisee-tslint/tslint.json"
}
```

Add the following to your `package.json` scripts:
```json
    "lint": "tslint --format verbose --project ./tsconfig.json",
    "lint-fix": "tslint --fix --format verbose --project ./tsconfig.json"
```

## Usage

Running the linter
```
npm run lint
```

Running the linter fixer
```
npm run lint-fix
```

## Contributors
- [Russley Shaw](https://github.com/russleyshaw)
- [user404d](https://github.com/user404d)
- [Hannah Reinbolt](https://github.com/LoneGalaxy)
- [Matthew Qualls](https://github.com/MatthewQualls)

## License

View our [LICENSE.md](https://github.com/siggame/colisee/blob/master/LICENSE.md)

## Contributing

View our [CONTRIBUTING.md](https://github.com/siggame/colisee/blob/master/CONTRIBUTING.md)
npm package: @siggame/stockage
Description: JavaScript utility that provides a common interface in communicating with Google Storage, AWS S3, and local storage.
Author: Russley Shaw
Latest version: 0.1.0

# siggame/stockage

JavaScript utility that provides a common interface in communicating with Google Storage, AWS S3, and local storage.

[![Travis](https://img.shields.io/travis/siggame/stockage.svg?style=flat-square)](https://travis-ci.org/siggame/stockage)
[![Dependencies](https://img.shields.io/david/siggame/stockage.svg)](https://github.com/siggame/stockage)
[![NPM Version](https://img.shields.io/npm/@siggame/stockage.svg?style=flat-square)](https://www.npmjs.com/package/@siggame/stockage)
[![NPM Total Downloads](https://img.shields.io/npm/dt/@siggame/stockage.svg?style=flat-square)](https://www.npmjs.com/package/@siggame/stockage)

## Table Of Contents
- [Description](#description)
- [Getting Started](#getting-started)
- [Usage](#usage)
- [Contributors](#contributors)
- [License](#license)
- [Contributing](#contributing)

## Description

This library is to act as a common interface to allow us to save, retrieve, and update arbitrary files from a cloud service.

## Getting Started
```
npm install siggame/stockage#stable
```

```typescript
import * as stockage from "@siggame/stockage";
```

## Usage

### Using Local Stockage
```typescript


// New instance
const stock = new stockage.LocalStockage();

// Writing data
const id = await stock.write("Hello, World");
const id = await stock.writeBuffer(buffer);
const id = await stock.writeJSON({hello: "world"});

// Reading data
const data = await stock.read(id);
const data = await stock.readBuffer(id);
const data = await stock.readJSON(id);
```

## Contributors
- [Russley Shaw](https://github.com/russleyshaw)
- [user404d](https://github.com/user404d)
- [Hannah Reinbolt](https://github.com/LoneGalaxy)
- [Matthew Qualls](https://github.com/MatthewQualls)

## License

View our [LICENSE.md](https://github.com/siggame/colisee/blob/master/LICENSE.md)

## Contributing

View our [CONTRIBUTING.md](https://github.com/siggame/colisee/blob/master/CONTRIBUTING.md)
npm package: @siggame/tourneyjs
Description: Tournament Algorithms
Author: siggame
Latest version: 0.3.4

# siggame/tourneyjs

Tournament Algorithms

[![Travis](https://img.shields.io/travis/siggame/tourneyjs.svg?style=flat-square)](https://travis-ci.org/siggame/tourneyjs)
[![GitHub Tag](https://img.shields.io/github/tag/siggame/tourneyjs.svg?style=flat-square)](https://github.com/siggame/tourneyjs/tags)
[![Dependencies](https://img.shields.io/david/siggame/tourneyjs.svg)](https://github.com/siggame/tourneyjs)
[![NPM Version](https://img.shields.io/npm/v/@siggame/tourneyjs.svg?style=flat-square)](https://www.npmjs.com/package/@siggame/tourneyjs)
[![NPM Total Downloads](https://img.shields.io/npm/dt/@siggame/tourneyjs.svg?style=flat-square)](https://www.npmjs.com/package/@siggame/tourneyjs)

## Table Of Contents

- [Description](#description)
- [Getting Started](#getting-started)
- [Usage](#usage)
- [Contributors](#contributors)
- [Change Log](#change-log)
- [License](#license)
- [Contributing](#contributing)

## Description

`tourneyjs` is a collection of different tournament algorithms along with the
building blocks to create custom tournaments.

## Getting Started

```bash
 npm install --save @siggame/tourneyjs
```

## Usage

### Single Elimination

```javascript
import { SingleEliminationTournament } from "tourneyjs";

// create single elimination tournament without bronze finals
/**
 * SingleEliminationTournament( teams: any[], settings: Settings )
 * Settings : { bronzeFinal : boolean, randomize : boolean }
*/

const single_elim = new SingleEliminationTournament<T>([...teams]: T[]);

// add finished event listener
single_elim.when("finished", some_callback);

// add error event listener
single_elim.when("error", some_error_handler);

/**
 * Allow for asynchronous progress of the tournament.
 *
 * fight(match: Duel<T>) => Promise<IMatchResult<T>>
 *
 * IMatchResult<T> = {
 *  winner: T; losers: T[];
 * }
 *
 * success(match: Duel<T>) => void
 *
 * will have the match with updated meta_data where the
 * result is stored
 *
 * failure(match: Duel<T>, error: any) => void
 *
 * will be called for each failure, but the error event
 * listener will only execute once. the match and error
 * are parameters to the callback
*/

single_elim.play(
    async (match) => {
        // define how match winner should be decided
    }, (match) => {
        // get access to match after winner has been decided
    }, (match, error) => {
        // report or recover from error
});

single_elim.pause();
single_elim.resume();

single_elim.stop();
single_elim.resume();
// Error thrown
```

## Contributors

- [user404d](https://github.com/user404d)

## Change Log

View our [CHANGELOG.md](https://github.com/siggame/tourneyjs/blob/master/CHANGELOG.md)

## License

View our [LICENSE](https://github.com/siggame/colisee/blob/master/LICENSE)

## Contributing

View our [CONTRIBUTING.md](https://github.com/siggame/colisee/blob/master/CONTRIBUTING.md)