code:
/**
 * This is the web browser implementation of `debug()`.
 *
 * Expose `debug()` as the module.
 */

exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
exports.storage = 'undefined' != typeof chrome
               && 'undefined' != typeof chrome.storage
                  ? chrome.storage.local
                  : localstorage();

/**
 * Colors.
 */

exports.colors = [
  'lightseagreen',
  'forestgreen',
  'goldenrod',
  'dodgerblue',
  'darkorchid',
  'crimson'
];

/**
 * Currently only WebKit-based Web Inspectors, Firefox >= v31,
 * and the Firebug extension (any Firefox version) are known
 * to support "%c" CSS customizations.
 *
 * TODO: add a `localStorage` variable to explicitly enable/disable colors
 */

function useColors() {
  // NB: In an Electron preload script, document will be defined but not fully
  // initialized. Since we know we're in Chrome, we'll just detect this case
  // explicitly
  if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
    return true;
  }

  // is webkit? http://stackoverflow.com/a/16459606/376773
  // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
  return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
    // is firebug? http://stackoverflow.com/a/398120/376773
    (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
    // is firefox >= v31?
    // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
    (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
    // double check webkit in userAgent just in case we are in a worker
    (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
}

/**
 * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
 */

exports.formatters.j = function(v) {
  try {
    return JSON.stringify(v);
  } catch (err) {
    return '[UnexpectedJSONParseError]: ' + err.message;
  }
};

/**
 * Colorize log arguments if enabled.
 *
 * @api public
 */

function formatArgs(args) {
  var useColors = this.useColors;

  args[0] = (useColors ? '%c' : '')
    + this.namespace
    + (useColors ? ' %c' : ' ')
    + args[0]
    + (useColors ? '%c ' : ' ')
    + '+' + exports.humanize(this.diff);

  if (!useColors) return;

  var c = 'color: ' + this.color;
  args.splice(1, 0, c, 'color: inherit')

  // the final "%c" is somewhat tricky, because there could be other
  // arguments passed either before or after the %c, so we need to
  // figure out the correct index to insert the CSS into
  var index = 0;
  var lastC = 0;
  args[0].replace(/%[a-zA-Z%]/g, function(match) {
    if ('%%' === match) return;
    index++;
    if ('%c' === match) {
      // we only are interested in the *last* %c
      // (the user may have provided their own)
      lastC = index;
    }
  });

  args.splice(lastC, 0, c);
}

/**
 * Invokes `console.log()` when available.
 * No-op when `console.log` is not a "function".
 *
 * @api public
 */

function log() {
  // this hackery is required for IE8/9, where
  // the `console.log` function doesn't have 'apply'
  return 'object' === typeof console
    && console.log
    && Function.prototype.apply.call(console.log, console, arguments);
}

/**
 * Save `namespaces`.
 *
 * @param {String} namespaces
 * @api private
 */

function save(namespaces) {
  try {
    if (null == namespaces) {
      exports.storage.removeItem('debug');
    } else {
      exports.storage.debug = namespaces;
    }
  } catch(e) {}
}

/**
 * Load `namespaces`.
 *
 * @return {String} returns the previously persisted debug modes
 * @api private
 */

function load() {
  var r;
  try {
    r = exports.storage.debug;
  } catch(e) {}

  // If debug isn't set in LS, and we're in Electron, try to load $DEBUG
  if (!r && typeof process !== 'undefined' && 'env' in process) {
    r = process.env.DEBUG;
  }

  return r;
}

/**
 * Enable namespaces listed in `localStorage.debug` initially.
 */

exports.enable(load());

/**
 * Localstorage attempts to return the localstorage.
 *
 * This is necessary because safari throws
 * when a user disables cookies/localstorage
 * and you attempt to access it.
 *
 * @return {LocalStorage}
 * @api private
 */

function localstorage() {
  try {
    return window.localStorage;
  } catch (e) {}
}


code:
/**
 * This is the common logic for both the Node.js and web browser
 * implementations of `debug()`.
 *
 * Expose `debug()` as the module.
 */

exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
exports.coerce = coerce;
exports.disable = disable;
exports.enable = enable;
exports.enabled = enabled;
exports.humanize = require('ms');

/**
 * The currently active debug mode names, and names to skip.
 */

exports.names = [];
exports.skips = [];

/**
 * Map of special "%n" handling functions, for the debug "format" argument.
 *
 * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
 */

exports.formatters = {};

/**
 * Previous log timestamp.
 */

var prevTime;

/**
 * Select a color.
 * @param {String} namespace
 * @return {Number}
 * @api private
 */

function selectColor(namespace) {
  var hash = 0, i;

  for (i in namespace) {
    hash  = ((hash << 5) - hash) + namespace.charCodeAt(i);
    hash |= 0; // Convert to 32bit integer
  }

  return exports.colors[Math.abs(hash) % exports.colors.length];
}

/**
 * Create a debugger with the given `namespace`.
 *
 * @param {String} namespace
 * @return {Function}
 * @api public
 */

function createDebug(namespace) {

  function debug() {
    // disabled?
    if (!debug.enabled) return;

    var self = debug;

    // set `diff` timestamp
    var curr = +new Date();
    var ms = curr - (prevTime || curr);
    self.diff = ms;
    self.prev = prevTime;
    self.curr = curr;
    prevTime = curr;

    // turn the `arguments` into a proper Array
    var args = new Array(arguments.length);
    for (var i = 0; i < args.length; i++) {
      args[i] = arguments[i];
    }

    args[0] = exports.coerce(args[0]);

    if ('string' !== typeof args[0]) {
      // anything else let's inspect with %O
      args.unshift('%O');
    }

    // apply any `formatters` transformations
    var index = 0;
    args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
      // if we encounter an escaped % then don't increase the array index
      if (match === '%%') return match;
      index++;
      var formatter = exports.formatters[format];
      if ('function' === typeof formatter) {
        var val = args[index];
        match = formatter.call(self, val);

        // now we need to remove `args[index]` since it's inlined in the `format`
        args.splice(index, 1);
        index--;
      }
      return match;
    });

    // apply env-specific formatting (colors, etc.)
    exports.formatArgs.call(self, args);

    var logFn = debug.log || exports.log || console.log.bind(console);
    logFn.apply(self, args);
  }

  debug.namespace = namespace;
  debug.enabled = exports.enabled(namespace);
  debug.useColors = exports.useColors();
  debug.color = selectColor(namespace);

  // env-specific initialization logic for debug instances
  if ('function' === typeof exports.init) {
    exports.init(debug);
  }

  return debug;
}

/**
 * Enables a debug mode by namespaces. This can include modes
 * separated by a colon and wildcards.
 *
 * @param {String} namespaces
 * @api public
 */

function enable(namespaces) {
  exports.save(namespaces);

  exports.names = [];
  exports.skips = [];

  var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
  var len = split.length;

  for (var i = 0; i < len; i++) {
    if (!split[i]) continue; // ignore empty strings
    namespaces = split[i].replace(/\*/g, '.*?');
    if (namespaces[0] === '-') {
      exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
    } else {
      exports.names.push(new RegExp('^' + namespaces + '$'));
    }
  }
}

/**
 * Disable debug output.
 *
 * @api public
 */

function disable() {
  exports.enable('');
}

/**
 * Returns true if the given mode name is enabled, false otherwise.
 *
 * @param {String} name
 * @return {Boolean}
 * @api public
 */

function enabled(name) {
  var i, len;
  for (i = 0, len = exports.skips.length; i < len; i++) {
    if (exports.skips[i].test(name)) {
      return false;
    }
  }
  for (i = 0, len = exports.names.length; i < len; i++) {
    if (exports.names[i].test(name)) {
      return true;
    }
  }
  return false;
}

/**
 * Coerce `val`.
 *
 * @param {Mixed} val
 * @return {Mixed}
 * @api private
 */

function coerce(val) {
  if (val instanceof Error) return val.stack || val.message;
  return val;
}

license: mit


code:
/**
 * Detect Electron renderer process, which is node, but we should
 * treat as a browser.
 */

if (typeof process !== 'undefined' && process.type === 'renderer') {
  module.exports = require('./browser.js');
} else {
  module.exports = require('./node.js');
}


code:
module.exports = inspectorLog;

// black hole
const nullStream = new (require('stream').Writable)();
nullStream._write = () => {};

/**
 * Outputs a `console.log()` to the Node.js Inspector console *only*.
 */
function inspectorLog() {
  const stdout = console._stdout;
  console._stdout = nullStream;
  console.log.apply(console, arguments);
  console._stdout = stdout;
}


code:
/**
 * Module dependencies.
 */

var tty = require('tty');
var util = require('util');

/**
 * This is the Node.js implementation of `debug()`.
 *
 * Expose `debug()` as the module.
 */

exports = module.exports = require('./debug');
exports.init = init;
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;

/**
 * Colors.
 */

exports.colors = [6, 2, 3, 4, 5, 1];

/**
 * Build up the default `inspectOpts` object from the environment variables.
 *
 *   $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js
 */

exports.inspectOpts = Object.keys(process.env).filter(function (key) {
  return /^debug_/i.test(key);
}).reduce(function (obj, key) {
  // camel-case
  var prop = key
    .substring(6)
    .toLowerCase()
    .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() });

  // coerce string value into JS value
  var val = process.env[key];
  if (/^(yes|on|true|enabled)$/i.test(val)) val = true;
  else if (/^(no|off|false|disabled)$/i.test(val)) val = false;
  else if (val === 'null') val = null;
  else val = Number(val);

  obj[prop] = val;
  return obj;
}, {});

/**
 * The file descriptor to write the `debug()` calls to.
 * Set the `DEBUG_FD` env variable to override with another value. i.e.:
 *
 *   $ DEBUG_FD=3 node script.js 3>debug.log
 */

var fd = parseInt(process.env.DEBUG_FD, 10) || 2;

if (1 !== fd && 2 !== fd) {
  util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')()
}

var stream = 1 === fd ? process.stdout :
             2 === fd ? process.stderr :
             createWritableStdioStream(fd);

/**
 * Is stdout a TTY? Colored output is enabled when `true`.
 */

function useColors() {
  return 'colors' in exports.inspectOpts
    ? Boolean(exports.inspectOpts.colors)
    : tty.isatty(fd);
}

/**
 * Map %o to `util.inspect()`, all on a single line.
 */

exports.formatters.o = function(v) {
  this.inspectOpts.colors = this.useColors;
  return util.inspect(v, this.inspectOpts)
    .split('\n').map(function(str) {
      return str.trim()
    }).join(' ');
};

/**
 * Map %o to `util.inspect()`, allowing multiple lines if needed.
 */

exports.formatters.O = function(v) {
  this.inspectOpts.colors = this.useColors;
  return util.inspect(v, this.inspectOpts);
};

/**
 * Adds ANSI color escape codes if enabled.
 *
 * @api public
 */

function formatArgs(args) {
  var name = this.namespace;
  var useColors = this.useColors;

  if (useColors) {
    var c = this.color;
    var prefix = '  \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m';

    args[0] = prefix + args[0].split('\n').join('\n' + prefix);
    args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m');
  } else {
    args[0] = new Date().toUTCString()
      + ' ' + name + ' ' + args[0];
  }
}

/**
 * Invokes `util.format()` with the specified arguments and writes to `stream`.
 */

function log() {
  return stream.write(util.format.apply(util, arguments) + '\n');
}

/**
 * Save `namespaces`.
 *
 * @param {String} namespaces
 * @api private
 */

function save(namespaces) {
  if (null == namespaces) {
    // If you set a process.env field to null or undefined, it gets cast to the
    // string 'null' or 'undefined'. Just delete instead.
    delete process.env.DEBUG;
  } else {
    process.env.DEBUG = namespaces;
  }
}

/**
 * Load `namespaces`.
 *
 * @return {String} returns the previously persisted debug modes
 * @api private
 */

function load() {
  return process.env.DEBUG;
}

/**
 * Copied from `node/src/node.js`.
 *
 * XXX: It's lame that node doesn't expose this API out-of-the-box. It also
 * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame.
 */

function createWritableStdioStream (fd) {
  var stream;
  var tty_wrap = process.binding('tty_wrap');

  // Note stream._type is used for test-module-load-list.js

  switch (tty_wrap.guessHandleType(fd)) {
    case 'TTY':
      stream = new tty.WriteStream(fd);
      stream._type = 'tty';

      // Hack to have stream not keep the event loop alive.
      // See https://github.com/joyent/node/issues/1726
      if (stream._handle && stream._handle.unref) {
        stream._handle.unref();
      }
      break;

    case 'FILE':
      var fs = require('fs');
      stream = new fs.SyncWriteStream(fd, { autoClose: false });
      stream._type = 'fs';
      break;

    case 'PIPE':
    case 'TCP':
      var net = require('net');
      stream = new net.Socket({
        fd: fd,
        readable: false,
        writable: true
      });

      // FIXME Should probably have an option in net.Socket to create a
      // stream from an existing fd which is writable only. But for now
      // we'll just add this hack and set the `readable` member to false.
      // Test: ./node test/fixtures/echo.js < /etc/passwd
      stream.readable = false;
      stream.read = null;
      stream._type = 'pipe';

      // FIXME Hack to have stream not keep the event loop alive.
      // See https://github.com/joyent/node/issues/1726
      if (stream._handle && stream._handle.unref) {
        stream._handle.unref();
      }
      break;

    default:
      // Probably an error on in uv_guess_handle()
      throw new Error('Implement me. Unknown stream file type!');
  }

  // For supporting legacy API we put the FD here.
  stream.fd = fd;

  stream._isStdio = true;

  return stream;
}

/**
 * Init logic for `debug` instances.
 *
 * Create a new `inspectOpts` object in case `useColors` is set
 * differently for a particular `debug` instance.
 */

function init (debug) {
  debug.inspectOpts = {};

  var keys = Object.keys(exports.inspectOpts);
  for (var i = 0; i < keys.length; i++) {
    debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]];
  }
}

/**
 * Enable namespaces listed in `process.env.DEBUG` initially.
 */

exports.enable(load());


code:
/**
 * Helpers.
 */

var s = 1000;
var m = s * 60;
var h = m * 60;
var d = h * 24;
var y = d * 365.25;

/**
 * Parse or format the given `val`.
 *
 * Options:
 *
 *  - `long` verbose formatting [false]
 *
 * @param {String|Number} val
 * @param {Object} [options]
 * @throws {Error} throw an error if val is not a non-empty string or a number
 * @return {String|Number}
 * @api public
 */

module.exports = function(val, options) {
  options = options || {};
  var type = typeof val;
  if (type === 'string' && val.length > 0) {
    return parse(val);
  } else if (type === 'number' && isNaN(val) === false) {
    return options.long ? fmtLong(val) : fmtShort(val);
  }
  throw new Error(
    'val is not a non-empty string or a valid number. val=' +
      JSON.stringify(val)
  );
};

/**
 * Parse the given `str` and return milliseconds.
 *
 * @param {String} str
 * @return {Number}
 * @api private
 */

function parse(str) {
  str = String(str);
  if (str.length > 100) {
    return;
  }
  var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(
    str
  );
  if (!match) {
    return;
  }
  var n = parseFloat(match[1]);
  var type = (match[2] || 'ms').toLowerCase();
  switch (type) {
    case 'years':
    case 'year':
    case 'yrs':
    case 'yr':
    case 'y':
      return n * y;
    case 'days':
    case 'day':
    case 'd':
      return n * d;
    case 'hours':
    case 'hour':
    case 'hrs':
    case 'hr':
    case 'h':
      return n * h;
    case 'minutes':
    case 'minute':
    case 'mins':
    case 'min':
    case 'm':
      return n * m;
    case 'seconds':
    case 'second':
    case 'secs':
    case 'sec':
    case 's':
      return n * s;
    case 'milliseconds':
    case 'millisecond':
    case 'msecs':
    case 'msec':
    case 'ms':
      return n;
    default:
      return undefined;
  }
}

/**
 * Short format for `ms`.
 *
 * @param {Number} ms
 * @return {String}
 * @api private
 */

function fmtShort(ms) {
  if (ms >= d) {
    return Math.round(ms / d) + 'd';
  }
  if (ms >= h) {
    return Math.round(ms / h) + 'h';
  }
  if (ms >= m) {
    return Math.round(ms / m) + 'm';
  }
  if (ms >= s) {
    return Math.round(ms / s) + 's';
  }
  return ms + 'ms';
}

/**
 * Long format for `ms`.
 *
 * @param {Number} ms
 * @return {String}
 * @api private
 */

function fmtLong(ms) {
  return plural(ms, d, 'day') ||
    plural(ms, h, 'hour') ||
    plural(ms, m, 'minute') ||
    plural(ms, s, 'second') ||
    ms + ' ms';
}

/**
 * Pluralization helper.
 */

function plural(ms, n, name) {
  if (ms < n) {
    return;
  }
  if (ms < n * 1.5) {
    return Math.floor(ms / n) + ' ' + name;
  }
  return Math.ceil(ms / n) + ' ' + name + 's';
}


ms

description: Tiny milisecond conversion utility

repository: zeit/ms

main: ./index

precommit: lint-staged

lint: eslint lib/* bin/*

test: mocha tests.js

*.js:
npm run lint
prettier --single-quote --write
git add

license: MIT


code:
# ms

[![Build Status](https://travis-ci.org/zeit/ms.svg?branch=master)](https://travis-ci.org/zeit/ms)
[![Slack Channel](http://zeit-slackin.now.sh/badge.svg)](https://zeit.chat/)

Use this package to easily convert various time formats to milliseconds.

## Examples

```js
ms('2 days')  // 172800000
ms('1d')      // 86400000
ms('10h')     // 36000000
ms('2.5 hrs') // 9000000
ms('2h')      // 7200000
ms('1m')      // 60000
ms('5s')      // 5000
ms('1y')      // 31557600000
ms('100')     // 100
```

### Convert from milliseconds

```js
ms(60000)             // "1m"
ms(2 * 60000)         // "2m"
ms(ms('10 hours'))    // "10h"
```

### Time format written-out

```js
ms(60000, { long: true })             // "1 minute"
ms(2 * 60000, { long: true })         // "2 minutes"
ms(ms('10 hours'), { long: true })    // "10 hours"
```

## Features

- Works both in [node](https://nodejs.org) and in the browser.
- If a number is supplied to `ms`, a string with a unit is returned.
- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`).
- If you pass a string with a number and a valid unit, the number of equivalent ms is returned.

## Caught a bug?

1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device
2. Link the package to the global module directory: `npm link`
3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, node will now use your clone of ms!

As always, you can run the tests using: `npm test`


finalhandler

description: Node.js final http responder

author: Douglas Christopher Wilson <doug@somethingdoug.com>

repository: pillarjs/finalhandler

lint: eslint .

test: mocha --reporter spec --bail --check-leaks test/

test-ci: nyc --reporter=lcovonly --reporter=text npm test

test-cov: nyc --reporter=html --reporter=text npm test


code:
'use strict';
const path = require('path');
const fs = require('fs');
const commonDir = require('commondir');
const pkgDir = require('pkg-dir');
const makeDir = require('make-dir');

const {env, cwd} = process;

const isWritable = path => {
	try {
		fs.accessSync(path, fs.constants.W_OK);
		return true;
	} catch (_) {
		return false;
	}
};

function useDirectory(directory, options) {
	if (options.create) {
		makeDir.sync(directory);
	}

	if (options.thunk) {
		return (...arguments_) => path.join(directory, ...arguments_);
	}

	return directory;
}

function getNodeModuleDirectory(directory) {
	const nodeModules = path.join(directory, 'node_modules');

	if (
		!isWritable(nodeModules) &&
		(fs.existsSync(nodeModules) || !isWritable(path.join(directory)))
	) {
		return;
	}

	return nodeModules;
}

module.exports = (options = {}) => {
	if (env.CACHE_DIR && !['true', 'false', '1', '0'].includes(env.CACHE_DIR)) {
		return useDirectory(path.join(env.CACHE_DIR, options.name), options);
	}

	let {cwd: directory = cwd()} = options;

	if (options.files) {
		directory = commonDir(directory, options.files);
	}

	directory = pkgDir.sync(directory);

	if (!directory) {
		return;
	}

	const nodeModules = getNodeModuleDirectory(directory);
	if (!nodeModules) {
		return undefined;
	}

	return useDirectory(path.join(directory, 'node_modules', '.cache', options.name), options);
};


find-cache-dir

description: Finds the common standard cache directory

repository: avajs/find-cache-dir

test: xo && nyc ava

keywords: cache directory dir caching find search

reporter: lcov text


code:
# find-cache-dir [![Coverage Status](https://codecov.io/gh/avajs/find-cache-dir/branch/master/graph/badge.svg)](https://codecov.io/gh/avajs/find-cache-dir/branch/master)

> Finds the common standard cache directory

The [`nyc`](https://github.com/istanbuljs/nyc) and [`AVA`](https://ava.li) projects decided to standardize on a common directory structure for storing cache information:

```sh
# nyc
./node_modules/.cache/nyc

# ava
./node_modules/.cache/ava

# your-module
./node_modules/.cache/your-module
```

This module makes it easy to correctly locate the cache directory according to this shared spec. If this pattern becomes ubiquitous, clearing the cache for multiple dependencies becomes easy and consistent:

```
rm -rf ./node_modules/.cache
```

If you decide to adopt this pattern, please file a PR adding your name to the list of adopters below.

## Install

```
$ npm install find-cache-dir
```

## Usage

```js
const findCacheDir = require('find-cache-dir');

findCacheDir({name: 'unicorns'});
//=> '/user/path/node-modules/.cache/unicorns'
```

## API

### findCacheDir(options?)

Finds the cache directory using the supplied options. The algorithm checks for the `CACHE_DIR` environmental variable and uses it if it is not set to `true`, `false`, `1` or `0`. If one is not found, it tries to find a `package.json` file, searching every parent directory of the `cwd` specified (or implied from other options). It returns a `string` containing the absolute path to the cache directory, or `undefined` if `package.json` was never found or if the `node_modules` directory is unwritable.

#### options

Type: `object`

##### name

*Required*\
Type: `string`

Should be the same as your project name in `package.json`.

##### files

Type: `string[] | string`

An array of files that will be searched for a common parent directory. This common parent directory will be used in lieu of the `cwd` option below.

##### cwd

Type: `string`\
Default `process.cwd()`

Directory to start searching for a `package.json` from.

##### create

Type: `boolean`\
Default `false`

If `true`, the directory will be created synchronously before returning.

##### thunk

Type: `boolean`\
Default `false`

If `true`, this modifies the return type to be a function that is a thunk for `path.join(theFoundCacheDirectory)`.

```js
const thunk = findCacheDir({name: 'foo', thunk: true});

thunk();
//=> '/some/path/node_modules/.cache/foo'

thunk('bar.js')
//=> '/some/path/node_modules/.cache/foo/bar.js'

thunk('baz', 'quz.js')
//=> '/some/path/node_modules/.cache/foo/baz/quz.js'
```

This is helpful for actually putting actual files in the cache!

## Tips

- To test modules using `find-cache-dir`, set the `CACHE_DIR` environment variable to temporarily override the directory that is resolved.

## Adopters

- [`ava`](https://avajs.dev)
- [`nyc`](https://github.com/istanbuljs/nyc)
- [`storybook`](https://github.com/storybookjs/storybook)
- [`babel-loader`](https://github.com/babel/babel-loader)
- [`eslint-loader`](https://github.com/MoOx/eslint-loader)
- [More…](https://www.npmjs.com/browse/depended/find-cache-dir)

---

		Get professional support for this package with a Tidelift subscription

		Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.


code:
/* eslint-disable @typescript-eslint/unified-signatures */
import {Options as LocatePathOptions} from 'locate-path';

declare const stop: unique symbol;

declare namespace findUp {
	interface Options extends LocatePathOptions {}

	type StopSymbol = typeof stop;

	type Match = string | StopSymbol | undefined;
}

declare const findUp: {
	sync: {
		/**
		Synchronously check if a path exists.

		@param path - Path to the file or directory.
		@returns Whether the path exists.

		@example
		```
		import findUp = require('find-up');

		console.log(findUp.sync.exists('/Users/sindresorhus/unicorn.png'));
		//=> true
		```
		*/
		exists: (path: string) => boolean;

		/**
		Synchronously find a file or directory by walking up parent directories.

		@param name - Name of the file or directory to find. Can be multiple.
		@returns The first path found (by respecting the order of `name`s) or `undefined` if none could be found.
		*/
		(name: string | readonly string[], options?: findUp.Options): string | undefined;

		/**
		Synchronously find a file or directory by walking up parent directories.

		@param matcher - Called for each directory in the search. Return a path or `findUp.stop` to stop the search.
		@returns The first path found or `undefined` if none could be found.

		@example
		```
		import path = require('path');
		import findUp = require('find-up');

		console.log(findUp.sync(directory => {
			const hasUnicorns = findUp.sync.exists(path.join(directory, 'unicorn.png'));
			return hasUnicorns && directory;
		}, {type: 'directory'}));
		//=> '/Users/sindresorhus'
		```
		*/
		(matcher: (directory: string) => findUp.Match, options?: findUp.Options): string | undefined;
	};

	/**
	Check if a path exists.

	@param path - Path to a file or directory.
	@returns Whether the path exists.

	@example
	```
	import findUp = require('find-up');

	(async () => {
		console.log(await findUp.exists('/Users/sindresorhus/unicorn.png'));
		//=> true
	})();
	```
	*/
	exists: (path: string) => Promise<boolean>;

	/**
	Return this in a `matcher` function to stop the search and force `findUp` to immediately return `undefined`.
	*/
	readonly stop: findUp.StopSymbol;

	/**
	Find a file or directory by walking up parent directories.

	@param name - Name of the file or directory to find. Can be multiple.
	@returns The first path found (by respecting the order of `name`s) or `undefined` if none could be found.

	@example
	```
	// /
	// └── Users
	//     └── sindresorhus
	//         ├── unicorn.png
	//         └── foo
	//             └── bar
	//                 ├── baz
	//                 └── example.js

	// example.js
	import findUp = require('find-up');

	(async () => {
		console.log(await findUp('unicorn.png'));
		//=> '/Users/sindresorhus/unicorn.png'

		console.log(await findUp(['rainbow.png', 'unicorn.png']));
		//=> '/Users/sindresorhus/unicorn.png'
	})();
	```
	*/
	(name: string | readonly string[], options?: findUp.Options): Promise<string | undefined>;

	/**
	Find a file or directory by walking up parent directories.

	@param matcher - Called for each directory in the search. Return a path or `findUp.stop` to stop the search.
	@returns The first path found or `undefined` if none could be found.

	@example
	```
	import path = require('path');
	import findUp = require('find-up');

	(async () => {
		console.log(await findUp(async directory => {
			const hasUnicorns = await findUp.exists(path.join(directory, 'unicorn.png'));
			return hasUnicorns && directory;
		}, {type: 'directory'}));
		//=> '/Users/sindresorhus'
	})();
	```
	*/
	(matcher: (directory: string) => (findUp.Match | Promise<findUp.Match>), options?: findUp.Options): Promise<string | undefined>;
};

export = findUp;


code:
'use strict';
const path = require('path');
const locatePath = require('locate-path');
const pathExists = require('path-exists');

const stop = Symbol('findUp.stop');

module.exports = async (name, options = {}) => {
	let directory = path.resolve(options.cwd || '');
	const {root} = path.parse(directory);
	const paths = [].concat(name);

	const runMatcher = async locateOptions => {
		if (typeof name !== 'function') {
			return locatePath(paths, locateOptions);
		}

		const foundPath = await name(locateOptions.cwd);
		if (typeof foundPath === 'string') {
			return locatePath([foundPath], locateOptions);
		}

		return foundPath;
	};

	// eslint-disable-next-line no-constant-condition
	while (true) {
		// eslint-disable-next-line no-await-in-loop
		const foundPath = await runMatcher({...options, cwd: directory});

		if (foundPath === stop) {
			return;
		}

		if (foundPath) {
			return path.resolve(directory, foundPath);
		}

		if (directory === root) {
			return;
		}

		directory = path.dirname(directory);
	}
};

module.exports.sync = (name, options = {}) => {
	let directory = path.resolve(options.cwd || '');
	const {root} = path.parse(directory);
	const paths = [].concat(name);

	const runMatcher = locateOptions => {
		if (typeof name !== 'function') {
			return locatePath.sync(paths, locateOptions);
		}

		const foundPath = name(locateOptions.cwd);
		if (typeof foundPath === 'string') {
			return locatePath.sync([foundPath], locateOptions);
		}

		return foundPath;
	};

	// eslint-disable-next-line no-constant-condition
	while (true) {
		const foundPath = runMatcher({...options, cwd: directory});

		if (foundPath === stop) {
			return;
		}

		if (foundPath) {
			return path.resolve(directory, foundPath);
		}

		if (directory === root) {
			return;
		}

		directory = path.dirname(directory);
	}
};

module.exports.exists = pathExists;

module.exports.sync.exists = pathExists.sync;

module.exports.stop = stop;


find-up

description: Find a file or directory by walking up parent directories

repository: sindresorhus/find-up

test: xo && ava && tsd

keywords: find up find-up findup look-up look file search match package resolve parent parents folder directory walk walking path


code:
# find-up [![Build Status](https://travis-ci.com/sindresorhus/find-up.svg?branch=master)](https://travis-ci.com/github/sindresorhus/find-up)

> Find a file or directory by walking up parent directories

## Install

```
$ npm install find-up
```

## Usage

```
/
└── Users
    └── sindresorhus
        ├── unicorn.png
        └── foo
            └── bar
                ├── baz
                └── example.js
```

`example.js`

```js
const path = require('path');
const findUp = require('find-up');

(async () => {
	console.log(await findUp('unicorn.png'));
	//=> '/Users/sindresorhus/unicorn.png'

	console.log(await findUp(['rainbow.png', 'unicorn.png']));
	//=> '/Users/sindresorhus/unicorn.png'

	console.log(await findUp(async directory => {
		const hasUnicorns = await findUp.exists(path.join(directory, 'unicorn.png'));
		return hasUnicorns && directory;
	}, {type: 'directory'}));
	//=> '/Users/sindresorhus'
})();
```

## API

### findUp(name, options?)
### findUp(matcher, options?)

Returns a `Promise` for either the path or `undefined` if it couldn't be found.

### findUp([...name], options?)

Returns a `Promise` for either the first path found (by respecting the order of the array) or `undefined` if none could be found.

### findUp.sync(name, options?)
### findUp.sync(matcher, options?)

Returns a path or `undefined` if it couldn't be found.

### findUp.sync([...name], options?)

Returns the first path found (by respecting the order of the array) or `undefined` if none could be found.

#### name

Type: `string`

Name of the file or directory to find.

#### matcher

Type: `Function`

A function that will be called with each directory until it returns a `string` with the path, which stops the search, or the root directory has been reached and nothing was found. Useful if you want to match files with certain patterns, set of permissions, or other advanced use-cases.

When using async mode, the `matcher` may optionally be an async or promise-returning function that returns the path.

#### options

Type: `object`

##### cwd

Type: `string`\
Default: `process.cwd()`

Directory to start from.

##### type

Type: `string`\
Default: `'file'`\
Values: `'file'` `'directory'`

The type of paths that can match.

##### allowSymlinks

Type: `boolean`\
Default: `true`

Allow symbolic links to match if they point to the chosen path type.

### findUp.exists(path)

Returns a `Promise<boolean>` of whether the path exists.

### findUp.sync.exists(path)

Returns a `boolean` of whether the path exists.

#### path

Type: `string`

Path to a file or directory.

### findUp.stop

A [`Symbol`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol) that can be returned by a `matcher` function to stop the search and cause `findUp` to immediately return `undefined`. Useful as a performance optimization in case the current working directory is deeply nested in the filesystem.

```js
const path = require('path');
const findUp = require('find-up');

(async () => {
	await findUp(directory => {
		return path.basename(directory) === 'work' ? findUp.stop : 'logo.png';
	});
})();
```

## Related

- [find-up-cli](https://github.com/sindresorhus/find-up-cli) - CLI for this module
- [pkg-up](https://github.com/sindresorhus/pkg-up) - Find the closest package.json file
- [pkg-dir](https://github.com/sindresorhus/pkg-dir) - Find the root directory of an npm package
- [resolve-from](https://github.com/sindresorhus/resolve-from) - Resolve the path of a module like `require.resolve()` but from a given path

---

		Get professional support for 'find-up' with a Tidelift subscription

		Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies.


code:
# flat-cache
> A stupidly simple key/value storage using files to persist the data

[![NPM Version](https://img.shields.io/npm/v/flat-cache.svg?style=flat)](https://npmjs.org/package/flat-cache)
[![tests](https://github.com/jaredwray/flat-cache/actions/workflows/tests.yaml/badge.svg?branch=master)](https://github.com/jaredwray/flat-cache/actions/workflows/tests.yaml)
[![codecov](https://codecov.io/github/jaredwray/flat-cache/branch/master/graph/badge.svg?token=KxR95XT3NF)](https://codecov.io/github/jaredwray/flat-cache)
[![npm](https://img.shields.io/npm/dm/flat-cache)](https://npmjs.com/package/flat-cache)

## install

```bash
npm i --save flat-cache
```

## Usage

```js
var flatCache = require('flat-cache')
// loads the cache, if one does not exists for the given
// Id a new one will be prepared to be created
var cache = flatCache.load('cacheId');

// sets a key on the cache
cache.setKey('key', { foo: 'var' });

// get a key from the cache
cache.getKey('key') // { foo: 'var' }

// fetch the entire persisted object
cache.all() // { 'key': { foo: 'var' } }

// remove a key
cache.removeKey('key'); // removes a key from the cache

// save it to disk
cache.save(); // very important, if you don't save no changes will be persisted.
// cache.save( true /* noPrune */) // can be used to prevent the removal of non visited keys

// loads the cache from a given directory, if one does
// not exists for the given Id a new one will be prepared to be created
var cache = flatCache.load('cacheId', path.resolve('./path/to/folder'));

// The following methods are useful to clear the cache
// delete a given cache
flatCache.clearCacheById('cacheId') // removes the cacheId document if one exists.

// delete all cache
flatCache.clearAll(); // remove the cache directory
```

## Motivation for this module

I needed a super simple and dumb **in-memory cache** with optional disk persistance in order to make
a script that will beutify files with `esformatter` only execute on the files that were changed since the last run.
To make that possible we need to store the `fileSize` and `modificationTime` of the files. So a simple `key/value`
storage was needed and Bam! this module was born.

## Important notes
- If no directory is especified when the `load` method is called, a folder named `.cache` will be created
  inside the module directory when `cache.save` is called. If you're committing your `node_modules` to any vcs, you
  might want to ignore the default `.cache` folder, or specify a custom directory.
- The values set on the keys of the cache should be `stringify-able` ones, meaning no circular references
- All the changes to the cache state are done to memory
- I could have used a timer or `Object.observe` to deliver the changes to disk, but I wanted to keep this module
  intentionally dumb and simple
- Non visited keys are removed when `cache.save()` is called. If this is not desired, you can pass `true` to the save call
  like: `cache.save( true /* noPrune */ )`.

## License

MIT

## Changelog

[changelog](./changelog.md)


code:
# flat-cache - Changelog
## v3.0.4
- **Refactoring**
  - add files by name to the list of exported files - [89a2698]( https://github.com/royriojas/flat-cache/commit/89a2698 ), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 02:35:39

## v3.0.3
- **Bug Fixes**
  - Fix wrong eslint command - [f268e42]( https://github.com/royriojas/flat-cache/commit/f268e42 ), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 02:15:04

## v3.0.2
- **Refactoring**
  - Update the files paths - [6983a80]( https://github.com/royriojas/flat-cache/commit/6983a80 ), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:58:39

  - Move code to src/ - [18ed6e8]( https://github.com/royriojas/flat-cache/commit/18ed6e8 ), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:57:17

  - Change eslint-cache location - [beed74c]( https://github.com/royriojas/flat-cache/commit/beed74c ), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:48:32

## v3.0.1
- **Refactoring**
  - Remove unused deps - [8c6d9dc]( https://github.com/royriojas/flat-cache/commit/8c6d9dc ), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:43:29

## v3.0.0
- **Refactoring**
  - Fix engines - [52b824c]( https://github.com/royriojas/flat-cache/commit/52b824c ), [Roy Riojas](https://github.com/Roy Riojas), 08/11/2020 01:01:52

- **Other changes**
  - Replace write with combination of mkdir and writeFile ([#49](https://github.com/royriojas/flat-cache/issues/49)) - [ef48276]( https://github.com/royriojas/flat-cache/commit/ef48276 ), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 08/11/2020 00:17:15

    Node v10 introduced a great "recursive" option for mkdir which allows to
    get rid from mkdirp package and easily rewrite "write" package usage
    with two function calls.

    https://nodejs.org/api/fs.html#fs_fs_mkdir_path_options_callback
  - Added a testcase for clearAll ([#48](https://github.com/royriojas/flat-cache/issues/48)) - [45b51ca]( https://github.com/royriojas/flat-cache/commit/45b51ca ), [Aaron Chen](https://github.com/Aaron Chen), 21/05/2020 08:40:03

  - requet node>=10 - [a5c482c]( https://github.com/royriojas/flat-cache/commit/a5c482c ), [yumetodo](https://github.com/yumetodo), 10/04/2020 23:14:53

    thanks @SuperITMan

  - Update README.md - [29fe40b]( https://github.com/royriojas/flat-cache/commit/29fe40b ), [Roy Riojas](https://github.com/Roy Riojas), 10/04/2020 20:08:05

  - reduce vulnerability to 1 - [e9db1b2]( https://github.com/royriojas/flat-cache/commit/e9db1b2 ), [yumetodo](https://github.com/yumetodo), 30/03/2020 11:10:43

  - reduce vulnerabilities dependencies to 8 - [b58d196]( https://github.com/royriojas/flat-cache/commit/b58d196 ), [yumetodo](https://github.com/yumetodo), 30/03/2020 10:54:56

  - use prettier instead of esbeautifier - [03b1db7]( https://github.com/royriojas/flat-cache/commit/03b1db7 ), [yumetodo](https://github.com/yumetodo), 30/03/2020 10:27:14

  - update proxyquire - [c2f048d]( https://github.com/royriojas/flat-cache/commit/c2f048d ), [yumetodo](https://github.com/yumetodo), 30/03/2020 10:16:16

  - update flatted and mocha - [a0e56da]( https://github.com/royriojas/flat-cache/commit/a0e56da ), [yumetodo](https://github.com/yumetodo), 30/03/2020 09:46:45

    mocha > mkdirp is updated
    istanble >>> optimist > minimist is not updated

  - drop support node.js < 10 in develop - [beba691]( https://github.com/royriojas/flat-cache/commit/beba691 ), [yumetodo](https://github.com/yumetodo), 18/03/2020 01:31:09

    see mkdirp

  - npm aufit fix(still remains) - [ce166cb]( https://github.com/royriojas/flat-cache/commit/ce166cb ), [yumetodo](https://github.com/yumetodo), 18/03/2020 01:18:08

    37 vulnerabilities required manual review and could not be updated

  - updtate sinon - [9f2d1b6]( https://github.com/royriojas/flat-cache/commit/9f2d1b6 ), [yumetodo](https://github.com/yumetodo), 18/03/2020 01:17:51

  - apply eslint-plugin-mocha - [07343b5]( https://github.com/royriojas/flat-cache/commit/07343b5 ), [yumetodo](https://github.com/yumetodo), 13/03/2020 22:17:21

  - Less strint version check ([#44](https://github.com/royriojas/flat-cache/issues/44)) - [92aca1c]( https://github.com/royriojas/flat-cache/commit/92aca1c ), [Wojciech Maj](https://github.com/Wojciech Maj), 13/11/2019 16:18:25

    * Use ^ version matching for production dependencies

    * Run npm audit fix

- **Bug Fixes**
  - update dependencies and use eslint directly - [73fbed2]( https://github.com/royriojas/flat-cache/commit/73fbed2 ), [yumetodo](https://github.com/yumetodo), 18/03/2020 01:17:27

## v2.0.1
- **Refactoring**
  - upgrade node modules to latest versions - [6402ed3]( https://github.com/royriojas/flat-cache/commit/6402ed3 ), [Roy Riojas](https://github.com/Roy Riojas), 08/01/2019 18:47:05

## v2.0.0
- **Bug Fixes**
  - upgrade package.json lock file - [8d21c7b]( https://github.com/royriojas/flat-cache/commit/8d21c7b ), [Roy Riojas](https://github.com/Roy Riojas), 08/01/2019 17:03:13

  - Use the same versions of node_js that eslint use - [8d23379]( https://github.com/royriojas/flat-cache/commit/8d23379 ), [Roy Riojas](https://github.com/Roy Riojas), 08/01/2019 16:25:11

- **Other changes**
  - Replace circular-json with flatted ([#36](https://github.com/royriojas/flat-cache/issues/36)) - [b93aced]( https://github.com/royriojas/flat-cache/commit/b93aced ), [C. K. Tang](https://github.com/C. K. Tang), 08/01/2019 17:03:01

  - Change JSON parser from circular-json to flatted & 1 more changes ([#37](https://github.com/royriojas/flat-cache/issues/37)) - [745e65a]( https://github.com/royriojas/flat-cache/commit/745e65a ), [Andy Chen](https://github.com/Andy Chen), 08/01/2019 16:17:20

    * Change JSON parser from circular-json to flatted & 1 more changes

    * Change JSON parser from circular-json
    * Audited 2 vulnerabilities

    * Update package.json

    * Update Engine require

    * There's a bunch of dependencies in this pkg requires node >=4, so I changed it to 4

    * Remove and add node versions

    * I have seen this pkg is not available with node 0.12 so I removed it
    * I have added a popular used LTS version of node - 10

## v1.3.4
- **Refactoring**
  - Add del.js and utils.js to the list of files to be beautified - [9d0ca9b]( https://github.com/royriojas/flat-cache/commit/9d0ca9b ), [Roy Riojas](https://github.com/Roy Riojas), 14/11/2018 12:19:02

## v1.3.3
- **Refactoring**
  - Make sure package-lock.json is up to date - [a7d2598]( https://github.com/royriojas/flat-cache/commit/a7d2598 ), [Roy Riojas](https://github.com/Roy Riojas), 14/11/2018 11:36:08

- **Other changes**
  - Removed the need for del ([#33](https://github.com/royriojas/flat-cache/issues/33)) - [c429012]( https://github.com/royriojas/flat-cache/commit/c429012 ), [S. Gilroy](https://github.com/S. Gilroy), 13/11/2018 13:56:37

    * Removed the need for del

    Removed the need for del as newer versions have broken backwards
    compatibility. del mainly uses rimraf for deleting folders
    and files, replaceing it with rimraf only is a minimal change.

    * Disable glob on rimraf calls

    * Added glob disable to wrong call

    * Wrapped rimraf to simplify solution

## v1.3.2
- **Refactoring**
  - remove yarn.lock file - [704c6c4]( https://github.com/royriojas/flat-cache/commit/704c6c4 ), [Roy Riojas](https://github.com/Roy Riojas), 07/11/2018 15:41:08

- **Other changes**
  - replace circular-json with flatted ([#23](https://github.com/royriojas/flat-cache/issues/23))" - [db12d74]( https://github.com/royriojas/flat-cache/commit/db12d74 ), [Roy Riojas](https://github.com/Roy Riojas), 07/11/2018 15:40:39

    This reverts commit 00f689277a75e85fef28e6a048fad227afc525e6.

## v1.3.1
- **Refactoring**
  - upgrade deps to remove some security warnings - [f405719]( https://github.com/royriojas/flat-cache/commit/f405719 ), [Roy Riojas](https://github.com/Roy Riojas), 06/11/2018 12:07:31

- **Bug Fixes**
  - replace circular-json with flatted ([#23](https://github.com/royriojas/flat-cache/issues/23)) - [00f6892]( https://github.com/royriojas/flat-cache/commit/00f6892 ), [Terry](https://github.com/Terry), 05/11/2018 18:44:16

- **Other changes**
  - update del to v3.0.0 ([#26](https://github.com/royriojas/flat-cache/issues/26)) - [d42883f]( https://github.com/royriojas/flat-cache/commit/d42883f ), [Patrick Silva](https://github.com/Patrick Silva), 03/11/2018 01:00:44

    Closes #25
## v1.3.0
- **Other changes**
  - Added #all method ([#16](https://github.com/royriojas/flat-cache/issues/16)) - [12293be]( https://github.com/royriojas/flat-cache/commit/12293be ), [Ozair Patel](https://github.com/Ozair Patel), 25/09/2017 14:46:38

    * Added #all method

    * Added #all method test

    * Updated readme

    * Added yarn.lock

    * Added more keys for #all test

    * Beautified file

  - fix changelog title style ([#14](https://github.com/royriojas/flat-cache/issues/14)) - [af8338a]( https://github.com/royriojas/flat-cache/commit/af8338a ), [前端小武](https://github.com/前端小武), 19/12/2016 20:34:48

## v1.2.2
- **Bug Fixes**
  - Do not crash if cache file is invalid JSON. ([#13](https://github.com/royriojas/flat-cache/issues/13)) - [87beaa6]( https://github.com/royriojas/flat-cache/commit/87beaa6 ), [Roy Riojas](https://github.com/Roy Riojas), 19/12/2016 18:03:35

    Fixes #12

    Not sure under which situations a cache file might exist that does
    not contain a valid JSON structure, but just in case to cover
    the possibility of this happening a try catch block has been added

    If the cache is somehow not valid the cache will be discarded an a
    a new cache will be stored instead
- **Other changes**
  - Added travis ci support for modern node versions ([#11](https://github.com/royriojas/flat-cache/issues/11)) - [1c2b1f7]( https://github.com/royriojas/flat-cache/commit/1c2b1f7 ), [Amila Welihinda](https://github.com/Amila Welihinda), 10/11/2016 23:47:52

  - Bumping `circular-son` version ([#10](https://github.com/royriojas/flat-cache/issues/10)) - [4d5e861]( https://github.com/royriojas/flat-cache/commit/4d5e861 ), [Andrea Giammarchi](https://github.com/Andrea Giammarchi), 02/08/2016 07:13:52

    As mentioned in https://github.com/WebReflection/circular-json/issues/25 `circular-json` wan't rightly implementing the license field.

    Latest version bump changed only that bit so that ESLint should now be happy.
## v1.2.1
- **Bug Fixes**
  - Add missing utils.js file to the package. closes [#8](https://github.com/royriojas/flat-cache/issues/8) - [ec10cf2]( https://github.com/royriojas/flat-cache/commit/ec10cf2 ), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 02:18:57

## v1.2.0
- **Documentation**
  - Add documentation about noPrune option - [23e11f9]( https://github.com/royriojas/flat-cache/commit/23e11f9 ), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 02:06:49

## v1.0.11
- **Features**
  - Add noPrune option to cache.save() method. closes [#7](https://github.com/royriojas/flat-cache/issues/7) - [2c8016a]( https://github.com/royriojas/flat-cache/commit/2c8016a ), [Roy Riojas](https://github.com/Roy Riojas), 01/08/2016 02:00:29

  - Add json read and write utility based on circular-json - [c31081e]( https://github.com/royriojas/flat-cache/commit/c31081e ), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 08:58:17

- **Bug Fixes**
  - Remove UTF16 BOM stripping - [4a41e22]( https://github.com/royriojas/flat-cache/commit/4a41e22 ), [Jean Ponchon](https://github.com/Jean Ponchon), 29/07/2016 02:18:06

    Since we control both writing and reading of JSON stream, there no needs
    to handle unicode BOM.
  - Use circular-json to handle circular references (fix [#5](https://github.com/royriojas/flat-cache/issues/5)) - [cd7aeed]( https://github.com/royriojas/flat-cache/commit/cd7aeed ), [Jean Ponchon](https://github.com/Jean Ponchon), 25/07/2016 11:11:59

- **Tests Related fixes**
  - Add missing file from eslint test - [d6fa3c3]( https://github.com/royriojas/flat-cache/commit/d6fa3c3 ), [Jean Ponchon](https://github.com/Jean Ponchon), 29/07/2016 02:15:51

  - Add test for circular json serialization / deserialization - [07d2ddd]( https://github.com/royriojas/flat-cache/commit/07d2ddd ), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 08:59:36

- **Refactoring**
  - Remove unused read-json-sync - [2be1c24]( https://github.com/royriojas/flat-cache/commit/2be1c24 ), [Jean Ponchon](https://github.com/Jean Ponchon), 28/07/2016 08:59:18

- **Build Scripts Changes**
  - travis tests on 0.12 and 4x - [3a613fd]( https://github.com/royriojas/flat-cache/commit/3a613fd ), [royriojas](https://github.com/royriojas), 15/11/2015 14:34:40

## v1.0.10
- **Build Scripts Changes**
  - add eslint-fix task - [fd29e52]( https://github.com/royriojas/flat-cache/commit/fd29e52 ), [royriojas](https://github.com/royriojas), 01/11/2015 15:04:08

  - make sure the test script also verify beautification and linting of files before running tests - [e94e176]( https://github.com/royriojas/flat-cache/commit/e94e176 ), [royriojas](https://github.com/royriojas), 01/11/2015 11:54:48

- **Other changes**
  - add clearAll for cacheDir - [97383d9]( https://github.com/royriojas/flat-cache/commit/97383d9 ), [xieyaowu](https://github.com/xieyaowu), 31/10/2015 21:02:18

## v1.0.9
- **Bug Fixes**
  - wrong default values for changelogx user repo name - [7bb52d1]( https://github.com/royriojas/flat-cache/commit/7bb52d1 ), [royriojas](https://github.com/royriojas), 11/09/2015 15:59:30

## v1.0.8
- **Build Scripts Changes**
  - test against node 4 - [c395b66]( https://github.com/royriojas/flat-cache/commit/c395b66 ), [royriojas](https://github.com/royriojas), 11/09/2015 15:51:39

## v1.0.7
- **Other changes**
  - Move dependencies into devDep - [7e47099]( https://github.com/royriojas/flat-cache/commit/7e47099 ), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 11/09/2015 15:10:57

- **Documentation**
  - Add missing changelog link - [f51197a]( https://github.com/royriojas/flat-cache/commit/f51197a ), [royriojas](https://github.com/royriojas), 11/09/2015 14:48:05

## v1.0.6
- **Build Scripts Changes**
  - Add helpers/code check scripts - [bdb82f3]( https://github.com/royriojas/flat-cache/commit/bdb82f3 ), [royriojas](https://github.com/royriojas), 11/09/2015 14:44:31

## v1.0.5
- **Documentation**
  - better description for the module - [436817f]( https://github.com/royriojas/flat-cache/commit/436817f ), [royriojas](https://github.com/royriojas), 11/09/2015 14:35:33

- **Other changes**
  - Update dependencies - [be88aa3]( https://github.com/royriojas/flat-cache/commit/be88aa3 ), [Bogdan Chadkin](https://github.com/Bogdan Chadkin), 11/09/2015 13:47:41

## v1.0.4
- **Refactoring**
  - load a cache file using the full filepath - [b8f68c2]( https://github.com/royriojas/flat-cache/commit/b8f68c2 ), [Roy Riojas](https://github.com/Roy Riojas), 30/08/2015 04:19:14

- **Documentation**
  - Add documentation about `clearAll` and `clearCacheById` - [13947c1]( https://github.com/royriojas/flat-cache/commit/13947c1 ), [Roy Riojas](https://github.com/Roy Riojas), 01/03/2015 23:44:05

- **Features**
  - Add methods to remove the cache documents created - [af40443]( https://github.com/royriojas/flat-cache/commit/af40443 ), [Roy Riojas](https://github.com/Roy Riojas), 01/03/2015 23:39:27

## v1.0.1
- **Other changes**
  - Update README.md - [c2b6805]( https://github.com/royriojas/flat-cache/commit/c2b6805 ), [Roy Riojas](https://github.com/Roy Riojas), 26/02/2015 04:28:07

## v1.0.0
- **Refactoring**
  - flat-cache v.1.0.0 - [c984274]( https://github.com/royriojas/flat-cache/commit/c984274 ), [Roy Riojas](https://github.com/Roy Riojas), 26/02/2015 04:11:50

- **Other changes**
  - Initial commit - [d43cccf]( https://github.com/royriojas/flat-cache/commit/d43cccf ), [Roy Riojas](https://github.com/Roy Riojas), 26/02/2015 01:12:16


flat-cache

description: A stupidly simple key/value storage using files to persist some data

repository: jaredwray/flat-cache

eslint: eslint --cache --cache-location=node_modules/.cache/ ./src/**/*.js ./test/**/*.js

eslint-fix: npm run eslint -- --fix

autofix: npm run eslint-fix

check: npm run eslint

verify: npm run eslint && npm run test:cache

test:cache: c8 mocha -R spec test/specs

test:ci:cache: c8 --reporter=lcov mocha -R spec test/specs

test: npm run verify --silent

keywords:
json cache
simple cache
file cache
key par
key value
cache


code:
var path = require('path');
var fs = require('fs');
var Keyv = require('keyv');
var utils = require('./utils');
var del = require('./del');
var writeJSON = utils.writeJSON;

var cache = {
  /**
   * Load a cache identified by the given Id. If the element does not exists, then initialize an empty
   * cache storage. If specified `cacheDir` will be used as the directory to persist the data to. If omitted
   * then the cache module directory `./cache` will be used instead
   *
   * @method load
   * @param docId {String} the id of the cache, would also be used as the name of the file cache
   * @param [cacheDir] {String} directory for the cache entry
   */
  load: function (docId, cacheDir) {
    var me = this;

    me.keyv = new Keyv();

    me.__visited = {};
    me.__persisted = {};
    me._pathToFile = cacheDir ? path.resolve(cacheDir, docId) : path.resolve(__dirname, '../.cache/', docId);

    if (fs.existsSync(me._pathToFile)) {
      me._persisted = utils.tryParse(me._pathToFile, {});
    }
  },

  get _persisted() {
    return this.__persisted;
  },

  set _persisted(value) {
    this.__persisted = value;
    this.keyv.set('persisted', value);
  },

  get _visited() {
    return this.__visited;
  },

  set _visited(value) {
    this.__visited = value;
    this.keyv.set('visited', value);
  },

  /**
   * Load the cache from the provided file
   * @method loadFile
   * @param  {String} pathToFile the path to the file containing the info for the cache
   */
  loadFile: function (pathToFile) {
    var me = this;
    var dir = path.dirname(pathToFile);
    var fName = path.basename(pathToFile);

    me.load(fName, dir);
  },

  /**
   * Returns the entire persisted object
   * @method all
   * @returns {*}
   */
  all: function () {
    return this._persisted;
  },

  keys: function () {
    return Object.keys(this._persisted);
  },
  /**
   * sets a key to a given value
   * @method setKey
   * @param key {string} the key to set
   * @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify
   */
  setKey: function (key, value) {
    this._visited[key] = true;
    this._persisted[key] = value;
  },
  /**
   * remove a given key from the cache
   * @method removeKey
   * @param key {String} the key to remove from the object
   */
  removeKey: function (key) {
    delete this._visited[key]; // esfmt-ignore-line
    delete this._persisted[key]; // esfmt-ignore-line
  },
  /**
   * Return the value of the provided key
   * @method getKey
   * @param key {String} the name of the key to retrieve
   * @returns {*} the value from the key
   */
  getKey: function (key) {
    this._visited[key] = true;
    return this._persisted[key];
  },

  /**
   * Remove keys that were not accessed/set since the
   * last time the `prune` method was called.
   * @method _prune
   * @private
   */
  _prune: function () {
    var me = this;
    var obj = {};

    var keys = Object.keys(me._visited);

    // no keys visited for either get or set value
    if (keys.length === 0) {
      return;
    }

    keys.forEach(function (key) {
      obj[key] = me._persisted[key];
    });

    me._visited = {};
    me._persisted = obj;
  },

  /**
   * Save the state of the cache identified by the docId to disk
   * as a JSON structure
   * @param [noPrune=false] {Boolean} whether to remove from cache the non visited files
   * @method save
   */
  save: function (noPrune) {
    var me = this;

    !noPrune && me._prune();
    writeJSON(me._pathToFile, me._persisted);
  },

  /**
   * remove the file where the cache is persisted
   * @method removeCacheFile
   * @return {Boolean} true or false if the file was successfully deleted
   */
  removeCacheFile: function () {
    return del(this._pathToFile);
  },
  /**
   * Destroy the file cache and cache content.
   * @method destroy
   */
  destroy: function () {
    var me = this;
    me._visited = {};
    me._persisted = {};

    me.removeCacheFile();
  },
};

module.exports = {
  /**
   * Alias for create. Should be considered depreacted. Will be removed in next releases
   *
   * @method load
   * @param docId {String} the id of the cache, would also be used as the name of the file cache
   * @param [cacheDir] {String} directory for the cache entry
   * @returns {cache} cache instance
   */
  load: function (docId, cacheDir) {
    return this.create(docId, cacheDir);
  },

  /**
   * Load a cache identified by the given Id. If the element does not exists, then initialize an empty
   * cache storage.
   *
   * @method create
   * @param docId {String} the id of the cache, would also be used as the name of the file cache
   * @param [cacheDir] {String} directory for the cache entry
   * @returns {cache} cache instance
   */
  create: function (docId, cacheDir) {
    var obj = Object.create(cache);
    obj.load(docId, cacheDir);
    return obj;
  },

  createFromFile: function (filePath) {
    var obj = Object.create(cache);
    obj.loadFile(filePath);
    return obj;
  },
  /**
   * Clear the cache identified by the given id. Caches stored in a different cache directory can be deleted directly
   *
   * @method clearCache
   * @param docId {String} the id of the cache, would also be used as the name of the file cache
   * @param cacheDir {String} the directory where the cache file was written
   * @returns {Boolean} true if the cache folder was deleted. False otherwise
   */
  clearCacheById: function (docId, cacheDir) {
    var filePath = cacheDir ? path.resolve(cacheDir, docId) : path.resolve(__dirname, '../.cache/', docId);
    return del(filePath);
  },
  /**
   * Remove all cache stored in the cache directory
   * @method clearAll
   * @returns {Boolean} true if the cache folder was deleted. False otherwise
   */
  clearAll: function (cacheDir) {
    var filePath = cacheDir ? path.resolve(cacheDir) : path.resolve(__dirname, '../.cache/');
    return del(filePath);
  },
};


code:
var rimraf = require('rimraf').sync;
var fs = require('fs');

module.exports = function del(file) {
  if (fs.existsSync(file)) {
    //if rimraf doesn't throw then the file has been deleted or didn't exist
    rimraf(file, {
      glob: false,
    });
    return true;
  }
  return false;
};


code:
var fs = require('fs');
var path = require('path');
var flatted = require('flatted');

module.exports = {
  tryParse: function (filePath, defaultValue) {
    var result;
    try {
      result = this.readJSON(filePath);
    } catch (ex) {
      result = defaultValue;
    }
    return result;
  },

  /**
   * Read json file synchronously using flatted
   *
   * @method readJSON
   * @param  {String} filePath Json filepath
   * @returns {*} parse result
   */
  readJSON: function (filePath) {
    return flatted.parse(
      fs.readFileSync(filePath, {
        encoding: 'utf8',
      })
    );
  },

  /**
   * Write json file synchronously using circular-json
   *
   * @method writeJSON
   * @param  {String} filePath Json filepath
   * @param  {*} data Object to serialize
   */
  writeJSON: function (filePath, data) {
    fs.mkdirSync(path.dirname(filePath), {
      recursive: true,
    });
    fs.writeFileSync(filePath, flatted.stringify(data));
  },
};


code:
# flat [![Build Status](https://secure.travis-ci.org/hughsk/flat.png?branch=master)](http://travis-ci.org/hughsk/flat)

Take a nested Javascript object and flatten it, or unflatten an object with
delimited keys.

## Installation

``` bash
$ npm install flat
```

## Methods

### flatten(original, options)

Flattens the object - it'll return an object one level deep, regardless of how
nested the original object was:

``` javascript
var flatten = require('flat')

flatten({
    key1: {
        keyA: 'valueI'
    },
    key2: {
        keyB: 'valueII'
    },
    key3: { a: { b: { c: 2 } } }
})

// {
//   'key1.keyA': 'valueI',
//   'key2.keyB': 'valueII',
//   'key3.a.b.c': 2
// }
```

### unflatten(original, options)

Flattening is reversible too, you can call `flatten.unflatten()` on an object:

``` javascript
var unflatten = require('flat').unflatten

unflatten({
    'three.levels.deep': 42,
    'three.levels': {
        nested: true
    }
})

// {
//     three: {
//         levels: {
//             deep: 42,
//             nested: true
//         }
//     }
// }
```

## Options

### delimiter

Use a custom delimiter for (un)flattening your objects, instead of `.`.

### safe

When enabled, both `flat` and `unflatten` will preserve arrays and their
contents. This is disabled by default.

``` javascript
var flatten = require('flat')

flatten({
    this: [
        { contains: 'arrays' },
        { preserving: {
              them: 'for you'
        }}
    ]
}, {
    safe: true
})

// {
//     'this': [
//         { contains: 'arrays' },
//         { preserving: {
//             them: 'for you'
//         }}
//     ]
// }
```

### object

When enabled, arrays will not be created automatically when calling unflatten, like so:

``` javascript
unflatten({
    'hello.you.0': 'ipsum',
    'hello.you.1': 'lorem',
    'hello.other.world': 'foo'
}, { object: true })

// hello: {
//     you: {
//         0: 'ipsum',
//         1: 'lorem',
//     },
//     other: { world: 'foo' }
// }
```

### overwrite

When enabled, existing keys in the unflattened object may be overwritten if they cannot hold a newly encountered nested value:

```javascript
unflatten({
    'TRAVIS': 'true',
    'TRAVIS.DIR': '/home/travis/build/kvz/environmental'
}, { overwrite: true })

// TRAVIS: {
//     DIR: '/home/travis/build/kvz/environmental'
// }
```

Without `overwrite` set to `true`, the `TRAVIS` key would already have been set to a string, thus could not accept the nested `DIR` element.

This only makes sense on ordered arrays, and since we're overwriting data, should be used with care.

### maxDepth

Maximum number of nested objects to flatten.

``` javascript
var flatten = require('flat')

flatten({
    key1: {
        keyA: 'valueI'
    },
    key2: {
        keyB: 'valueII'
    },
    key3: { a: { b: { c: 2 } } }
}, { maxDepth: 2 })

// {
//   'key1.keyA': 'valueI',
//   'key2.keyB': 'valueII',
//   'key3.a': { b: { c: 2 } }
// }
```

### transformKey

Transform each part of a flat key before and after flattening.

```javascript
var flatten = require('flat')
var unflatten = require('flat').unflatten

flatten({
    key1: {
        keyA: 'valueI'
    },
    key2: {
        keyB: 'valueII'
    },
    key3: { a: { b: { c: 2 } } }
}, {
    transformKey: function(key){
      return '__' + key + '__';
    }
})

// {
//   '__key1__.__keyA__': 'valueI',
//   '__key2__.__keyB__': 'valueII',
//   '__key3__.__a__.__b__.__c__': 2
// }

unflatten({
      '__key1__.__keyA__': 'valueI',
      '__key2__.__keyB__': 'valueII',
      '__key3__.__a__.__b__.__c__': 2
}, {
    transformKey: function(key){
      return key.substring(2, key.length - 2)
    }
})

// {
//     key1: {
//         keyA: 'valueI'
//     },
//     key2: {
//         keyB: 'valueII'
//     },
//     key3: { a: { b: { c: 2 } } }
// }
```

## Command Line Usage

`flat` is also available as a command line tool. You can run it with
[`npx`](https://ghub.io/npx):

```sh
npx flat foo.json
```

Or install the `flat` command globally:

```sh
npm i -g flat && flat foo.json
```

Accepts a filename as an argument:

```sh
flat foo.json
```

Also accepts JSON on stdin:

```sh
cat foo.json | flat
```


code:
#!/usr/bin/env node

const fs = require('fs')
const path = require('path')
const readline = require('readline')

const flat = require('./index')

const filepath = process.argv.slice(2)[0]
if (filepath) {
  // Read from file
  const file = path.resolve(process.cwd(), filepath)
  fs.accessSync(file, fs.constants.R_OK) // allow to throw if not readable
  out(require(file))
} else if (process.stdin.isTTY) {
  usage(0)
} else {
  // Read from newline-delimited STDIN
  const lines = []
  readline.createInterface({
    input: process.stdin,
    output: process.stdout,
    terminal: false
  })
    .on('line', line => lines.push(line))
    .on('close', () => out(JSON.parse(lines.join('\n'))))
}

function out (data) {
  process.stdout.write(JSON.stringify(flat(data), null, 2))
}

function usage (code) {
  console.log(`
Usage:

flat foo.json
cat foo.json | flat
`)

  process.exit(code || 0)
}


code:
module.exports = flatten
flatten.flatten = flatten
flatten.unflatten = unflatten

function isBuffer (obj) {
  return obj &&
    obj.constructor &&
    (typeof obj.constructor.isBuffer === 'function') &&
    obj.constructor.isBuffer(obj)
}

function keyIdentity (key) {
  return key
}

function flatten (target, opts) {
  opts = opts || {}

  const delimiter = opts.delimiter || '.'
  const maxDepth = opts.maxDepth
  const transformKey = opts.transformKey || keyIdentity
  const output = {}

  function step (object, prev, currentDepth) {
    currentDepth = currentDepth || 1
    Object.keys(object).forEach(function (key) {
      const value = object[key]
      const isarray = opts.safe && Array.isArray(value)
      const type = Object.prototype.toString.call(value)
      const isbuffer = isBuffer(value)
      const isobject = (
        type === '[object Object]' ||
        type === '[object Array]'
      )

      const newKey = prev
        ? prev + delimiter + transformKey(key)
        : transformKey(key)

      if (!isarray && !isbuffer && isobject && Object.keys(value).length &&
        (!opts.maxDepth || currentDepth < maxDepth)) {
        return step(value, newKey, currentDepth + 1)
      }

      output[newKey] = value
    })
  }

  step(target)

  return output
}

function unflatten (target, opts) {
  opts = opts || {}

  const delimiter = opts.delimiter || '.'
  const overwrite = opts.overwrite || false
  const transformKey = opts.transformKey || keyIdentity
  const result = {}

  const isbuffer = isBuffer(target)
  if (isbuffer || Object.prototype.toString.call(target) !== '[object Object]') {
    return target
  }

  // safely ensure that the key is
  // an integer.
  function getkey (key) {
    const parsedKey = Number(key)

    return (
      isNaN(parsedKey) ||
      key.indexOf('.') !== -1 ||
      opts.object
    ) ? key
      : parsedKey
  }

  function addKeys (keyPrefix, recipient, target) {
    return Object.keys(target).reduce(function (result, key) {
      result[keyPrefix + delimiter + key] = target[key]

      return result
    }, recipient)
  }

  function isEmpty (val) {
    const type = Object.prototype.toString.call(val)
    const isArray = type === '[object Array]'
    const isObject = type === '[object Object]'

    if (!val) {
      return true
    } else if (isArray) {
      return !val.length
    } else if (isObject) {
      return !Object.keys(val).length
    }
  }

  target = Object.keys(target).reduce(function (result, key) {
    const type = Object.prototype.toString.call(target[key])
    const isObject = (type === '[object Object]' || type === '[object Array]')
    if (!isObject || isEmpty(target[key])) {
      result[key] = target[key]
      return result
    } else {
      return addKeys(
        key,
        result,
        flatten(target[key], opts)
      )
    }
  }, {})

  Object.keys(target).forEach(function (key) {
    const split = key.split(delimiter).map(transformKey)
    let key1 = getkey(split.shift())
    let key2 = getkey(split[0])
    let recipient = result

    while (key2 !== undefined) {
      if (key1 === '__proto__') {
        return
      }

      const type = Object.prototype.toString.call(recipient[key1])
      const isobject = (
        type === '[object Object]' ||
        type === '[object Array]'
      )

      // do not write over falsey, non-undefined values if overwrite is false
      if (!overwrite && !isobject && typeof recipient[key1] !== 'undefined') {
        return
      }

      if ((overwrite && !isobject) || (!overwrite && recipient[key1] == null)) {
        recipient[key1] = (
          typeof key2 === 'number' &&
          !opts.object ? [] : {}
        )
      }

      recipient = recipient[key1]
      if (split.length > 0) {
        key1 = getkey(split.shift())
        key2 = getkey(split[0])
      }
    }

    // unflatten again for 'messy objects'
    recipient[key1] = unflatten(target[key], opts)
  })

  return result
}


flat

test: mocha -u tdd --reporter spec && standard cli.js index.js test/index.js

description: Take a nested Javascript object and flatten it, or unflatten an object with delimited keys

test: test

type: git

keywords: flat json flatten unflatten split object nested

author: Hugh Kennedy <hughskennedy@gmail.com> (http://hughskennedy.com)


code:
/* globals suite test */

const assert = require('assert')
const path = require('path')
const { exec } = require('child_process')
const pkg = require('../package.json')
const flat = require('../index')

const flatten = flat.flatten
const unflatten = flat.unflatten

const primitives = {
  String: 'good morning',
  Number: 1234.99,
  Boolean: true,
  Date: new Date(),
  null: null,
  undefined: undefined
}

suite('Flatten Primitives', function () {
  Object.keys(primitives).forEach(function (key) {
    const value = primitives[key]

    test(key, function () {
      assert.deepStrictEqual(flatten({
        hello: {
          world: value
        }
      }), {
        'hello.world': value
      })
    })
  })
})

suite('Unflatten Primitives', function () {
  Object.keys(primitives).forEach(function (key) {
    const value = primitives[key]

    test(key, function () {
      assert.deepStrictEqual(unflatten({
        'hello.world': value
      }), {
        hello: {
          world: value
        }
      })
    })
  })
})

suite('Flatten', function () {
  test('Nested once', function () {
    assert.deepStrictEqual(flatten({
      hello: {
        world: 'good morning'
      }
    }), {
      'hello.world': 'good morning'
    })
  })

  test('Nested twice', function () {
    assert.deepStrictEqual(flatten({
      hello: {
        world: {
          again: 'good morning'
        }
      }
    }), {
      'hello.world.again': 'good morning'
    })
  })

  test('Multiple Keys', function () {
    assert.deepStrictEqual(flatten({
      hello: {
        lorem: {
          ipsum: 'again',
          dolor: 'sit'
        }
      },
      world: {
        lorem: {
          ipsum: 'again',
          dolor: 'sit'
        }
      }
    }), {
      'hello.lorem.ipsum': 'again',
      'hello.lorem.dolor': 'sit',
      'world.lorem.ipsum': 'again',
      'world.lorem.dolor': 'sit'
    })
  })

  test('Custom Delimiter', function () {
    assert.deepStrictEqual(flatten({
      hello: {
        world: {
          again: 'good morning'
        }
      }
    }, {
      delimiter: ':'
    }), {
      'hello:world:again': 'good morning'
    })
  })

  test('Empty Objects', function () {
    assert.deepStrictEqual(flatten({
      hello: {
        empty: {
          nested: {}
        }
      }
    }), {
      'hello.empty.nested': {}
    })
  })

  if (typeof Buffer !== 'undefined') {
    test('Buffer', function () {
      assert.deepStrictEqual(flatten({
        hello: {
          empty: {
            nested: Buffer.from('test')
          }
        }
      }), {
        'hello.empty.nested': Buffer.from('test')
      })
    })
  }

  if (typeof Uint8Array !== 'undefined') {
    test('typed arrays', function () {
      assert.deepStrictEqual(flatten({
        hello: {
          empty: {
            nested: new Uint8Array([1, 2, 3, 4])
          }
        }
      }), {
        'hello.empty.nested': new Uint8Array([1, 2, 3, 4])
      })
    })
  }

  test('Custom Depth', function () {
    assert.deepStrictEqual(flatten({
      hello: {
        world: {
          again: 'good morning'
        }
      },
      lorem: {
        ipsum: {
          dolor: 'good evening'
        }
      }
    }, {
      maxDepth: 2
    }), {
      'hello.world': {
        again: 'good morning'
      },
      'lorem.ipsum': {
        dolor: 'good evening'
      }
    })
  })

  test('Transformed Keys', function () {
    assert.deepStrictEqual(flatten({
      hello: {
        world: {
          again: 'good morning'
        }
      },
      lorem: {
        ipsum: {
          dolor: 'good evening'
        }
      }
    }, {
      transformKey: function (key) {
        return '__' + key + '__'
      }
    }), {
      '__hello__.__world__.__again__': 'good morning',
      '__lorem__.__ipsum__.__dolor__': 'good evening'
    })
  })

  test('Should keep number in the left when object', function () {
    assert.deepStrictEqual(flatten({
      hello: {
        '0200': 'world',
        '0500': 'darkness my old friend'
      }
    }), {
      'hello.0200': 'world',
      'hello.0500': 'darkness my old friend'
    })
  })
})

suite('Unflatten', function () {
  test('Nested once', function () {
    assert.deepStrictEqual({
      hello: {
        world: 'good morning'
      }
    }, unflatten({
      'hello.world': 'good morning'
    }))
  })

  test('Nested twice', function () {
    assert.deepStrictEqual({
      hello: {
        world: {
          again: 'good morning'
        }
      }
    }, unflatten({
      'hello.world.again': 'good morning'
    }))
  })

  test('Multiple Keys', function () {
    assert.deepStrictEqual({
      hello: {
        lorem: {
          ipsum: 'again',
          dolor: 'sit'
        }
      },
      world: {
        greet: 'hello',
        lorem: {
          ipsum: 'again',
          dolor: 'sit'
        }
      }
    }, unflatten({
      'hello.lorem.ipsum': 'again',
      'hello.lorem.dolor': 'sit',
      'world.lorem.ipsum': 'again',
      'world.lorem.dolor': 'sit',
      world: { greet: 'hello' }
    }))
  })

  test('nested objects do not clobber each other when a.b inserted before a', function () {
    const x = {}
    x['foo.bar'] = { t: 123 }
    x.foo = { p: 333 }
    assert.deepStrictEqual(unflatten(x), {
      foo: {
        bar: {
          t: 123
        },
        p: 333
      }
    })
  })

  test('Custom Delimiter', function () {
    assert.deepStrictEqual({
      hello: {
        world: {
          again: 'good morning'
        }
      }
    }, unflatten({
      'hello world again': 'good morning'
    }, {
      delimiter: ' '
    }))
  })

  test('Overwrite', function () {
    assert.deepStrictEqual({
      travis: {
        build: {
          dir: '/home/travis/build/kvz/environmental'
        }
      }
    }, unflatten({
      travis: 'true',
      travis_build_dir: '/home/travis/build/kvz/environmental'
    }, {
      delimiter: '_',
      overwrite: true
    }))
  })

  test('Transformed Keys', function () {
    assert.deepStrictEqual(unflatten({
      '__hello__.__world__.__again__': 'good morning',
      '__lorem__.__ipsum__.__dolor__': 'good evening'
    }, {
      transformKey: function (key) {
        return key.substring(2, key.length - 2)
      }
    }), {
      hello: {
        world: {
          again: 'good morning'
        }
      },
      lorem: {
        ipsum: {
          dolor: 'good evening'
        }
      }
    })
  })

  test('Messy', function () {
    assert.deepStrictEqual({
      hello: { world: 'again' },
      lorem: { ipsum: 'another' },
      good: {
        morning: {
          hash: {
            key: {
              nested: {
                deep: {
                  and: {
                    even: {
                      deeper: { still: 'hello' }
                    }
                  }
                }
              }
            }
          },
          again: { testing: { this: 'out' } }
        }
      }
    }, unflatten({
      'hello.world': 'again',
      'lorem.ipsum': 'another',
      'good.morning': {
        'hash.key': {
          'nested.deep': {
            'and.even.deeper.still': 'hello'
          }
        }
      },
      'good.morning.again': {
        'testing.this': 'out'
      }
    }))
  })

  suite('Overwrite + non-object values in key positions', function () {
    test('non-object keys + overwrite should be overwritten', function () {
      assert.deepStrictEqual(flat.unflatten({ a: null, 'a.b': 'c' }, { overwrite: true }), { a: { b: 'c' } })
      assert.deepStrictEqual(flat.unflatten({ a: 0, 'a.b': 'c' }, { overwrite: true }), { a: { b: 'c' } })
      assert.deepStrictEqual(flat.unflatten({ a: 1, 'a.b': 'c' }, { overwrite: true }), { a: { b: 'c' } })
      assert.deepStrictEqual(flat.unflatten({ a: '', 'a.b': 'c' }, { overwrite: true }), { a: { b: 'c' } })
    })

    test('overwrite value should not affect undefined keys', function () {
      assert.deepStrictEqual(flat.unflatten({ a: undefined, 'a.b': 'c' }, { overwrite: true }), { a: { b: 'c' } })
      assert.deepStrictEqual(flat.unflatten({ a: undefined, 'a.b': 'c' }, { overwrite: false }), { a: { b: 'c' } })
    })

    test('if no overwrite, should ignore nested values under non-object key', function () {
      assert.deepStrictEqual(flat.unflatten({ a: null, 'a.b': 'c' }), { a: null })
      assert.deepStrictEqual(flat.unflatten({ a: 0, 'a.b': 'c' }), { a: 0 })
      assert.deepStrictEqual(flat.unflatten({ a: 1, 'a.b': 'c' }), { a: 1 })
      assert.deepStrictEqual(flat.unflatten({ a: '', 'a.b': 'c' }), { a: '' })
    })
  })

  suite('.safe', function () {
    test('Should protect arrays when true', function () {
      assert.deepStrictEqual(flatten({
        hello: [
          { world: { again: 'foo' } },
          { lorem: 'ipsum' }
        ],
        another: {
          nested: [{ array: { too: 'deep' } }]
        },
        lorem: {
          ipsum: 'whoop'
        }
      }, {
        safe: true
      }), {
        hello: [
          { world: { again: 'foo' } },
          { lorem: 'ipsum' }
        ],
        'lorem.ipsum': 'whoop',
        'another.nested': [{ array: { too: 'deep' } }]
      })
    })

    test('Should not protect arrays when false', function () {
      assert.deepStrictEqual(flatten({
        hello: [
          { world: { again: 'foo' } },
          { lorem: 'ipsum' }
        ]
      }, {
        safe: false
      }), {
        'hello.0.world.again': 'foo',
        'hello.1.lorem': 'ipsum'
      })
    })

    test('Empty objects should not be removed', function () {
      assert.deepStrictEqual(unflatten({
        foo: [],
        bar: {}
      }), { foo: [], bar: {} })
    })
  })

  suite('.object', function () {
    test('Should create object instead of array when true', function () {
      const unflattened = unflatten({
        'hello.you.0': 'ipsum',
        'hello.you.1': 'lorem',
        'hello.other.world': 'foo'
      }, {
        object: true
      })
      assert.deepStrictEqual({
        hello: {
          you: {
            0: 'ipsum',
            1: 'lorem'
          },
          other: { world: 'foo' }
        }
      }, unflattened)
      assert(!Array.isArray(unflattened.hello.you))
    })

    test('Should create object instead of array when nested', function () {
      const unflattened = unflatten({
        hello: {
          'you.0': 'ipsum',
          'you.1': 'lorem',
          'other.world': 'foo'
        }
      }, {
        object: true
      })
      assert.deepStrictEqual({
        hello: {
          you: {
            0: 'ipsum',
            1: 'lorem'
          },
          other: { world: 'foo' }
        }
      }, unflattened)
      assert(!Array.isArray(unflattened.hello.you))
    })

    test('Should keep the zero in the left when object is true', function () {
      const unflattened = unflatten({
        'hello.0200': 'world',
        'hello.0500': 'darkness my old friend'
      }, {
        object: true
      })

      assert.deepStrictEqual({
        hello: {
          '0200': 'world',
          '0500': 'darkness my old friend'
        }
      }, unflattened)
    })

    test('Should not create object when false', function () {
      const unflattened = unflatten({
        'hello.you.0': 'ipsum',
        'hello.you.1': 'lorem',
        'hello.other.world': 'foo'
      }, {
        object: false
      })
      assert.deepStrictEqual({
        hello: {
          you: ['ipsum', 'lorem'],
          other: { world: 'foo' }
        }
      }, unflattened)
      assert(Array.isArray(unflattened.hello.you))
    })
  })

  if (typeof Buffer !== 'undefined') {
    test('Buffer', function () {
      assert.deepStrictEqual(unflatten({
        'hello.empty.nested': Buffer.from('test')
      }), {
        hello: {
          empty: {
            nested: Buffer.from('test')
          }
        }
      })
    })
  }

  if (typeof Uint8Array !== 'undefined') {
    test('typed arrays', function () {
      assert.deepStrictEqual(unflatten({
        'hello.empty.nested': new Uint8Array([1, 2, 3, 4])
      }), {
        hello: {
          empty: {
            nested: new Uint8Array([1, 2, 3, 4])
          }
        }
      })
    })
  }

  test('should not pollute prototype', function () {
    unflatten({
      '__proto__.polluted': true
    })
    unflatten({
      'prefix.__proto__.polluted': true
    })
    unflatten({
      'prefix.0.__proto__.polluted': true
    })

    assert.notStrictEqual({}.polluted, true)
  })
})

suite('Arrays', function () {
  test('Should be able to flatten arrays properly', function () {
    assert.deepStrictEqual({
      'a.0': 'foo',
      'a.1': 'bar'
    }, flatten({
      a: ['foo', 'bar']
    }))
  })

  test('Should be able to revert and reverse array serialization via unflatten', function () {
    assert.deepStrictEqual({
      a: ['foo', 'bar']
    }, unflatten({
      'a.0': 'foo',
      'a.1': 'bar'
    }))
  })

  test('Array typed objects should be restored by unflatten', function () {
    assert.strictEqual(
      Object.prototype.toString.call(['foo', 'bar'])
      , Object.prototype.toString.call(unflatten({
        'a.0': 'foo',
        'a.1': 'bar'
      }).a)
    )
  })

  test('Do not include keys with numbers inside them', function () {
    assert.deepStrictEqual(unflatten({
      '1key.2_key': 'ok'
    }), {
      '1key': {
        '2_key': 'ok'
      }
    })
  })
})

suite('Order of Keys', function () {
  test('Order of keys should not be changed after round trip flatten/unflatten', function () {
    const obj = {
      b: 1,
      abc: {
        c: [{
          d: 1,
          bca: 1,
          a: 1
        }]
      },
      a: 1
    }
    const result = unflatten(
      flatten(obj)
    )

    assert.deepStrictEqual(Object.keys(obj), Object.keys(result))
    assert.deepStrictEqual(Object.keys(obj.abc), Object.keys(result.abc))
    assert.deepStrictEqual(Object.keys(obj.abc.c[0]), Object.keys(result.abc.c[0]))
  })
})

suite('CLI', function () {
  test('can take filename', function (done) {
    const cli = path.resolve(__dirname, '..', pkg.bin)
    const pkgJSON = path.resolve(__dirname, '..', 'package.json')
    exec(`${cli} ${pkgJSON}`, (err, stdout, stderr) => {
      assert.ifError(err)
      assert.strictEqual(stdout.trim(), JSON.stringify(flatten(pkg), null, 2))
      done()
    })
  })

  test('exits with usage if no file', function (done) {
    const cli = path.resolve(__dirname, '..', pkg.bin)
    const pkgJSON = path.resolve(__dirname, '..', 'package.json')
    exec(`${cli} ${pkgJSON}`, (err, stdout, stderr) => {
      assert.ifError(err)
      assert.strictEqual(stdout.trim(), JSON.stringify(flatten(pkg), null, 2))
      done()
    })
  })

  test('can take piped file', function (done) {
    const cli = path.resolve(__dirname, '..', pkg.bin)
    const pkgJSON = path.resolve(__dirname, '..', 'package.json')
    exec(`cat ${pkgJSON} | ${cli}`, (err, stdout, stderr) => {
      assert.ifError(err)
      assert.strictEqual(stdout.trim(), JSON.stringify(flatten(pkg), null, 2))
      done()
    })
  })
})


code:
# flatted

[![Downloads](https://img.shields.io/npm/dm/flatted.svg)](https://www.npmjs.com/package/flatted) [![Coverage Status](https://coveralls.io/repos/github/WebReflection/flatted/badge.svg?branch=main)](https://coveralls.io/github/WebReflection/flatted?branch=main) [![Build Status](https://travis-ci.com/WebReflection/flatted.svg?branch=main)](https://travis-ci.com/WebReflection/flatted) [![License: ISC](https://img.shields.io/badge/License-ISC-yellow.svg)](https://opensource.org/licenses/ISC) ![WebReflection status](https://offline.report/status/webreflection.svg)

![snow flake](./flatted.jpg)

**Social Media Photo by [Matt Seymour](https://unsplash.com/@mattseymour) on [Unsplash](https://unsplash.com/)**

A super light (0.5K) and fast circular JSON parser, directly from the creator of [CircularJSON](https://github.com/WebReflection/circular-json/#circularjson).

Available also for **[PHP](./php/flatted.php)**.

Available also for **[Python](./python/flatted.py)**.

- - -

## Announcement 📣

There is a standard approach to recursion and more data-types than what JSON allows, and it's part of the [Structured Clone polyfill](https://github.com/ungap/structured-clone/#readme).

Beside acting as a polyfill, its `@ungap/structured-clone/json` export provides both `stringify` and `parse`, and it's been tested for being faster than *flatted*, but its produced output is also smaller than *flatted* in general.

The *@ungap/structured-clone* module is, in short, a drop in replacement for *flatted*, but it's not compatible with *flatted* specialized syntax.

However, if recursion, as well as more data-types, are what you are after, or interesting for your projects/use cases, consider switching to this new module whenever you can 👍

- - -

```js
npm i flatted
```

Usable via [CDN](https://unpkg.com/flatted) or as regular module.

```js
// ESM
import {parse, stringify, toJSON, fromJSON} from 'flatted';

// CJS
const {parse, stringify, toJSON, fromJSON} = require('flatted');

const a = [{}];
a[0].a = a;
a.push(a);

stringify(a); // [["1","0"],{"a":"0"}]
```

## toJSON and fromJSON

If you'd like to implicitly survive JSON serialization, these two helpers helps:

```js
import {toJSON, fromJSON} from 'flatted';

class RecursiveMap extends Map {
  static fromJSON(any) {
    return new this(fromJSON(any));
  }
  toJSON() {
    return toJSON([...this.entries()]);
  }
}

const recursive = new RecursiveMap;
const same = {};
same.same = same;
recursive.set('same', same);

const asString = JSON.stringify(recursive);
const asMap = RecursiveMap.fromJSON(JSON.parse(asString));
asMap.get('same') === asMap.get('same').same;
// true
```

## Flatted VS JSON

As it is for every other specialized format capable of serializing and deserializing circular data, you should never `JSON.parse(Flatted.stringify(data))`, and you should never `Flatted.parse(JSON.stringify(data))`.

The only way this could work is to `Flatted.parse(Flatted.stringify(data))`, as it is also for _CircularJSON_ or any other, otherwise there's no granted data integrity.

Also please note this project serializes and deserializes only data compatible with JSON, so that sockets, or anything else with internal classes different from those allowed by JSON standard, won't be serialized and unserialized as expected.

### New in V1: Exact same JSON API

  * Added a [reviver](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Syntax) parameter to `.parse(string, reviver)` and revive your own objects.
  * Added a [replacer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#Syntax) and a `space` parameter to `.stringify(object, replacer, space)` for feature parity with JSON signature.

### Compatibility
All ECMAScript engines compatible with `Map`, `Set`, `Object.keys`, and `Array.prototype.reduce` will work, even if polyfilled.

### How does it work ?
While stringifying, all Objects, including Arrays, and strings, are flattened out and replaced as unique index. `*`

Once parsed, all indexes will be replaced through the flattened collection.

`*` represented as string to avoid conflicts with numbers

```js
// logic example
var a = [{one: 1}, {two: '2'}];
a[0].a = a;
// a is the main object, will be at index '0'
// {one: 1} is the second object, index '1'
// {two: '2'} the third, in '2', and it has a string
// which will be found at index '3'

Flatted.stringify(a);
// [["1","2"],{"one":1,"a":"0"},{"two":"3"},"2"]
// a[one,two]    {one: 1, a}    {two: '2'}  '2'
```


code:
'use strict';
/// <reference types="../types/index.d.ts" />

// (c) 2020-present Andrea Giammarchi

const {parse: $parse, stringify: $stringify} = JSON;
const {keys} = Object;

const Primitive = String;   // it could be Number
const primitive = 'string'; // it could be 'number'

const ignore = {};
const object = 'object';

const noop = (_, value) => value;

const primitives = value => (
  value instanceof Primitive ? Primitive(value) : value
);

const Primitives = (_, value) => (
  typeof value === primitive ? new Primitive(value) : value
);

const revive = (input, parsed, output, $) => {
  const lazy = [];
  for (let ke = keys(output), {length} = ke, y = 0; y < length; y++) {
    const k = ke[y];
    const value = output[k];
    if (value instanceof Primitive) {
      const tmp = input[value];
      if (typeof tmp === object && !parsed.has(tmp)) {
        parsed.add(tmp);
        output[k] = ignore;
        lazy.push({k, a: [input, parsed, tmp, $]});
      }
      else
        output[k] = $.call(output, k, tmp);
    }
    else if (output[k] !== ignore)
      output[k] = $.call(output, k, value);
  }
  for (let {length} = lazy, i = 0; i < length; i++) {
    const {k, a} = lazy[i];
    output[k] = $.call(output, k, revive.apply(null, a));
  }
  return output;
};

const set = (known, input, value) => {
  const index = Primitive(input.push(value) - 1);
  known.set(value, index);
  return index;
};

/**
 * Converts a specialized flatted string into a JS value.
 * @param {string} text
 * @param {((this: any, key: string, value: any) => any) | undefined): any} [reviver]
 * @returns {any}
 */
const parse = (text, reviver) => {
  const input = $parse(text, Primitives).map(primitives);
  const value = input[0];
  const $ = reviver || noop;
  const tmp = typeof value === object && value ?
              revive(input, new Set, value, $) :
              value;
  return $.call({'': tmp}, '', tmp);
};
exports.parse = parse;

/**
 * Converts a JS value into a specialized flatted string.
 * @param {any} value
 * @param {((this: any, key: string, value: any) => any) | (string | number)[] | null | undefined} [replacer]
 * @param {string | number | undefined} [space]
 * @returns {string}
 */
const stringify = (value, replacer, space) => {
  const $ = replacer && typeof replacer === object ?
            (k, v) => (k === '' || -1 < replacer.indexOf(k) ? v : void 0) :
            (replacer || noop);
  const known = new Map;
  const input = [];
  const output = [];
  let i = +set(known, input, $.call({'': value}, '', value));
  let firstRun = !i;
  while (i < input.length) {
    firstRun = true;
    output[i] = $stringify(input[i++], replace, space);
  }
  return '[' + output.join(',') + ']';
  function replace(key, value) {
    if (firstRun) {
      firstRun = !firstRun;
      return value;
    }
    const after = $.call(this, key, value);
    switch (typeof after) {
      case object:
        if (after === null) return after;
      case primitive:
        return known.get(after) || set(known, input, after);
    }
    return after;
  }
};
exports.stringify = stringify;

/**
 * Converts a generic value into a JSON serializable object without losing recursion.
 * @param {any} value
 * @returns {any}
 */
const toJSON = value => $parse(stringify(value));
exports.toJSON = toJSON;

/**
 * Converts a previously serialized object with recursion into a recursive one.
 * @param {any} value
 * @returns {any}
 */
const fromJSON = value => parse($stringify(value));
exports.fromJSON = fromJSON;


code:
/// <reference types="../types/index.d.ts" />

// (c) 2020-present Andrea Giammarchi

const {parse: $parse, stringify: $stringify} = JSON;
const {keys} = Object;

const Primitive = String;   // it could be Number
const primitive = 'string'; // it could be 'number'

const ignore = {};
const object = 'object';

const noop = (_, value) => value;

const primitives = value => (
  value instanceof Primitive ? Primitive(value) : value
);

const Primitives = (_, value) => (
  typeof value === primitive ? new Primitive(value) : value
);

const revive = (input, parsed, output, $) => {
  const lazy = [];
  for (let ke = keys(output), {length} = ke, y = 0; y < length; y++) {
    const k = ke[y];
    const value = output[k];
    if (value instanceof Primitive) {
      const tmp = input[value];
      if (typeof tmp === object && !parsed.has(tmp)) {
        parsed.add(tmp);
        output[k] = ignore;
        lazy.push({k, a: [input, parsed, tmp, $]});
      }
      else
        output[k] = $.call(output, k, tmp);
    }
    else if (output[k] !== ignore)
      output[k] = $.call(output, k, value);
  }
  for (let {length} = lazy, i = 0; i < length; i++) {
    const {k, a} = lazy[i];
    output[k] = $.call(output, k, revive.apply(null, a));
  }
  return output;
};

const set = (known, input, value) => {
  const index = Primitive(input.push(value) - 1);
  known.set(value, index);
  return index;
};

/**
 * Converts a specialized flatted string into a JS value.
 * @param {string} text
 * @param {(this: any, key: string, value: any) => any} [reviver]
 * @returns {any}
 */
export const parse = (text, reviver) => {
  const input = $parse(text, Primitives).map(primitives);
  const value = input[0];
  const $ = reviver || noop;
  const tmp = typeof value === object && value ?
              revive(input, new Set, value, $) :
              value;
  return $.call({'': tmp}, '', tmp);
};

/**
 * Converts a JS value into a specialized flatted string.
 * @param {any} value
 * @param {((this: any, key: string, value: any) => any) | (string | number)[] | null | undefined} [replacer]
 * @param {string | number | undefined} [space]
 * @returns {string}
 */
export const stringify = (value, replacer, space) => {
  const $ = replacer && typeof replacer === object ?
            (k, v) => (k === '' || -1 < replacer.indexOf(k) ? v : void 0) :
            (replacer || noop);
  const known = new Map;
  const input = [];
  const output = [];
  let i = +set(known, input, $.call({'': value}, '', value));
  let firstRun = !i;
  while (i < input.length) {
    firstRun = true;
    output[i] = $stringify(input[i++], replace, space);
  }
  return '[' + output.join(',') + ']';
  function replace(key, value) {
    if (firstRun) {
      firstRun = !firstRun;
      return value;
    }
    const after = $.call(this, key, value);
    switch (typeof after) {
      case object:
        if (after === null) return after;
      case primitive:
        return known.get(after) || set(known, input, after);
    }
    return after;
  }
};

/**
 * Converts a generic value into a JSON serializable object without losing recursion.
 * @param {any} value
 * @returns {any}
 */
export const toJSON = value => $parse(stringify(value));

/**
 * Converts a previously serialized object with recursion into a recursive one.
 * @param {any} value
 * @returns {any}
 */
export const fromJSON = value => parse($stringify(value));