[
  {
    "path": ".editorconfig",
    "content": "root = true\n\n[*]\nindent_style = space\nindent_size = 2\nend_of_line = lf\ncharset = utf-8\ntrim_trailing_whitespace = true\ninsert_final_newline = true\n"
  },
  {
    "path": ".eslintignore",
    "content": "/test/build/require.js\n"
  },
  {
    "path": ".eslintrc.json",
    "content": "{\n  \"root\": true,\n  \"extends\": [\"warp\"],\n  \"parserOptions\": {\n    \"ecmaVersion\": 2015,\n    \"sourceType\": \"module\"\n  },\n  \"globals\": {\n    \"setTimeout\": false,\n    \"clearTimeout\": false,\n    \"Promise\": false\n  },\n  \"rules\": {\n    \"space-before-blocks\": [2, \"never\"],\n    \"consistent-this\": [2, \"_this\"],\n    \"semi\": [2, \"always\", {\"omitLastInOneLineBlock\": true}],\n    \"curly\": [\"off\"],\n    \"func-style\": [\"off\"],\n    \"prefer-template\": [\"off\"],\n    \"prefer-arrow-callback\": [\"off\"],\n    \"no-use-before-define\": [\"off\"],\n    \"max-statements-per-line\": [\"off\"],\n    \"prefer-rest-params\": [\"off\"],\n    \"class-methods-use-this\": [\"off\"],\n    \"camelcase\": [\"off\"],\n    \"indent\": [\"off\"],\n    \"func-name-matching\": [\"off\"],\n    \"no-console\": 2,\n    \"eqeqeq\": [2, \"smart\"],\n    \"no-eq-null\": [\"off\"],\n    \"no-param-reassign\": [\"off\"],\n    \"no-shadow\": [\"off\"],\n    \"keyword-spacing\": [\"off\"],\n    \"no-plusplus\": [\"off\"],\n    \"operator-assignment\": [\"off\"],\n    \"one-var\": [\"off\"],\n    \"generator-star-spacing\": [\"error\", {\"before\": false, \"after\": false}],\n    \"no-mixed-operators\": [\"off\"],\n    \"capitalized-comments\": [\"off\"],\n    \"init-declarations\": [\"off\"],\n    \"function-call-argument-newline\": [\"off\"],\n    \"no-multi-assign\": [\"off\"],\n    \"no-invalid-this\": [\"off\"]\n  },\n  \"overrides\": [\n    {\n      \"files\": [\"test/**\"],\n      \"env\": {\"node\": true},\n      \"globals\": {\"Promise\": false},\n      \"rules\": {\n        \"arrow-body-style\": [\"off\"],\n        \"no-sequences\": [\"off\"],\n        \"max-len\": [\"off\"],\n        \"space-before-function-paren\": [\"error\", \"always\"]\n      }\n    }\n  ]\n}\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "github: [Avaq]\n"
  },
  {
    "path": ".github/dependabot.yml",
    "content": "version: 2\nupdates:\n- package-ecosystem: npm\n  directory: \"/\"\n  schedule:\n    interval: daily\n  open-pull-requests-limit: 10\n  reviewers:\n  - Avaq\n"
  },
  {
    "path": ".github/workflows/test.yml",
    "content": "name: Test\n\non:\n  pull_request:\n  push:\n    branches:\n      - master\n      - 11.x\n\njobs:\n  test:\n    runs-on: ubuntu-latest\n    steps:\n    - name: Checkout Code\n      uses: actions/checkout@v1\n    - name: Install NodeJS\n      uses: actions/setup-node@v1\n      with:\n        node-version: 18.x\n    - name: Install Dependencies\n      run: npm install\n    - name: Execute Tests\n      run: npm test\n    - name: Upload Coverage Report\n      run: npm run coverage:upload\n      env:\n        CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}\n"
  },
  {
    "path": ".gitignore",
    "content": "/bench/node_modules/\n/coverage/\n/node_modules/\n/perf/\n\n/index.cjs\n"
  },
  {
    "path": ".npmrc",
    "content": "package-lock=false\n"
  },
  {
    "path": "CHANGELOG.md",
    "content": "# Change Log\n\nPlease refer to the [release notes](https://github.com/fluture-js/Fluture/releases).\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contribution guide\n\n## Making a contribution\n\n* Fork and clone the project\n* Commit changes to a branch named after the work that was done\n* Make sure the tests pass locally\n* Create a pull request\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\nCopyright (c) 2020 Aldwin Vlasblom\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# [![Fluture](logo.png)](#butterfly)\n\n[![Build Status][]](https://github.com/fluture-js/Fluture/actions?query=branch%3Amaster+workflow%3ATest)\n[![Code Coverage][]](https://codecov.io/gh/fluture-js/Fluture/branch/master)\n[![Dependency Status][]](https://david-dm.org/fluture-js/Fluture)\n[![NPM Package][]](https://www.npmjs.com/package/fluture)\n[![Gitter Chat][]](https://gitter.im/fluture-js/Fluture)\n\n[Build Status]: https://github.com/fluture-js/Fluture/workflows/Test/badge.svg\n[Code Coverage]: https://img.shields.io/codecov/c/github/fluture-js/Fluture/master.svg\n[Dependency Status]: https://img.shields.io/david/fluture-js/Fluture.svg\n[NPM Package]: https://img.shields.io/npm/v/fluture.svg\n[Gitter Chat]: https://img.shields.io/gitter/room/fluture-js/Fluture.svg?colorB=blue\n\nFluture offers a control structure similar to Promises, Tasks, Deferreds, and\nwhat-have-you. Let's call them Futures.\n\nMuch like Promises, Futures represent the value arising from the success or\nfailure of an asynchronous operation (I/O). Though unlike Promises, Futures are\n*lazy* and adhere to [the *monadic* interface](#interoperability).\n\nSome of the features provided by Fluture include:\n\n* [Cancellation](#cancellation).\n* [Resource management utilities](#resource-management).\n* [Stack safe composition and recursion](#stack-safety).\n* [Integration](#sanctuary) with [Sanctuary][S].\n* [A pleasant debugging experience](#debugging).\n\nFor more information:\n\n* [API documentation](#documentation)\n* [Article: Introduction to Fluture - A Functional Alternative to Promises][10]\n* [Wiki: Compare Futures to Promises][wiki:promises]\n* [Wiki: Compare Fluture to similar libraries][wiki:similar]\n* [Video: Monad a Day - Futures by @DrBoolean][5]\n\n## Installation\n\n### With NPM\n\n```console\n$ npm install --save fluture\n```\n\n### Bundled from a CDN\n\nTo load Fluture directly into a browser, a code pen, or [Deno][], use one of\nthe following downloads from the JSDelivr content delivery network. These are\nsingle files that come with all of Fluture's dependencies pre-bundled.\n\n- [Fluture Script][]: A JavaScript file that adds `Fluture` to the global\n  scope. Ideal for older browsers and code pens.\n- [Fluture Script Minified][]: The same as above, but minified.\n- [Fluture Module][]: An EcmaScript module with named exports. Ideal for Deno\n  or modern browsers.\n- [Fluture Module Minified][]: A minified EcmaScript module without TypeScript\n  typings. Not recommended for Deno.\n\n[Fluture Script]: https://cdn.jsdelivr.net/gh/fluture-js/Fluture@14.0.0/dist/bundle.js\n[Fluture Script Minified]: https://cdn.jsdelivr.net/gh/fluture-js/Fluture@14.0.0/dist/bundle.min.js\n[Fluture Module]: https://cdn.jsdelivr.net/gh/fluture-js/Fluture@14.0.0/dist/module.js\n[Fluture Module Minified]: https://cdn.jsdelivr.net/gh/fluture-js/Fluture@14.0.0/dist/module.min.js\n\n## Usage\n\n### EcmaScript Module\n\nFluture is written as modular JavaScript.\n\n- On Node 12 and up, Fluture can be loaded directly with `import 'fluture'`.\n- On some older (minor) Node versions, you may need to import from\n  `'fluture/index.js'` instead, and/or pass `--experimental-modules` to `node`.\n- On Node versions below 12, the [esm loader][esm] can be used. Alternatively,\n  there is a [CommonJS Module](#commonjs-module) available.\n- Modern browsers can run Fluture directly. If you'd like to try this out,\n  I recommend installing Fluture with [Pika][] or [Snowpack][]. You can also\n  try the [bundled module](#bundled-from-a-cdn) to avoid a package manager.\n- For older browsers, use a bundler such as [Rollup][] or WebPack. Besides the\n  module system, Fluture uses purely ES5-compatible syntax, so the source does\n  not have to be transpiled after bundling. Alternatively, there is a\n  [CommonJS Module](#commonjs-module) available.\n\n```js\nimport {readFile} from 'fs'\nimport {node, encase, chain, map, fork} from 'fluture'\n\nconst getPackageName = file => (\n  node (done => { readFile (file, 'utf8', done) })\n  .pipe (chain (encase (JSON.parse)))\n  .pipe (map (x => x.name))\n)\n\ngetPackageName ('package.json')\n.pipe (fork (console.error) (console.log))\n```\n\n### CommonJS Module\n\nAlthough the Fluture source uses the EcmaScript module system,\nthe `main` file points to a CommonJS version of Fluture.\n\nOn older environments one or more of the following functions may need to be\npolyfilled: [`Object.create`][JS:Object.create],\n[`Object.assign`][JS:Object.assign] and [`Array.isArray`][JS:Array.isArray].\n\n```js\nconst fs = require ('fs')\nconst Future = require ('fluture')\n\nconst getPackageName = function (file) {\n  return Future.node (function (done) { fs.readFile (file, 'utf8', done) })\n  .pipe (Future.chain (Future.encase (JSON.parse)))\n  .pipe (Future.map (function (x) { return x.name }))\n}\n\ngetPackageName ('package.json')\n.pipe (Future.fork (console.error) (console.log))\n```\n\n## Documentation\n\n### Table of contents\n\n<details open><summary>General</summary>\n\n- [Installation instructions](#installation)\n- [Usage instructions](#usage)\n- [About the Fluture project](#butterfly)\n- [On interoperability with other libraries](#interoperability)\n- [How to read the type signatures](#type-signatures)\n- [How cancellation works](#cancellation)\n- [On stack safety](#stack-safety)\n- [Debugging with Fluture](#debugging)\n- [Casting Futures to String](#casting-futures-to-string)\n- [Usage with Sanctuary](#sanctuary)\n- [Using multiple versions of Fluture alongside each other](#incompatible-fluture-versions)\n\n</details>\n\n<details><summary>Creating new Futures</summary>\n\n- [`Future`: Create a possibly cancellable Future](#future)\n- [`resolve`: Create a resolved Future](#resolve)\n- [`reject`: Create a rejected Future](#reject)\n- [`after`: Create a Future that resolves after a timeout](#after)\n- [`rejectAfter`: Create a Future that rejects after a timeout](#rejectafter)\n- [`go`: Create a \"coroutine\" using a generator function](#go)\n- [`attempt`: Create a Future using a possibly throwing function](#attempt)\n- [`attemptP`: Create a Future using a Promise-returning function](#attemptp)\n- [`node`: Create a Future using a Node-style callback](#node)\n- [`encase`: Convert a possibly throwing function to a Future function](#encase)\n- [`encaseP`: Convert a Promise-returning function to a Future function](#encasep)\n\n</details>\n\n<details><summary>Converting between Nodeback APIs and Futures</summary>\n\n- [`node`: Create a Future using a Node-style callback](#node)\n- [`done`: Consume a Future by providing a Nodeback](#done)\n\n</details>\n\n<details><summary>Converting between Promises and Futures</summary>\n\n- [`attemptP`: Create a Future using a Promise-returning function](#attemptp)\n- [`encaseP`: Convert a Promise-returning function to a Future function](#encasep)\n- [`promise`: Convert a Future to a Promise](#promise)\n\n</details>\n\n<details><summary>Transforming and combining Futures</summary>\n\n- [`pipe`: Apply a function to a Future in a fluent method chain](#pipe)\n- [`map`: Synchronously process the success value in a Future](#map)\n- [`bimap`: Synchronously process the success or failure value in a Future](#bimap)\n- [`chain`: Asynchronously process the success value in a Future](#chain)\n- [`bichain`: Asynchronously process the success or failure value in a Future](#bichain)\n- [`swap`: Swap the success with the failure value](#swap)\n- [`mapRej`: Synchronously process the failure value in a Future](#maprej)\n- [`chainRej`: Asynchronously process the failure value in a Future](#chainrej)\n- [`coalesce`: Coerce success and failure values into the same success value](#coalesce)\n- [`ap`: Combine the success values of multiple Futures using a function](#ap)\n- [`pap`: Combine the success values of multiple Futures in parallel using a function](#pap)\n- [`and`: Logical *and* for Futures](#and)\n- [`alt`: Logical *or* for Futures](#alt)\n- [`lastly`: Run a Future after the previous settles](#lastly)\n- [`race`: Race two Futures against each other](#race)\n- [`both`: Await both success values from two Futures](#both)\n- [`parallel`: Await all success values from many Futures](#parallel)\n\n</details>\n\n<details><summary>Consuming/forking Futures</summary>\n\n- [`fork`: Standard way to run a Future and get at its result](#fork)\n- [`forkCatch`: Fork with exception recovery](#forkcatch)\n- [`value`: Shorter variant of `fork` for Futures sure to succeed](#value)\n- [`done`: Nodeback style `fork`](#done)\n- [`promise`: Convert a Future to a Promise](#promise)\n\n</details>\n\n<details><summary>Concurrency related utilities and data structures</summary>\n\n- [`pap`: Combine the success values of multiple Futures in parallel using a function](#pap)\n- [`race`: Race two Futures against each other](#race)\n- [`both`: Await both success values from two Futures](#both)\n- [`parallel`: Await all success values from many Futures](#parallel)\n- [`ConcurrentFuture`: A separate data-type for doing algebraic concurrency](#concurrentfuture)\n- [`alt`: Behaves like `race` on `ConcurrentFuture` instances](#alt)\n\n</details>\n\n<details><summary>Resource management</summary>\n\n- [`hook`: Safely create and dispose resources](#hook)\n- [`lastly`: Run a Future after the previous settles](#lastly)\n\n</details>\n\n<details><summary>Other utilities</summary>\n\n- [`pipe`: Apply a function to a Future in a fluent method chain](#pipe)\n- [`cache`: Cache a Future so that it can be forked multiple times](#cache)\n- [`isFuture`: Determine whether a value is a Fluture compatible Future](#isfuture)\n- [`never`: A Future that never settles](#never)\n- [`debugMode`: Configure Fluture's debug mode](#debugmode)\n- [`context`: The debugging context of a Future instance](#context)\n\n</details>\n\n### Butterfly\n\nThe name \"Fluture\" is a conjunction of \"FL\" (the acronym to [Fantasy Land][FL])\nand \"future\". Fluture means butterfly in Romanian: A creature one might expect\nto see in Fantasy Land.\n\nCredit goes to Erik Fuente for styling the logo, and [WEAREREASONABLEPEOPLE][9]\nfor sponsoring the project.\n\n### Interoperability\n\n[<img src=\"https://raw.github.com/fantasyland/fantasy-land/master/logo.png\" align=\"right\" width=\"82\" height=\"82\" alt=\"Fantasy Land\" />][FL]\n\n* `Future` implements [Fantasy Land][FL] 1.0+ -compatible\n  `Alt`, `Bifunctor`, `Monad`, and `ChainRec`\n  (`of`, `ap`, `alt`, `map`, `bimap`, `chain`, `chainRec`).\n* `Future.Par` implements [Fantasy Land 3][FL] -compatible\n  `Alternative` (`of`, `zero`, `map`, `ap`, `alt`).\n* The Future and ConcurrentFuture representatives contain `@@type` properties\n  for [Sanctuary Type Identifiers][STI].\n* The Future and ConcurrentFuture instances contain `@@show` properties for\n  [Sanctuary Show][SS].\n\n### Type signatures\n\nThe various function signatures are provided in a small language referred to as\nHindley-Milner notation.\n\nIn summary, the syntax is as follows: `InputType -> OutputType`. Now,\nbecause functions in Fluture are [curried][Guide:currying], the \"output\" of a\nfunction is often *another function*. In Hindley-Milner that's simply written\nas `InputType -> InputToSecondFunction -> OutputType` and so forth.\n\nBy convention, types starting with an upper-case letter are\n[concrete types](#types). When they start with a lower-case letter they're\n*type variables*. You can think of these type variables as generic types.\nSo `a -> b` denotes a function from generic type `a` to generic type `b`.\n\nFinally, through so-called [*constraints*](#type-classes), type variables can\nbe forced to conform to an \"interface\" (or *Type Class* in functional jargon).\nFor example, `MyInterface a => a -> b`, denotes a function from generic type\n`a` to generic type `b`, *where `a` must implement `MyInterface`*.\n\nYou can read in depth about [Hindley-Milner in JavaScript][Guide:HM] here.\n\n#### Types\n\nThe concrete types you will encounter throughout this documentation:\n\n- **Future** - Instances of Future provided by\n  [compatible versions](#incompatible-fluture-versions) of Fluture.\n- **ConcurrentFuture** - Futures wrapped with ([`Future.Par`](#concurrentfuture)).\n- **Promise a b** - Values which conform to the [Promises/A+ specification][7]\n  and have a rejection reason of type `a` and a resolution value of type `b`.\n- **Nodeback a b** - A Node-style callback; A function of signature `(a | Nil, b) -> x`.\n- **Pair a b** - An array with exactly two elements: `[a, b]`.\n- **Iterator** - Objects with `next`-methods which conform to the [Iterator protocol][3].\n- **Cancel** - The nullary [cancellation](#cancellation) functions returned from computations.\n- **Throwing e a b** - A function from `a` to `b` that may throw an exception `e`.\n- **List** - Fluture's internal linked-list structure: `{ head :: Any, tail :: List }`.\n- **Context** - Fluture's internal debugging context object:\n  `{ tag :: String, name :: String, stack :: String }`.\n\n#### Type classes\n\nSome signatures contain [constrained type variables][Guide:constraints].\nGenerally, these constraints express that some value must conform to a\n[Fantasy Land][FL]-specified interface.\n\n- **Functor** - [Fantasy Land Functor][FL:functor] conformant values.\n- **Bifunctor** - [Fantasy Land Bifunctor][FL:bifunctor] conformant values.\n- **Chain** - [Fantasy Land Chain][FL:chain] conformant values.\n- **Apply** - [Fantasy Land Apply][FL:apply] conformant values.\n- **Alt** - [Fantasy Land Alt][FL:alt] conformant values.\n\n### Cancellation\n\nCancellation is a system whereby running Futures get an opportunity to stop\nwhat they're doing and release resources that they were holding, when the\nconsumer indicates it is no longer interested in the result.\n\nTo cancel a Future, it must be unsubscribed from. Most of the\n[consumption functions](#consuming-futures) return an `unsubscribe` function.\nCalling it signals that we are no longer interested in the result. After\ncalling `unsubscribe`, Fluture guarantees that our callbacks will not be\ncalled; but more importantly: a cancellation signal is sent upstream.\n\nThe cancellation signal travels all the way back to the source (with the\nexception of cached Futures - see [`cache`](#cache)), allowing all parties\nalong the way to clean up.\n\nWith the [`Future` constructor](#future), we can provide a custom cancellation\nhandler by returning it from the computation. Let's see what this looks like:\n\n```js\n// We use the Future constructor to create a Future instance.\nconst eventualAnswer = Future (function computeTheAnswer (rej, res) {\n\n  // We give the computer time to think about the answer, which is 42.\n  const timeoutId = setTimeout (res, 60000, 42)\n\n  // Here is how we handle cancellation. This signal is received when nobody\n  // is interested in the answer any more.\n  return function onCancel () {\n    // Clearing the timeout releases the resources we were holding.\n    clearTimeout (timeoutId)\n  }\n\n})\n\n// Now, let's fork our computation and wait for an answer. Forking gives us\n// the unsubscribe function.\nconst unsubscribe = fork (log ('rejection')) (log ('resolution')) (eventualAnswer)\n\n// After some time passes, we might not care about the answer any more.\n// Calling unsubscribe will send a cancellation signal back to the source,\n// and trigger the onCancel function.\nunsubscribe ()\n```\n\nMany natural sources in Fluture have cancellation handlers of their own.\n[`after`](#after), for example, does exactly what we've done just now: calling\n`clearTimeout`.\n\nFinally, Fluture unsubscribes from Futures that it forks *for us*, when it no\nlonger needs the result. For example, both Futures passed into [race](#race)\nare forked, but once one of them produces a result, the other is unsubscribed\nfrom, triggering cancellation. This means that generally, unsubscription and\ncancellation is fully managed for us behind the scenes.\n\n### Stack safety\n\nFluture interprets our transformations in a stack safe way.\nThis means that none of the following operations result in a\n`RangeError: Maximum call stack size exceeded`:\n\n```js\n> const add1 = x => x + 1\n\n> let m = resolve (1)\n\n> for (let i = 0; i < 100000; i++) {\n.   m = map (add1) (m)\n. }\n\n> fork (log ('rejection')) (log ('resolution')) (m)\n[resolution]: 100001\n```\n\n```js\n> const m = (function recur (x) {\n.   const mx = resolve (x + 1)\n.   return x < 100000 ? chain (recur) (mx) : mx\n. }(1))\n\n> fork (log ('rejection')) (log ('resolution')) (m)\n[resolution]: 100001\n```\n\nTo learn more about memory and stack usage under different types of recursion,\nsee (or execute) [`scripts/test-mem`](scripts/test-mem).\n\n### Debugging\n\nFirst and foremost, Fluture type-checks all of its input and throws TypeErrors\nwhen incorrect input is provided. The messages they carry are designed to\nprovide enough insight to figure out what went wrong.\n\nSecondly, Fluture catches exceptions that are thrown asynchronously, and\nexposes them to you in one of two ways:\n\n1. By throwing an Error when it happens.\n2. By calling your [exception handler](#forkcatch) with an Error.\n\nThe original exception isn't used because it might have been any value.\nInstead, a regular JavaScript Error instance whose properties are based on the\noriginal exception is created. Its properties are as follows:\n\n- `name`: Always just `\"Error\"`.\n- `message`: The original error message, or a message describing the value.\n- `reason`: The original value that was caught by Fluture.\n- `context`: A linked list of \"context\" objects. This is used to create the\n  `stack` property, and you generally don't need to look at it. If debug mode\n  is not enabled, the list is always empty.\n- `stack`: The stack trace of the original exception if it had one, or the\n  Error's own stack trace otherwise. If debug mode (see below) is enabled,\n  additional stack traces from the steps leading up to the crash are included.\n- `future`: The instance of [`Future`](#future) that was being\n  [consumed](#consuming-futures) when the exception happened. Often\n  [printing it as a String](#casting-futures-to-string) can yield useful\n  information. You can also try to consume it in isolation to better identify\n  what's going wrong.\n\nFinally, as mentioned, Fluture has a [debug mode](#debugmode) wherein\nadditional contextual information across multiple JavaScript ticks is\ncollected, included as an extended \"async stack trace\" on Errors, and\n[exposed on Future instances](#context).\n\nDebug mode can have a significant impact on performance, and uses up memory,\nso I would advise against using it in production.\n\n### Casting Futures to String\n\nThere are multiple ways to print a Future to String. Let's take a simple\ncomputation as an example:\n\n```js\nconst add = a => b => a + b;\nconst eventualAnswer = ap (resolve (22)) (map (add) (resolve (20)));\n```\n\n1. Casting it to String directly by calling `String(eventualAnswer)` or\n   `eventualAnswer.toString()` will yield an approximation of the code that\n   was used to create the Future. In this case:\n\n   ```js\n   \"ap (resolve (22)) (map (a => b => a + b) (resolve (20)))\"\n   ```\n\n2. Casting it to String using `JSON.stringify(eventualAnswer, null, 2)` will\n   yield a kind of abstract syntax tree.\n\n   ```json\n   {\n     \"$\": \"fluture/Future@5\",\n     \"kind\": \"interpreter\",\n     \"type\": \"transform\",\n     \"args\": [\n       {\n         \"$\": \"fluture/Future@5\",\n         \"kind\": \"interpreter\",\n         \"type\": \"resolve\",\n         \"args\": [\n           20\n         ]\n       },\n       [\n         {\n           \"$\": \"fluture/Future@5\",\n           \"kind\": \"transformation\",\n           \"type\": \"ap\",\n           \"args\": [\n             {\n               \"$\": \"fluture/Future@5\",\n               \"kind\": \"interpreter\",\n               \"type\": \"resolve\",\n               \"args\": [\n                 22\n               ]\n             }\n           ]\n         },\n         {\n           \"$\": \"fluture/Future@5\",\n           \"kind\": \"transformation\",\n           \"type\": \"map\",\n           \"args\": [\n             null\n           ]\n         }\n       ]\n     ]\n   }\n   ```\n\n### Sanctuary\n\nWhen using this module with [Sanctuary Def][$] (and [Sanctuary][S] by\nextension) one might run into the following issue:\n\n```js\n> import S from 'sanctuary'\n\n> import {resolve} from 'fluture'\n\n> S.I (resolve (1))\n! TypeError: Since there is no type of which all the above values are members,\n. the type-variable constraint has been violated.\n```\n\nThis happens because Sanctuary Def needs to know about the types created by\nFluture to determine whether the type-variables are consistent.\n\nTo let Sanctuary know about these types, we can obtain the type definitions\nfrom [`fluture-sanctuary-types`][FST] and pass them to [`S.create`][S:create]:\n\n```js\n> import sanctuary from 'sanctuary'\n\n> import {env as flutureEnv} from 'fluture-sanctuary-types'\n\n> import {resolve} from 'fluture'\n\n> const S = sanctuary.create ({checkTypes: true, env: sanctuary.env.concat (flutureEnv)})\n\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (S.I (resolve (42)))\n[resolution]: 42\n```\n\n### Incompatible Fluture Versions\n\nMost versions of Fluture understand how to consume instances from most other\nversions, even across Fluture's major releases. This allows for different\npackages that depend on Fluture to interact.\n\nHowever, sometimes it's unavoidable that a newer version of Fluture is released\nthat can no longer understand older versions, and vice-versa. This only ever\nhappens on a major release, and will be mentioned in the breaking change log.\nWhen two incompatible versions of Fluture meet instances, they do their best to\nissue a clear error message about it.\n\nWhen this happens, you need to manually convert the older instance to a newer\ninstance of Future. When [`isFuture`](#isfuture) returns `false`, a conversion\nis necessary. You can also apply this trick if the Future comes from another\nlibrary similar to Fluture.\n\n```js\nconst NoFuture = require ('incompatible-future')\n\nconst incompatible = NoFuture.of ('Hello')\n\nconst compatible = Future ((rej, res) => {\n  return NoFuture.fork (rej) (res) (incompatible)\n})\n\nboth (compatible) (resolve ('world'))\n```\n\n### Creating Futures\n\n#### Future\n\n```hs\nFuture :: ((a -> Undefined, b -> Undefined) -> Cancel) -> Future a b\n```\n\nCreates a Future with the given computation. A computation is a function which\ntakes two callbacks. Both are continuations for the computation. The first is\n`reject`, commonly abbreviated to `rej`; The second is `resolve`, or `res`.\nWhen the computation is finished (possibly asynchronously) it may call the\nappropriate continuation with a failure or success value.\n\nAdditionally, the computation must return a nullary function containing\ncancellation logic. See [Cancellation](#cancellation).\n\nIf you find that there is no way to cancel your computation, you can return a\n`noop` function as a cancellation function. However, at this point there is\nusually a more fitting way to [create that Future](#creating-futures)\n(like for example via [`node`](#node)).\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (Future (function computation (reject, resolve) {\n.        const t = setTimeout (resolve, 20, 42)\n.        return () => clearTimeout (t)\n.      }))\n[resolution]: 42\n```\n\n#### resolve\n\n```hs\nresolve :: b -> Future a b\n```\n\nCreates a Future which immediately resolves with the given value.\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (resolve (42))\n[answer]: 42\n```\n\n#### reject\n\n```hs\nreject :: a -> Future a b\n```\n\nCreates a Future which immediately rejects with the given value.\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (reject ('It broke!'))\n[rejection]: \"It broke!\"\n```\n\n#### after\n\n```hs\nafter :: Number -> b -> Future a b\n```\n\nCreates a Future which resolves with the given value after\nthe given number of milliseconds.\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (after (20) (42))\n[resolution]: 42\n```\n\n#### rejectAfter\n\n```hs\nrejectAfter :: Number -> a -> Future a b\n```\n\nCreates a Future which rejects with the given reason after the given number of\nmilliseconds.\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (rejectAfter (20) ('It broke!'))\n[rejection]: \"It broke!\"\n```\n\n#### go\n\n```hs\ngo :: (() -> Iterator) -> Future a b\n```\n\nA way to do `async`/`await` with Futures, similar to Promise Coroutines or\nHaskell Do-notation.\n\nTakes a function which returns an [Iterator](#types), commonly a\ngenerator-function, and chains every produced Future over the previous.\n\n```js\n> fork (log ('rejection')) (log ('resolution')) (go (function*() {\n.   const thing = yield after (20) ('world')\n.   const message = yield after (20) ('Hello ' + thing)\n.   return message + '!'\n. }))\n[resolution]: \"Hello world!\"\n```\n\nA rejected Future short-circuits the whole coroutine.\n\n```js\n> fork (log ('rejection')) (log ('resolution')) (go (function*() {\n.   const thing = yield reject ('It broke!')\n.   const message = yield after (20) ('Hello ' + thing)\n.   return message + '!'\n. }))\n[rejection]: \"It broke!\"\n```\n\nTo handle rejections *inside* the coroutine, we need to [`coalesce`](#coalesce)\nthe error into our control domain.\n\nI recommend using coalesce with an [`Either`][S:Either].\n\n```js\n> const control = coalesce (S.Left) (S.Right)\n\n> fork (log ('rejection')) (log ('resolution')) (go (function*() {\n.   const thing = yield control (reject ('It broke!'))\n.   return S.either (x => `Oh no! ${x}`)\n.                   (x => `Yippee! ${x}`)\n.                   (thing)\n. }))\n[resolution]: \"Oh no! It broke!\"\n```\n\n#### attempt\n\n```hs\nattempt :: Throwing e Undefined r -> Future e r\n```\n\nCreates a Future which resolves with the result of calling the given function,\nor rejects with the error thrown by the given function.\n\nShort for [`encase (f) (undefined)`](#encase).\n\n```js\n> const data = {foo: 'bar'}\n\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (attempt (() => data.foo.bar.baz))\n[rejection]: new TypeError (\"Cannot read property 'baz' of undefined\")\n```\n\n#### attemptP\n\n```hs\nattemptP :: (Undefined -> Promise a b) -> Future a b\n```\n\nCreate a Future which when forked spawns a Promise using the given function and\nresolves with its resolution value, or rejects with its rejection reason.\n\nShort for [`encaseP (f) (undefined)`](#encasep).\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (attemptP (() => Promise.resolve (42)))\n[resolution]: 42\n```\n\n#### node\n\n```hs\nnode :: (Nodeback e r -> x) -> Future e r\n```\n\nCreates a Future which rejects with the first argument given to the function,\nor resolves with the second if the first is not present.\n\nNote that this function **does not support cancellation**.\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (node (done => done (null, 42)))\n[resolution]: 42\n```\n\n#### encase\n\n```hs\nencase :: Throwing e a r -> a -> Future e r\n```\n\nTakes a function and a value, and returns a Future which when forked calls the\nfunction with the value and resolves with the result. If the function throws\nan exception, it is caught and the Future will reject with the exception.\n\nApplying `encase` with a function `f` creates a \"safe\" version of `f`. Instead\nof throwing exceptions, the encased version always returns a Future.\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (encase (JSON.parse) ('{\"foo\" = \"bar\"}'))\n[rejection]: new SyntaxError ('Unexpected token =')\n```\n\n#### encaseP\n\n```hs\nencaseP :: (a -> Promise e r) -> a -> Future e r\n```\n\nTurns Promise-returning functions into Future-returning functions.\n\nTakes a function which returns a Promise, and a value, and returns a Future.\nWhen forked, the Future calls the function with the value to produce the\nPromise, and resolves with its resolution value, or rejects with its rejection\nreason.\n\n```js\n> encaseP (fetch) ('https://api.github.com/users/Avaq')\n. .pipe (chain (encaseP (res => res.json ())))\n. .pipe (map (user => user.name))\n. .pipe (fork (log ('rejection')) (log ('resolution')))\n[resolution]: \"Aldwin Vlasblom\"\n```\n\n### Transforming Futures\n\n#### map\n\n```hs\nmap :: Functor m => (a -> b) -> m a -> m b\n```\n\nTransforms the resolution value inside the Future or [Functor][FL:functor],\nand returns a Future or Functor with the new value. The transformation is only\napplied to the resolution branch: if the Future is rejected, the transformation\nis ignored.\n\nSee also [`chain`](#chain) and [`mapRej`](#maprej).\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (map (x => x + 1) (resolve (41)))\n[resolution]: 42\n```\n\nFor comparison, an approximation with Promises is:\n\n```js\n> Promise.resolve (41)\n. .then (x => x + 1)\n. .then (log ('resolution'), log ('rejection'))\n[resolution]: 42\n```\n\n#### bimap\n\n```hs\nbimap :: Bifunctor m => (a -> c) -> (b -> d) -> m a b -> m c d\n```\n\nMaps the left function over the rejection reason, or the right function over\nthe resolution value, depending on which is present. Can be used on any\n[Bifunctor][FL:bifunctor].\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (bimap (x => x + '!') (x => x + 1) (resolve (41)))\n[resolution]: 42\n\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (bimap (x => x + '!') (x => x + 1) (reject ('It broke!')))\n[rejection]: \"It broke!!\"\n```\n\nFor comparison, an approximation with Promises is:\n\n```js\n> Promise.resolve (41)\n. .then (x => x + 1, x => Promise.reject (x + '!'))\n. .then (log ('resolution'), log ('rejection'))\n[resolution]: 42\n\n> Promise.reject ('It broke!')\n. .then (x => x + 1, x => Promise.reject (x + '!'))\n. .then (log ('resolution'), log ('rejection'))\n[rejection]: \"It broke!!\"\n```\n\n#### chain\n\n```hs\nchain :: Chain m => (a -> m b) -> m a -> m b\n```\n\nSequence a new Future or [Chain][FL:chain] using the resolution value from\nanother. Similarly to [`map`](#map), `chain` expects a function. But instead\nof returning the new *value*, chain expects a Future (or instance of the same\nChain) to be returned.\n\nThe transformation is only applied to the resolution branch: if the Future is\nrejected, the transformation is ignored.\n\nSee also [`chainRej`](#chainrej).\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (chain (x => resolve (x + 1)) (resolve (41)))\n[resolution]: 42\n```\n\nFor comparison, an approximation with Promises is:\n\n```js\n> Promise.resolve (41)\n. .then (x => Promise.resolve (x + 1))\n. .then (log ('resolution'), log ('rejection'))\n[resolution]: 42\n```\n\n#### bichain\n\n```hs\nbichain :: (a -> Future c d) -> (b -> Future c d) -> Future a b -> Future c d\n```\n\nSequence a new Future using either the resolution or the rejection value from\nanother. Similarly to [`bimap`](#bimap), `bichain` expects two functions. But\ninstead of returning the new *value*, bichain expects Futures to be returned.\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (bichain (resolve) (x => resolve (x + 1)) (resolve (41)))\n[resolution]: 42\n\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (bichain (x => resolve (x + 1)) (resolve) (reject (41)))\n[resolution]: 42\n```\n\nFor comparison, an approximation with Promises is:\n\n```js\n> Promise.resolve (41)\n. .then (x => Promise.resolve (x + 1), Promise.resolve)\n. .then (log ('resolution'), log ('rejection'))\n[resolution]: 42\n\n> Promise.reject (41)\n. .then (Promise.resolve, x => Promise.resolve (x + 1))\n. .then (log ('resolution'), log ('rejection'))\n[resolution]: 42\n```\n\n#### swap\n\n```hs\nswap :: Future a b -> Future b a\n```\n\nSwap the rejection and resolution branches.\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (swap (resolve (42)))\n[rejection]: 42\n\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (swap (reject (42)))\n[resolution]: 42\n```\n\n#### mapRej\n\n```hs\nmapRej :: (a -> c) -> Future a b -> Future c b\n```\n\nMap over the **rejection** reason of the Future. This is like [`map`](#map),\nbut for the rejection branch.\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (mapRej (s => `Oh no! ${s}`) (reject ('It broke!')))\n[rejection]: \"Oh no! It broke!\"\n```\n\nFor comparison, an approximation with Promises is:\n\n```js\n> Promise.reject ('It broke!')\n. .then (null, s => Promise.reject (`Oh no! ${s}`))\n. .then (log ('resolution'), log ('rejection'))\n[rejection]: \"Oh no! It broke!\"\n```\n\n#### chainRej\n\n```hs\nchainRej :: (a -> Future c b) -> Future a b -> Future c b\n```\n\nChain over the **rejection** reason of the Future. This is like\n[`chain`](#chain), but for the rejection branch.\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (chainRej (s => resolve (`${s} But it's all good.`)) (reject ('It broke!')))\n[resolution]: \"It broke! But it's all good.\"\n```\n\nFor comparison, an approximation with Promises is:\n\n```js\n> Promise.reject ('It broke!')\n. .then (null, s => `${s} But it's all good.`)\n. .then (log ('resolution'), log ('rejection'))\n[resolution]: \"It broke! But it's all good.\"\n```\n\n#### coalesce\n\n```hs\ncoalesce :: (a -> c) -> (b -> c) -> Future a b -> Future d c\n```\n\nApplies the left function to the rejection value, or the right function to the\nresolution value, depending on which is present, and resolves with the result.\n\nThis provides a convenient means to ensure a Future is always resolved. It can\nbe used with other type constructors, like [`S.Either`][S:Either], to maintain\na representation of failure.\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (coalesce (S.Left) (S.Right) (resolve ('hello'))\n[resolution]: Right (\"hello\")\n\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (coalesce (S.Left) (S.Right) (reject ('It broke!'))\n[resolution]: Left (\"It broke!\")\n```\n\nFor comparison, an approximation with Promises is:\n\n```js\n> Promise.resolve ('hello')\n. .then (S.Right, S.Left)\n. .then (log ('resolution'), log ('rejection'))\n[resolution]: Right (\"hello\")\n\n> Promise.reject ('It broke!')\n. .then (S.Right, S.Left)\n. .then (log ('resolution'), log ('rejection'))\n[resolution]: Left (\"It broke!\")\n```\n\n### Combining Futures\n\n#### ap\n\n```hs\nap :: Apply m => m a -> m (a -> b) -> m b\n```\n\nApplies the function contained in the right-hand Future or [Apply][FL:apply]\nto the value contained in the left-hand Future or Apply. This process can be\nrepeated to gradually fill out multiple function arguments of a curried\nfunction, as shown below.\n\nNote that the Futures will be executed in sequence - not in parallel\\* -\nbecause of the Monadic nature of Futures. The execution order is, as\nspecified by Fantasy Land, `m (a -> b)` first followed by `m a`.\nSo that's *right before left*.\n\n\\* Have a look at [`pap`](#pap) for an `ap` function that runs its arguments\n   in parallel. If you must use `ap` (because you're creating a generalized\n   function), but still want Futures passed into it to run in parallel, then\n   you could use [ConcurrentFuture](#concurrentfuture) instead.\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (ap (resolve (7)) (ap (resolve (49)) (resolve (x => y => x - y))))\n[resolution]: 42\n```\n\n#### pap\n\n```hs\npap :: Future a b -> Future a (b -> c) -> Future a c\n```\n\nHas the same signature and function as [`ap`](#ap), but runs the two Futures\ngiven to it in parallel. See also [ConcurrentFuture](#concurrentfuture) for a\nmore general way to achieve this.\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (pap (resolve (7)) (pap (resolve (49)) (resolve (x => y => x - y))))\n[resolution]: 42\n```\n\n#### alt\n\n```hs\nalt :: Alt f => f a -> f a -> f a\n```\n\nSelect one of two [Alts](#types).\n\nBehaves like logical *or* on [`Future`](#future) instances, returning a new\nFuture which either resolves with the first resolution value, or rejects with\nthe last rejection reason. We can use it if we want a computation to run only\nif another has failed.\n\nNote that the Futures will be executed in sequence - not in parallel\\* -\nbecause of the Monadic nature of Futures. The *right* Future is evaluated\nbefore the *left* Future.\n\nSee also [`and`](#and) and [`lastly`](#lastly).\n\n\\* If you'd like to use a parallel implementation of `alt`, you could simply\n   use [`race`](#race). Alternatively you could wrap your Future instances\n   with [`Par`](#concurrentfuture) before passing them to `alt`.\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (alt (resolve ('left')) (resolve ('right')))\n[resolution]: \"right\"\n\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (alt (resolve ('left')) (reject ('It broke!')))\n[resolution]: \"left\"\n```\n\n#### and\n\n```hs\nand :: Future a c -> Future a b -> Future a c\n```\n\nLogical *and* for Futures.\n\nReturns a new Future which either rejects with the first rejection reason, or\nresolves with the last resolution value once and if both Futures resolve. We\ncan use it if we want a computation to run only after another has succeeded.\nThe *right* Future is evaluated before the *left* Future.\n\nSee also [`alt`](#alt) and [`lastly`](#lastly).\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (and (resolve ('left')) (resolve ('right')))\n[resolution]: \"left\"\n\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (and (resolve ('left')) (reject ('It broke!')))\n[rejection]: \"It broke!\"\n```\n\n#### lastly\n\n```hs\nlastly :: Future a c -> Future a b -> Future a b\n```\n\nRun a second Future after the first settles (successfully or unsuccessfully).\nRejects with the rejection reason from the first or second Future, or resolves\nwith the resolution value from the first Future. This can be used to run a\ncomputation after another settles, successfully or unsuccessfully.\n\nIf you're looking to clean up resources after running a computation which\nacquires them, you should use [`hook`](#hook), which has many more fail-safes\nin place.\n\nSee also [`and`](#and) and [`alt`](#alt).\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (lastly (encase (log ('lastly')) ('All done!')) (resolve (42)))\n[lastly]: \"All done!\"\n[resolution]: 42\n```\n\n### Consuming Futures\n\n#### fork\n\n```hs\nfork :: (a -> Any) -> (b -> Any) -> Future a b -> Cancel\n```\n\nExecute the computation represented by a Future, passing `reject` and `resolve`\ncallbacks to continue once there is a result.\n\nThis function is called `fork` because it literally represents a fork in our\nprogram: a point where a single code-path splits in two. It is recommended to\nkeep the number of calls to `fork` at a minimum for this reason. The more\nforks, the higher the code complexity.\n\nGenerally, one only needs to call `fork` in a single place in the entire\nprogram.\n\nAfter we `fork` a Future, the computation will start running. If the program\ndecides halfway through that it's no longer interested in the result of the\ncomputation, it can call the `unsubscribe` function returned by `fork`. See\n[Cancellation](#cancellation).\n\nIf an exception was encountered during the computation, it will be re-thrown\nby `fork` and likely not be catchable. You can handle it using\n`process.on('uncaughtException')` in Node, or use [`forkCatch`](#forkcatch).\n\nAlmost all code examples in Fluture use `fork` to run the computation. There\nare some variations on `fork` that serve different purposes below.\n\n#### forkCatch\n\n```hs\nforkCatch :: (Error -> Any) -> (a -> Any) -> (b -> Any) -> Future a b -> Cancel\n```\n\nAn advanced version of [fork](#fork) that allows us to react to a fatal error\nin a custom way. Fatal errors occur when unexpected exceptions are thrown, when\nthe Fluture API is used incorrectly, or when resources couldn't be disposed.\n\nThe exception handler will always be called with an instance of `Error`,\nindependent of what caused the crash.\n\n**Using this function is a trade-off;**\n\nGenerally it's best to let a program crash and restart when an a fatal error\noccurs. Restarting is the surest way to restore the memory that was allocated\nby the program to an expected state.\n\nBy using `forkCatch`, we can keep our program alive after a fatal error, which\ncan be very beneficial when the program is being used by multiple clients.\nHowever, since fatal errors might indicate that something, somewhere has\nentered an invalid state, it's probably still best to restart our program upon\nencountering one.\n\nSee [Debugging](#debugging) for information about the Error object that is\npassed to your exception handler.\n\n```js\n> forkCatch (log ('fatal error'))\n.           (log ('rejection'))\n.           (log ('resolution'))\n.           (map (x => x.foo) (resolve (null)))\n[fatal error]: new Error (\"Cannot read property 'foo' of null\")\n```\n\n#### value\n\n```hs\nvalue :: (b -> Any) -> Future a b -> Cancel\n```\n\nLike [`fork`](#fork) but for the resolution branch only. Only use this function\nif you are sure the Future is going to be resolved, for example; after using\n[`coalesce`](#coalesce). If the Future rejects, `value` will throw an Error.\n\nAs with [`fork`](#fork), `value` returns an `unsubscribe` function. See\n[Cancellation](#cancellation).\n\n```js\n> value (log ('resolution')) (resolve (42))\n[resolution]: 42\n```\n\n#### done\n\n```hs\ndone :: Nodeback a b -> Future a b -> Cancel\n```\n\nRun the Future using a [Nodeback](#types) as the continuation.\n\nThis is like [`fork`](#fork), but instead of taking two unary functions, it\ntakes a single binary function.\n\nAs with [`fork`](#fork), `done` returns an `unsubscribe` function. See\n[Cancellation](#cancellation).\n\n```js\n> done ((err, val) => log ('resolution') (val)) (resolve (42))\n[resolution]: 42\n```\n\n#### promise\n\n```hs\npromise :: Future Error a -> Promise Error a\n```\n\nRun the Future and get a Promise to represent its continuation.\n\nReturns a Promise which resolves with the resolution value, or rejects with\nthe rejection reason of the Future.\n\nIf an exception was encountered during the computation, the promise will reject\nwith it. I recommend using [`coalesce`](#coalesce) before `promise` to ensure\nthat exceptions and rejections are not mixed into the Promise rejection branch.\n\nCancellation capabilities are lost when using `promise` to consume the Future.\n\n```js\n> promise (resolve (42)) .then (log ('resolution'))\n[resolution]: 42\n\n> promise (reject ('failure')) .then (log ('resolution'), log ('rejection'))\n[rejection]: \"failure\"\n```\n\n### Parallelism\n\n#### race\n\n```hs\nrace :: Future a b -> Future a b -> Future a b\n```\n\nRace two Futures against each other. Creates a new Future which resolves or\nrejects with the resolution or rejection value of the first Future to settle.\n\nWhen one Future settles, the other gets cancelled automatically.\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (race (after (15) ('left')) (after (30) ('right')))\n[resolution]: \"left\"\n```\n\n#### both\n\n```hs\nboth :: Future a b -> Future a c -> Future a (Pair b c)\n```\n\nRun two Futures in parallel and get a [`Pair`](#types) of the results. When\neither Future rejects, the other Future will be cancelled and the resulting\nFuture will reject.\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (both (after (15) ('left')) (after (30) ('right')))\n[resolution]: [\"left\", \"right\"]\n```\n\n#### parallel\n\n```hs\nparallel :: PositiveInteger -> Array (Future a b) -> Future a (Array b)\n```\n\nCreates a Future which when forked runs all Futures in the given Array in\nparallel, ensuring no more than `limit` Futures are running at once.\n\nIn the following example, we're running up to 5 Futures in parallel. Every\nFuture takes about 20ms to settle, which means the result should appear after\nabout 40ms.\n\nIf we use `1` for the limit, the Futures would run in sequence, causing the\nresult to appear only after 200ms.\n\nWe can also use `Infinity` as the limit. This would create a function similar\nto `Promise.all`, which always runs all Futures in parallel. This can easily\ncause the computation to consume too many resources, however, so I would\nadvise using a number roughly equal to maximum size of Array you think your\nprogram should handle.\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (parallel (5) (Array.from (Array (10) .keys ()) .map (after (20))))\n[resolution]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n```\n\nWhen one Future rejects, all currently running Futures will be cancelled and\nthe resulting Future will reject. If you want to settle all Futures, even if\nsome may fail, you can use `parallel` in combination with\n[coalesce](#coalesce).\n\n```js\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (parallel (2) ([resolve (42), reject ('It broke!')]\n.                     .map (coalesce (S.Left) (S.Right))))\n[resolution]: [Right (42), Left (\"It broke!\")]\n```\n\n#### ConcurrentFuture\n\nThe `ConcurrentFuture` type is very similar to the `Future` type, except that\nit has *parallel* semantics where `Future` has *sequential* semantics.\n\nThese sematics are most notable in the implementation of Applicative for\n`ConcurrentFuture`. When using [`ap`](#ap) on two ConcurrentFutures, they\nrun parallely, whereas regular `Future` instances would've run sequentially.\nThis means that `ConcurrentFuture` cannot be a Monad, which is why we have\nit as a separate type.\n\nThe implementation of Alternative on `ConcurrentFuture` has parallel semantics\nas well. Whereas [`alt`](#alt) on regular Futures uses the failure effect to\ndetermine a winner, on ConcurrentFutures *timing* is used, and the winner will\nbe whichever ConcurrentFuture settled first.\n\nThe idea is that we can switch back and forth between `Future` and\n`ConcurrentFuture`, using [`Par`](#par) and [`seq`](#seq), to get sequential or\nconcurrent behaviour respectively. It's a useful type to pass to abstractions\nthat don't know about Future-specific functions like [`parallel`](#parallel) or\n[`race`](#race), but *do* know how to operate on Apply and Alternative.\n\n```js\n//Some dummy values\nconst x = 41;\nconst f = a => a + 1;\n\n//The following two are equal ways to construct a ConcurrentFuture\nconst parx = S.of (Par) (x)\nconst parf = Par (S.of (Future) (f))\n\n//We can make use of parallel apply\nvalue (log ('resolution')) (seq (ap (parx) (parf)))\n[resolution]: 42\n\n//Concurrent sequencing\nvalue (log ('resolution')) (seq (S.sequence (Par) ([parx, parx, parx])))\n[resolution]: [41, 41, 41]\n\n//And concurrent alt\nvalue (log ('resolution')) (alt (after (15) ('left')) (after (30) ('right')))\n[resolution]: \"left\"\n```\n\n##### Par\n\n```hs\nPar :: Future a b -> ConcurrentFuture a b\n```\n\nConverts a Future to a ConcurrentFuture.\n\n##### seq\n\nConverts a ConcurrentFuture to a Future.\n\n```hs\nseq :: ConcurrentFuture a b -> Future a b\n```\n\n### Resource management\n\nFunctions listed under this category allow for more fine-grained control over\nthe flow of acquired values.\n\n#### hook\n\n```hs\nhook :: Future a b -> (b -> Future c d) -> (b -> Future a e) -> Future a e\n```\n\nCombines resource acquisition, consumption, and disposal in such a way that you\ncan be sure that a resource will always be disposed if it was acquired, even if\nan exception is thrown during consumption; Sometimes referred to as bracketing.\n\nThe signature is like `hook (acquire, dispose, consume)`, where:\n\n- `acquire` is a Future which might create connections, open files, etc.\n- `dispose` is a function that takes the result from `acquire` and should be\n  used to clean up (close connections etc). The Future it returns must\n  resolve, and its resolution value is ignored. If it rejects, a fatal error\n  is raised which can only be handled with [`forkCatch`](#forkcatch).\n- `consume` is another Function takes the result from `acquire`, and may be\n  used to perform any arbitrary computations using the resource.\n\nTypically, you'd want to partially apply this function with the first two\narguments (acquisition and disposal), as shown in the example.\n\n```js\n> import {open, read, close} from 'fs'\n\n> const withFile = hook (node (done => open ('package.json', 'r', done)))\n.                       (fd => node (done => close (fd, done)))\n\n> fork (log ('rejection'))\n.      (log ('resolution'))\n.      (withFile (fd => node (done => (\n.        read (fd, Buffer.alloc (1), 0, 1, null, (e, _, x) => done (e, x)))\n.      )))\n[resolution]: <Buffer 7b>\n```\n\nWhen a hooked Future is cancelled while acquiring its resource, nothing else\nwill happen. When it's cancelled after acquistion completes, however, the\ndisposal will still run, and if it fails, an exception will be thrown.\n\nIf you have multiple resources that you'd like to consume all at once, you can\nuse [Fluture Hooks](https://github.com/fluture-js/fluture-hooks) to combine\nmultiple hooks into one.\n\n### Utility functions\n\n#### pipe\n\n```hs\nFuture.prototype.pipe :: Future a b ~> (Future a b -> c) -> c\n```\n\nA method available on all Futures to allow arbitrary functions over Futures to\nbe included in a fluent-style method chain.\n\nYou can think of this as a fallback for the [ESNext pipe operator (`|>`)][2].\n\n```js\n> resolve (x => y => x * y)\n. .pipe (ap (after (20) (Math.PI)))\n. .pipe (ap (after (20) (13.37)))\n. .pipe (map (Math.round))\n. .pipe (fork (log ('rejection')) (log ('resolution')))\n[resolution]: 42\n```\n\n#### cache\n\n```hs\ncache :: Future a b -> Future a b\n```\n\nReturns a Future which caches the resolution value or rejection reason of the\ngiven Future so that whenever it's forked, it can load the value from cache\nrather than re-executing the underlying computation.\n\nThis essentially turns a unicast Future into a multicast Future, allowing\nmultiple consumers to subscribe to the same result. The underlying computation\nis never [cancelled](#cancellation) unless *all* consumers unsubscribe before\nit completes.\n\n**There is a glaring drawback to using `cache`**, which is that returned\nFutures are no longer referentially transparent, making reasoning about them\nmore difficult and refactoring code that uses them harder.\n\n```js\n> import {readFile} from 'fs'\n\n> const eventualPackageName = (\n.   node (done => readFile ('package.json', 'utf8', done))\n.   .pipe (chain (encase (JSON.parse)))\n.   .pipe (chain (encase (x => x.name)))\n.   .pipe (map (data => {\n.      log ('debug') ('Read, parsed, and traversed the package data')\n.      return data\n.    }))\n. )\n\n> fork (log ('rejection')) (log ('resolution')) (eventualPackageName)\n[debug]: \"Read, parsed, and traversed the package data\"\n[resolution]: \"Fluture\"\n\n> fork (log ('rejection')) (log ('resolution')) (eventualPackageName)\n[debug]: \"Read, parsed, and traversed the package data\"\n[resolution]: \"Fluture\"\n\n> const eventualCachedPackageName = cache (eventualPackageName)\n\n> fork (log ('rejection')) (log ('resolution')) (eventualCachedPackageName)\n[debug]: \"Read, parsed, and traversed the package data\"\n[resolution]: \"Fluture\"\n\n> fork (log ('rejection')) (log ('resolution')) (eventualCachedPackageName)\n[resolution]: \"Fluture\"\n```\n\n#### isFuture\n\n```hs\nisFuture :: a -> Boolean\n```\n\nReturns true for [Futures](#types) and false for everything else. This function\n(and [`S.is`][S:is]) also return `true` for instances of Future that were\ncreated within other contexts. It is therefore recommended to use this over\n`instanceof`, unless your intent is to explicitly check for Futures created\nusing the exact `Future` constructor you're testing against.\n\n```js\n> isFuture (resolve (42))\ntrue\n\n> isFuture (42)\nfalse\n```\n\n#### never\n\n```hs\nnever :: Future a b\n```\n\nA Future that never settles. Can be useful as an initial value when reducing\nwith [`race`](#race), for example.\n\n#### isNever\n\n```hs\nisNever :: a -> Boolean\n```\n\nReturns `true` if the given input is a `never`.\n\n#### extractLeft\n\n```hs\nextractLeft :: Future a b -> Array a\n```\n\nReturns an array whose only element is the rejection reason of the Future.\nIn many cases it will be impossible to extract this value; In those cases, the\narray will be empty. This function is meant to be used for type introspection:\nit is **not** the correct way to [consume a Future](#consuming-futures).\n\n#### extractRight\n\n```hs\nextractRight :: Future a b -> Array b\n```\n\nReturns an array whose only element is the resolution value of the Future.\nIn many cases it will be impossible to extract this value; In those cases, the\narray will be empty. This function is meant to be used for type introspection:\nit is **not** the correct way to [consume a Future](#consuming-futures).\n\n#### debugMode\n\n```hs\ndebugMode :: Boolean -> Undefined\n```\n\nEnable or disable Fluture's debug mode. Debug mode is disabled by default.\nPass `true` to enable, or `false` to disable.\n\n```js\ndebugMode (true)\n```\n\nFor more information, see [Debugging](#debugging) and [Context](#context).\n\n#### context\n\n```hs\nFuture.prototype.context :: Future a b ~> List Context\n```\n\nA linked list of debugging contexts made available on every instance of\n`Future`. When [debug mode](#debugmode) is disabled, the list is always empty.\n\nThe context objects have `stack` properties which contain snapshots of the\nstacktraces leading up to the creation of the `Future` instance. They are used\nby Fluture to generate contextual stack traces.\n\n## License\n\n[MIT licensed](LICENSE)\n\n<!-- References -->\n\n[wiki:similar]:         https://github.com/fluture-js/Fluture/wiki/Comparison-of-Future-Implementations\n[wiki:promises]:        https://github.com/fluture-js/Fluture/wiki/Comparison-to-Promises\n\n[FL]:                   https://github.com/fantasyland/fantasy-land\n[FL:alt]:               https://github.com/fantasyland/fantasy-land#alt\n[FL:alternative]:       https://github.com/fantasyland/fantasy-land#alternative\n[FL:functor]:           https://github.com/fantasyland/fantasy-land#functor\n[FL:chain]:             https://github.com/fantasyland/fantasy-land#chain\n[FL:apply]:             https://github.com/fantasyland/fantasy-land#apply\n[FL:bifunctor]:         https://github.com/fantasyland/fantasy-land#bifunctor\n[FL:chainrec]:          https://github.com/fantasyland/fantasy-land#chainrec\n\n[JS:Object.create]:     https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create\n[JS:Object.assign]:     https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign\n[JS:Array.isArray]:     https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray\n\n[S]:                    https://sanctuary.js.org/\n[S:Either]:             https://sanctuary.js.org/#either-type\n[S:is]:                 https://sanctuary.js.org/#is\n[S:create]:             https://sanctuary.js.org/#create\n[S:join]:               https://sanctuary.js.org/#join\n\n[SS]:                   https://github.com/sanctuary-js/sanctuary-show\n[STI]:                  https://github.com/sanctuary-js/sanctuary-type-identifiers\n[FST]:                  https://github.com/fluture-js/fluture-sanctuary-types\n\n[$]:                    https://github.com/sanctuary-js/sanctuary-def\n\n[Rollup]:               https://rollupjs.org/\n[Pika]:                 https://www.pikapkg.com/\n[Snowpack]:             https://www.snowpack.dev/\n[esm]:                  https://github.com/standard-things/esm\n[Deno]:                 https://deno.land/\n\n[Guide:HM]:             https://mostly-adequate.gitbook.io/mostly-adequate-guide/ch07\n[Guide:constraints]:    https://mostly-adequate.gitbook.io/mostly-adequate-guide/ch07#constraints\n[Guide:currying]:       https://mostly-adequate.gitbook.io/mostly-adequate-guide/ch04\n\n[1]:                    https://en.wikipedia.org/wiki/Continuation-passing_style\n[2]:                    https://github.com/tc39/proposal-pipeline-operator\n[3]:                    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterator\n[5]:                    https://vimeo.com/106008027\n[7]:                    https://promisesaplus.com/\n[9]:                    https://wearereasonablepeople.nl/\n[10]:                   https://dev.to/avaq/fluture-a-functional-alternative-to-promises-21b\n"
  },
  {
    "path": "bench/.eslintrc.json",
    "content": "{\n  \"root\": true,\n  \"extends\": [\"warp/node\", \"warp/es6\"],\n  \"rules\": {\n    \"max-len\": [0]\n  }\n}\n"
  },
  {
    "path": "bench/.npmrc",
    "content": "package-lock=false\nsave=false\n"
  },
  {
    "path": "bench/README.md",
    "content": "# Benchmarks\n\n## Running\n\n* Install node modules required for the benchmark you wish to run\n* Use `npm run bench -- --help` for options\n\nFor example, let's say you like to know how the performance of `parallel`\ncompares to what it was at version 5.x.x:\n\n```console\n$ (cd bench && npm install fluture@5.x.x)\n$ npm run bench -- --benchmark fluture --match *.parallel.*\n```\n"
  },
  {
    "path": "bench/fluture.js",
    "content": "/* global setImmediate */\n\nimport bench from 'sanctuary-benchmark';\nimport Old from 'fluture';\nimport * as New from '../index.js';\n\nconst config = {leftHeader: 'Old', rightHeader: 'New'};\n\nconst noop = () => {};\nconst compose = (f, g) => x => f(g(x));\nconst run = m => m.constructor.fork(noop)(noop)(m);\nconst plus1 = x => x + 1;\nconst arr = (T, length) => Array.from({length}, (_, i) => T.resolve(i));\nconst fast = (T, x) => T((rej, res) => void setImmediate(res, x));\nconst slow = (T, x) => T.after(1)(x);\n\nexport default bench(Old, New, config, {\n\n  'def.interpreter.Future': [\n    {}, ({Future}) => Future((rej, res) => res(1))\n  ],\n\n  'def.interpreter.resolve': [\n    {}, ({resolve}) => resolve(1)\n  ],\n\n  'def.interpreter.reject': [\n    {}, ({reject}) => reject(1)\n  ],\n\n  'def.interpreter.after': [\n    {}, ({after}) => after(1)(1)\n  ],\n\n  'def.interpreter.attempt': [\n    {}, ({attempt}) => attempt(noop)\n  ],\n\n  'def.interpreter.cache': [\n    {}, ({resolve, cache}) => cache(resolve(1))\n  ],\n\n  'def.interpreter.encase': [\n    {}, ({encase}) => encase(noop)(1)\n  ],\n\n  'def.interpreter.encaseP': [\n    {}, ({encaseP}) => encaseP(noop)(1)\n  ],\n\n  'def.interpreter.go': [\n    {}, ({go}) => go(noop)\n  ],\n\n  'def.interpreter.hook': [\n    {}, ({resolve, hook}) => hook(resolve(1))(noop)(noop)\n  ],\n\n  'def.interpreter.node': [\n    {}, ({node}) => node(done => done(null, 1))\n  ],\n\n  'def.interpreter.parallel': [\n    {}, ({resolve, parallel}) => parallel(1)([resolve(1)])\n  ],\n\n  'def.transformation.map': [\n    {}, ({resolve, map}) => map(plus1)(resolve(1))\n  ],\n\n  'def.transformation.chain': [\n    {}, ({resolve, chain}) => chain(plus1)(resolve(1))\n  ],\n\n  'run.interpreter.Future': [\n    {}, ({Future}) => run(Future((rej, res) => res(1)))\n  ],\n\n  'run.interpreter.parallel.empty': [\n    {}, ({parallel}) => run(parallel(1)([]))\n  ],\n\n  'run.interpreter.parallel.small.sequential': [\n    {}, ({Future, parallel}) => run(parallel(1)(arr(Future, 2)))\n  ],\n\n  'run.interpreter.parallel.small.concurrent': [\n    {}, ({Future, parallel}) => run(parallel(2)(arr(Future, 2)))\n  ],\n\n  'run.interpreter.parallel.big.sequential': [\n    {}, ({Future, parallel}) => run(parallel(1)(arr(Future, 100)))\n  ],\n\n  'run.interpreter.parallel.big.concurrent': [\n    {}, ({Future, parallel}) => run(parallel(2)(arr(Future, 100)))\n  ],\n\n  'run.interpreter.go': [\n    {}, ({go, resolve}) => run(go(function*(){\n      return (yield resolve(1)) + (yield resolve(2));\n    }))\n  ],\n\n  'run.transformation.sync.map': [\n    {}, ({resolve, map}) => run(map(plus1)(resolve(1)))\n  ],\n\n  'run.transformation.sync.swap.one': [\n    {}, ({resolve, swap}) => run(swap(resolve(42)))\n  ],\n\n  'run.transformation.sync.swap.many': [\n    {}, ({resolve, swap}) => {\n      let m = resolve(1);\n      for(let i = 0; i < 1000; i++){ m = swap(m) }\n      run(m);\n    }\n  ],\n\n  'run.transformation.sync.chain.one': [\n    {}, ({resolve, chain}) => run(chain(compose(resolve, plus1))(resolve(1)))\n  ],\n\n  'run.transformation.sync.chain.many': [\n    {}, ({chain, resolve}) => {\n      const f = compose(resolve, plus1);\n      let m = resolve(1);\n      for(let i = 0; i < 1000; i++){ m = chain(f)(m) }\n      run(m);\n    }\n  ],\n\n  'run.transformation.async.map': [\n    {defer: true}, ({Future, map, value}, [d]) => {\n      map(plus1)(fast(Future, 1)).pipe(value(() => d.resolve()));\n    }\n  ],\n\n  'run.transformation.async.chain.one': [\n    {defer: true}, ({Future, chain, value}, [d]) => {\n      chain(x => fast(Future, plus1(x)))(fast(Future, 1))\n      .pipe(value(() => d.resolve()));\n    }\n  ],\n\n  'run.transformation.async.chain.many': [\n    {defer: true}, ({Future, chain, value}, [d]) => {\n      const f = x => fast(Future, plus1(x));\n      let m = fast(Future, 1);\n      for(let i = 0; i < 100; i++){ m = chain(f)(m) }\n      m.pipe(value(() => d.resolve()));\n    }\n  ],\n\n  'run.transformation.parallel.async.race.fast-vs-slow': [\n    {defer: true}, ({Future, race, value}, [d]) => {\n      const a = fast(Future, 1);\n      const b = slow(Future, 1);\n      race(a)(b).pipe(value(() => d.resolve()));\n    }\n  ],\n\n  'run.transformation.parallel.async.race.slow-vs-fast': [\n    {defer: true}, ({Future, race, value}, [d]) => {\n      const a = slow(Future, 1);\n      const b = fast(Future, 1);\n      race(a)(b).pipe(value(() => d.resolve()));\n    }\n  ],\n\n  'run.transformation.parallel.async.race.slow-vs-slow': [\n    {defer: true}, ({Future, race, value}, [d]) => {\n      const a = slow(Future, 1);\n      const b = slow(Future, 1);\n      race(a)(b).pipe(value(() => d.resolve()));\n    }\n  ],\n\n});\n"
  },
  {
    "path": "bench/folktale.js",
    "content": "import bench from 'sanctuary-benchmark';\nimport * as Future from '../index.js';\nimport folktale from 'folktale/concurrency/task/index.js';\n\nconst noop = () => {};\nconst plus1 = x => x + 1;\nconst repeat = (n, f) => x => Array.from({length: n}).reduce(x => f(x), x);\n\nconst map1000 = repeat(1000, Future.map(plus1));\nconst chain1000 = repeat(1000, Future.chain(plus1));\n\nconst createTask = x => folktale.task(resolver => resolver.resolve(x));\nconst createFuture = x => Future.Future((rej, res) => { res(x); return noop });\nconst consumeTask = m => m.run().listen({onCancelled: noop, onRejected: noop, onResolved: noop});\nconst consumeFuture = Future.fork(noop)(noop);\n\nconst config = {leftHeader: 'Folktale', rightHeader: 'Fluture'};\n\nconst left = {\n  create: createTask,\n  consume: consumeTask,\n  one: createTask(1),\n  mapped: map1000(createTask(1))\n};\n\nconst right = {\n  create: createFuture,\n  consume: consumeFuture,\n  one: createFuture(1),\n  mapped: map1000(createFuture(1))\n};\n\nexport default bench(left, right, config, {\n\n  'create.construct': [\n    {}, ({create}) => repeat(1000, create)(1)\n  ],\n\n  'create.map': [\n    {}, ({one}) => map1000(one)\n  ],\n\n  'create.chain': [\n    {}, ({one}) => chain1000(one)\n  ],\n\n  'consume.noop': [\n    {}, ({one, consume}) => consume(one)\n  ],\n\n  'consume.map.1': [\n    {}, ({one, consume}) => consume(Future.map(plus1)(one))\n  ],\n\n  'consume.map.1000': [\n    {}, ({mapped, consume}) => consume(mapped)\n  ],\n\n  'consume.chain': [\n    {}, ({create, consume, one}) => consume(Future.chain(x => create(x + 1))(one))\n  ],\n\n});\n"
  },
  {
    "path": "bench/package.json",
    "content": "{\n  \"name\": \"fluture-benchmarks\",\n  \"type\": \"module\",\n  \"version\": \"1.0.0\",\n  \"description\": \"A package.json for the purpose of being able to install dependencies in here\",\n  \"author\": \"Aldwin Vlasblom <aldwin.vlasblom@gmail.com> (https://github.com/Avaq)\",\n  \"license\": \"MIT\",\n  \"private\": true\n}\n"
  },
  {
    "path": "bench/promise.js",
    "content": "import bench from 'sanctuary-benchmark';\nimport * as Future from '../index.js';\n\nconst plus1 = x => x + 1;\nconst repeat = (n, f, x) => Array.from({length: n}).reduce(x => f(x), x);\nconst Left = x => ({left: true, right: false, value: x});\nconst Right = x => ({left: false, right: true, value: x});\n\nconst config = {leftHeader: 'Promise', rightHeader: 'Fluture'};\n\nconst def = f => [\n  {defer: true},\n  (x, [d]) => f(x).then(() => d.resolve()),\n  (x, [d]) => Future.value(() => d.resolve())(f(x))\n];\n\nconst PromiseInterop = {\n  resolve: x => Promise.resolve(x),\n  map: f => p => p.then(f),\n  chain: f => p => p.then(f),\n  coalesce: f => g => p => p.then(g, f),\n  race: a => b => Promise.race([a, b]),\n  after: n => x => new Promise(res => setTimeout(res, n, x))\n};\n\nexport default bench(PromiseInterop, Future, config, {\n\n  'resolve': def(\n    ({resolve}) => repeat(1000, resolve, 1)\n  ),\n\n  'after': def(\n    ({after}) => after(10)(1)\n  ),\n\n  'map': def(\n    ({map, resolve}) => repeat(1000, map(plus1), resolve(1))\n  ),\n\n  'coalesce': def(\n    ({coalesce, resolve}) => repeat(1000, coalesce(Left)(Right), resolve(1))\n  ),\n\n  'chain.sync': def(\n    ({chain, resolve}) => repeat(1000, chain(x => resolve(plus1(x))), resolve(1))\n  ),\n\n  'chain.async': def(\n    ({chain, after}) => repeat(5, chain(x => after(1)(plus1(x))), after(1)(1))\n  ),\n\n  'race.sync': def(\n    ({race, resolve}) => repeat(1000, race(resolve(2)), resolve(1))\n  ),\n\n  'race.async': def(\n    ({race, after}) => repeat(5, race(after(1)(2)), after(1)(1))\n  ),\n\n});\n"
  },
  {
    "path": "dist/bundle.js",
    "content": "/**\n * Fluture bundled; version 14.0.0\n */\n\nvar Fluture = (function () {\n\t'use strict';\n\n\tfunction createCommonjsModule(fn) {\n\t  var module = { exports: {} };\n\t\treturn fn(module, module.exports), module.exports;\n\t}\n\n\t/*\n\t        @@@@@@@            @@@@@@@         @@\n\t      @@       @@        @@       @@      @@@\n\t    @@   @@@ @@  @@    @@   @@@ @@  @@   @@@@@@ @@   @@@  @@ @@@      @@@@\n\t   @@  @@   @@@   @@  @@  @@   @@@   @@   @@@   @@   @@@  @@@   @@  @@@   @@\n\t   @@  @@   @@@   @@  @@  @@   @@@   @@   @@@   @@   @@@  @@@   @@  @@@@@@@@\n\t   @@  @@   @@@  @@   @@  @@   @@@  @@    @@@   @@   @@@  @@@   @@  @@@\n\t    @@   @@@ @@@@@     @@   @@@ @@@@@      @@@    @@@ @@  @@@@@@      @@@@@\n\t      @@                 @@                           @@  @@\n\t        @@@@@@@            @@@@@@@               @@@@@    @@\n\t                                                          */\n\n\tvar sanctuaryTypeIdentifiers = createCommonjsModule(function (module) {\n\t//. # sanctuary-type-identifiers\n\t//.\n\t//. A type is a set of values. Boolean, for example, is the type comprising\n\t//. `true` and `false`. A value may be a member of multiple types (`42` is a\n\t//. member of Number, PositiveNumber, Integer, and many other types).\n\t//.\n\t//. In certain situations it is useful to divide JavaScript values into\n\t//. non-overlapping types. The language provides two constructs for this\n\t//. purpose: the [`typeof`][1] operator and [`Object.prototype.toString`][2].\n\t//. Each has pros and cons, but neither supports user-defined types.\n\t//.\n\t//. sanctuary-type-identifiers comprises:\n\t//.\n\t//.   - an npm and browser -compatible package for deriving the\n\t//.     _type identifier_ of a JavaScript value; and\n\t//.   - a specification which authors may follow to specify type\n\t//.     identifiers for their types.\n\t//.\n\t//. ### Specification\n\t//.\n\t//. For a type to be compatible with the algorithm:\n\t//.\n\t//.   - every member of the type MUST have a `@@type` property\n\t//.     (the _type identifier_); and\n\t//.\n\t//.   - the type identifier MUST be a string primitive and SHOULD have\n\t//.     format `'<namespace>/<name>[@<version>]'`, where:\n\t//.\n\t//.       - `<namespace>` MUST consist of one or more characters, and\n\t//.         SHOULD equal the name of the npm package which defines the\n\t//.         type (including [scope][3] where appropriate);\n\t//.\n\t//.       - `<name>` MUST consist of one or more characters, and SHOULD\n\t//.         be the unique name of the type; and\n\t//.\n\t//.       - `<version>` MUST consist of one or more digits, and SHOULD\n\t//.         represent the version of the type.\n\t//.\n\t//. If the type identifier does not conform to the format specified above,\n\t//. it is assumed that the entire string represents the _name_ of the type;\n\t//. _namespace_ will be `null` and _version_ will be `0`.\n\t//.\n\t//. If the _version_ is not given, it is assumed to be `0`.\n\n\t(function(f) {\n\n\t  /* istanbul ignore else */\n\t  {\n\t    module.exports = f ();\n\t  }\n\n\t} (function() {\n\n\t  //  $$type :: String\n\t  var $$type = '@@type';\n\n\t  //  pattern :: RegExp\n\t  var pattern = new RegExp (\n\t    '^'\n\t  + '([\\\\s\\\\S]+)'   //  <namespace>\n\t  + '/'             //  SOLIDUS (U+002F)\n\t  + '([\\\\s\\\\S]+?)'  //  <name>\n\t  + '(?:'           //  optional non-capturing group {\n\t  +   '@'           //    COMMERCIAL AT (U+0040)\n\t  +   '([0-9]+)'    //    <version>\n\t  + ')?'            //  }\n\t  + '$'\n\t  );\n\n\t  //. ### Usage\n\t  //.\n\t  //. ```javascript\n\t  //. const type = require ('sanctuary-type-identifiers');\n\t  //. ```\n\t  //.\n\t  //. ```javascript\n\t  //. > const Identity$prototype = {\n\t  //. .   '@@type': 'my-package/Identity@1',\n\t  //. .   '@@show': function() {\n\t  //. .     return 'Identity (' + show (this.value) + ')';\n\t  //. .   }\n\t  //. . }\n\t  //.\n\t  //. > const Identity = value =>\n\t  //. .   Object.assign (Object.create (Identity$prototype), {value})\n\t  //.\n\t  //. > type (Identity (0))\n\t  //. 'my-package/Identity@1'\n\t  //.\n\t  //. > type.parse (type (Identity (0)))\n\t  //. {namespace: 'my-package', name: 'Identity', version: 1}\n\t  //. ```\n\t  //.\n\t  //. ### API\n\t  //.\n\t  //# type :: Any -> String\n\t  //.\n\t  //. Takes any value and returns a string which identifies its type. If the\n\t  //. value conforms to the [specification][4], the custom type identifier is\n\t  //. returned.\n\t  //.\n\t  //. ```javascript\n\t  //. > type (null)\n\t  //. 'Null'\n\t  //.\n\t  //. > type (true)\n\t  //. 'Boolean'\n\t  //.\n\t  //. > type (Identity (0))\n\t  //. 'my-package/Identity@1'\n\t  //. ```\n\t  function type(x) {\n\t    return x != null &&\n\t           x.constructor != null &&\n\t           x.constructor.prototype !== x &&\n\t           typeof x[$$type] === 'string' ?\n\t      x[$$type] :\n\t      (Object.prototype.toString.call (x)).slice ('[object '.length,\n\t                                                  -']'.length);\n\t  }\n\n\t  //# type.parse :: String -> { namespace :: Nullable String, name :: String, version :: Number }\n\t  //.\n\t  //. Takes any string and parses it according to the [specification][4],\n\t  //. returning an object with `namespace`, `name`, and `version` fields.\n\t  //.\n\t  //. ```javascript\n\t  //. > type.parse ('my-package/List@2')\n\t  //. {namespace: 'my-package', name: 'List', version: 2}\n\t  //.\n\t  //. > type.parse ('nonsense!')\n\t  //. {namespace: null, name: 'nonsense!', version: 0}\n\t  //.\n\t  //. > type.parse (type (Identity (0)))\n\t  //. {namespace: 'my-package', name: 'Identity', version: 1}\n\t  //. ```\n\t  type.parse = function parse(s) {\n\t    var namespace = null;\n\t    var name = s;\n\t    var version = 0;\n\t    var groups = pattern.exec (s);\n\t    if (groups != null) {\n\t      namespace = groups[1];\n\t      name = groups[2];\n\t      if (groups[3] != null) version = Number (groups[3]);\n\t    }\n\t    return {namespace: namespace, name: name, version: version};\n\t  };\n\n\t  return type;\n\n\t}));\n\n\t//. [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof\n\t//. [2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString\n\t//. [3]: https://docs.npmjs.com/misc/scope\n\t//. [4]: #specification\n\t});\n\n\tvar FL = {\n\t  alt: 'fantasy-land/alt',\n\t  ap: 'fantasy-land/ap',\n\t  bimap: 'fantasy-land/bimap',\n\t  chain: 'fantasy-land/chain',\n\t  chainRec: 'fantasy-land/chainRec',\n\t  map: 'fantasy-land/map',\n\t  of: 'fantasy-land/of',\n\t  zero: 'fantasy-land/zero'\n\t};\n\n\tvar ordinal = ['first', 'second', 'third', 'fourth', 'fifth'];\n\n\tvar namespace = 'fluture';\n\tvar name = 'Future';\n\tvar version = 5;\n\n\tvar $$type$1 = namespace + '/' + name + '@' + version;\n\n\tfunction List(head, tail){\n\t  this.head = head;\n\t  this.tail = tail;\n\t}\n\n\tList.prototype.toJSON = function(){\n\t  return toArray(this);\n\t};\n\n\tvar nil = new List(null, null);\n\tnil.tail = nil;\n\n\tfunction isNil(list){\n\t  return list.tail === list;\n\t}\n\n\t// cons :: (a, List a) -> List a\n\t//      -- O(1) append operation\n\tfunction cons(head, tail){\n\t  return new List(head, tail);\n\t}\n\n\t// reverse :: List a -> List a\n\t//         -- O(n) list reversal\n\tfunction reverse(xs){\n\t  var ys = nil, tail = xs;\n\t  while(!isNil(tail)){\n\t    ys = cons(tail.head, ys);\n\t    tail = tail.tail;\n\t  }\n\t  return ys;\n\t}\n\n\t// cat :: (List a, List a) -> List a\n\t//     -- O(n) list concatenation\n\tfunction cat(xs, ys){\n\t  var zs = ys, tail = reverse(xs);\n\t  while(!isNil(tail)){\n\t    zs = cons(tail.head, zs);\n\t    tail = tail.tail;\n\t  }\n\t  return zs;\n\t}\n\n\t// toArray :: List a -> Array a\n\t//         -- O(n) list to Array\n\tfunction toArray(xs){\n\t  var tail = xs, arr = [];\n\t  while(!isNil(tail)){\n\t    arr.push(tail.head);\n\t    tail = tail.tail;\n\t  }\n\t  return arr;\n\t}\n\n\t/* c8 ignore next */\n\tvar captureStackTrace = Error.captureStackTrace || captureStackTraceFallback;\n\tvar _debug = debugHandleNone;\n\n\tfunction debugMode(debug){\n\t  _debug = debug ? debugHandleAll : debugHandleNone;\n\t}\n\n\tfunction debugHandleNone(x){\n\t  return x;\n\t}\n\n\tfunction debugHandleAll(x, fn, a, b, c){\n\t  return fn(a, b, c);\n\t}\n\n\tfunction debug(x, fn, a, b, c){\n\t  return _debug(x, fn, a, b, c);\n\t}\n\n\tfunction captureContext(previous, tag, fn){\n\t  return debug(previous, debugCaptureContext, previous, tag, fn);\n\t}\n\n\tfunction debugCaptureContext(previous, tag, fn){\n\t  var context = {tag: tag, name: ' from ' + tag + ':'};\n\t  captureStackTrace(context, fn);\n\t  return cons(context, previous);\n\t}\n\n\tfunction captureApplicationContext(context, n, f){\n\t  return debug(context, debugCaptureApplicationContext, context, n, f);\n\t}\n\n\tfunction debugCaptureApplicationContext(context, n, f){\n\t  return debugCaptureContext(context, ordinal[n - 1] + ' application of ' + f.name, f);\n\t}\n\n\tfunction captureStackTraceFallback(x){\n\t  var e = new Error;\n\t  if(typeof e.stack === 'string'){\n\t    x.stack = x.name + '\\n' + e.stack.split('\\n').slice(1).join('\\n');\n\t  /* c8 ignore next 3 */\n\t  }else {\n\t    x.stack = x.name;\n\t  }\n\t}\n\n\tvar sanctuaryShow = createCommonjsModule(function (module) {\n\t//. # sanctuary-show\n\t//.\n\t//. Haskell has a `show` function which can be applied to a compatible value to\n\t//. produce a descriptive string representation of that value. The idea is that\n\t//. the string representation should, if possible, be an expression which would\n\t//. produce the original value if evaluated.\n\t//.\n\t//. This library provides a similar [`show`](#show) function.\n\t//.\n\t//. In general, this property should hold: `eval (show (x)) = x`. In some cases\n\t//. parens are necessary to ensure correct interpretation (`{}`, for example,\n\t//. is an empty block rather than an empty object in some contexts). Thus the\n\t//. property is more accurately stated `eval ('(' + show (x) + ')') = x`.\n\t//.\n\t//. One can make values of a custom type compatible with [`show`](#show) by\n\t//. defining a `@@show` method. For example:\n\t//.\n\t//. ```javascript\n\t//. //# Maybe#@@show :: Maybe a ~> () -> String\n\t//. //.\n\t//. //. ```javascript\n\t//. //. > show (Nothing)\n\t//. //. 'Nothing'\n\t//. //.\n\t//. //. > show (Just (['foo', 'bar', 'baz']))\n\t//. //. 'Just ([\"foo\", \"bar\", \"baz\"])'\n\t//. //. ```\n\t//. Maybe.prototype['@@show'] = function() {\n\t//.   return this.isNothing ? 'Nothing' : 'Just (' + show (this.value) + ')';\n\t//. };\n\t//. ```\n\n\t(function(f) {\n\n\t  /* istanbul ignore else */\n\t  {\n\t    module.exports = f ();\n\t  }\n\n\t} (function() {\n\n\t  //  $$show :: String\n\t  var $$show = '@@show';\n\n\t  //  seen :: Array Any\n\t  var seen = [];\n\n\t  //  entry :: Object -> String -> String\n\t  function entry(o) {\n\t    return function(k) {\n\t      return show (k) + ': ' + show (o[k]);\n\t    };\n\t  }\n\n\t  //  sortedKeys :: Object -> Array String\n\t  function sortedKeys(o) {\n\t    return (Object.keys (o)).sort ();\n\t  }\n\n\t  //# show :: Showable a => a -> String\n\t  //.\n\t  //. Returns a useful string representation of the given value.\n\t  //.\n\t  //. Dispatches to the value's `@@show` method if present.\n\t  //.\n\t  //. Where practical, `show (eval ('(' + show (x) + ')')) = show (x)`.\n\t  //.\n\t  //. ```javascript\n\t  //. > show (null)\n\t  //. 'null'\n\t  //.\n\t  //. > show (undefined)\n\t  //. 'undefined'\n\t  //.\n\t  //. > show (true)\n\t  //. 'true'\n\t  //.\n\t  //. > show (new Boolean (false))\n\t  //. 'new Boolean (false)'\n\t  //.\n\t  //. > show (-0)\n\t  //. '-0'\n\t  //.\n\t  //. > show (NaN)\n\t  //. 'NaN'\n\t  //.\n\t  //. > show (new Number (Infinity))\n\t  //. 'new Number (Infinity)'\n\t  //.\n\t  //. > show ('foo\\n\"bar\"\\nbaz\\n')\n\t  //. '\"foo\\\\n\\\\\"bar\\\\\"\\\\nbaz\\\\n\"'\n\t  //.\n\t  //. > show (new String (''))\n\t  //. 'new String (\"\")'\n\t  //.\n\t  //. > show (['foo', 'bar', 'baz'])\n\t  //. '[\"foo\", \"bar\", \"baz\"]'\n\t  //.\n\t  //. > show ([[[[[0]]]]])\n\t  //. '[[[[[0]]]]]'\n\t  //.\n\t  //. > show ({x: [1, 2], y: [3, 4], z: [5, 6]})\n\t  //. '{\"x\": [1, 2], \"y\": [3, 4], \"z\": [5, 6]}'\n\t  //. ```\n\t  function show(x) {\n\t    if (seen.indexOf (x) >= 0) return '<Circular>';\n\n\t    switch (Object.prototype.toString.call (x)) {\n\n\t      case '[object Boolean]':\n\t        return typeof x === 'object' ?\n\t          'new Boolean (' + show (x.valueOf ()) + ')' :\n\t          x.toString ();\n\n\t      case '[object Number]':\n\t        return typeof x === 'object' ?\n\t          'new Number (' + show (x.valueOf ()) + ')' :\n\t          1 / x === -Infinity ? '-0' : x.toString (10);\n\n\t      case '[object String]':\n\t        return typeof x === 'object' ?\n\t          'new String (' + show (x.valueOf ()) + ')' :\n\t          JSON.stringify (x);\n\n\t      case '[object Date]':\n\t        return 'new Date (' +\n\t               show (isNaN (x.valueOf ()) ? NaN : x.toISOString ()) +\n\t               ')';\n\n\t      case '[object Error]':\n\t        return 'new ' + x.name + ' (' + show (x.message) + ')';\n\n\t      case '[object Arguments]':\n\t        return 'function () { return arguments; } (' +\n\t               (Array.prototype.map.call (x, show)).join (', ') +\n\t               ')';\n\n\t      case '[object Array]':\n\t        seen.push (x);\n\t        try {\n\t          return '[' + ((x.map (show)).concat (\n\t            sortedKeys (x)\n\t            .filter (function(k) { return !(/^\\d+$/.test (k)); })\n\t            .map (entry (x))\n\t          )).join (', ') + ']';\n\t        } finally {\n\t          seen.pop ();\n\t        }\n\n\t      case '[object Object]':\n\t        seen.push (x);\n\t        try {\n\t          return (\n\t            $$show in x &&\n\t            (x.constructor == null || x.constructor.prototype !== x) ?\n\t              x[$$show] () :\n\t              '{' + ((sortedKeys (x)).map (entry (x))).join (', ') + '}'\n\t          );\n\t        } finally {\n\t          seen.pop ();\n\t        }\n\n\t      case '[object Set]':\n\t        seen.push (x);\n\t        try {\n\t          return 'new Set (' + show (Array.from (x.values ())) + ')';\n\t        } finally {\n\t          seen.pop ();\n\t        }\n\n\t      case '[object Map]':\n\t        seen.push (x);\n\t        try {\n\t          return 'new Map (' + show (Array.from (x.entries ())) + ')';\n\t        } finally {\n\t          seen.pop ();\n\t        }\n\n\t      default:\n\t        return String (x);\n\n\t    }\n\t  }\n\n\t  return show;\n\n\t}));\n\t});\n\n\t/* c8 ignore next */\n\tvar setImmediate = typeof setImmediate === 'undefined' ? setImmediateFallback : setImmediate;\n\n\tfunction noop(){}\n\tfunction moop(){ return this }\n\tfunction call(f, x){ return f(x) }\n\n\tfunction setImmediateFallback(f, x){\n\t  return setTimeout(f, 0, x);\n\t}\n\n\tfunction raise(x){\n\t  setImmediate(function rethrowErrorDelayedToEscapePromiseCatch(){\n\t    throw x;\n\t  });\n\t}\n\n\tfunction showArg$1(x){\n\t  return sanctuaryShow(x) + ' :: ' + sanctuaryTypeIdentifiers.parse(sanctuaryTypeIdentifiers(x)).name;\n\t}\n\n\tfunction error(message){\n\t  return new Error(message);\n\t}\n\n\tfunction typeError(message){\n\t  return new TypeError(message);\n\t}\n\n\tfunction invalidArgument(it, at, expected, actual){\n\t  return typeError(\n\t    it + '() expects its ' + ordinal[at] + ' argument to ' + expected + '.' +\n\t    '\\n  Actual: ' + showArg$1(actual)\n\t  );\n\t}\n\n\tfunction invalidArgumentOf(expected){\n\t  return function(it, at, actual){\n\t    return invalidArgument(it, at, expected, actual);\n\t  };\n\t}\n\n\tfunction invalidArity(f, args){\n\t  return new TypeError(\n\t    f.name + '() expects to be called with a single argument per invocation\\n' +\n\t    '  Saw: ' + args.length + ' arguments' +\n\t    Array.prototype.slice.call(args).map(function(arg, i){\n\t      return '\\n  ' + (\n\t        ordinal[i] ?\n\t        ordinal[i].charAt(0).toUpperCase() + ordinal[i].slice(1) :\n\t        'Argument ' + String(i + 1)\n\t      ) + ': ' + showArg$1(arg);\n\t    }).join('')\n\t  );\n\t}\n\n\tfunction invalidNamespace(m, x){\n\t  return (\n\t    'The Future was not created by ' + namespace + '. '\n\t  + 'Make sure you transform other Futures to ' + namespace + ' Futures. '\n\t  + 'Got ' + (x ? ('a Future from ' + x) : 'an unscoped Future') + '.'\n\t  + '\\n  See: https://github.com/fluture-js/Fluture#casting-futures'\n\t  );\n\t}\n\n\tfunction invalidVersion(m, x){\n\t  return (\n\t    'The Future was created by ' + (x < version ? 'an older' : 'a newer')\n\t  + ' version of ' + namespace + '. '\n\t  + 'This means that one of the sources which creates Futures is outdated. '\n\t  + 'Update this source, or transform its created Futures to be compatible.'\n\t  + '\\n  See: https://github.com/fluture-js/Fluture#casting-futures'\n\t  );\n\t}\n\n\tfunction invalidFuture(desc, m, s){\n\t  var id = sanctuaryTypeIdentifiers.parse(sanctuaryTypeIdentifiers(m));\n\t  var info = id.name === name ? '\\n' + (\n\t    id.namespace !== namespace ? invalidNamespace(m, id.namespace)\n\t  : id.version !== version ? invalidVersion(m, id.version)\n\t  : 'Nothing seems wrong. Contact the Fluture maintainers.') : '';\n\t  return typeError(\n\t    desc + ' to be a valid Future.' + info + '\\n' +\n\t    '  Actual: ' + sanctuaryShow(m) + ' :: ' + id.name + (s || '')\n\t  );\n\t}\n\n\tfunction invalidFutureArgument(it, at, m, s){\n\t  return invalidFuture(it + '() expects its ' + ordinal[at] + ' argument', m, s);\n\t}\n\n\tfunction ensureError(value, fn){\n\t  var message;\n\t  try{\n\t    if(value instanceof Error) return value;\n\t    message = 'A Non-Error was thrown from a Future: ' + sanctuaryShow(value);\n\t  }catch (_){\n\t    message = 'Something was thrown from a Future, but it could not be converted to String';\n\t  }\n\t  var e = error(message);\n\t  captureStackTrace(e, fn);\n\t  return e;\n\t}\n\n\tfunction assignUnenumerable(o, prop, value){\n\t  Object.defineProperty(o, prop, {value: value, writable: true, configurable: true});\n\t}\n\n\tfunction wrapException(caught, callingFuture){\n\t  var origin = ensureError(caught, wrapException);\n\t  var context = cat(origin.context || nil, callingFuture.context);\n\t  var e = error(origin.message);\n\t  assignUnenumerable(e, 'future', origin.future || callingFuture);\n\t  assignUnenumerable(e, 'reason', origin.reason || origin);\n\t  assignUnenumerable(e, 'stack', e.reason.stack);\n\t  return withExtraContext(e, context);\n\t}\n\n\tfunction withExtraContext(e, context){\n\t  assignUnenumerable(e, 'context', context);\n\t  assignUnenumerable(e, 'stack', e.stack + contextToStackTrace(context));\n\t  return e;\n\t}\n\n\tfunction contextToStackTrace(context){\n\t  var stack = '', tail = context;\n\t  while(tail !== nil){\n\t    stack = stack + '\\n' + tail.head.stack;\n\t    tail = tail.tail;\n\t  }\n\t  return stack;\n\t}\n\n\tfunction isFunction(f){\n\t  return typeof f === 'function';\n\t}\n\n\tfunction isThenable(m){\n\t  return m instanceof Promise || m != null && isFunction(m.then);\n\t}\n\n\tfunction isBoolean(f){\n\t  return typeof f === 'boolean';\n\t}\n\n\tfunction isNumber(f){\n\t  return typeof f === 'number';\n\t}\n\n\tfunction isUnsigned(n){\n\t  return (n === Infinity || isNumber(n) && n > 0 && n % 1 === 0);\n\t}\n\n\tfunction isObject(o){\n\t  return o !== null && typeof o === 'object';\n\t}\n\n\tfunction isIterator(i){\n\t  return isObject(i) && isFunction(i.next);\n\t}\n\n\tfunction isArray(x){\n\t  return Array.isArray(x);\n\t}\n\n\tfunction hasMethod(method, x){\n\t  return x != null && isFunction(x[method]);\n\t}\n\n\tfunction isFunctor(x){\n\t  return hasMethod(FL.map, x);\n\t}\n\n\tfunction isAlt(x){\n\t  return isFunctor(x) && hasMethod(FL.alt, x);\n\t}\n\n\tfunction isApply(x){\n\t  return isFunctor(x) && hasMethod(FL.ap, x);\n\t}\n\n\tfunction isBifunctor(x){\n\t  return isFunctor(x) && hasMethod(FL.bimap, x);\n\t}\n\n\tfunction isChain(x){\n\t  return isApply(x) && hasMethod(FL.chain, x);\n\t}\n\n\tfunction Next(x){\n\t  return {done: false, value: x};\n\t}\n\n\tfunction Done(x){\n\t  return {done: true, value: x};\n\t}\n\n\tfunction isIteration(x){\n\t  return isObject(x) && isBoolean(x.done);\n\t}\n\n\t/*eslint no-cond-assign:0, no-constant-condition:0 */\n\n\tfunction alwaysTrue(){\n\t  return true;\n\t}\n\n\tfunction getArgs(it){\n\t  var args = new Array(it.arity);\n\t  for(var i = 1; i <= it.arity; i++){\n\t    args[i - 1] = it['$' + String(i)];\n\t  }\n\t  return args;\n\t}\n\n\tfunction showArg(arg){\n\t  return ' (' + sanctuaryShow(arg) + ')';\n\t}\n\n\tvar any = {pred: alwaysTrue, error: invalidArgumentOf('be anything')};\n\tvar func = {pred: isFunction, error: invalidArgumentOf('be a Function')};\n\tvar future = {pred: isFuture, error: invalidFutureArgument};\n\tvar positiveInteger = {pred: isUnsigned, error: invalidArgumentOf('be a positive Integer')};\n\n\tfunction application(n, f, type, args, prev){\n\t  if(args.length < 2 && type.pred(args[0])) return captureApplicationContext(prev, n, f);\n\t  var e = args.length > 1 ? invalidArity(f, args) : type.error(f.name, n - 1, args[0]);\n\t  captureStackTrace(e, f);\n\t  throw withExtraContext(e, prev);\n\t}\n\n\tfunction application1(f, type, args){\n\t  return application(1, f, type, args, nil);\n\t}\n\n\tfunction Future(computation){\n\t  var context = application1(Future, func, arguments);\n\t  return new Computation(context, computation);\n\t}\n\n\tfunction isFuture(x){\n\t  return x instanceof Future || sanctuaryTypeIdentifiers(x) === $$type$1;\n\t}\n\n\t// Compliance with sanctuary-type-identifiers versions 1 and 2.\n\t// To prevent sanctuary-type-identifiers version 3 from identifying 'Future'\n\t// as being of the type denoted by $$type, we ensure that\n\t// Future.constructor.prototype is equal to Future.\n\tFuture['@@type'] = $$type$1;\n\tFuture.constructor = {prototype: Future};\n\n\tFuture[FL.of] = resolve;\n\tFuture[FL.chainRec] = chainRec;\n\n\tFuture.prototype['@@type'] = $$type$1;\n\n\tFuture.prototype['@@show'] = function Future$show(){\n\t  return this.toString();\n\t};\n\n\tFuture.prototype.pipe = function Future$pipe(f){\n\t  if(!isFunction(f)) throw invalidArgument('Future#pipe', 0, 'be a Function', f);\n\t  return f(this);\n\t};\n\n\tFuture.prototype[FL.ap] = function Future$FL$ap(other){\n\t  var context = captureContext(nil, 'a Fantasy Land dispatch to ap', Future$FL$ap);\n\t  return other._transform(new ApTransformation(context, this));\n\t};\n\n\tFuture.prototype[FL.map] = function Future$FL$map(mapper){\n\t  var context = captureContext(nil, 'a Fantasy Land dispatch to map', Future$FL$map);\n\t  return this._transform(new MapTransformation(context, mapper));\n\t};\n\n\tFuture.prototype[FL.bimap] = function Future$FL$bimap(lmapper, rmapper){\n\t  var context = captureContext(nil, 'a Fantasy Land dispatch to bimap', Future$FL$bimap);\n\t  return this._transform(new BimapTransformation(context, lmapper, rmapper));\n\t};\n\n\tFuture.prototype[FL.chain] = function Future$FL$chain(mapper){\n\t  var context = captureContext(nil, 'a Fantasy Land dispatch to chain', Future$FL$chain);\n\t  return this._transform(new ChainTransformation(context, mapper));\n\t};\n\n\tFuture.prototype[FL.alt] = function Future$FL$alt(other){\n\t  var context = captureContext(nil, 'a Fantasy Land dispatch to alt', Future$FL$alt);\n\t  return this._transform(new AltTransformation(context, other));\n\t};\n\n\tFuture.prototype.extractLeft = function Future$extractLeft(){\n\t  return [];\n\t};\n\n\tFuture.prototype.extractRight = function Future$extractRight(){\n\t  return [];\n\t};\n\n\tFuture.prototype._transform = function Future$transform(transformation){\n\t  return new Transformer(transformation.context, this, cons(transformation, nil));\n\t};\n\n\tFuture.prototype.isTransformer = false;\n\tFuture.prototype.context = nil;\n\tFuture.prototype.arity = 0;\n\tFuture.prototype.name = 'future';\n\n\tFuture.prototype.toString = function Future$toString(){\n\t  return this.name + getArgs(this).map(showArg).join('');\n\t};\n\n\tFuture.prototype.toJSON = function Future$toJSON(){\n\t  return {$: $$type$1, kind: 'interpreter', type: this.name, args: getArgs(this)};\n\t};\n\n\tfunction createInterpreter(arity, name, interpret){\n\t  var Interpreter = function(context, $1, $2, $3){\n\t    this.context = context;\n\t    this.$1 = $1;\n\t    this.$2 = $2;\n\t    this.$3 = $3;\n\t  };\n\n\t  Interpreter.prototype = Object.create(Future.prototype);\n\t  Interpreter.prototype.arity = arity;\n\t  Interpreter.prototype.name = name;\n\t  Interpreter.prototype._interpret = interpret;\n\n\t  return Interpreter;\n\t}\n\n\tvar Computation =\n\tcreateInterpreter(1, 'Future', function Computation$interpret(rec, rej, res){\n\t  var computation = this.$1, open = false, cancel = noop, cont = function(){ open = true; };\n\t  try{\n\t    cancel = computation(function Computation$rej(x){\n\t      cont = function Computation$rej$cont(){\n\t        open = false;\n\t        rej(x);\n\t      };\n\t      if(open){\n\t        cont();\n\t      }\n\t    }, function Computation$res(x){\n\t      cont = function Computation$res$cont(){\n\t        open = false;\n\t        res(x);\n\t      };\n\t      if(open){\n\t        cont();\n\t      }\n\t    });\n\t  }catch(e){\n\t    rec(wrapException(e, this));\n\t    return noop;\n\t  }\n\t  if(!(isFunction(cancel) && cancel.length === 0)){\n\t    rec(wrapException(typeError(\n\t      'The computation was expected to return a nullary cancellation function\\n' +\n\t      '  Actual: ' + sanctuaryShow(cancel)\n\t    ), this));\n\t    return noop;\n\t  }\n\t  cont();\n\t  return function Computation$cancel(){\n\t    if(open){\n\t      open = false;\n\t      cancel && cancel();\n\t    }\n\t  };\n\t});\n\n\tvar Never = createInterpreter(0, 'never', function Never$interpret(){\n\t  return noop;\n\t});\n\n\tNever.prototype._isNever = true;\n\n\tvar never = new Never(nil);\n\n\tfunction isNever(x){\n\t  return isFuture(x) && x._isNever === true;\n\t}\n\n\tvar Crash = createInterpreter(1, 'crash', function Crash$interpret(rec){\n\t  rec(this.$1);\n\t  return noop;\n\t});\n\n\tfunction crash(x){\n\t  return new Crash(application1(crash, any, arguments), x);\n\t}\n\n\tvar Reject = createInterpreter(1, 'reject', function Reject$interpret(rec, rej){\n\t  rej(this.$1);\n\t  return noop;\n\t});\n\n\tReject.prototype.extractLeft = function Reject$extractLeft(){\n\t  return [this.$1];\n\t};\n\n\tfunction reject(x){\n\t  return new Reject(application1(reject, any, arguments), x);\n\t}\n\n\tvar Resolve = createInterpreter(1, 'resolve', function Resolve$interpret(rec, rej, res){\n\t  res(this.$1);\n\t  return noop;\n\t});\n\n\tResolve.prototype.extractRight = function Resolve$extractRight(){\n\t  return [this.$1];\n\t};\n\n\tfunction resolve(x){\n\t  return new Resolve(application1(resolve, any, arguments), x);\n\t}\n\n\t//Note: This function is not curried because it's only used to satisfy the\n\t//      Fantasy Land ChainRec specification.\n\tfunction chainRec(step, init){\n\t  return resolve(Next(init))._transform(new ChainTransformation(nil, function chainRec$recur(o){\n\t    return o.done ?\n\t           resolve(o.value) :\n\t           step(Next, Done, o.value)._transform(new ChainTransformation(nil, chainRec$recur));\n\t  }));\n\t}\n\n\tvar Transformer =\n\tcreateInterpreter(2, 'transform', function Transformer$interpret(rec, rej, res){\n\n\t  //These are the cold, and hot, transformation stacks. The cold actions are those that\n\t  //have yet to run parallel computations, and hot are those that have.\n\t  var cold = nil, hot = nil;\n\n\t  //These combined variables define our current state.\n\t  // future         = the future we are currently forking\n\t  // transformation = the transformation to be informed when the future settles\n\t  // cancel         = the cancel function of the current future\n\t  // settled        = a boolean indicating whether a new tick should start\n\t  // async          = a boolean indicating whether we are awaiting a result asynchronously\n\t  var future, transformation, cancel = noop, settled, async = true, it;\n\n\t  //Takes a transformation from the top of the hot stack and returns it.\n\t  function nextHot(){\n\t    var x = hot.head;\n\t    hot = hot.tail;\n\t    return x;\n\t  }\n\n\t  //Takes a transformation from the top of the cold stack and returns it.\n\t  function nextCold(){\n\t    var x = cold.head;\n\t    cold = cold.tail;\n\t    return x;\n\t  }\n\n\t  //This function is called with a future to use in the next tick.\n\t  //Here we \"flatten\" the actions of another Sequence into our own actions,\n\t  //this is the magic that allows for infinitely stack safe recursion because\n\t  //actions like ChainAction will return a new Sequence.\n\t  //If we settled asynchronously, we call drain() directly to run the next tick.\n\t  function settle(m){\n\t    settled = true;\n\t    future = m;\n\t    if(future.isTransformer){\n\t      var tail = future.$2;\n\t      while(!isNil(tail)){\n\t        cold = cons(tail.head, cold);\n\t        tail = tail.tail;\n\t      }\n\t      future = future.$1;\n\t    }\n\t    if(async) drain();\n\t  }\n\n\t  //This function serves as a rejection handler for our current future.\n\t  //It will tell the current transformation that the future rejected, and it will\n\t  //settle the current tick with the transformation's answer to that.\n\t  function rejected(x){\n\t    settle(transformation.rejected(x));\n\t  }\n\n\t  //This function serves as a resolution handler for our current future.\n\t  //It will tell the current transformation that the future resolved, and it will\n\t  //settle the current tick with the transformation's answer to that.\n\t  function resolved(x){\n\t    settle(transformation.resolved(x));\n\t  }\n\n\t  //This function is passed into actions when they are \"warmed up\".\n\t  //If the transformation decides that it has its result, without the need to await\n\t  //anything else, then it can call this function to force \"early termination\".\n\t  //When early termination occurs, all actions which were stacked prior to the\n\t  //terminator will be skipped. If they were already hot, they will also be\n\t  //sent a cancel signal so they can cancel their own concurrent computations,\n\t  //as their results are no longer needed.\n\t  function early(m, terminator){\n\t    cancel();\n\t    cold = nil;\n\t    if(async && transformation !== terminator){\n\t      transformation.cancel();\n\t      while((it = nextHot()) && it !== terminator) it.cancel();\n\t    }\n\t    settle(m);\n\t  }\n\n\t  //This will cancel the current Future, the current transformation, and all stacked hot actions.\n\t  function Sequence$cancel(){\n\t    cancel();\n\t    transformation && transformation.cancel();\n\t    while(it = nextHot()) it.cancel();\n\t  }\n\n\t  //This function is called when an exception is caught.\n\t  function exception(e){\n\t    Sequence$cancel();\n\t    settled = true;\n\t    cold = hot = nil;\n\t    var error = wrapException(e, future);\n\t    future = never;\n\t    rec(error);\n\t  }\n\n\t  //This function serves to kickstart concurrent computations.\n\t  //Takes all actions from the cold stack in reverse order, and calls run() on\n\t  //each of them, passing them the \"early\" function. If any of them settles (by\n\t  //calling early()), we abort. After warming up all actions in the cold queue,\n\t  //we warm up the current transformation as well.\n\t  function warmupActions(){\n\t    cold = reverse(cold);\n\t    while(cold !== nil){\n\t      it = cold.head.run(early);\n\t      if(settled) return;\n\t      hot = cons(it, hot);\n\t      cold = cold.tail;\n\t    }\n\t    transformation = transformation.run(early);\n\t  }\n\n\t  //This function represents our main execution loop. By \"tick\", we've been\n\t  //referring to the execution of one iteration in the while-loop below.\n\t  function drain(){\n\t    async = false;\n\t    while(true){\n\t      settled = false;\n\t      if(transformation = nextCold()){\n\t        cancel = future._interpret(exception, rejected, resolved);\n\t        if(!settled) warmupActions();\n\t      }else if(transformation = nextHot()){\n\t        cancel = future._interpret(exception, rejected, resolved);\n\t      }else break;\n\t      if(settled) continue;\n\t      async = true;\n\t      return;\n\t    }\n\t    cancel = future._interpret(exception, rej, res);\n\t  }\n\n\t  //Start the execution loop.\n\t  settle(this);\n\n\t  //Return the cancellation function.\n\t  return Sequence$cancel;\n\n\t});\n\n\tTransformer.prototype.isTransformer = true;\n\n\tTransformer.prototype._transform = function Transformer$_transform(transformation){\n\t  return new Transformer(transformation.context, this.$1, cons(transformation, this.$2));\n\t};\n\n\tTransformer.prototype.toString = function Transformer$toString(){\n\t  return toArray(reverse(this.$2)).reduce(function(str, action){\n\t    return action.name + getArgs(action).map(showArg).join('') + ' (' + str + ')';\n\t  }, this.$1.toString());\n\t};\n\n\tfunction BaseTransformation$rejected(x){\n\t  this.cancel();\n\t  return new Reject(this.context, x);\n\t}\n\n\tfunction BaseTransformation$resolved(x){\n\t  this.cancel();\n\t  return new Resolve(this.context, x);\n\t}\n\n\tfunction BaseTransformation$toJSON(){\n\t  return {$: $$type$1, kind: 'transformation', type: this.name, args: getArgs(this)};\n\t}\n\n\tvar BaseTransformation = {\n\t  rejected: BaseTransformation$rejected,\n\t  resolved: BaseTransformation$resolved,\n\t  run: moop,\n\t  cancel: noop,\n\t  context: nil,\n\t  arity: 0,\n\t  name: 'transform',\n\t  toJSON: BaseTransformation$toJSON\n\t};\n\n\tfunction wrapHandler(handler){\n\t  return function transformationHandler(x){\n\t    var m;\n\t    try{\n\t      m = handler.call(this, x);\n\t    }catch(e){\n\t      return new Crash(this.context, e);\n\t    }\n\t    if(isFuture(m)){\n\t      return m;\n\t    }\n\t    return new Crash(this.context, invalidFuture(\n\t      this.name + ' expects the return value from the function it\\'s given', m,\n\t      '\\n  When called with: ' + sanctuaryShow(x)\n\t    ));\n\t  };\n\t}\n\n\tfunction createTransformation(arity, name, prototype){\n\t  var Transformation = function(context, $1, $2){\n\t    this.context = context;\n\t    this.$1 = $1;\n\t    this.$2 = $2;\n\t  };\n\n\t  Transformation.prototype = Object.create(BaseTransformation);\n\t  Transformation.prototype.arity = arity;\n\t  Transformation.prototype.name = name;\n\n\t  if(typeof prototype.rejected === 'function'){\n\t    Transformation.prototype.rejected = wrapHandler(prototype.rejected);\n\t  }\n\n\t  if(typeof prototype.resolved === 'function'){\n\t    Transformation.prototype.resolved = wrapHandler(prototype.resolved);\n\t  }\n\n\t  if(typeof prototype.run === 'function'){\n\t    Transformation.prototype.run = prototype.run;\n\t  }\n\n\t  return Transformation;\n\t}\n\n\tvar ApTransformation = createTransformation(1, 'ap', {\n\t  resolved: function ApTransformation$resolved(f){\n\t    if(isFunction(f)) return this.$1._transform(new MapTransformation(this.context, f));\n\t    throw typeError(\n\t      'ap expects the second Future to resolve to a Function\\n' +\n\t      '  Actual: ' + sanctuaryShow(f)\n\t    );\n\t  }\n\t});\n\n\tvar AltTransformation = createTransformation(1, 'alt', {\n\t  rejected: function AltTransformation$rejected(){ return this.$1 }\n\t});\n\n\tvar MapTransformation = createTransformation(1, 'map', {\n\t  resolved: function MapTransformation$resolved(x){\n\t    return new Resolve(this.context, call(this.$1, x));\n\t  }\n\t});\n\n\tvar BimapTransformation = createTransformation(2, 'bimap', {\n\t  rejected: function BimapTransformation$rejected(x){\n\t    return new Reject(this.context, call(this.$1, x));\n\t  },\n\t  resolved: function BimapTransformation$resolved(x){\n\t    return new Resolve(this.context, call(this.$2, x));\n\t  }\n\t});\n\n\tvar ChainTransformation = createTransformation(1, 'chain', {\n\t  resolved: function ChainTransformation$resolved(x){ return call(this.$1, x) }\n\t});\n\n\tvar After = createInterpreter(2, 'after', function After$interpret(rec, rej, res){\n\t  var id = setTimeout(res, this.$1, this.$2);\n\t  return function After$cancel(){ clearTimeout(id); };\n\t});\n\n\tAfter.prototype.extractRight = function After$extractRight(){\n\t  return [this.$2];\n\t};\n\n\tfunction alwaysNever$1(_){\n\t  return never;\n\t}\n\n\tfunction after(time){\n\t  var context1 = application1(after, positiveInteger, arguments);\n\t  return time === Infinity ? alwaysNever$1 : (function after(value){\n\t    var context2 = application(2, after, any, arguments, context1);\n\t    return new After(context2, time, value);\n\t  });\n\t}\n\n\tvar alternative = {pred: isAlt, error: invalidArgumentOf('have Alt implemented')};\n\n\tfunction alt(left){\n\t  if(isFuture(left)){\n\t    var context1 = application1(alt, future, arguments);\n\t    return function alt(right){\n\t      var context2 = application(2, alt, future, arguments, context1);\n\t      return right._transform(new AltTransformation(context2, left));\n\t    };\n\t  }\n\n\t  var context = application1(alt, alternative, arguments);\n\t  return function alt(right){\n\t    application(2, alt, alternative, arguments, context);\n\t    return left[FL.alt](right);\n\t  };\n\t}\n\n\tvar AndTransformation = createTransformation(1, 'and', {\n\t  resolved: function AndTransformation$resolved(){ return this.$1 }\n\t});\n\n\tfunction and(left){\n\t  var context1 = application1(and, future, arguments);\n\t  return function and(right){\n\t    var context2 = application(2, and, future, arguments, context1);\n\t    return right._transform(new AndTransformation(context2, left));\n\t  };\n\t}\n\n\tvar apply = {pred: isApply, error: invalidArgumentOf('have Apply implemented')};\n\n\tfunction ap(mx){\n\t  if(isFuture(mx)){\n\t    var context1 = application1(ap, future, arguments);\n\t    return function ap(mf){\n\t      var context2 = application(2, ap, future, arguments, context1);\n\t      return mf._transform(new ApTransformation(context2, mx));\n\t    };\n\t  }\n\n\t  var context = application1(ap, apply, arguments);\n\t  return function ap(mf){\n\t    application(2, ap, apply, arguments, context);\n\t    return mx[FL.ap](mf);\n\t  };\n\t}\n\n\tfunction invalidPromise(p, f, a){\n\t  return typeError(\n\t    'encaseP() expects the function it\\'s given to return a Promise/Thenable'\n\t    + '\\n  Actual: ' + sanctuaryShow(p) + '\\n  From calling: ' + sanctuaryShow(f)\n\t    + '\\n  With: ' + sanctuaryShow(a)\n\t  );\n\t}\n\n\tvar EncaseP = createInterpreter(2, 'encaseP', function EncaseP$interpret(rec, rej, res){\n\t  var open = true, fn = this.$1, arg = this.$2, p;\n\t  try{\n\t    p = fn(arg);\n\t  }catch(e){\n\t    rec(wrapException(e, this));\n\t    return noop;\n\t  }\n\t  if(!isThenable(p)){\n\t    rec(wrapException(invalidPromise(p, fn, arg), this));\n\t    return noop;\n\t  }\n\t  p.then(function EncaseP$res(x){\n\t    if(open){\n\t      open = false;\n\t      res(x);\n\t    }\n\t  }, function EncaseP$rej(x){\n\t    if(open){\n\t      open = false;\n\t      rej(x);\n\t    }\n\t  });\n\t  return function EncaseP$cancel(){ open = false; };\n\t});\n\n\tfunction encaseP(f){\n\t  var context1 = application1(encaseP, func, arguments);\n\t  return function encaseP(x){\n\t    var context2 = application(2, encaseP, any, arguments, context1);\n\t    return new EncaseP(context2, f, x);\n\t  };\n\t}\n\n\tfunction attemptP(_){\n\t  return encaseP.apply(this, arguments)(undefined);\n\t}\n\n\tvar Encase = createInterpreter(2, 'encase', function Encase$interpret(rec, rej, res){\n\t  var fn = this.$1, r;\n\t  try{ r = fn(this.$2); }catch(e){ rej(e); return noop }\n\t  res(r);\n\t  return noop;\n\t});\n\n\tfunction encase(f){\n\t  var context1 = application1(encase, func, arguments);\n\t  return function encase(x){\n\t    var context2 = application(2, encase, any, arguments, context1);\n\t    return new Encase(context2, f, x);\n\t  };\n\t}\n\n\tfunction attempt(_){\n\t  return encase.apply(this, arguments)(undefined);\n\t}\n\n\tvar bifunctor = {pred: isBifunctor, error: invalidArgumentOf('have Bifunctor implemented')};\n\n\tfunction bimap(f){\n\t  var context1 = application1(bimap, func, arguments);\n\t  return function bimap(g){\n\t    var context2 = application(2, bimap, func, arguments, context1);\n\t    return function bimap(m){\n\t      var context3 = application(3, bimap, bifunctor, arguments, context2);\n\t      return isFuture(m) ?\n\t             m._transform(new BimapTransformation(context3, f, g)) :\n\t             m[FL.bimap](f, g);\n\t    };\n\t  };\n\t}\n\n\tvar BichainTransformation = createTransformation(2, 'bichain', {\n\t  rejected: function BichainTransformation$rejected(x){ return call(this.$1, x) },\n\t  resolved: function BichainTransformation$resolved(x){ return call(this.$2, x) }\n\t});\n\n\tfunction bichain(f){\n\t  var context1 = application1(bichain, func, arguments);\n\t  return function bichain(g){\n\t    var context2 = application(2, bichain, func, arguments, context1);\n\t    return function bichain(m){\n\t      var context3 = application(3, bichain, future, arguments, context2);\n\t      return m._transform(new BichainTransformation(context3, f, g));\n\t    };\n\t  };\n\t}\n\n\tfunction Eager(future){\n\t  var _this = this;\n\t  _this.rec = noop;\n\t  _this.rej = noop;\n\t  _this.res = noop;\n\t  _this.crashed = false;\n\t  _this.rejected = false;\n\t  _this.resolved = false;\n\t  _this.value = null;\n\t  _this.cancel = future._interpret(function Eager$crash(x){\n\t    _this.value = x;\n\t    _this.crashed = true;\n\t    _this.cancel = noop;\n\t    _this.rec(x);\n\t  }, function Eager$reject(x){\n\t    _this.value = x;\n\t    _this.rejected = true;\n\t    _this.cancel = noop;\n\t    _this.rej(x);\n\t  }, function Eager$resolve(x){\n\t    _this.value = x;\n\t    _this.resolved = true;\n\t    _this.cancel = noop;\n\t    _this.res(x);\n\t  });\n\t}\n\n\tEager.prototype = Object.create(Future.prototype);\n\n\tEager.prototype._interpret = function Eager$interpret(rec, rej, res){\n\t  if(this.crashed) rec(this.value);\n\t  else if(this.rejected) rej(this.value);\n\t  else if(this.resolved) res(this.value);\n\t  else {\n\t    this.rec = rec;\n\t    this.rej = rej;\n\t    this.res = res;\n\t  }\n\t  return this.cancel;\n\t};\n\n\tfunction earlyCrash(early, x){\n\t  early(crash(x));\n\t}\n\n\tfunction earlyReject(early, x){\n\t  early(reject(x));\n\t}\n\n\tfunction earlyResolve(early, x){\n\t  early(resolve(x));\n\t}\n\n\tfunction createParallelTransformation(name, rec, rej, res, prototype){\n\t  var ParallelTransformation = createTransformation(1, name, Object.assign({\n\t    run: function Parallel$run(early){\n\t      var eager = new Eager(this.$1);\n\t      var transformation = new ParallelTransformation(this.context, eager);\n\t      function Parallel$early(m){ early(m, transformation); }\n\t      transformation.cancel = eager._interpret(\n\t        function Parallel$rec(x){ rec(Parallel$early, x); },\n\t        function Parallel$rej(x){ rej(Parallel$early, x); },\n\t        function Parallel$res(x){ res(Parallel$early, x); }\n\t      );\n\t      return transformation;\n\t    }\n\t  }, prototype));\n\t  return ParallelTransformation;\n\t}\n\n\tvar PairTransformation = createTransformation(1, 'pair', {\n\t  resolved: function PairTransformation$resolved(x){\n\t    return new Resolve(this.context, [x, this.$1]);\n\t  }\n\t});\n\n\tvar BothTransformation =\n\tcreateParallelTransformation('both', earlyCrash, earlyReject, noop, {\n\t  resolved: function BothTransformation$resolved(x){\n\t    return this.$1._transform(new PairTransformation(this.context, x));\n\t  }\n\t});\n\n\tfunction both(left){\n\t  var context1 = application1(both, future, arguments);\n\t  return function both(right){\n\t    var context2 = application(2, both, future, arguments, context1);\n\t    return right._transform(new BothTransformation(context2, left));\n\t  };\n\t}\n\n\tvar Cold = 0;\n\tvar Pending = 1;\n\tvar Crashed = 2;\n\tvar Rejected = 3;\n\tvar Resolved = 4;\n\n\tfunction Queued(rec, rej, res){\n\t  this[Crashed] = rec;\n\t  this[Rejected] = rej;\n\t  this[Resolved] = res;\n\t}\n\n\tvar Cache = createInterpreter(1, 'cache', function Cache$interpret(rec, rej, res){\n\t  var cancel = noop;\n\n\t  switch(this._state){\n\t    /* c8 ignore next 4 */\n\t    case Pending: cancel = this._addToQueue(rec, rej, res); break;\n\t    case Crashed: rec(this._value); break;\n\t    case Rejected: rej(this._value); break;\n\t    case Resolved: res(this._value); break;\n\t    default:\n\t      this._queue = [];\n\t      cancel = this._addToQueue(rec, rej, res);\n\t      this.run();\n\t  }\n\n\t  return cancel;\n\t});\n\n\tCache.prototype._cancel = noop;\n\tCache.prototype._queue = null;\n\tCache.prototype._queued = 0;\n\tCache.prototype._value = undefined;\n\tCache.prototype._state = Cold;\n\n\tCache.prototype.extractLeft = function Cache$extractLeft(){\n\t  return this._state === Rejected ? [this._value] : [];\n\t};\n\n\tCache.prototype.extractRight = function Cache$extractRight(){\n\t  return this._state === Resolved ? [this._value] : [];\n\t};\n\n\tCache.prototype._addToQueue = function Cache$addToQueue(rec, rej, res){\n\t  var _this = this;\n\t  if(_this._state > Pending) return noop;\n\t  var i = _this._queue.push(new Queued(rec, rej, res)) - 1;\n\t  _this._queued = _this._queued + 1;\n\n\t  return function Cache$removeFromQueue(){\n\t    if(_this._state > Pending) return;\n\t    _this._queue[i] = undefined;\n\t    _this._queued = _this._queued - 1;\n\t    if(_this._queued === 0) _this.reset();\n\t  };\n\t};\n\n\tCache.prototype._drainQueue = function Cache$drainQueue(){\n\t  if(this._state <= Pending) return;\n\t  if(this._queued === 0) return;\n\t  var queue = this._queue;\n\t  var length = queue.length;\n\t  var state = this._state;\n\t  var value = this._value;\n\n\t  for(var i = 0; i < length; i++){\n\t    queue[i] && queue[i][state](value);\n\t    queue[i] = undefined;\n\t  }\n\n\t  this._queue = undefined;\n\t  this._queued = 0;\n\t};\n\n\tCache.prototype.crash = function Cache$crash(error){\n\t  if(this._state > Pending) return;\n\t  this._value = error;\n\t  this._state = Crashed;\n\t  this._drainQueue();\n\t};\n\n\tCache.prototype.reject = function Cache$reject(reason){\n\t  if(this._state > Pending) return;\n\t  this._value = reason;\n\t  this._state = Rejected;\n\t  this._drainQueue();\n\t};\n\n\tCache.prototype.resolve = function Cache$resolve(value){\n\t  if(this._state > Pending) return;\n\t  this._value = value;\n\t  this._state = Resolved;\n\t  this._drainQueue();\n\t};\n\n\tCache.prototype.run = function Cache$run(){\n\t  var _this = this;\n\t  if(_this._state > Cold) return;\n\t  _this._state = Pending;\n\t  _this._cancel = _this.$1._interpret(\n\t    function Cache$fork$rec(x){ _this.crash(x); },\n\t    function Cache$fork$rej(x){ _this.reject(x); },\n\t    function Cache$fork$res(x){ _this.resolve(x); }\n\t  );\n\t};\n\n\tCache.prototype.reset = function Cache$reset(){\n\t  if(this._state === Cold) return;\n\t  if(this._state === Pending) this._cancel();\n\t  this._cancel = noop;\n\t  this._queue = [];\n\t  this._queued = 0;\n\t  this._value = undefined;\n\t  this._state = Cold;\n\t};\n\n\tfunction cache(m){\n\t  return new Cache(application1(cache, future, arguments), m);\n\t}\n\n\tvar ChainRejTransformation = createTransformation(1, 'chainRej', {\n\t  rejected: function ChainRejTransformation$rejected(x){ return call(this.$1, x) }\n\t});\n\n\tfunction chainRej(f){\n\t  var context1 = application1(chainRej, func, arguments);\n\t  return function chainRej(m){\n\t    var context2 = application(2, chainRej, future, arguments, context1);\n\t    return m._transform(new ChainRejTransformation(context2, f));\n\t  };\n\t}\n\n\tvar monad = {pred: isChain, error: invalidArgumentOf('have Chain implemented')};\n\n\tfunction chain(f){\n\t  var context1 = application1(chain, func, arguments);\n\t  return function chain(m){\n\t    var context2 = application(2, chain, monad, arguments, context1);\n\t    return isFuture(m) ?\n\t           m._transform(new ChainTransformation(context2, f)) :\n\t           m[FL.chain](f);\n\t  };\n\t}\n\n\tfunction done(callback){\n\t  var context1 = application1(done, func, arguments);\n\t  function done$res(x){\n\t    callback(null, x);\n\t  }\n\t  return function done(m){\n\t    application(2, done, future, arguments, context1);\n\t    return m._interpret(raise, callback, done$res);\n\t  };\n\t}\n\n\tfunction extractLeft(m){\n\t  application1(extractLeft, future, arguments);\n\t  return m.extractLeft();\n\t}\n\n\tfunction extractRight(m){\n\t  application1(extractRight, future, arguments);\n\t  return m.extractRight();\n\t}\n\n\tvar CoalesceTransformation = createTransformation(2, 'coalesce', {\n\t  rejected: function CoalesceTransformation$rejected(x){\n\t    return new Resolve(this.context, call(this.$1, x));\n\t  },\n\t  resolved: function CoalesceTransformation$resolved(x){\n\t    return new Resolve(this.context, call(this.$2, x));\n\t  }\n\t});\n\n\tfunction coalesce(f){\n\t  var context1 = application1(coalesce, func, arguments);\n\t  return function coalesce(g){\n\t    var context2 = application(2, coalesce, func, arguments, context1);\n\t    return function coalesce(m){\n\t      var context3 = application(3, coalesce, future, arguments, context2);\n\t      return m._transform(new CoalesceTransformation(context3, f, g));\n\t    };\n\t  };\n\t}\n\n\tfunction forkCatch(f){\n\t  var context1 = application1(forkCatch, func, arguments);\n\t  return function forkCatch(g){\n\t    var context2 = application(2, forkCatch, func, arguments, context1);\n\t    return function forkCatch(h){\n\t      var context3 = application(3, forkCatch, func, arguments, context2);\n\t      return function forkCatch(m){\n\t        application(4, forkCatch, future, arguments, context3);\n\t        return m._interpret(f, g, h);\n\t      };\n\t    };\n\t  };\n\t}\n\n\tfunction fork(f){\n\t  var context1 = application1(fork, func, arguments);\n\t  return function fork(g){\n\t    var context2 = application(2, fork, func, arguments, context1);\n\t    return function fork(m){\n\t      application(3, fork, future, arguments, context2);\n\t      return m._interpret(raise, f, g);\n\t    };\n\t  };\n\t}\n\n\tvar Undetermined = 0;\n\tvar Synchronous = 1;\n\tvar Asynchronous = 2;\n\n\t/*eslint consistent-return: 0 */\n\n\tfunction invalidIteration(o){\n\t  return typeError(\n\t    'The iterator did not return a valid iteration from iterator.next()\\n' +\n\t    '  Actual: ' + sanctuaryShow(o)\n\t  );\n\t}\n\n\tfunction invalidState(x){\n\t  return invalidFuture(\n\t    'go() expects the value produced by the iterator', x,\n\t    '\\n  Tip: If you\\'re using a generator, make sure you always yield a Future'\n\t  );\n\t}\n\n\tvar Go = createInterpreter(1, 'go', function Go$interpret(rec, rej, res){\n\n\t  var _this = this, timing = Undetermined, cancel = noop, state, value, iterator;\n\n\t  function crash(e){\n\t    rec(wrapException(e, _this));\n\t  }\n\n\t  try{\n\t    iterator = _this.$1();\n\t  }catch(e){\n\t    crash(e);\n\t    return noop;\n\t  }\n\n\t  if(!isIterator(iterator)){\n\t    crash(invalidArgument('go', 0, 'return an iterator, maybe you forgot the \"*\"', iterator));\n\t    return noop;\n\t  }\n\n\t  function resolved(x){\n\t    value = x;\n\t    if(timing === Asynchronous) return drain();\n\t    timing = Synchronous;\n\t  }\n\n\t  function drain(){\n\t    //eslint-disable-next-line no-constant-condition\n\t    while(true){\n\t      try{\n\t        state = iterator.next(value);\n\t      }catch(e){\n\t        return crash(e);\n\t      }\n\t      if(!isIteration(state)) return crash(invalidIteration(state));\n\t      if(state.done) break;\n\t      if(!isFuture(state.value)){\n\t        return crash(invalidState(state.value));\n\t      }\n\t      timing = Undetermined;\n\t      cancel = state.value._interpret(crash, rej, resolved);\n\t      if(timing === Undetermined) return timing = Asynchronous;\n\t    }\n\t    res(state.value);\n\t  }\n\n\t  drain();\n\n\t  return function Go$cancel(){ cancel(); };\n\n\t});\n\n\tfunction go(generator){\n\t  return new Go(application1(go, func, arguments), generator);\n\t}\n\n\tfunction invalidDisposal(m, f, x){\n\t  return invalidFuture(\n\t    'hook() expects the return value from the first function it\\'s given', m,\n\t    '\\n  From calling: ' + sanctuaryShow(f) + '\\n  With: ' + sanctuaryShow(x)\n\t  );\n\t}\n\n\tfunction invalidConsumption(m, f, x){\n\t  return invalidFuture(\n\t    'hook() expects the return value from the second function it\\'s given', m,\n\t    '\\n  From calling: ' + sanctuaryShow(f) + '\\n  With: ' + sanctuaryShow(x)\n\t  );\n\t}\n\n\tvar Hook = createInterpreter(3, 'hook', function Hook$interpret(rec, rej, res){\n\n\t  var _this = this, _acquire = this.$1, _dispose = this.$2, _consume = this.$3;\n\t  var cancel, cancelConsume = noop, resource, value, cont = noop;\n\n\t  function Hook$done(){\n\t    cont(value);\n\t  }\n\n\t  function Hook$rec(x){\n\t    rec(wrapException(x, _this));\n\t  }\n\n\t  function Hook$dispose(){\n\t    var disposal;\n\t    try{\n\t      disposal = _dispose(resource);\n\t    }catch(e){\n\t      return Hook$rec(e);\n\t    }\n\t    if(!isFuture(disposal)){\n\t      return Hook$rec(invalidDisposal(disposal, _dispose, resource));\n\t    }\n\t    cancel = Hook$cancelDisposal;\n\t    disposal._interpret(Hook$rec, Hook$disposalRejected, Hook$done);\n\t  }\n\n\t  function Hook$cancelConsumption(){\n\t    cancelConsume();\n\t    Hook$dispose();\n\t    Hook$cancelDisposal();\n\t  }\n\n\t  function Hook$cancelDisposal(){\n\t    cont = noop;\n\t  }\n\n\t  function Hook$disposalRejected(x){\n\t    Hook$rec(new Error('The disposal Future rejected with ' + sanctuaryShow(x)));\n\t  }\n\n\t  function Hook$consumptionException(x){\n\t    cont = Hook$rec;\n\t    value = x;\n\t    Hook$dispose();\n\t  }\n\n\t  function Hook$consumptionRejected(x){\n\t    cont = rej;\n\t    value = x;\n\t    Hook$dispose();\n\t  }\n\n\t  function Hook$consumptionResolved(x){\n\t    cont = res;\n\t    value = x;\n\t    Hook$dispose();\n\t  }\n\n\t  function Hook$consume(x){\n\t    resource = x;\n\t    var consumption;\n\t    try{\n\t      consumption = _consume(resource);\n\t    }catch(e){\n\t      return Hook$consumptionException(e);\n\t    }\n\t    if(!isFuture(consumption)){\n\t      return Hook$consumptionException(invalidConsumption(consumption, _consume, resource));\n\t    }\n\t    cancel = Hook$cancelConsumption;\n\t    cancelConsume = consumption._interpret(\n\t      Hook$consumptionException,\n\t      Hook$consumptionRejected,\n\t      Hook$consumptionResolved\n\t    );\n\t  }\n\n\t  var cancelAcquire = _acquire._interpret(Hook$rec, rej, Hook$consume);\n\t  cancel = cancel || cancelAcquire;\n\n\t  return function Hook$fork$cancel(){\n\t    rec = raise;\n\t    cancel();\n\t  };\n\n\t});\n\n\tfunction hook(acquire){\n\t  var context1 = application1(hook, future, arguments);\n\t  return function hook(dispose){\n\t    var context2 = application(2, hook, func, arguments, context1);\n\t    return function hook(consume){\n\t      var context3 = application(3, hook, func, arguments, context2);\n\t      return new Hook(context3, acquire, dispose, consume);\n\t    };\n\t  };\n\t}\n\n\tvar LastlyTransformation = createTransformation(1, 'lastly', {\n\t  rejected: function LastlyAction$rejected(x){\n\t    return this.$1._transform(new AndTransformation(this.context, new Reject(this.context, x)));\n\t  },\n\t  resolved: function LastlyAction$resolved(x){\n\t    return this.$1._transform(new AndTransformation(this.context, new Resolve(this.context, x)));\n\t  }\n\t});\n\n\tfunction lastly(cleanup){\n\t  var context1 = application1(lastly, future, arguments);\n\t  return function lastly(program){\n\t    var context2 = application(2, lastly, future, arguments, context1);\n\t    return program._transform(new LastlyTransformation(context2, cleanup));\n\t  };\n\t}\n\n\tvar MapRejTransformation = createTransformation(1, 'mapRej', {\n\t  rejected: function MapRejTransformation$rejected(x){\n\t    return new Reject(this.context, call(this.$1, x));\n\t  }\n\t});\n\n\tfunction mapRej(f){\n\t  var context1 = application1(mapRej, func, arguments);\n\t  return function mapRej(m){\n\t    var context2 = application(2, mapRej, future, arguments, context1);\n\t    return m._transform(new MapRejTransformation(context2, f));\n\t  };\n\t}\n\n\tvar functor = {pred: isFunctor, error: invalidArgumentOf('have Functor implemented')};\n\n\tfunction map(f){\n\t  var context1 = application1(map, func, arguments);\n\t  return function map(m){\n\t    var context2 = application(2, map, functor, arguments, context1);\n\t    return isFuture(m) ?\n\t           m._transform(new MapTransformation(context2, f)) :\n\t           m[FL.map](f);\n\t  };\n\t}\n\n\tvar Node = createInterpreter(1, 'node', function Node$interpret(rec, rej, res){\n\t  function Node$done(err, val){\n\t    cont = err ? function EncaseN3$rej(){\n\t      open = false;\n\t      rej(err);\n\t    } : function EncaseN3$res(){\n\t      open = false;\n\t      res(val);\n\t    };\n\t    if(open){\n\t      cont();\n\t    }\n\t  }\n\t  var open = false, cont = function(){ open = true; };\n\t  try{\n\t    call(this.$1, Node$done);\n\t  }catch(e){\n\t    rec(wrapException(e, this));\n\t    open = false;\n\t    return noop;\n\t  }\n\t  cont();\n\t  return function Node$cancel(){ open = false; };\n\t});\n\n\tfunction node(f){\n\t  return new Node(application1(node, func, arguments), f);\n\t}\n\n\tvar ParallelApTransformation =\n\tcreateParallelTransformation('pap', earlyCrash, earlyReject, noop, {\n\t  resolved: function ParallelApTransformation$resolved(f){\n\t    if(isFunction(f)) return this.$1._transform(new MapTransformation(this.context, f));\n\t    throw typeError(\n\t      'pap expects the second Future to resolve to a Function\\n' +\n\t      '  Actual: ' + sanctuaryShow(f)\n\t    );\n\t  }\n\t});\n\n\tfunction pap(mx){\n\t  var context1 = application1(pap, future, arguments);\n\t  return function pap(mf){\n\t    var context2 = application(2, pap, future, arguments, context1);\n\t    return mf._transform(new ParallelApTransformation(context2, mx));\n\t  };\n\t}\n\n\tfunction isFutureArray(xs){\n\t  if(!isArray(xs)) return false;\n\t  for(var i = 0; i < xs.length; i++){\n\t    if(!isFuture(xs[i])) return false;\n\t  }\n\t  return true;\n\t}\n\n\tvar futureArray = {\n\t  pred: isFutureArray,\n\t  error: invalidArgumentOf('be an Array of valid Futures')\n\t};\n\n\tvar Parallel = createInterpreter(2, 'parallel', function Parallel$interpret(rec, rej, res){\n\n\t  var _this = this, futures = this.$2, length = futures.length;\n\t  var max = Math.min(this.$1, length), cancels = new Array(length), out = new Array(length);\n\t  var cursor = 0, running = 0, blocked = false, cont = noop;\n\n\t  function Parallel$cancel(){\n\t    rec = noop;\n\t    rej = noop;\n\t    res = noop;\n\t    cursor = length;\n\t    for(var n = 0; n < length; n++) cancels[n] && cancels[n]();\n\t  }\n\n\t  function Parallel$run(idx){\n\t    running++;\n\t    cancels[idx] = futures[idx]._interpret(function Parallel$rec(e){\n\t      cont = rec;\n\t      cancels[idx] = noop;\n\t      Parallel$cancel();\n\t      cont(wrapException(e, _this));\n\t    }, function Parallel$rej(reason){\n\t      cont = rej;\n\t      cancels[idx] = noop;\n\t      Parallel$cancel();\n\t      cont(reason);\n\t    }, function Parallel$res(value){\n\t      cancels[idx] = noop;\n\t      out[idx] = value;\n\t      running--;\n\t      if(cursor === length && running === 0) res(out);\n\t      else if(blocked) Parallel$drain();\n\t    });\n\t  }\n\n\t  function Parallel$drain(){\n\t    blocked = false;\n\t    while(cursor < length && running < max) Parallel$run(cursor++);\n\t    blocked = true;\n\t  }\n\n\t  Parallel$drain();\n\n\t  return Parallel$cancel;\n\n\t});\n\n\tvar emptyArray = resolve([]);\n\n\tfunction parallel$1(max){\n\t  var context1 = application1(parallel$1, positiveInteger, arguments);\n\t  return function parallel(ms){\n\t    var context2 = application(2, parallel, futureArray, arguments, context1);\n\t    return ms.length === 0 ? emptyArray : new Parallel(context2, max, ms);\n\t  };\n\t}\n\n\tvar RaceTransformation =\n\tcreateParallelTransformation('race', earlyCrash, earlyReject, earlyResolve, {});\n\n\tfunction race(left){\n\t  var context1 = application1(race, future, arguments);\n\t  return function race(right){\n\t    var context2 = application(2, race, future, arguments, context1);\n\t    return right._transform(new RaceTransformation(context2, left));\n\t  };\n\t}\n\n\tfunction ConcurrentFuture (sequential){\n\t  this.sequential = sequential;\n\t}\n\n\tConcurrentFuture.prototype = Object.create(Par.prototype);\n\n\tfunction Par (sequential){\n\t  if(!isFuture(sequential)) throw invalidFutureArgument(Par.name, 0, sequential);\n\t  return new ConcurrentFuture(sequential);\n\t}\n\n\tvar $$type = namespace + '/ConcurrentFuture@' + version;\n\tvar zeroInstance = new ConcurrentFuture(never);\n\n\t// Compliance with sanctuary-type-identifiers versions 1 and 2.\n\t// To prevent sanctuary-type-identifiers version 3 from identifying\n\t// 'Par' as being of the type denoted by $$type, we ensure that\n\t// Par.constructor.prototype is equal to Par.\n\tPar['@@type'] = $$type;\n\tPar.constructor = {prototype: Par};\n\n\tPar[FL.of] = function Par$of(x){\n\t  return new ConcurrentFuture(resolve(x));\n\t};\n\n\tPar[FL.zero] = function Par$zero(){\n\t  return zeroInstance;\n\t};\n\n\tPar.prototype['@@type'] = $$type;\n\n\tPar.prototype['@@show'] = function Par$show(){\n\t  return this.toString();\n\t};\n\n\tPar.prototype.toString = function Par$toString(){\n\t  return 'Par (' + this.sequential.toString() + ')';\n\t};\n\n\tPar.prototype[FL.map] = function Par$FL$map(f){\n\t  var context = captureContext(\n\t    nil,\n\t    'a Fantasy Land dispatch to map via ConcurrentFuture',\n\t    Par$FL$map\n\t  );\n\t  return new ConcurrentFuture(this.sequential._transform(new MapTransformation(context, f)));\n\t};\n\n\tPar.prototype[FL.ap] = function Par$FL$ap(other){\n\t  var context = captureContext(\n\t    nil,\n\t    'a Fantasy Land dispatch to ap via ConcurrentFuture',\n\t    Par$FL$ap\n\t  );\n\t  return new ConcurrentFuture(other.sequential._transform(\n\t    new ParallelApTransformation(context, this.sequential)\n\t  ));\n\t};\n\n\tPar.prototype[FL.alt] = function Par$FL$alt(other){\n\t  var context = captureContext(\n\t    nil,\n\t    'a Fantasy Land dispatch to alt via ConcurrentFuture',\n\t    Par$FL$alt\n\t  );\n\t  return new ConcurrentFuture(other.sequential._transform(\n\t    new RaceTransformation(context, this.sequential)\n\t  ));\n\t};\n\n\tfunction isParallel(x){\n\t  return x instanceof ConcurrentFuture || sanctuaryTypeIdentifiers(x) === $$type;\n\t}\n\n\tfunction promise(m){\n\t  application1(promise, future, arguments);\n\t  return new Promise(function promise$computation(res, rej){\n\t    m._interpret(rej, rej, res);\n\t  });\n\t}\n\n\tvar RejectAfter =\n\tcreateInterpreter(2, 'rejectAfter', function RejectAfter$interpret(rec, rej){\n\t  var id = setTimeout(rej, this.$1, this.$2);\n\t  return function RejectAfter$cancel(){ clearTimeout(id); };\n\t});\n\n\tRejectAfter.prototype.extractLeft = function RejectAfter$extractLeft(){\n\t  return [this.$2];\n\t};\n\n\tfunction alwaysNever(_){\n\t  return never;\n\t}\n\n\tfunction rejectAfter(time){\n\t  var context1 = application1(rejectAfter, positiveInteger, arguments);\n\t  return time === Infinity ? alwaysNever : (function rejectAfter(value){\n\t    var context2 = application(2, rejectAfter, any, arguments, context1);\n\t    return new RejectAfter(context2, time, value);\n\t  });\n\t}\n\n\tvar parallel = {pred: isParallel, error: invalidArgumentOf('be a ConcurrentFuture')};\n\n\tfunction seq(par){\n\t  application1(seq, parallel, arguments);\n\t  return par.sequential;\n\t}\n\n\tvar SwapTransformation = createTransformation(0, 'swap', {\n\t  resolved: function SwapTransformation$resolved(x){\n\t    return new Reject(this.context, x);\n\t  },\n\t  rejected: function SwapTransformation$rejected(x){\n\t    return new Resolve(this.context, x);\n\t  }\n\t});\n\n\tfunction swap(m){\n\t  var context = application1(swap, future, arguments);\n\t  return m._transform(new SwapTransformation(context));\n\t}\n\n\tfunction value(res){\n\t  var context1 = application1(value, func, arguments);\n\t  return function value(m){\n\t    application(2, value, future, arguments, context1);\n\t    function value$rej(x){\n\t      raise(error(\n\t        'Future#value was called on a rejected Future\\n' +\n\t        '  Rejection: ' + sanctuaryShow(x) + '\\n' +\n\t        '  Future: ' + sanctuaryShow(m)\n\t      ));\n\t    }\n\t    return m._interpret(raise, value$rej, res);\n\t  };\n\t}\n\n\tvar Fluture = /*#__PURE__*/Object.freeze({\n\t\t__proto__: null,\n\t\t'default': Future,\n\t\tFuture: Future,\n\t\tisFuture: isFuture,\n\t\tisNever: isNever,\n\t\tnever: never,\n\t\treject: reject,\n\t\tresolve: resolve,\n\t\tafter: after,\n\t\talt: alt,\n\t\tand: and,\n\t\tap: ap,\n\t\tattemptP: attemptP,\n\t\tattempt: attempt,\n\t\tbimap: bimap,\n\t\tbichain: bichain,\n\t\tboth: both,\n\t\tcache: cache,\n\t\tchainRej: chainRej,\n\t\tchain: chain,\n\t\tdone: done,\n\t\tencaseP: encaseP,\n\t\tencase: encase,\n\t\textractLeft: extractLeft,\n\t\textractRight: extractRight,\n\t\tcoalesce: coalesce,\n\t\tforkCatch: forkCatch,\n\t\tfork: fork,\n\t\tgo: go,\n\t\thook: hook,\n\t\tlastly: lastly,\n\t\tmapRej: mapRej,\n\t\tmap: map,\n\t\tnode: node,\n\t\tpap: pap,\n\t\tparallel: parallel$1,\n\t\tPar: Par,\n\t\tpromise: promise,\n\t\trace: race,\n\t\trejectAfter: rejectAfter,\n\t\tseq: seq,\n\t\tswap: swap,\n\t\tvalue: value,\n\t\tdebugMode: debugMode\n\t});\n\n\tvar index_cjs = Object.assign(Future, Fluture);\n\n\treturn index_cjs;\n\n}());\n/** Fluture license\n\nThe MIT License (MIT)\nCopyright (c) 2020 Aldwin Vlasblom\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/** sanctuary-show license\n\nThe MIT License (MIT)\n\nCopyright (c) 2020 Sanctuary\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and/or\nsell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n*/\n\n/** sanctuary-type-identifiers license\n\nThe MIT License (MIT)\n\nCopyright (c) 2019 Sanctuary\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and/or\nsell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n*/\n"
  },
  {
    "path": "dist/module.js",
    "content": "/**\n * Fluture bundled; version 14.0.0\n */\n\n/// <reference types=\"https://cdn.jsdelivr.net/gh/fluture-js/Fluture@14.0.0/index.d.ts\" />\n\nfunction createCommonjsModule(fn) {\n  var module = { exports: {} };\n\treturn fn(module, module.exports), module.exports;\n}\n\n/*\n        @@@@@@@            @@@@@@@         @@\n      @@       @@        @@       @@      @@@\n    @@   @@@ @@  @@    @@   @@@ @@  @@   @@@@@@ @@   @@@  @@ @@@      @@@@\n   @@  @@   @@@   @@  @@  @@   @@@   @@   @@@   @@   @@@  @@@   @@  @@@   @@\n   @@  @@   @@@   @@  @@  @@   @@@   @@   @@@   @@   @@@  @@@   @@  @@@@@@@@\n   @@  @@   @@@  @@   @@  @@   @@@  @@    @@@   @@   @@@  @@@   @@  @@@\n    @@   @@@ @@@@@     @@   @@@ @@@@@      @@@    @@@ @@  @@@@@@      @@@@@\n      @@                 @@                           @@  @@\n        @@@@@@@            @@@@@@@               @@@@@    @@\n                                                          */\n\nvar sanctuaryTypeIdentifiers = createCommonjsModule(function (module) {\n//. # sanctuary-type-identifiers\n//.\n//. A type is a set of values. Boolean, for example, is the type comprising\n//. `true` and `false`. A value may be a member of multiple types (`42` is a\n//. member of Number, PositiveNumber, Integer, and many other types).\n//.\n//. In certain situations it is useful to divide JavaScript values into\n//. non-overlapping types. The language provides two constructs for this\n//. purpose: the [`typeof`][1] operator and [`Object.prototype.toString`][2].\n//. Each has pros and cons, but neither supports user-defined types.\n//.\n//. sanctuary-type-identifiers comprises:\n//.\n//.   - an npm and browser -compatible package for deriving the\n//.     _type identifier_ of a JavaScript value; and\n//.   - a specification which authors may follow to specify type\n//.     identifiers for their types.\n//.\n//. ### Specification\n//.\n//. For a type to be compatible with the algorithm:\n//.\n//.   - every member of the type MUST have a `@@type` property\n//.     (the _type identifier_); and\n//.\n//.   - the type identifier MUST be a string primitive and SHOULD have\n//.     format `'<namespace>/<name>[@<version>]'`, where:\n//.\n//.       - `<namespace>` MUST consist of one or more characters, and\n//.         SHOULD equal the name of the npm package which defines the\n//.         type (including [scope][3] where appropriate);\n//.\n//.       - `<name>` MUST consist of one or more characters, and SHOULD\n//.         be the unique name of the type; and\n//.\n//.       - `<version>` MUST consist of one or more digits, and SHOULD\n//.         represent the version of the type.\n//.\n//. If the type identifier does not conform to the format specified above,\n//. it is assumed that the entire string represents the _name_ of the type;\n//. _namespace_ will be `null` and _version_ will be `0`.\n//.\n//. If the _version_ is not given, it is assumed to be `0`.\n\n(function(f) {\n\n  /* istanbul ignore else */\n  {\n    module.exports = f ();\n  }\n\n} (function() {\n\n  //  $$type :: String\n  var $$type = '@@type';\n\n  //  pattern :: RegExp\n  var pattern = new RegExp (\n    '^'\n  + '([\\\\s\\\\S]+)'   //  <namespace>\n  + '/'             //  SOLIDUS (U+002F)\n  + '([\\\\s\\\\S]+?)'  //  <name>\n  + '(?:'           //  optional non-capturing group {\n  +   '@'           //    COMMERCIAL AT (U+0040)\n  +   '([0-9]+)'    //    <version>\n  + ')?'            //  }\n  + '$'\n  );\n\n  //. ### Usage\n  //.\n  //. ```javascript\n  //. const type = require ('sanctuary-type-identifiers');\n  //. ```\n  //.\n  //. ```javascript\n  //. > const Identity$prototype = {\n  //. .   '@@type': 'my-package/Identity@1',\n  //. .   '@@show': function() {\n  //. .     return 'Identity (' + show (this.value) + ')';\n  //. .   }\n  //. . }\n  //.\n  //. > const Identity = value =>\n  //. .   Object.assign (Object.create (Identity$prototype), {value})\n  //.\n  //. > type (Identity (0))\n  //. 'my-package/Identity@1'\n  //.\n  //. > type.parse (type (Identity (0)))\n  //. {namespace: 'my-package', name: 'Identity', version: 1}\n  //. ```\n  //.\n  //. ### API\n  //.\n  //# type :: Any -> String\n  //.\n  //. Takes any value and returns a string which identifies its type. If the\n  //. value conforms to the [specification][4], the custom type identifier is\n  //. returned.\n  //.\n  //. ```javascript\n  //. > type (null)\n  //. 'Null'\n  //.\n  //. > type (true)\n  //. 'Boolean'\n  //.\n  //. > type (Identity (0))\n  //. 'my-package/Identity@1'\n  //. ```\n  function type(x) {\n    return x != null &&\n           x.constructor != null &&\n           x.constructor.prototype !== x &&\n           typeof x[$$type] === 'string' ?\n      x[$$type] :\n      (Object.prototype.toString.call (x)).slice ('[object '.length,\n                                                  -']'.length);\n  }\n\n  //# type.parse :: String -> { namespace :: Nullable String, name :: String, version :: Number }\n  //.\n  //. Takes any string and parses it according to the [specification][4],\n  //. returning an object with `namespace`, `name`, and `version` fields.\n  //.\n  //. ```javascript\n  //. > type.parse ('my-package/List@2')\n  //. {namespace: 'my-package', name: 'List', version: 2}\n  //.\n  //. > type.parse ('nonsense!')\n  //. {namespace: null, name: 'nonsense!', version: 0}\n  //.\n  //. > type.parse (type (Identity (0)))\n  //. {namespace: 'my-package', name: 'Identity', version: 1}\n  //. ```\n  type.parse = function parse(s) {\n    var namespace = null;\n    var name = s;\n    var version = 0;\n    var groups = pattern.exec (s);\n    if (groups != null) {\n      namespace = groups[1];\n      name = groups[2];\n      if (groups[3] != null) version = Number (groups[3]);\n    }\n    return {namespace: namespace, name: name, version: version};\n  };\n\n  return type;\n\n}));\n\n//. [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof\n//. [2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString\n//. [3]: https://docs.npmjs.com/misc/scope\n//. [4]: #specification\n});\n\nvar FL = {\n  alt: 'fantasy-land/alt',\n  ap: 'fantasy-land/ap',\n  bimap: 'fantasy-land/bimap',\n  chain: 'fantasy-land/chain',\n  chainRec: 'fantasy-land/chainRec',\n  map: 'fantasy-land/map',\n  of: 'fantasy-land/of',\n  zero: 'fantasy-land/zero'\n};\n\nvar ordinal = ['first', 'second', 'third', 'fourth', 'fifth'];\n\nvar namespace = 'fluture';\nvar name = 'Future';\nvar version = 5;\n\nvar $$type$1 = namespace + '/' + name + '@' + version;\n\nfunction List(head, tail){\n  this.head = head;\n  this.tail = tail;\n}\n\nList.prototype.toJSON = function(){\n  return toArray(this);\n};\n\nvar nil = new List(null, null);\nnil.tail = nil;\n\nfunction isNil(list){\n  return list.tail === list;\n}\n\n// cons :: (a, List a) -> List a\n//      -- O(1) append operation\nfunction cons(head, tail){\n  return new List(head, tail);\n}\n\n// reverse :: List a -> List a\n//         -- O(n) list reversal\nfunction reverse(xs){\n  var ys = nil, tail = xs;\n  while(!isNil(tail)){\n    ys = cons(tail.head, ys);\n    tail = tail.tail;\n  }\n  return ys;\n}\n\n// cat :: (List a, List a) -> List a\n//     -- O(n) list concatenation\nfunction cat(xs, ys){\n  var zs = ys, tail = reverse(xs);\n  while(!isNil(tail)){\n    zs = cons(tail.head, zs);\n    tail = tail.tail;\n  }\n  return zs;\n}\n\n// toArray :: List a -> Array a\n//         -- O(n) list to Array\nfunction toArray(xs){\n  var tail = xs, arr = [];\n  while(!isNil(tail)){\n    arr.push(tail.head);\n    tail = tail.tail;\n  }\n  return arr;\n}\n\n/* c8 ignore next */\nvar captureStackTrace = Error.captureStackTrace || captureStackTraceFallback;\nvar _debug = debugHandleNone;\n\nfunction debugMode(debug){\n  _debug = debug ? debugHandleAll : debugHandleNone;\n}\n\nfunction debugHandleNone(x){\n  return x;\n}\n\nfunction debugHandleAll(x, fn, a, b, c){\n  return fn(a, b, c);\n}\n\nfunction debug(x, fn, a, b, c){\n  return _debug(x, fn, a, b, c);\n}\n\nfunction captureContext(previous, tag, fn){\n  return debug(previous, debugCaptureContext, previous, tag, fn);\n}\n\nfunction debugCaptureContext(previous, tag, fn){\n  var context = {tag: tag, name: ' from ' + tag + ':'};\n  captureStackTrace(context, fn);\n  return cons(context, previous);\n}\n\nfunction captureApplicationContext(context, n, f){\n  return debug(context, debugCaptureApplicationContext, context, n, f);\n}\n\nfunction debugCaptureApplicationContext(context, n, f){\n  return debugCaptureContext(context, ordinal[n - 1] + ' application of ' + f.name, f);\n}\n\nfunction captureStackTraceFallback(x){\n  var e = new Error;\n  if(typeof e.stack === 'string'){\n    x.stack = x.name + '\\n' + e.stack.split('\\n').slice(1).join('\\n');\n  /* c8 ignore next 3 */\n  }else {\n    x.stack = x.name;\n  }\n}\n\nvar sanctuaryShow = createCommonjsModule(function (module) {\n//. # sanctuary-show\n//.\n//. Haskell has a `show` function which can be applied to a compatible value to\n//. produce a descriptive string representation of that value. The idea is that\n//. the string representation should, if possible, be an expression which would\n//. produce the original value if evaluated.\n//.\n//. This library provides a similar [`show`](#show) function.\n//.\n//. In general, this property should hold: `eval (show (x)) = x`. In some cases\n//. parens are necessary to ensure correct interpretation (`{}`, for example,\n//. is an empty block rather than an empty object in some contexts). Thus the\n//. property is more accurately stated `eval ('(' + show (x) + ')') = x`.\n//.\n//. One can make values of a custom type compatible with [`show`](#show) by\n//. defining a `@@show` method. For example:\n//.\n//. ```javascript\n//. //# Maybe#@@show :: Maybe a ~> () -> String\n//. //.\n//. //. ```javascript\n//. //. > show (Nothing)\n//. //. 'Nothing'\n//. //.\n//. //. > show (Just (['foo', 'bar', 'baz']))\n//. //. 'Just ([\"foo\", \"bar\", \"baz\"])'\n//. //. ```\n//. Maybe.prototype['@@show'] = function() {\n//.   return this.isNothing ? 'Nothing' : 'Just (' + show (this.value) + ')';\n//. };\n//. ```\n\n(function(f) {\n\n  /* istanbul ignore else */\n  {\n    module.exports = f ();\n  }\n\n} (function() {\n\n  //  $$show :: String\n  var $$show = '@@show';\n\n  //  seen :: Array Any\n  var seen = [];\n\n  //  entry :: Object -> String -> String\n  function entry(o) {\n    return function(k) {\n      return show (k) + ': ' + show (o[k]);\n    };\n  }\n\n  //  sortedKeys :: Object -> Array String\n  function sortedKeys(o) {\n    return (Object.keys (o)).sort ();\n  }\n\n  //# show :: Showable a => a -> String\n  //.\n  //. Returns a useful string representation of the given value.\n  //.\n  //. Dispatches to the value's `@@show` method if present.\n  //.\n  //. Where practical, `show (eval ('(' + show (x) + ')')) = show (x)`.\n  //.\n  //. ```javascript\n  //. > show (null)\n  //. 'null'\n  //.\n  //. > show (undefined)\n  //. 'undefined'\n  //.\n  //. > show (true)\n  //. 'true'\n  //.\n  //. > show (new Boolean (false))\n  //. 'new Boolean (false)'\n  //.\n  //. > show (-0)\n  //. '-0'\n  //.\n  //. > show (NaN)\n  //. 'NaN'\n  //.\n  //. > show (new Number (Infinity))\n  //. 'new Number (Infinity)'\n  //.\n  //. > show ('foo\\n\"bar\"\\nbaz\\n')\n  //. '\"foo\\\\n\\\\\"bar\\\\\"\\\\nbaz\\\\n\"'\n  //.\n  //. > show (new String (''))\n  //. 'new String (\"\")'\n  //.\n  //. > show (['foo', 'bar', 'baz'])\n  //. '[\"foo\", \"bar\", \"baz\"]'\n  //.\n  //. > show ([[[[[0]]]]])\n  //. '[[[[[0]]]]]'\n  //.\n  //. > show ({x: [1, 2], y: [3, 4], z: [5, 6]})\n  //. '{\"x\": [1, 2], \"y\": [3, 4], \"z\": [5, 6]}'\n  //. ```\n  function show(x) {\n    if (seen.indexOf (x) >= 0) return '<Circular>';\n\n    switch (Object.prototype.toString.call (x)) {\n\n      case '[object Boolean]':\n        return typeof x === 'object' ?\n          'new Boolean (' + show (x.valueOf ()) + ')' :\n          x.toString ();\n\n      case '[object Number]':\n        return typeof x === 'object' ?\n          'new Number (' + show (x.valueOf ()) + ')' :\n          1 / x === -Infinity ? '-0' : x.toString (10);\n\n      case '[object String]':\n        return typeof x === 'object' ?\n          'new String (' + show (x.valueOf ()) + ')' :\n          JSON.stringify (x);\n\n      case '[object Date]':\n        return 'new Date (' +\n               show (isNaN (x.valueOf ()) ? NaN : x.toISOString ()) +\n               ')';\n\n      case '[object Error]':\n        return 'new ' + x.name + ' (' + show (x.message) + ')';\n\n      case '[object Arguments]':\n        return 'function () { return arguments; } (' +\n               (Array.prototype.map.call (x, show)).join (', ') +\n               ')';\n\n      case '[object Array]':\n        seen.push (x);\n        try {\n          return '[' + ((x.map (show)).concat (\n            sortedKeys (x)\n            .filter (function(k) { return !(/^\\d+$/.test (k)); })\n            .map (entry (x))\n          )).join (', ') + ']';\n        } finally {\n          seen.pop ();\n        }\n\n      case '[object Object]':\n        seen.push (x);\n        try {\n          return (\n            $$show in x &&\n            (x.constructor == null || x.constructor.prototype !== x) ?\n              x[$$show] () :\n              '{' + ((sortedKeys (x)).map (entry (x))).join (', ') + '}'\n          );\n        } finally {\n          seen.pop ();\n        }\n\n      case '[object Set]':\n        seen.push (x);\n        try {\n          return 'new Set (' + show (Array.from (x.values ())) + ')';\n        } finally {\n          seen.pop ();\n        }\n\n      case '[object Map]':\n        seen.push (x);\n        try {\n          return 'new Map (' + show (Array.from (x.entries ())) + ')';\n        } finally {\n          seen.pop ();\n        }\n\n      default:\n        return String (x);\n\n    }\n  }\n\n  return show;\n\n}));\n});\n\n/* c8 ignore next */\nvar setImmediate = typeof setImmediate === 'undefined' ? setImmediateFallback : setImmediate;\n\nfunction noop(){}\nfunction moop(){ return this }\nfunction call(f, x){ return f(x) }\n\nfunction setImmediateFallback(f, x){\n  return setTimeout(f, 0, x);\n}\n\nfunction raise(x){\n  setImmediate(function rethrowErrorDelayedToEscapePromiseCatch(){\n    throw x;\n  });\n}\n\nfunction showArg$1(x){\n  return sanctuaryShow(x) + ' :: ' + sanctuaryTypeIdentifiers.parse(sanctuaryTypeIdentifiers(x)).name;\n}\n\nfunction error(message){\n  return new Error(message);\n}\n\nfunction typeError(message){\n  return new TypeError(message);\n}\n\nfunction invalidArgument(it, at, expected, actual){\n  return typeError(\n    it + '() expects its ' + ordinal[at] + ' argument to ' + expected + '.' +\n    '\\n  Actual: ' + showArg$1(actual)\n  );\n}\n\nfunction invalidArgumentOf(expected){\n  return function(it, at, actual){\n    return invalidArgument(it, at, expected, actual);\n  };\n}\n\nfunction invalidArity(f, args){\n  return new TypeError(\n    f.name + '() expects to be called with a single argument per invocation\\n' +\n    '  Saw: ' + args.length + ' arguments' +\n    Array.prototype.slice.call(args).map(function(arg, i){\n      return '\\n  ' + (\n        ordinal[i] ?\n        ordinal[i].charAt(0).toUpperCase() + ordinal[i].slice(1) :\n        'Argument ' + String(i + 1)\n      ) + ': ' + showArg$1(arg);\n    }).join('')\n  );\n}\n\nfunction invalidNamespace(m, x){\n  return (\n    'The Future was not created by ' + namespace + '. '\n  + 'Make sure you transform other Futures to ' + namespace + ' Futures. '\n  + 'Got ' + (x ? ('a Future from ' + x) : 'an unscoped Future') + '.'\n  + '\\n  See: https://github.com/fluture-js/Fluture#casting-futures'\n  );\n}\n\nfunction invalidVersion(m, x){\n  return (\n    'The Future was created by ' + (x < version ? 'an older' : 'a newer')\n  + ' version of ' + namespace + '. '\n  + 'This means that one of the sources which creates Futures is outdated. '\n  + 'Update this source, or transform its created Futures to be compatible.'\n  + '\\n  See: https://github.com/fluture-js/Fluture#casting-futures'\n  );\n}\n\nfunction invalidFuture(desc, m, s){\n  var id = sanctuaryTypeIdentifiers.parse(sanctuaryTypeIdentifiers(m));\n  var info = id.name === name ? '\\n' + (\n    id.namespace !== namespace ? invalidNamespace(m, id.namespace)\n  : id.version !== version ? invalidVersion(m, id.version)\n  : 'Nothing seems wrong. Contact the Fluture maintainers.') : '';\n  return typeError(\n    desc + ' to be a valid Future.' + info + '\\n' +\n    '  Actual: ' + sanctuaryShow(m) + ' :: ' + id.name + (s || '')\n  );\n}\n\nfunction invalidFutureArgument(it, at, m, s){\n  return invalidFuture(it + '() expects its ' + ordinal[at] + ' argument', m, s);\n}\n\nfunction ensureError(value, fn){\n  var message;\n  try{\n    if(value instanceof Error) return value;\n    message = 'A Non-Error was thrown from a Future: ' + sanctuaryShow(value);\n  }catch (_){\n    message = 'Something was thrown from a Future, but it could not be converted to String';\n  }\n  var e = error(message);\n  captureStackTrace(e, fn);\n  return e;\n}\n\nfunction assignUnenumerable(o, prop, value){\n  Object.defineProperty(o, prop, {value: value, writable: true, configurable: true});\n}\n\nfunction wrapException(caught, callingFuture){\n  var origin = ensureError(caught, wrapException);\n  var context = cat(origin.context || nil, callingFuture.context);\n  var e = error(origin.message);\n  assignUnenumerable(e, 'future', origin.future || callingFuture);\n  assignUnenumerable(e, 'reason', origin.reason || origin);\n  assignUnenumerable(e, 'stack', e.reason.stack);\n  return withExtraContext(e, context);\n}\n\nfunction withExtraContext(e, context){\n  assignUnenumerable(e, 'context', context);\n  assignUnenumerable(e, 'stack', e.stack + contextToStackTrace(context));\n  return e;\n}\n\nfunction contextToStackTrace(context){\n  var stack = '', tail = context;\n  while(tail !== nil){\n    stack = stack + '\\n' + tail.head.stack;\n    tail = tail.tail;\n  }\n  return stack;\n}\n\nfunction isFunction(f){\n  return typeof f === 'function';\n}\n\nfunction isThenable(m){\n  return m instanceof Promise || m != null && isFunction(m.then);\n}\n\nfunction isBoolean(f){\n  return typeof f === 'boolean';\n}\n\nfunction isNumber(f){\n  return typeof f === 'number';\n}\n\nfunction isUnsigned(n){\n  return (n === Infinity || isNumber(n) && n > 0 && n % 1 === 0);\n}\n\nfunction isObject(o){\n  return o !== null && typeof o === 'object';\n}\n\nfunction isIterator(i){\n  return isObject(i) && isFunction(i.next);\n}\n\nfunction isArray(x){\n  return Array.isArray(x);\n}\n\nfunction hasMethod(method, x){\n  return x != null && isFunction(x[method]);\n}\n\nfunction isFunctor(x){\n  return hasMethod(FL.map, x);\n}\n\nfunction isAlt(x){\n  return isFunctor(x) && hasMethod(FL.alt, x);\n}\n\nfunction isApply(x){\n  return isFunctor(x) && hasMethod(FL.ap, x);\n}\n\nfunction isBifunctor(x){\n  return isFunctor(x) && hasMethod(FL.bimap, x);\n}\n\nfunction isChain(x){\n  return isApply(x) && hasMethod(FL.chain, x);\n}\n\nfunction Next(x){\n  return {done: false, value: x};\n}\n\nfunction Done(x){\n  return {done: true, value: x};\n}\n\nfunction isIteration(x){\n  return isObject(x) && isBoolean(x.done);\n}\n\n/*eslint no-cond-assign:0, no-constant-condition:0 */\n\nfunction alwaysTrue(){\n  return true;\n}\n\nfunction getArgs(it){\n  var args = new Array(it.arity);\n  for(var i = 1; i <= it.arity; i++){\n    args[i - 1] = it['$' + String(i)];\n  }\n  return args;\n}\n\nfunction showArg(arg){\n  return ' (' + sanctuaryShow(arg) + ')';\n}\n\nvar any = {pred: alwaysTrue, error: invalidArgumentOf('be anything')};\nvar func = {pred: isFunction, error: invalidArgumentOf('be a Function')};\nvar future = {pred: isFuture, error: invalidFutureArgument};\nvar positiveInteger = {pred: isUnsigned, error: invalidArgumentOf('be a positive Integer')};\n\nfunction application(n, f, type, args, prev){\n  if(args.length < 2 && type.pred(args[0])) return captureApplicationContext(prev, n, f);\n  var e = args.length > 1 ? invalidArity(f, args) : type.error(f.name, n - 1, args[0]);\n  captureStackTrace(e, f);\n  throw withExtraContext(e, prev);\n}\n\nfunction application1(f, type, args){\n  return application(1, f, type, args, nil);\n}\n\nfunction Future(computation){\n  var context = application1(Future, func, arguments);\n  return new Computation(context, computation);\n}\n\nfunction isFuture(x){\n  return x instanceof Future || sanctuaryTypeIdentifiers(x) === $$type$1;\n}\n\n// Compliance with sanctuary-type-identifiers versions 1 and 2.\n// To prevent sanctuary-type-identifiers version 3 from identifying 'Future'\n// as being of the type denoted by $$type, we ensure that\n// Future.constructor.prototype is equal to Future.\nFuture['@@type'] = $$type$1;\nFuture.constructor = {prototype: Future};\n\nFuture[FL.of] = resolve;\nFuture[FL.chainRec] = chainRec;\n\nFuture.prototype['@@type'] = $$type$1;\n\nFuture.prototype['@@show'] = function Future$show(){\n  return this.toString();\n};\n\nFuture.prototype.pipe = function Future$pipe(f){\n  if(!isFunction(f)) throw invalidArgument('Future#pipe', 0, 'be a Function', f);\n  return f(this);\n};\n\nFuture.prototype[FL.ap] = function Future$FL$ap(other){\n  var context = captureContext(nil, 'a Fantasy Land dispatch to ap', Future$FL$ap);\n  return other._transform(new ApTransformation(context, this));\n};\n\nFuture.prototype[FL.map] = function Future$FL$map(mapper){\n  var context = captureContext(nil, 'a Fantasy Land dispatch to map', Future$FL$map);\n  return this._transform(new MapTransformation(context, mapper));\n};\n\nFuture.prototype[FL.bimap] = function Future$FL$bimap(lmapper, rmapper){\n  var context = captureContext(nil, 'a Fantasy Land dispatch to bimap', Future$FL$bimap);\n  return this._transform(new BimapTransformation(context, lmapper, rmapper));\n};\n\nFuture.prototype[FL.chain] = function Future$FL$chain(mapper){\n  var context = captureContext(nil, 'a Fantasy Land dispatch to chain', Future$FL$chain);\n  return this._transform(new ChainTransformation(context, mapper));\n};\n\nFuture.prototype[FL.alt] = function Future$FL$alt(other){\n  var context = captureContext(nil, 'a Fantasy Land dispatch to alt', Future$FL$alt);\n  return this._transform(new AltTransformation(context, other));\n};\n\nFuture.prototype.extractLeft = function Future$extractLeft(){\n  return [];\n};\n\nFuture.prototype.extractRight = function Future$extractRight(){\n  return [];\n};\n\nFuture.prototype._transform = function Future$transform(transformation){\n  return new Transformer(transformation.context, this, cons(transformation, nil));\n};\n\nFuture.prototype.isTransformer = false;\nFuture.prototype.context = nil;\nFuture.prototype.arity = 0;\nFuture.prototype.name = 'future';\n\nFuture.prototype.toString = function Future$toString(){\n  return this.name + getArgs(this).map(showArg).join('');\n};\n\nFuture.prototype.toJSON = function Future$toJSON(){\n  return {$: $$type$1, kind: 'interpreter', type: this.name, args: getArgs(this)};\n};\n\nfunction createInterpreter(arity, name, interpret){\n  var Interpreter = function(context, $1, $2, $3){\n    this.context = context;\n    this.$1 = $1;\n    this.$2 = $2;\n    this.$3 = $3;\n  };\n\n  Interpreter.prototype = Object.create(Future.prototype);\n  Interpreter.prototype.arity = arity;\n  Interpreter.prototype.name = name;\n  Interpreter.prototype._interpret = interpret;\n\n  return Interpreter;\n}\n\nvar Computation =\ncreateInterpreter(1, 'Future', function Computation$interpret(rec, rej, res){\n  var computation = this.$1, open = false, cancel = noop, cont = function(){ open = true; };\n  try{\n    cancel = computation(function Computation$rej(x){\n      cont = function Computation$rej$cont(){\n        open = false;\n        rej(x);\n      };\n      if(open){\n        cont();\n      }\n    }, function Computation$res(x){\n      cont = function Computation$res$cont(){\n        open = false;\n        res(x);\n      };\n      if(open){\n        cont();\n      }\n    });\n  }catch(e){\n    rec(wrapException(e, this));\n    return noop;\n  }\n  if(!(isFunction(cancel) && cancel.length === 0)){\n    rec(wrapException(typeError(\n      'The computation was expected to return a nullary cancellation function\\n' +\n      '  Actual: ' + sanctuaryShow(cancel)\n    ), this));\n    return noop;\n  }\n  cont();\n  return function Computation$cancel(){\n    if(open){\n      open = false;\n      cancel && cancel();\n    }\n  };\n});\n\nvar Never = createInterpreter(0, 'never', function Never$interpret(){\n  return noop;\n});\n\nNever.prototype._isNever = true;\n\nvar never = new Never(nil);\n\nfunction isNever(x){\n  return isFuture(x) && x._isNever === true;\n}\n\nvar Crash = createInterpreter(1, 'crash', function Crash$interpret(rec){\n  rec(this.$1);\n  return noop;\n});\n\nfunction crash(x){\n  return new Crash(application1(crash, any, arguments), x);\n}\n\nvar Reject = createInterpreter(1, 'reject', function Reject$interpret(rec, rej){\n  rej(this.$1);\n  return noop;\n});\n\nReject.prototype.extractLeft = function Reject$extractLeft(){\n  return [this.$1];\n};\n\nfunction reject(x){\n  return new Reject(application1(reject, any, arguments), x);\n}\n\nvar Resolve = createInterpreter(1, 'resolve', function Resolve$interpret(rec, rej, res){\n  res(this.$1);\n  return noop;\n});\n\nResolve.prototype.extractRight = function Resolve$extractRight(){\n  return [this.$1];\n};\n\nfunction resolve(x){\n  return new Resolve(application1(resolve, any, arguments), x);\n}\n\n//Note: This function is not curried because it's only used to satisfy the\n//      Fantasy Land ChainRec specification.\nfunction chainRec(step, init){\n  return resolve(Next(init))._transform(new ChainTransformation(nil, function chainRec$recur(o){\n    return o.done ?\n           resolve(o.value) :\n           step(Next, Done, o.value)._transform(new ChainTransformation(nil, chainRec$recur));\n  }));\n}\n\nvar Transformer =\ncreateInterpreter(2, 'transform', function Transformer$interpret(rec, rej, res){\n\n  //These are the cold, and hot, transformation stacks. The cold actions are those that\n  //have yet to run parallel computations, and hot are those that have.\n  var cold = nil, hot = nil;\n\n  //These combined variables define our current state.\n  // future         = the future we are currently forking\n  // transformation = the transformation to be informed when the future settles\n  // cancel         = the cancel function of the current future\n  // settled        = a boolean indicating whether a new tick should start\n  // async          = a boolean indicating whether we are awaiting a result asynchronously\n  var future, transformation, cancel = noop, settled, async = true, it;\n\n  //Takes a transformation from the top of the hot stack and returns it.\n  function nextHot(){\n    var x = hot.head;\n    hot = hot.tail;\n    return x;\n  }\n\n  //Takes a transformation from the top of the cold stack and returns it.\n  function nextCold(){\n    var x = cold.head;\n    cold = cold.tail;\n    return x;\n  }\n\n  //This function is called with a future to use in the next tick.\n  //Here we \"flatten\" the actions of another Sequence into our own actions,\n  //this is the magic that allows for infinitely stack safe recursion because\n  //actions like ChainAction will return a new Sequence.\n  //If we settled asynchronously, we call drain() directly to run the next tick.\n  function settle(m){\n    settled = true;\n    future = m;\n    if(future.isTransformer){\n      var tail = future.$2;\n      while(!isNil(tail)){\n        cold = cons(tail.head, cold);\n        tail = tail.tail;\n      }\n      future = future.$1;\n    }\n    if(async) drain();\n  }\n\n  //This function serves as a rejection handler for our current future.\n  //It will tell the current transformation that the future rejected, and it will\n  //settle the current tick with the transformation's answer to that.\n  function rejected(x){\n    settle(transformation.rejected(x));\n  }\n\n  //This function serves as a resolution handler for our current future.\n  //It will tell the current transformation that the future resolved, and it will\n  //settle the current tick with the transformation's answer to that.\n  function resolved(x){\n    settle(transformation.resolved(x));\n  }\n\n  //This function is passed into actions when they are \"warmed up\".\n  //If the transformation decides that it has its result, without the need to await\n  //anything else, then it can call this function to force \"early termination\".\n  //When early termination occurs, all actions which were stacked prior to the\n  //terminator will be skipped. If they were already hot, they will also be\n  //sent a cancel signal so they can cancel their own concurrent computations,\n  //as their results are no longer needed.\n  function early(m, terminator){\n    cancel();\n    cold = nil;\n    if(async && transformation !== terminator){\n      transformation.cancel();\n      while((it = nextHot()) && it !== terminator) it.cancel();\n    }\n    settle(m);\n  }\n\n  //This will cancel the current Future, the current transformation, and all stacked hot actions.\n  function Sequence$cancel(){\n    cancel();\n    transformation && transformation.cancel();\n    while(it = nextHot()) it.cancel();\n  }\n\n  //This function is called when an exception is caught.\n  function exception(e){\n    Sequence$cancel();\n    settled = true;\n    cold = hot = nil;\n    var error = wrapException(e, future);\n    future = never;\n    rec(error);\n  }\n\n  //This function serves to kickstart concurrent computations.\n  //Takes all actions from the cold stack in reverse order, and calls run() on\n  //each of them, passing them the \"early\" function. If any of them settles (by\n  //calling early()), we abort. After warming up all actions in the cold queue,\n  //we warm up the current transformation as well.\n  function warmupActions(){\n    cold = reverse(cold);\n    while(cold !== nil){\n      it = cold.head.run(early);\n      if(settled) return;\n      hot = cons(it, hot);\n      cold = cold.tail;\n    }\n    transformation = transformation.run(early);\n  }\n\n  //This function represents our main execution loop. By \"tick\", we've been\n  //referring to the execution of one iteration in the while-loop below.\n  function drain(){\n    async = false;\n    while(true){\n      settled = false;\n      if(transformation = nextCold()){\n        cancel = future._interpret(exception, rejected, resolved);\n        if(!settled) warmupActions();\n      }else if(transformation = nextHot()){\n        cancel = future._interpret(exception, rejected, resolved);\n      }else break;\n      if(settled) continue;\n      async = true;\n      return;\n    }\n    cancel = future._interpret(exception, rej, res);\n  }\n\n  //Start the execution loop.\n  settle(this);\n\n  //Return the cancellation function.\n  return Sequence$cancel;\n\n});\n\nTransformer.prototype.isTransformer = true;\n\nTransformer.prototype._transform = function Transformer$_transform(transformation){\n  return new Transformer(transformation.context, this.$1, cons(transformation, this.$2));\n};\n\nTransformer.prototype.toString = function Transformer$toString(){\n  return toArray(reverse(this.$2)).reduce(function(str, action){\n    return action.name + getArgs(action).map(showArg).join('') + ' (' + str + ')';\n  }, this.$1.toString());\n};\n\nfunction BaseTransformation$rejected(x){\n  this.cancel();\n  return new Reject(this.context, x);\n}\n\nfunction BaseTransformation$resolved(x){\n  this.cancel();\n  return new Resolve(this.context, x);\n}\n\nfunction BaseTransformation$toJSON(){\n  return {$: $$type$1, kind: 'transformation', type: this.name, args: getArgs(this)};\n}\n\nvar BaseTransformation = {\n  rejected: BaseTransformation$rejected,\n  resolved: BaseTransformation$resolved,\n  run: moop,\n  cancel: noop,\n  context: nil,\n  arity: 0,\n  name: 'transform',\n  toJSON: BaseTransformation$toJSON\n};\n\nfunction wrapHandler(handler){\n  return function transformationHandler(x){\n    var m;\n    try{\n      m = handler.call(this, x);\n    }catch(e){\n      return new Crash(this.context, e);\n    }\n    if(isFuture(m)){\n      return m;\n    }\n    return new Crash(this.context, invalidFuture(\n      this.name + ' expects the return value from the function it\\'s given', m,\n      '\\n  When called with: ' + sanctuaryShow(x)\n    ));\n  };\n}\n\nfunction createTransformation(arity, name, prototype){\n  var Transformation = function(context, $1, $2){\n    this.context = context;\n    this.$1 = $1;\n    this.$2 = $2;\n  };\n\n  Transformation.prototype = Object.create(BaseTransformation);\n  Transformation.prototype.arity = arity;\n  Transformation.prototype.name = name;\n\n  if(typeof prototype.rejected === 'function'){\n    Transformation.prototype.rejected = wrapHandler(prototype.rejected);\n  }\n\n  if(typeof prototype.resolved === 'function'){\n    Transformation.prototype.resolved = wrapHandler(prototype.resolved);\n  }\n\n  if(typeof prototype.run === 'function'){\n    Transformation.prototype.run = prototype.run;\n  }\n\n  return Transformation;\n}\n\nvar ApTransformation = createTransformation(1, 'ap', {\n  resolved: function ApTransformation$resolved(f){\n    if(isFunction(f)) return this.$1._transform(new MapTransformation(this.context, f));\n    throw typeError(\n      'ap expects the second Future to resolve to a Function\\n' +\n      '  Actual: ' + sanctuaryShow(f)\n    );\n  }\n});\n\nvar AltTransformation = createTransformation(1, 'alt', {\n  rejected: function AltTransformation$rejected(){ return this.$1 }\n});\n\nvar MapTransformation = createTransformation(1, 'map', {\n  resolved: function MapTransformation$resolved(x){\n    return new Resolve(this.context, call(this.$1, x));\n  }\n});\n\nvar BimapTransformation = createTransformation(2, 'bimap', {\n  rejected: function BimapTransformation$rejected(x){\n    return new Reject(this.context, call(this.$1, x));\n  },\n  resolved: function BimapTransformation$resolved(x){\n    return new Resolve(this.context, call(this.$2, x));\n  }\n});\n\nvar ChainTransformation = createTransformation(1, 'chain', {\n  resolved: function ChainTransformation$resolved(x){ return call(this.$1, x) }\n});\n\nvar After = createInterpreter(2, 'after', function After$interpret(rec, rej, res){\n  var id = setTimeout(res, this.$1, this.$2);\n  return function After$cancel(){ clearTimeout(id); };\n});\n\nAfter.prototype.extractRight = function After$extractRight(){\n  return [this.$2];\n};\n\nfunction alwaysNever$1(_){\n  return never;\n}\n\nfunction after(time){\n  var context1 = application1(after, positiveInteger, arguments);\n  return time === Infinity ? alwaysNever$1 : (function after(value){\n    var context2 = application(2, after, any, arguments, context1);\n    return new After(context2, time, value);\n  });\n}\n\nvar alternative = {pred: isAlt, error: invalidArgumentOf('have Alt implemented')};\n\nfunction alt(left){\n  if(isFuture(left)){\n    var context1 = application1(alt, future, arguments);\n    return function alt(right){\n      var context2 = application(2, alt, future, arguments, context1);\n      return right._transform(new AltTransformation(context2, left));\n    };\n  }\n\n  var context = application1(alt, alternative, arguments);\n  return function alt(right){\n    application(2, alt, alternative, arguments, context);\n    return left[FL.alt](right);\n  };\n}\n\nvar AndTransformation = createTransformation(1, 'and', {\n  resolved: function AndTransformation$resolved(){ return this.$1 }\n});\n\nfunction and(left){\n  var context1 = application1(and, future, arguments);\n  return function and(right){\n    var context2 = application(2, and, future, arguments, context1);\n    return right._transform(new AndTransformation(context2, left));\n  };\n}\n\nvar apply = {pred: isApply, error: invalidArgumentOf('have Apply implemented')};\n\nfunction ap(mx){\n  if(isFuture(mx)){\n    var context1 = application1(ap, future, arguments);\n    return function ap(mf){\n      var context2 = application(2, ap, future, arguments, context1);\n      return mf._transform(new ApTransformation(context2, mx));\n    };\n  }\n\n  var context = application1(ap, apply, arguments);\n  return function ap(mf){\n    application(2, ap, apply, arguments, context);\n    return mx[FL.ap](mf);\n  };\n}\n\nfunction invalidPromise(p, f, a){\n  return typeError(\n    'encaseP() expects the function it\\'s given to return a Promise/Thenable'\n    + '\\n  Actual: ' + sanctuaryShow(p) + '\\n  From calling: ' + sanctuaryShow(f)\n    + '\\n  With: ' + sanctuaryShow(a)\n  );\n}\n\nvar EncaseP = createInterpreter(2, 'encaseP', function EncaseP$interpret(rec, rej, res){\n  var open = true, fn = this.$1, arg = this.$2, p;\n  try{\n    p = fn(arg);\n  }catch(e){\n    rec(wrapException(e, this));\n    return noop;\n  }\n  if(!isThenable(p)){\n    rec(wrapException(invalidPromise(p, fn, arg), this));\n    return noop;\n  }\n  p.then(function EncaseP$res(x){\n    if(open){\n      open = false;\n      res(x);\n    }\n  }, function EncaseP$rej(x){\n    if(open){\n      open = false;\n      rej(x);\n    }\n  });\n  return function EncaseP$cancel(){ open = false; };\n});\n\nfunction encaseP(f){\n  var context1 = application1(encaseP, func, arguments);\n  return function encaseP(x){\n    var context2 = application(2, encaseP, any, arguments, context1);\n    return new EncaseP(context2, f, x);\n  };\n}\n\nfunction attemptP(_){\n  return encaseP.apply(this, arguments)(undefined);\n}\n\nvar Encase = createInterpreter(2, 'encase', function Encase$interpret(rec, rej, res){\n  var fn = this.$1, r;\n  try{ r = fn(this.$2); }catch(e){ rej(e); return noop }\n  res(r);\n  return noop;\n});\n\nfunction encase(f){\n  var context1 = application1(encase, func, arguments);\n  return function encase(x){\n    var context2 = application(2, encase, any, arguments, context1);\n    return new Encase(context2, f, x);\n  };\n}\n\nfunction attempt(_){\n  return encase.apply(this, arguments)(undefined);\n}\n\nvar bifunctor = {pred: isBifunctor, error: invalidArgumentOf('have Bifunctor implemented')};\n\nfunction bimap(f){\n  var context1 = application1(bimap, func, arguments);\n  return function bimap(g){\n    var context2 = application(2, bimap, func, arguments, context1);\n    return function bimap(m){\n      var context3 = application(3, bimap, bifunctor, arguments, context2);\n      return isFuture(m) ?\n             m._transform(new BimapTransformation(context3, f, g)) :\n             m[FL.bimap](f, g);\n    };\n  };\n}\n\nvar BichainTransformation = createTransformation(2, 'bichain', {\n  rejected: function BichainTransformation$rejected(x){ return call(this.$1, x) },\n  resolved: function BichainTransformation$resolved(x){ return call(this.$2, x) }\n});\n\nfunction bichain(f){\n  var context1 = application1(bichain, func, arguments);\n  return function bichain(g){\n    var context2 = application(2, bichain, func, arguments, context1);\n    return function bichain(m){\n      var context3 = application(3, bichain, future, arguments, context2);\n      return m._transform(new BichainTransformation(context3, f, g));\n    };\n  };\n}\n\nfunction Eager(future){\n  var _this = this;\n  _this.rec = noop;\n  _this.rej = noop;\n  _this.res = noop;\n  _this.crashed = false;\n  _this.rejected = false;\n  _this.resolved = false;\n  _this.value = null;\n  _this.cancel = future._interpret(function Eager$crash(x){\n    _this.value = x;\n    _this.crashed = true;\n    _this.cancel = noop;\n    _this.rec(x);\n  }, function Eager$reject(x){\n    _this.value = x;\n    _this.rejected = true;\n    _this.cancel = noop;\n    _this.rej(x);\n  }, function Eager$resolve(x){\n    _this.value = x;\n    _this.resolved = true;\n    _this.cancel = noop;\n    _this.res(x);\n  });\n}\n\nEager.prototype = Object.create(Future.prototype);\n\nEager.prototype._interpret = function Eager$interpret(rec, rej, res){\n  if(this.crashed) rec(this.value);\n  else if(this.rejected) rej(this.value);\n  else if(this.resolved) res(this.value);\n  else {\n    this.rec = rec;\n    this.rej = rej;\n    this.res = res;\n  }\n  return this.cancel;\n};\n\nfunction earlyCrash(early, x){\n  early(crash(x));\n}\n\nfunction earlyReject(early, x){\n  early(reject(x));\n}\n\nfunction earlyResolve(early, x){\n  early(resolve(x));\n}\n\nfunction createParallelTransformation(name, rec, rej, res, prototype){\n  var ParallelTransformation = createTransformation(1, name, Object.assign({\n    run: function Parallel$run(early){\n      var eager = new Eager(this.$1);\n      var transformation = new ParallelTransformation(this.context, eager);\n      function Parallel$early(m){ early(m, transformation); }\n      transformation.cancel = eager._interpret(\n        function Parallel$rec(x){ rec(Parallel$early, x); },\n        function Parallel$rej(x){ rej(Parallel$early, x); },\n        function Parallel$res(x){ res(Parallel$early, x); }\n      );\n      return transformation;\n    }\n  }, prototype));\n  return ParallelTransformation;\n}\n\nvar PairTransformation = createTransformation(1, 'pair', {\n  resolved: function PairTransformation$resolved(x){\n    return new Resolve(this.context, [x, this.$1]);\n  }\n});\n\nvar BothTransformation =\ncreateParallelTransformation('both', earlyCrash, earlyReject, noop, {\n  resolved: function BothTransformation$resolved(x){\n    return this.$1._transform(new PairTransformation(this.context, x));\n  }\n});\n\nfunction both(left){\n  var context1 = application1(both, future, arguments);\n  return function both(right){\n    var context2 = application(2, both, future, arguments, context1);\n    return right._transform(new BothTransformation(context2, left));\n  };\n}\n\nvar Cold = 0;\nvar Pending = 1;\nvar Crashed = 2;\nvar Rejected = 3;\nvar Resolved = 4;\n\nfunction Queued(rec, rej, res){\n  this[Crashed] = rec;\n  this[Rejected] = rej;\n  this[Resolved] = res;\n}\n\nvar Cache = createInterpreter(1, 'cache', function Cache$interpret(rec, rej, res){\n  var cancel = noop;\n\n  switch(this._state){\n    /* c8 ignore next 4 */\n    case Pending: cancel = this._addToQueue(rec, rej, res); break;\n    case Crashed: rec(this._value); break;\n    case Rejected: rej(this._value); break;\n    case Resolved: res(this._value); break;\n    default:\n      this._queue = [];\n      cancel = this._addToQueue(rec, rej, res);\n      this.run();\n  }\n\n  return cancel;\n});\n\nCache.prototype._cancel = noop;\nCache.prototype._queue = null;\nCache.prototype._queued = 0;\nCache.prototype._value = undefined;\nCache.prototype._state = Cold;\n\nCache.prototype.extractLeft = function Cache$extractLeft(){\n  return this._state === Rejected ? [this._value] : [];\n};\n\nCache.prototype.extractRight = function Cache$extractRight(){\n  return this._state === Resolved ? [this._value] : [];\n};\n\nCache.prototype._addToQueue = function Cache$addToQueue(rec, rej, res){\n  var _this = this;\n  if(_this._state > Pending) return noop;\n  var i = _this._queue.push(new Queued(rec, rej, res)) - 1;\n  _this._queued = _this._queued + 1;\n\n  return function Cache$removeFromQueue(){\n    if(_this._state > Pending) return;\n    _this._queue[i] = undefined;\n    _this._queued = _this._queued - 1;\n    if(_this._queued === 0) _this.reset();\n  };\n};\n\nCache.prototype._drainQueue = function Cache$drainQueue(){\n  if(this._state <= Pending) return;\n  if(this._queued === 0) return;\n  var queue = this._queue;\n  var length = queue.length;\n  var state = this._state;\n  var value = this._value;\n\n  for(var i = 0; i < length; i++){\n    queue[i] && queue[i][state](value);\n    queue[i] = undefined;\n  }\n\n  this._queue = undefined;\n  this._queued = 0;\n};\n\nCache.prototype.crash = function Cache$crash(error){\n  if(this._state > Pending) return;\n  this._value = error;\n  this._state = Crashed;\n  this._drainQueue();\n};\n\nCache.prototype.reject = function Cache$reject(reason){\n  if(this._state > Pending) return;\n  this._value = reason;\n  this._state = Rejected;\n  this._drainQueue();\n};\n\nCache.prototype.resolve = function Cache$resolve(value){\n  if(this._state > Pending) return;\n  this._value = value;\n  this._state = Resolved;\n  this._drainQueue();\n};\n\nCache.prototype.run = function Cache$run(){\n  var _this = this;\n  if(_this._state > Cold) return;\n  _this._state = Pending;\n  _this._cancel = _this.$1._interpret(\n    function Cache$fork$rec(x){ _this.crash(x); },\n    function Cache$fork$rej(x){ _this.reject(x); },\n    function Cache$fork$res(x){ _this.resolve(x); }\n  );\n};\n\nCache.prototype.reset = function Cache$reset(){\n  if(this._state === Cold) return;\n  if(this._state === Pending) this._cancel();\n  this._cancel = noop;\n  this._queue = [];\n  this._queued = 0;\n  this._value = undefined;\n  this._state = Cold;\n};\n\nfunction cache(m){\n  return new Cache(application1(cache, future, arguments), m);\n}\n\nvar ChainRejTransformation = createTransformation(1, 'chainRej', {\n  rejected: function ChainRejTransformation$rejected(x){ return call(this.$1, x) }\n});\n\nfunction chainRej(f){\n  var context1 = application1(chainRej, func, arguments);\n  return function chainRej(m){\n    var context2 = application(2, chainRej, future, arguments, context1);\n    return m._transform(new ChainRejTransformation(context2, f));\n  };\n}\n\nvar monad = {pred: isChain, error: invalidArgumentOf('have Chain implemented')};\n\nfunction chain(f){\n  var context1 = application1(chain, func, arguments);\n  return function chain(m){\n    var context2 = application(2, chain, monad, arguments, context1);\n    return isFuture(m) ?\n           m._transform(new ChainTransformation(context2, f)) :\n           m[FL.chain](f);\n  };\n}\n\nfunction done(callback){\n  var context1 = application1(done, func, arguments);\n  function done$res(x){\n    callback(null, x);\n  }\n  return function done(m){\n    application(2, done, future, arguments, context1);\n    return m._interpret(raise, callback, done$res);\n  };\n}\n\nfunction extractLeft(m){\n  application1(extractLeft, future, arguments);\n  return m.extractLeft();\n}\n\nfunction extractRight(m){\n  application1(extractRight, future, arguments);\n  return m.extractRight();\n}\n\nvar CoalesceTransformation = createTransformation(2, 'coalesce', {\n  rejected: function CoalesceTransformation$rejected(x){\n    return new Resolve(this.context, call(this.$1, x));\n  },\n  resolved: function CoalesceTransformation$resolved(x){\n    return new Resolve(this.context, call(this.$2, x));\n  }\n});\n\nfunction coalesce(f){\n  var context1 = application1(coalesce, func, arguments);\n  return function coalesce(g){\n    var context2 = application(2, coalesce, func, arguments, context1);\n    return function coalesce(m){\n      var context3 = application(3, coalesce, future, arguments, context2);\n      return m._transform(new CoalesceTransformation(context3, f, g));\n    };\n  };\n}\n\nfunction forkCatch(f){\n  var context1 = application1(forkCatch, func, arguments);\n  return function forkCatch(g){\n    var context2 = application(2, forkCatch, func, arguments, context1);\n    return function forkCatch(h){\n      var context3 = application(3, forkCatch, func, arguments, context2);\n      return function forkCatch(m){\n        application(4, forkCatch, future, arguments, context3);\n        return m._interpret(f, g, h);\n      };\n    };\n  };\n}\n\nfunction fork(f){\n  var context1 = application1(fork, func, arguments);\n  return function fork(g){\n    var context2 = application(2, fork, func, arguments, context1);\n    return function fork(m){\n      application(3, fork, future, arguments, context2);\n      return m._interpret(raise, f, g);\n    };\n  };\n}\n\nvar Undetermined = 0;\nvar Synchronous = 1;\nvar Asynchronous = 2;\n\n/*eslint consistent-return: 0 */\n\nfunction invalidIteration(o){\n  return typeError(\n    'The iterator did not return a valid iteration from iterator.next()\\n' +\n    '  Actual: ' + sanctuaryShow(o)\n  );\n}\n\nfunction invalidState(x){\n  return invalidFuture(\n    'go() expects the value produced by the iterator', x,\n    '\\n  Tip: If you\\'re using a generator, make sure you always yield a Future'\n  );\n}\n\nvar Go = createInterpreter(1, 'go', function Go$interpret(rec, rej, res){\n\n  var _this = this, timing = Undetermined, cancel = noop, state, value, iterator;\n\n  function crash(e){\n    rec(wrapException(e, _this));\n  }\n\n  try{\n    iterator = _this.$1();\n  }catch(e){\n    crash(e);\n    return noop;\n  }\n\n  if(!isIterator(iterator)){\n    crash(invalidArgument('go', 0, 'return an iterator, maybe you forgot the \"*\"', iterator));\n    return noop;\n  }\n\n  function resolved(x){\n    value = x;\n    if(timing === Asynchronous) return drain();\n    timing = Synchronous;\n  }\n\n  function drain(){\n    //eslint-disable-next-line no-constant-condition\n    while(true){\n      try{\n        state = iterator.next(value);\n      }catch(e){\n        return crash(e);\n      }\n      if(!isIteration(state)) return crash(invalidIteration(state));\n      if(state.done) break;\n      if(!isFuture(state.value)){\n        return crash(invalidState(state.value));\n      }\n      timing = Undetermined;\n      cancel = state.value._interpret(crash, rej, resolved);\n      if(timing === Undetermined) return timing = Asynchronous;\n    }\n    res(state.value);\n  }\n\n  drain();\n\n  return function Go$cancel(){ cancel(); };\n\n});\n\nfunction go(generator){\n  return new Go(application1(go, func, arguments), generator);\n}\n\nfunction invalidDisposal(m, f, x){\n  return invalidFuture(\n    'hook() expects the return value from the first function it\\'s given', m,\n    '\\n  From calling: ' + sanctuaryShow(f) + '\\n  With: ' + sanctuaryShow(x)\n  );\n}\n\nfunction invalidConsumption(m, f, x){\n  return invalidFuture(\n    'hook() expects the return value from the second function it\\'s given', m,\n    '\\n  From calling: ' + sanctuaryShow(f) + '\\n  With: ' + sanctuaryShow(x)\n  );\n}\n\nvar Hook = createInterpreter(3, 'hook', function Hook$interpret(rec, rej, res){\n\n  var _this = this, _acquire = this.$1, _dispose = this.$2, _consume = this.$3;\n  var cancel, cancelConsume = noop, resource, value, cont = noop;\n\n  function Hook$done(){\n    cont(value);\n  }\n\n  function Hook$rec(x){\n    rec(wrapException(x, _this));\n  }\n\n  function Hook$dispose(){\n    var disposal;\n    try{\n      disposal = _dispose(resource);\n    }catch(e){\n      return Hook$rec(e);\n    }\n    if(!isFuture(disposal)){\n      return Hook$rec(invalidDisposal(disposal, _dispose, resource));\n    }\n    cancel = Hook$cancelDisposal;\n    disposal._interpret(Hook$rec, Hook$disposalRejected, Hook$done);\n  }\n\n  function Hook$cancelConsumption(){\n    cancelConsume();\n    Hook$dispose();\n    Hook$cancelDisposal();\n  }\n\n  function Hook$cancelDisposal(){\n    cont = noop;\n  }\n\n  function Hook$disposalRejected(x){\n    Hook$rec(new Error('The disposal Future rejected with ' + sanctuaryShow(x)));\n  }\n\n  function Hook$consumptionException(x){\n    cont = Hook$rec;\n    value = x;\n    Hook$dispose();\n  }\n\n  function Hook$consumptionRejected(x){\n    cont = rej;\n    value = x;\n    Hook$dispose();\n  }\n\n  function Hook$consumptionResolved(x){\n    cont = res;\n    value = x;\n    Hook$dispose();\n  }\n\n  function Hook$consume(x){\n    resource = x;\n    var consumption;\n    try{\n      consumption = _consume(resource);\n    }catch(e){\n      return Hook$consumptionException(e);\n    }\n    if(!isFuture(consumption)){\n      return Hook$consumptionException(invalidConsumption(consumption, _consume, resource));\n    }\n    cancel = Hook$cancelConsumption;\n    cancelConsume = consumption._interpret(\n      Hook$consumptionException,\n      Hook$consumptionRejected,\n      Hook$consumptionResolved\n    );\n  }\n\n  var cancelAcquire = _acquire._interpret(Hook$rec, rej, Hook$consume);\n  cancel = cancel || cancelAcquire;\n\n  return function Hook$fork$cancel(){\n    rec = raise;\n    cancel();\n  };\n\n});\n\nfunction hook(acquire){\n  var context1 = application1(hook, future, arguments);\n  return function hook(dispose){\n    var context2 = application(2, hook, func, arguments, context1);\n    return function hook(consume){\n      var context3 = application(3, hook, func, arguments, context2);\n      return new Hook(context3, acquire, dispose, consume);\n    };\n  };\n}\n\nvar LastlyTransformation = createTransformation(1, 'lastly', {\n  rejected: function LastlyAction$rejected(x){\n    return this.$1._transform(new AndTransformation(this.context, new Reject(this.context, x)));\n  },\n  resolved: function LastlyAction$resolved(x){\n    return this.$1._transform(new AndTransformation(this.context, new Resolve(this.context, x)));\n  }\n});\n\nfunction lastly(cleanup){\n  var context1 = application1(lastly, future, arguments);\n  return function lastly(program){\n    var context2 = application(2, lastly, future, arguments, context1);\n    return program._transform(new LastlyTransformation(context2, cleanup));\n  };\n}\n\nvar MapRejTransformation = createTransformation(1, 'mapRej', {\n  rejected: function MapRejTransformation$rejected(x){\n    return new Reject(this.context, call(this.$1, x));\n  }\n});\n\nfunction mapRej(f){\n  var context1 = application1(mapRej, func, arguments);\n  return function mapRej(m){\n    var context2 = application(2, mapRej, future, arguments, context1);\n    return m._transform(new MapRejTransformation(context2, f));\n  };\n}\n\nvar functor = {pred: isFunctor, error: invalidArgumentOf('have Functor implemented')};\n\nfunction map(f){\n  var context1 = application1(map, func, arguments);\n  return function map(m){\n    var context2 = application(2, map, functor, arguments, context1);\n    return isFuture(m) ?\n           m._transform(new MapTransformation(context2, f)) :\n           m[FL.map](f);\n  };\n}\n\nvar Node = createInterpreter(1, 'node', function Node$interpret(rec, rej, res){\n  function Node$done(err, val){\n    cont = err ? function EncaseN3$rej(){\n      open = false;\n      rej(err);\n    } : function EncaseN3$res(){\n      open = false;\n      res(val);\n    };\n    if(open){\n      cont();\n    }\n  }\n  var open = false, cont = function(){ open = true; };\n  try{\n    call(this.$1, Node$done);\n  }catch(e){\n    rec(wrapException(e, this));\n    open = false;\n    return noop;\n  }\n  cont();\n  return function Node$cancel(){ open = false; };\n});\n\nfunction node(f){\n  return new Node(application1(node, func, arguments), f);\n}\n\nvar ParallelApTransformation =\ncreateParallelTransformation('pap', earlyCrash, earlyReject, noop, {\n  resolved: function ParallelApTransformation$resolved(f){\n    if(isFunction(f)) return this.$1._transform(new MapTransformation(this.context, f));\n    throw typeError(\n      'pap expects the second Future to resolve to a Function\\n' +\n      '  Actual: ' + sanctuaryShow(f)\n    );\n  }\n});\n\nfunction pap(mx){\n  var context1 = application1(pap, future, arguments);\n  return function pap(mf){\n    var context2 = application(2, pap, future, arguments, context1);\n    return mf._transform(new ParallelApTransformation(context2, mx));\n  };\n}\n\nfunction isFutureArray(xs){\n  if(!isArray(xs)) return false;\n  for(var i = 0; i < xs.length; i++){\n    if(!isFuture(xs[i])) return false;\n  }\n  return true;\n}\n\nvar futureArray = {\n  pred: isFutureArray,\n  error: invalidArgumentOf('be an Array of valid Futures')\n};\n\nvar Parallel = createInterpreter(2, 'parallel', function Parallel$interpret(rec, rej, res){\n\n  var _this = this, futures = this.$2, length = futures.length;\n  var max = Math.min(this.$1, length), cancels = new Array(length), out = new Array(length);\n  var cursor = 0, running = 0, blocked = false, cont = noop;\n\n  function Parallel$cancel(){\n    rec = noop;\n    rej = noop;\n    res = noop;\n    cursor = length;\n    for(var n = 0; n < length; n++) cancels[n] && cancels[n]();\n  }\n\n  function Parallel$run(idx){\n    running++;\n    cancels[idx] = futures[idx]._interpret(function Parallel$rec(e){\n      cont = rec;\n      cancels[idx] = noop;\n      Parallel$cancel();\n      cont(wrapException(e, _this));\n    }, function Parallel$rej(reason){\n      cont = rej;\n      cancels[idx] = noop;\n      Parallel$cancel();\n      cont(reason);\n    }, function Parallel$res(value){\n      cancels[idx] = noop;\n      out[idx] = value;\n      running--;\n      if(cursor === length && running === 0) res(out);\n      else if(blocked) Parallel$drain();\n    });\n  }\n\n  function Parallel$drain(){\n    blocked = false;\n    while(cursor < length && running < max) Parallel$run(cursor++);\n    blocked = true;\n  }\n\n  Parallel$drain();\n\n  return Parallel$cancel;\n\n});\n\nvar emptyArray = resolve([]);\n\nfunction parallel$1(max){\n  var context1 = application1(parallel$1, positiveInteger, arguments);\n  return function parallel(ms){\n    var context2 = application(2, parallel, futureArray, arguments, context1);\n    return ms.length === 0 ? emptyArray : new Parallel(context2, max, ms);\n  };\n}\n\nvar RaceTransformation =\ncreateParallelTransformation('race', earlyCrash, earlyReject, earlyResolve, {});\n\nfunction race(left){\n  var context1 = application1(race, future, arguments);\n  return function race(right){\n    var context2 = application(2, race, future, arguments, context1);\n    return right._transform(new RaceTransformation(context2, left));\n  };\n}\n\nfunction ConcurrentFuture (sequential){\n  this.sequential = sequential;\n}\n\nConcurrentFuture.prototype = Object.create(Par.prototype);\n\nfunction Par (sequential){\n  if(!isFuture(sequential)) throw invalidFutureArgument(Par.name, 0, sequential);\n  return new ConcurrentFuture(sequential);\n}\n\nvar $$type = namespace + '/ConcurrentFuture@' + version;\nvar zeroInstance = new ConcurrentFuture(never);\n\n// Compliance with sanctuary-type-identifiers versions 1 and 2.\n// To prevent sanctuary-type-identifiers version 3 from identifying\n// 'Par' as being of the type denoted by $$type, we ensure that\n// Par.constructor.prototype is equal to Par.\nPar['@@type'] = $$type;\nPar.constructor = {prototype: Par};\n\nPar[FL.of] = function Par$of(x){\n  return new ConcurrentFuture(resolve(x));\n};\n\nPar[FL.zero] = function Par$zero(){\n  return zeroInstance;\n};\n\nPar.prototype['@@type'] = $$type;\n\nPar.prototype['@@show'] = function Par$show(){\n  return this.toString();\n};\n\nPar.prototype.toString = function Par$toString(){\n  return 'Par (' + this.sequential.toString() + ')';\n};\n\nPar.prototype[FL.map] = function Par$FL$map(f){\n  var context = captureContext(\n    nil,\n    'a Fantasy Land dispatch to map via ConcurrentFuture',\n    Par$FL$map\n  );\n  return new ConcurrentFuture(this.sequential._transform(new MapTransformation(context, f)));\n};\n\nPar.prototype[FL.ap] = function Par$FL$ap(other){\n  var context = captureContext(\n    nil,\n    'a Fantasy Land dispatch to ap via ConcurrentFuture',\n    Par$FL$ap\n  );\n  return new ConcurrentFuture(other.sequential._transform(\n    new ParallelApTransformation(context, this.sequential)\n  ));\n};\n\nPar.prototype[FL.alt] = function Par$FL$alt(other){\n  var context = captureContext(\n    nil,\n    'a Fantasy Land dispatch to alt via ConcurrentFuture',\n    Par$FL$alt\n  );\n  return new ConcurrentFuture(other.sequential._transform(\n    new RaceTransformation(context, this.sequential)\n  ));\n};\n\nfunction isParallel(x){\n  return x instanceof ConcurrentFuture || sanctuaryTypeIdentifiers(x) === $$type;\n}\n\nfunction promise(m){\n  application1(promise, future, arguments);\n  return new Promise(function promise$computation(res, rej){\n    m._interpret(rej, rej, res);\n  });\n}\n\nvar RejectAfter =\ncreateInterpreter(2, 'rejectAfter', function RejectAfter$interpret(rec, rej){\n  var id = setTimeout(rej, this.$1, this.$2);\n  return function RejectAfter$cancel(){ clearTimeout(id); };\n});\n\nRejectAfter.prototype.extractLeft = function RejectAfter$extractLeft(){\n  return [this.$2];\n};\n\nfunction alwaysNever(_){\n  return never;\n}\n\nfunction rejectAfter(time){\n  var context1 = application1(rejectAfter, positiveInteger, arguments);\n  return time === Infinity ? alwaysNever : (function rejectAfter(value){\n    var context2 = application(2, rejectAfter, any, arguments, context1);\n    return new RejectAfter(context2, time, value);\n  });\n}\n\nvar parallel = {pred: isParallel, error: invalidArgumentOf('be a ConcurrentFuture')};\n\nfunction seq(par){\n  application1(seq, parallel, arguments);\n  return par.sequential;\n}\n\nvar SwapTransformation = createTransformation(0, 'swap', {\n  resolved: function SwapTransformation$resolved(x){\n    return new Reject(this.context, x);\n  },\n  rejected: function SwapTransformation$rejected(x){\n    return new Resolve(this.context, x);\n  }\n});\n\nfunction swap(m){\n  var context = application1(swap, future, arguments);\n  return m._transform(new SwapTransformation(context));\n}\n\nfunction value(res){\n  var context1 = application1(value, func, arguments);\n  return function value(m){\n    application(2, value, future, arguments, context1);\n    function value$rej(x){\n      raise(error(\n        'Future#value was called on a rejected Future\\n' +\n        '  Rejection: ' + sanctuaryShow(x) + '\\n' +\n        '  Future: ' + sanctuaryShow(m)\n      ));\n    }\n    return m._interpret(raise, value$rej, res);\n  };\n}\n\nexport default Future;\nexport { Future, Par, after, alt, and, ap, attempt, attemptP, bichain, bimap, both, cache, chain, chainRej, coalesce, debugMode, done, encase, encaseP, extractLeft, extractRight, fork, forkCatch, go, hook, isFuture, isNever, lastly, map, mapRej, never, node, pap, parallel$1 as parallel, promise, race, reject, rejectAfter, resolve, seq, swap, value };\n/** Fluture license\n\nThe MIT License (MIT)\nCopyright (c) 2020 Aldwin Vlasblom\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies\nof the Software, and to permit persons to whom the Software is furnished to do\nso, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*/\n\n/** sanctuary-show license\n\nThe MIT License (MIT)\n\nCopyright (c) 2020 Sanctuary\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and/or\nsell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n*/\n\n/** sanctuary-type-identifiers license\n\nThe MIT License (MIT)\n\nCopyright (c) 2019 Sanctuary\n\nPermission is hereby granted, free of charge, to any person\nobtaining a copy of this software and associated documentation\nfiles (the \"Software\"), to deal in the Software without\nrestriction, including without limitation the rights to use,\ncopy, modify, merge, publish, distribute, sublicense, and/or\nsell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice shall be\nincluded in all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\nEXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\nOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\nNONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\nHOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,\nWHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\nOTHER DEALINGS IN THE SOFTWARE.\n*/\n"
  },
  {
    "path": "index.cjs.js",
    "content": "import * as Fluture from './index.js';\nexport default Object.assign(Fluture.Future, Fluture);\n"
  },
  {
    "path": "index.d.ts",
    "content": "/// <reference lib=\"es2015.generator\" />\n/// <reference lib=\"es2015.iterable\" />\n\nexport interface RecoverFunction {\n  (exception: Error): void\n}\n\nexport interface RejectFunction<L> {\n  (error: L): void\n}\n\nexport interface ResolveFunction<R> {\n  (value: R): void\n}\n\nexport interface Cancel {\n  (): void\n}\n\nexport interface Nodeback<E, R> {\n  (err: E | null, value?: R): void\n}\n\ndeclare const $T: unique symbol\n\nexport interface Functor<A> {\n  [$T]: unknown\n  'fantasy-land/map'<B extends this[typeof $T]>(mapper: (value: A) => B): Functor<B>\n}\n\ntype Mapped<F extends Functor<unknown>, B> = ReturnType<(F & { [$T]: B })['fantasy-land/map']>\n\nexport interface ConcurrentFutureInstance<L, R> extends Functor<R> {\n  sequential: FutureInstance<L, R>\n  'fantasy-land/ap'<A, B>(this: ConcurrentFutureInstance<L, (value: A) => B>, right: ConcurrentFutureInstance<L, A>): ConcurrentFutureInstance<L, B>\n  'fantasy-land/map'<RB extends this[typeof $T]>(mapper: (value: R) => RB): ConcurrentFutureInstance<L, RB>\n  'fantasy-land/alt'(right: ConcurrentFutureInstance<L, R>): ConcurrentFutureInstance<L, R>\n}\n\nexport interface FutureInstance<L, R> extends Functor<R> {\n\n  /** The Future constructor */\n  constructor: FutureTypeRep\n\n  /** Apply a function to this Future. See https://github.com/fluture-js/Fluture#pipe */\n  pipe<T>(fn: (future: this) => T): T\n\n  /** Attempt to extract the rejection reason. See https://github.com/fluture-js/Fluture#extractleft */\n  extractLeft(): Array<L>\n\n  /** Attempt to extract the resolution value. See https://github.com/fluture-js/Fluture#extractright */\n  extractRight(): Array<R>\n\n  'fantasy-land/ap'<A, B>(this: FutureInstance<L, (value: A) => B>, right: FutureInstance<L, A>): FutureInstance<L, B>\n  'fantasy-land/map'<RB extends this[typeof $T]>(mapper: (value: R) => RB): FutureInstance<L, RB>\n  'fantasy-land/alt'(right: FutureInstance<L, R>): FutureInstance<L, R>\n  'fantasy-land/bimap'<LB, RB>(lmapper: (reason: L) => LB, rmapper: (value: R) => RB): FutureInstance<LB, RB>\n  'fantasy-land/chain'<LB, RB>(mapper: (value: R) => FutureInstance<LB, RB>): FutureInstance<L | LB, RB>\n\n}\n\n/** Creates a Future which resolves after the given duration with the given value. See https://github.com/fluture-js/Fluture#after */\nexport function after(duration: number): <R>(value: R) => FutureInstance<never, R>\n\n/** Logical and for Futures. See https://github.com/fluture-js/Fluture#and */\nexport function and<L, R>(left: FutureInstance<L, R>): (right: FutureInstance<L, any>) => FutureInstance<L, R>\n\n/** Logical or for Futures. See https://github.com/fluture-js/Fluture#alt */\nexport function alt<L, R>(left: FutureInstance<L, R>): (right: FutureInstance<L, R>) => FutureInstance<L, R>\n\n/** Race two ConcurrentFutures. See https://github.com/fluture-js/Fluture#alt */\nexport function alt<L, R>(left: ConcurrentFutureInstance<L, R>): (right: ConcurrentFutureInstance<L, R>) => ConcurrentFutureInstance<L, R>\n\n/** Apply the function in the right Future to the value in the left Future. See https://github.com/fluture-js/Fluture#ap */\nexport function ap<L, RA>(value: FutureInstance<L, RA>): <RB>(apply: FutureInstance<L, (value: RA) => RB>) => FutureInstance<L, RB>\n\n/** Apply the function in the right ConcurrentFuture to the value in the left ConcurrentFuture. See https://github.com/fluture-js/Fluture#ap */\nexport function ap<L, RA>(value: ConcurrentFutureInstance<L, RA>): <RB>(apply: ConcurrentFutureInstance<L, (value: RA) => RB>) => ConcurrentFutureInstance<L, RB>\n\n/** Apply the function in the right Future to the value in the left Future in parallel. See https://github.com/fluture-js/Fluture#pap */\nexport function pap<L, RA>(value: FutureInstance<L, RA>): <RB>(apply: FutureInstance<L, (value: RA) => RB>) => FutureInstance<L, RB>\n\n/** Create a Future which resolves with the return value of the given function, or rejects with the error it throws. See https://github.com/fluture-js/Fluture#attempt */\nexport function attempt<L, R>(fn: () => R): FutureInstance<L, R>\n\n/** Convert a Promise-returning function to a Future. See https://github.com/fluture-js/Fluture#attemptP */\nexport function attemptP<L, R>(fn: () => Promise<R>): FutureInstance<L, R>\n\n/** Create a Future using the inner value of the given Future. See https://github.com/fluture-js/Fluture#bichain */\nexport function bichain<LA, LB, RB>(lmapper: (reason: LA) => FutureInstance<LB, RB>): <RA>(rmapper: (value: RA) => FutureInstance<LB, RB>) => (source: FutureInstance<LA, RA>) => FutureInstance<LB, RB>\n\n/** Map over both branches of the given Bifunctor at once. See https://github.com/fluture-js/Fluture#bimap */\nexport function bimap<LA, LB>(lmapper: (reason: LA) => LB): <RA, RB>(rmapper: (value: RA) => RB) => (source: FutureInstance<LA, RA>) => FutureInstance<LB, RB>\n\n/** Wait for both Futures to resolve in parallel. See https://github.com/fluture-js/Fluture#both */\nexport function both<L, A>(left: FutureInstance<L, A>): <B>(right: FutureInstance<L, B>) => FutureInstance<L, [A, B]>\n\n/** Cache the outcome of the given Future. See https://github.com/fluture-js/Fluture#cache */\nexport function cache<L, R>(source: FutureInstance<L, R>): FutureInstance<L, R>\n\n/** Create a Future using the resolution value of the given Future. See https://github.com/fluture-js/Fluture#chain */\nexport function chain<LB, RA, RB>(mapper: (value: RA) => FutureInstance<LB, RB>): <LA>(source: FutureInstance<LA, RA>) => FutureInstance<LA | LB, RB>\n\n/** Create a Future using the rejection reason of the given Future. See https://github.com/fluture-js/Fluture#chain */\nexport function chainRej<LA, LB, RB>(mapper: (reason: LA) => FutureInstance<LB, RB>): <RA>(source: FutureInstance<LA, RA>) => FutureInstance<LB, RA | RB>\n\n/** Fork the given Future into a Node-style callback. See https://github.com/fluture-js/Fluture#done */\nexport function done<L, R>(callback: Nodeback<L, R>): (source: FutureInstance<L, R>) => Cancel\n\n/** Encase the given function such that it returns a Future of its return value. See https://github.com/fluture-js/Fluture#encase */\nexport function encase<L, R, A>(fn: (a: A) => R): (a: A) => FutureInstance<L, R>\n\n/** Encase the given Promise-returning function such that it returns a Future of its resolution value. See https://github.com/fluture-js/Fluture#encasep */\nexport function encaseP<L, R, A>(fn: (a: A) => Promise<R>): (a: A) => FutureInstance<L, R>\n\n/** Attempt to extract the rejection reason. See https://github.com/fluture-js/Fluture#extractleft */\nexport function extractLeft<L, R>(source: FutureInstance<L, R>): Array<L>\n\n/** Attempt to extract the resolution value. See https://github.com/fluture-js/Fluture#extractright */\nexport function extractRight<L, R>(source: FutureInstance<L, R>): Array<R>\n\n/** Coalesce both branches into the resolution branch. See https://github.com/fluture-js/Fluture#coalesce */\nexport function coalesce<LA, R>(lmapper: (left: LA) => R): <RA>(rmapper: (right: RA) => R) => (source: FutureInstance<LA, RA>) => FutureInstance<never, R>\n\n/** Fork the given Future into the given continuations. See https://github.com/fluture-js/Fluture#fork */\nexport function fork<L>(reject: RejectFunction<L>): <R>(resolve: ResolveFunction<R>) => (source: FutureInstance<L, R>) => Cancel\n\n/** Fork with exception recovery. See https://github.com/fluture-js/Fluture#forkCatch */\nexport function forkCatch(recover: RecoverFunction): <L>(reject: RejectFunction<L>) => <R>(resolve: ResolveFunction<R>) => (source: FutureInstance<L, R>) => Cancel\n\n/** Build a coroutine using Futures. See https://github.com/fluture-js/Fluture#go */\nexport function go<L, R>(generator: () => Generator<FutureInstance<L, any>, R, any>): FutureInstance<L, R>\n\n/** Manage resources before and after the computation that needs them. See https://github.com/fluture-js/Fluture#hook */\nexport function hook<L, H>(acquire: FutureInstance<L, H>): (dispose: (handle: H) => FutureInstance<any, any>) => <R>(consume: (handle: H) => FutureInstance<L, R>) => FutureInstance<L, R>\n\n/** Returns true for Futures. See https://github.com/fluture-js/Fluture#isfuture */\nexport function isFuture(value: any): boolean\n\n/** Returns true for Futures that will certainly never settle. See https://github.com/fluture-js/Fluture#isnever */\nexport function isNever(value: any): boolean\n\n/** Set up a cleanup Future to run after the given action has settled. See https://github.com/fluture-js/Fluture#lastly */\nexport function lastly<L>(cleanup: FutureInstance<L, any>): <R>(action: FutureInstance<L, R>) => FutureInstance<L, R>\n\n/** Map over the resolution value of the given Future or ConcurrentFuture. See https://github.com/fluture-js/Fluture#map */\nexport const map: {\n  <B, F extends Functor<unknown>>(mapper: Functor<unknown> extends F ? never : (a: F extends Functor<infer A> ? A : never) => B): (source: F) => Mapped<F, B>\n  <A, B>(mapper: (a: A) => B): <F extends Functor<A>>(source: F) => Mapped<F, B>\n}\n\n/** Map over the rejection reason of the given Future. See https://github.com/fluture-js/Fluture#maprej */\nexport function mapRej<LA, LB>(mapper: (reason: LA) => LB): <R>(source: FutureInstance<LA, R>) => FutureInstance<LB, R>\n\n/** A Future that never settles. See https://github.com/fluture-js/Fluture#never */\nexport var never: FutureInstance<never, never>\n\n/** Create a Future using a provided Node-style callback. See https://github.com/fluture-js/Fluture#node */\nexport function node<L, R>(fn: (done: Nodeback<L, R>) => void): FutureInstance<L, R>\n\n/** Create a Future with the given resolution value. See https://github.com/fluture-js/Fluture#of */\nexport function resolve<R>(value: R): FutureInstance<never, R>\n\n/** Run an Array of Futures in parallel, under the given concurrency limit. See https://github.com/fluture-js/Fluture#parallel */\nexport function parallel(concurrency: number): <L, R>(futures: Array<FutureInstance<L, R>>) => FutureInstance<L, Array<R>>\n\n/** Convert a Future to a Promise. See https://github.com/fluture-js/Fluture#promise */\nexport function promise<R>(source: FutureInstance<Error, R>): Promise<R>\n\n/** Race two Futures against one another. See https://github.com/fluture-js/Fluture#race */\nexport function race<L, R>(left: FutureInstance<L, R>): (right: FutureInstance<L, R>) => FutureInstance<L, R>\n\n/** Create a Future with the given rejection reason. See https://github.com/fluture-js/Fluture#reject */\nexport function reject<L>(reason: L): FutureInstance<L, never>\n\n/** Creates a Future which rejects after the given duration with the given reason. See https://github.com/fluture-js/Fluture#rejectafter */\nexport function rejectAfter(duration: number): <L>(reason: L) => FutureInstance<L, never>\n\n/** Convert a ConcurrentFuture to a regular Future. See https://github.com/fluture-js/Fluture#concurrentfuture */\nexport function seq<L, R>(source: ConcurrentFutureInstance<L, R>): FutureInstance<L, R>\n\n/** Swap the rejection reason and the resolution value. See https://github.com/fluture-js/Fluture#swap */\nexport function swap<L, R>(source: FutureInstance<L, R>): FutureInstance<R, L>\n\n/** Fork the Future into the given continuation. See https://github.com/fluture-js/Fluture#value */\nexport function value<R>(resolve: ResolveFunction<R>): (source: FutureInstance<never, R>) => Cancel\n\n/** Enable or disable debug mode. See https://github.com/fluture-js/Fluture#debugmode */\nexport function debugMode(debug: boolean): void;\n\nexport interface FutureTypeRep {\n\n  /** Create a Future from a possibly cancellable computation. See https://github.com/fluture-js/Fluture#future */\n  <L, R>(computation: (\n    reject: RejectFunction<L>,\n    resolve: ResolveFunction<R>\n  ) => Cancel): FutureInstance<L, R>\n\n  'fantasy-land/chainRec'<L, I, R>(iterator: (next: (value: I) => IteratorYieldResult<I>, done: (value: R) => IteratorReturnResult<R>, value: I) => FutureInstance<L, IteratorResult<I, R>>, initial: I): FutureInstance<L, R>\n  'fantasy-land/of': typeof resolve\n\n  '@@type': string\n\n}\n\nexport var Future: FutureTypeRep\nexport default Future\n\nexport interface ConcurrentFutureTypeRep {\n\n  /** Create a ConcurrentFuture using a Future. See https://github.com/fluture-js/Fluture#concurrentfuture */\n  <L, R>(source: FutureInstance<L, R>): ConcurrentFutureInstance<L, R>\n\n  'fantasy-land/of'<L, R>(value: R): ConcurrentFutureInstance<L, R>\n  'fantasy-land/zero'<L, R>(): ConcurrentFutureInstance<L, R>\n\n  '@@type': string\n\n}\n\nexport var Par: ConcurrentFutureTypeRep\n"
  },
  {
    "path": "index.js",
    "content": "export {\n  Future as default,\n  Future,\n  isFuture,\n  isNever,\n  never,\n  reject,\n  resolve,\n} from './src/future.js';\n\nexport {after} from './src/after.js';\nexport {alt} from './src/alt.js';\nexport {and} from './src/and.js';\nexport {ap} from './src/ap.js';\nexport {attemptP} from './src/attempt-p.js';\nexport {attempt} from './src/attempt.js';\nexport {bimap} from './src/bimap.js';\nexport {bichain} from './src/bichain.js';\nexport {both} from './src/both.js';\nexport {cache} from './src/cache.js';\nexport {chainRej} from './src/chain-rej.js';\nexport {chain} from './src/chain.js';\nexport {done} from './src/done.js';\nexport {encaseP} from './src/encase-p.js';\nexport {encase} from './src/encase.js';\nexport {extractLeft} from './src/extract-left.js';\nexport {extractRight} from './src/extract-right.js';\nexport {coalesce} from './src/coalesce.js';\nexport {forkCatch} from './src/fork-catch.js';\nexport {fork} from './src/fork.js';\nexport {go} from './src/go.js';\nexport {hook} from './src/hook.js';\nexport {lastly} from './src/lastly.js';\nexport {mapRej} from './src/map-rej.js';\nexport {map} from './src/map.js';\nexport {node} from './src/node.js';\nexport {pap} from './src/pap.js';\nexport {parallel} from './src/parallel.js';\nexport {Par} from './src/par.js';\nexport {promise} from './src/promise.js';\nexport {race} from './src/race.js';\nexport {rejectAfter} from './src/reject-after.js';\nexport {seq} from './src/seq.js';\nexport {swap} from './src/swap.js';\nexport {value} from './src/value.js';\n\nexport {debugMode} from './src/internal/debug.js';\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"fluture\",\n  \"version\": \"14.0.0\",\n  \"description\": \"FantasyLand compliant (monadic) alternative to Promises\",\n  \"main\": \"index.cjs\",\n  \"type\": \"module\",\n  \"types\": \"index.d.ts\",\n  \"module\": \"index.js\",\n  \"exports\": {\n    \".\": {\n      \"require\": \"./index.cjs\",\n      \"import\": \"./index.js\",\n      \"default\": \"./index.cjs\"\n    },\n    \"./index.js\": \"./index.js\",\n    \"./test/arbitraries.js\": \"./test/arbitraries.js\",\n    \"./test/assertions.js\": \"./test/assertions.js\"\n  },\n  \"files\": [\n    \"src\",\n    \"index.cjs\",\n    \"index.js\",\n    \"index.d.ts\",\n    \"test/arbitraries.js\",\n    \"test/assertions.js\"\n  ],\n  \"repository\": \"https://github.com/fluture-js/Fluture.git\",\n  \"scripts\": {\n    \"bench\": \"node ./scripts/bench.js\",\n    \"build\": \"rollup -c rollup.config.js\",\n    \"build:dist\": \"rollup -c rollup.config.dist.js\",\n    \"clean\": \"rimraf npm-debug.log coverage index.cjs .esm-cache .nyc_output node_modules/.cache\",\n    \"lint\": \"eslint src test index.js index.cjs.js\",\n    \"lint:readme\": \"remark --no-stdout --frail -u remark-validate-links README.md\",\n    \"release\": \"xyz --edit --repo git@github.com:fluture-js/Fluture.git --tag 'X.Y.Z' --script scripts/distribute --increment\",\n    \"test\": \"npm run lint && npm run lint:readme && ./scripts/test-esm && npm run test:code && npm run test:types && npm run test:build\",\n    \"test:code\": \"c8 oletus test/unit/*.js test/integration/*.js test/prop/*.js\",\n    \"test:mem\": \"NODE_OPTIONS='--experimental-modules --no-warnings' ./scripts/test-mem\",\n    \"test:build\": \"npm run build && oletus test/build/*.js\",\n    \"coverage:upload\": \"c8 report --reporter=text-lcov > coverage.lcov && codecov\",\n    \"coverage:report\": \"c8 report --reporter=html\",\n    \"test:types\": \"tsd\"\n  },\n  \"author\": \"Aldwin Vlasblom <aldwin.vlasblom@gmail.com> (https://github.com/Avaq)\",\n  \"homepage\": \"https://github.com/fluture-js/Fluture\",\n  \"bugs\": {\n    \"url\": \"https://github.com/fluture-js/Fluture/issues\"\n  },\n  \"license\": \"MIT\",\n  \"engines\": {\n    \"node\": \">=4.0.0\"\n  },\n  \"keywords\": [\n    \"algebraic\",\n    \"async\",\n    \"asynchronous\",\n    \"browser\",\n    \"control-flow\",\n    \"fantasy-land\",\n    \"fp\",\n    \"functional\",\n    \"functor\",\n    \"future\",\n    \"library\",\n    \"monad\",\n    \"monadic\",\n    \"node\",\n    \"parallel\",\n    \"promise\",\n    \"sequential\"\n  ],\n  \"dependencies\": {\n    \"sanctuary-show\": \"^2.0.0\",\n    \"sanctuary-type-identifiers\": \"^4.0.0\"\n  },\n  \"devDependencies\": {\n    \"@rollup/plugin-commonjs\": \"^25.0.0\",\n    \"@rollup/plugin-node-resolve\": \"^15.0.1\",\n    \"c8\": \"^9.0.0\",\n    \"chai\": \"^4.1.2\",\n    \"codecov\": \"^3.6.1\",\n    \"es-check\": \"^7.0.0\",\n    \"eslint\": \"^8.54.0\",\n    \"eslint-config-warp\": \"^7.1.0\",\n    \"fantasy-laws\": \"^2.0.1\",\n    \"jsverify\": \"^0.8.3\",\n    \"oletus\": \"^4.0.0\",\n    \"ramda\": \"^0.29.1\",\n    \"remark-cli\": \"^12.0.0\",\n    \"remark-validate-links\": \"^13.0.0\",\n    \"rimraf\": \"^5.0.0\",\n    \"rollup\": \"^4.5.2\",\n    \"sanctuary-benchmark\": \"^1.0.0\",\n    \"sanctuary-either\": \"^2.0.0\",\n    \"sanctuary-type-classes\": \"^13.0.0\",\n    \"tsd\": \"^0.30.0\",\n    \"typescript\": \"^5.0.4\",\n    \"xyz\": \"^4.0.0\"\n  },\n  \"tsd\": {\n    \"directory\": \"test/types\"\n  }\n}\n"
  },
  {
    "path": "rollup.config.dist.js",
    "content": "/* global process Set */\n\nimport {readFileSync} from 'fs';\nimport node from '@rollup/plugin-node-resolve';\nimport commonjs from '@rollup/plugin-commonjs';\n\nvar pkg = JSON.parse(readFileSync('package.json', 'utf8'));\n\nvar dependencies = pkg => {\n  var deps = Object.keys(pkg.dependencies || {}).concat(Object.keys(pkg.peerDependencies || {}));\n  return Array.from(new Set(deps.concat(deps.flatMap(dependency => (\n    dependencies(JSON.parse(readFileSync(`node_modules/${dependency}/package.json`, 'utf8')))\n  )))));\n};\n\nvar banner = `/**\n * Fluture bundled; version ${process.env.VERSION || `${pkg.version} (dirty)`}\n */\n`;\n\nvar footer = `/** Fluture license\n\n${readFileSync('./LICENSE')}*/\n\n${dependencies(pkg).map(dependency => `/** ${dependency} license\n\n${readFileSync(`./node_modules/${dependency}/LICENSE`)}*/`).join('\\n\\n')}`;\n\nvar typeref = `/// <reference types=\"https://cdn.jsdelivr.net/gh/fluture-js/Fluture@${\n  process.env.VERSION || pkg.version\n}/index.d.ts\" />`;\n\nexport default [{\n  input: 'index.cjs.js',\n  plugins: [node(), commonjs({include: 'node_modules/**'})],\n  output: {\n    banner: banner,\n    footer: footer,\n    format: 'iife',\n    name: 'Fluture',\n    file: 'dist/bundle.js',\n  },\n}, {\n  input: 'index.js',\n  plugins: [node(), commonjs({include: 'node_modules/**'})],\n  output: {\n    banner: `${banner}\\n${typeref}\\n`,\n    footer: footer,\n    format: 'es',\n    file: 'dist/module.js',\n  },\n}];\n"
  },
  {
    "path": "rollup.config.js",
    "content": "var dependencies = {\n  'sanctuary-show': 'sanctuaryShow',\n  'sanctuary-type-identifiers': 'sanctuaryTypeIdentifiers',\n};\n\nexport default {\n  input: 'index.cjs.js',\n  external: Object.keys(dependencies),\n  output: {\n    format: 'umd',\n    file: 'index.cjs',\n    name: 'Fluture',\n    globals: dependencies,\n  },\n};\n"
  },
  {
    "path": "scripts/bench.js",
    "content": "const suite = process.argv[2];\nconst options = process.argv[3] ? JSON.parse(process.argv[3]) : {};\n\nimport(`../bench/${suite}.js`).then(module => (\n  module.default(options)\n), e => {\n  console.error(e.stack);\n});\n"
  },
  {
    "path": "scripts/distribute",
    "content": "#!/usr/bin/env bash\nset -eufo pipefail\n\necho \"Publishing as $(npm whoami).\"\n\nif ! npm outdated --long; then\n  read -rp \"Continue? [y/N] \" choice\n  if [[ \"${choice-n}\" != 'y' ]]; then\n    echo 'Package distribution aborted.'\n    exit 2\n  fi\nfi\n\nnpm run build\nnpm run build:dist\nsed --in-place \"s/Fluture@$PREVIOUS_VERSION/Fluture@$VERSION/\" README.md\ngit add dist README.md\n"
  },
  {
    "path": "scripts/test-esm",
    "content": "#!/usr/bin/env bash\nset -eufo pipefail\n\nversion=$(node --print 'process.versions.node.split(\".\")[0]')\n\nif [[ \"$version\" -lt 12 ]]; then\n  echo 'Skipping esm test on Node versions below 12'\nelif node --experimental-modules --no-warnings index.js; then\n  echo 'No problems with the EcmaScript module'\nelse\n  echo 'Problem encountered loading the EcmaScript module'\n  exit 1\nfi\n"
  },
  {
    "path": "scripts/test-mem",
    "content": "#!/usr/bin/env node\n\n/* global process setImmediate */\n\nimport {Future, fork, race, chain, resolve as sync} from '../index.js';\nimport {log} from 'util';\n\nvar start = Date.now();\nvar batch = 0;\nvar stamp = Date.now();\n\nfunction report(){\n  var memMB = process.memoryUsage().rss / 1048576;\n  var now = Date.now();\n  var passed = now - stamp;\n  batch = batch + 1;\n  if(passed >= 5000){\n    log(\n      '-BATCH:', batch,\n      '-OPS:', Math.round(batch / ((now - start) / passed) / (passed / 1000)),\n      '-MEM:', memMB, 'MB'\n    );\n    stamp = now;\n  }\n}\n\nfunction noop(){}\n\nfunction async(x){\n  return Future(function(l, r){ setImmediate(r, x); return noop });\n}\n\nvar cases = Object.create(null);\n\n//Should infinitely run until finally running out of memory.\ncases.syncHeadRecursion = function recur(){\n  report();\n  return race(sync('r'))(chain(recur)(sync('l')));\n};\n\n//Should immediately exit with \"l\".\ncases.syncDeepRecursion = function recur(){\n  report();\n  return race(chain(recur)(sync('r')))(sync('l'));\n};\n\n//Should infinitely run without any problems.\ncases.syncTailRecursion = function recur(){\n  report();\n  return chain(recur)(race(sync('r'))(sync('l')));\n};\n\n//Should immediately exit with \"r\".\ncases.asyncHeadRecursion = function recur(){\n  report();\n  return race(async('r'))(chain(recur)(async('l')));\n};\n\n//Should immediately exit with \"l\".\ncases.asyncDeepRecursion = function recur(){\n  report();\n  return race(chain(recur)(async('r')))(async('l'));\n};\n\n//Should infinitely run without any problems.\ncases.asyncTailRecursion = function recur(){\n  report();\n  return chain(recur)(race(async('r'))(async('l')));\n};\n\n//Expected to run out of memory.\ncases.debugModeSyncTailRecursion = function(){\n  Future.debugMode(true);\n  return cases.syncTailRecursion();\n};\n\n//Expected to run out of memory.\ncases.debugModeAsyncTailRecursion = function(){\n  Future.debugMode(true);\n  return cases.asyncTailRecursion();\n};\n\nvar f = cases[process.argv[2]];\n\nif(typeof f !== 'function'){\n  console.log('Usage:\\n\\n  test-mem <case>\\n\\nPossible cases:\\n');\n  Object.keys(cases).forEach(function(k){console.log(`  ${k}`)});\n  process.exit(0);\n}\n\nlog('PID', process.pid);\n\nvar cancel = fork\n  (function(e){console.error(e.stack); process.exit(1)})\n  (function(v){log('resolved', v)})\n  (f());\n\nprocess.once('SIGINT', () => {\n  log('SIGINT caught. Cancelling...');\n  cancel();\n});\n"
  },
  {
    "path": "src/after.js",
    "content": "import {\n  any,\n  application,\n  application1,\n  createInterpreter,\n  never,\n  positiveInteger,\n} from './future.js';\n\nexport var After = createInterpreter(2, 'after', function After$interpret(rec, rej, res){\n  var id = setTimeout(res, this.$1, this.$2);\n  return function After$cancel(){ clearTimeout(id) };\n});\n\nAfter.prototype.extractRight = function After$extractRight(){\n  return [this.$2];\n};\n\nfunction alwaysNever(_){\n  return never;\n}\n\nexport function after(time){\n  var context1 = application1(after, positiveInteger, arguments);\n  return time === Infinity ? alwaysNever : (function after(value){\n    var context2 = application(2, after, any, arguments, context1);\n    return new After(context2, time, value);\n  });\n}\n"
  },
  {
    "path": "src/alt.js",
    "content": "import {FL} from './internal/const.js';\nimport {invalidArgumentOf} from './internal/error.js';\nimport {isAlt} from './internal/predicates.js';\nimport {\n  AltTransformation,\n  application,\n  application1,\n  future,\n  isFuture,\n} from './future.js';\n\nexport var alternative = {pred: isAlt, error: invalidArgumentOf('have Alt implemented')};\n\nexport function alt(left){\n  if(isFuture(left)){\n    var context1 = application1(alt, future, arguments);\n    return function alt(right){\n      var context2 = application(2, alt, future, arguments, context1);\n      return right._transform(new AltTransformation(context2, left));\n    };\n  }\n\n  var context = application1(alt, alternative, arguments);\n  return function alt(right){\n    application(2, alt, alternative, arguments, context);\n    return left[FL.alt](right);\n  };\n}\n"
  },
  {
    "path": "src/and.js",
    "content": "import {createTransformation, application1, application, future} from './future.js';\n\nexport var AndTransformation = createTransformation(1, 'and', {\n  resolved: function AndTransformation$resolved(){ return this.$1 },\n});\n\nexport function and(left){\n  var context1 = application1(and, future, arguments);\n  return function and(right){\n    var context2 = application(2, and, future, arguments, context1);\n    return right._transform(new AndTransformation(context2, left));\n  };\n}\n"
  },
  {
    "path": "src/ap.js",
    "content": "import {FL} from './internal/const.js';\nimport {invalidArgumentOf} from './internal/error.js';\nimport {isApply} from './internal/predicates.js';\nimport {isFuture, ApTransformation, application1, application, future} from './future.js';\n\nexport var apply = {pred: isApply, error: invalidArgumentOf('have Apply implemented')};\n\nexport function ap(mx){\n  if(isFuture(mx)){\n    var context1 = application1(ap, future, arguments);\n    return function ap(mf){\n      var context2 = application(2, ap, future, arguments, context1);\n      return mf._transform(new ApTransformation(context2, mx));\n    };\n  }\n\n  var context = application1(ap, apply, arguments);\n  return function ap(mf){\n    application(2, ap, apply, arguments, context);\n    return mx[FL.ap](mf);\n  };\n}\n"
  },
  {
    "path": "src/attempt-p.js",
    "content": "import {encaseP} from './encase-p.js';\n\nexport function attemptP(_){\n  return encaseP.apply(this, arguments)(undefined);\n}\n"
  },
  {
    "path": "src/attempt.js",
    "content": "import {encase} from './encase.js';\n\nexport function attempt(_){\n  return encase.apply(this, arguments)(undefined);\n}\n"
  },
  {
    "path": "src/bichain.js",
    "content": "import {createTransformation, future, application1, application, func} from './future.js';\nimport {call} from './internal/utils.js';\n\nexport var BichainTransformation = createTransformation(2, 'bichain', {\n  rejected: function BichainTransformation$rejected(x){ return call(this.$1, x) },\n  resolved: function BichainTransformation$resolved(x){ return call(this.$2, x) },\n});\n\nexport function bichain(f){\n  var context1 = application1(bichain, func, arguments);\n  return function bichain(g){\n    var context2 = application(2, bichain, func, arguments, context1);\n    return function bichain(m){\n      var context3 = application(3, bichain, future, arguments, context2);\n      return m._transform(new BichainTransformation(context3, f, g));\n    };\n  };\n}\n"
  },
  {
    "path": "src/bimap.js",
    "content": "import {FL} from './internal/const.js';\nimport {invalidArgumentOf} from './internal/error.js';\nimport {isBifunctor} from './internal/predicates.js';\nimport {isFuture, BimapTransformation, application1, application, func} from './future.js';\n\nexport var bifunctor = {pred: isBifunctor, error: invalidArgumentOf('have Bifunctor implemented')};\n\nexport function bimap(f){\n  var context1 = application1(bimap, func, arguments);\n  return function bimap(g){\n    var context2 = application(2, bimap, func, arguments, context1);\n    return function bimap(m){\n      var context3 = application(3, bimap, bifunctor, arguments, context2);\n      return isFuture(m) ?\n             m._transform(new BimapTransformation(context3, f, g)) :\n             m[FL.bimap](f, g);\n    };\n  };\n}\n"
  },
  {
    "path": "src/both.js",
    "content": "import {createParallelTransformation, earlyCrash, earlyReject} from './internal/parallel.js';\nimport {noop} from './internal/utils.js';\nimport {createTransformation, Resolve, application1, application, future} from './future.js';\n\nexport var PairTransformation = createTransformation(1, 'pair', {\n  resolved: function PairTransformation$resolved(x){\n    return new Resolve(this.context, [x, this.$1]);\n  },\n});\n\nexport var BothTransformation =\ncreateParallelTransformation('both', earlyCrash, earlyReject, noop, {\n  resolved: function BothTransformation$resolved(x){\n    return this.$1._transform(new PairTransformation(this.context, x));\n  },\n});\n\nexport function both(left){\n  var context1 = application1(both, future, arguments);\n  return function both(right){\n    var context2 = application(2, both, future, arguments, context1);\n    return right._transform(new BothTransformation(context2, left));\n  };\n}\n"
  },
  {
    "path": "src/cache.js",
    "content": "import {noop} from './internal/utils.js';\nimport {createInterpreter, application1, future} from './future.js';\n\nexport var Cold = 0;\nexport var Pending = 1;\nexport var Crashed = 2;\nexport var Rejected = 3;\nexport var Resolved = 4;\n\nexport function Queued(rec, rej, res){\n  this[Crashed] = rec;\n  this[Rejected] = rej;\n  this[Resolved] = res;\n}\n\nexport var Cache = createInterpreter(1, 'cache', function Cache$interpret(rec, rej, res){\n  var cancel = noop;\n\n  switch(this._state){\n    /* c8 ignore next 4 */\n    case Pending: cancel = this._addToQueue(rec, rej, res); break;\n    case Crashed: rec(this._value); break;\n    case Rejected: rej(this._value); break;\n    case Resolved: res(this._value); break;\n    default:\n      this._queue = [];\n      cancel = this._addToQueue(rec, rej, res);\n      this.run();\n  }\n\n  return cancel;\n});\n\nCache.prototype._cancel = noop;\nCache.prototype._queue = null;\nCache.prototype._queued = 0;\nCache.prototype._value = undefined;\nCache.prototype._state = Cold;\n\nCache.prototype.extractLeft = function Cache$extractLeft(){\n  return this._state === Rejected ? [this._value] : [];\n};\n\nCache.prototype.extractRight = function Cache$extractRight(){\n  return this._state === Resolved ? [this._value] : [];\n};\n\nCache.prototype._addToQueue = function Cache$addToQueue(rec, rej, res){\n  var _this = this;\n  if(_this._state > Pending) return noop;\n  var i = _this._queue.push(new Queued(rec, rej, res)) - 1;\n  _this._queued = _this._queued + 1;\n\n  return function Cache$removeFromQueue(){\n    if(_this._state > Pending) return;\n    _this._queue[i] = undefined;\n    _this._queued = _this._queued - 1;\n    if(_this._queued === 0) _this.reset();\n  };\n};\n\nCache.prototype._drainQueue = function Cache$drainQueue(){\n  if(this._state <= Pending) return;\n  if(this._queued === 0) return;\n  var queue = this._queue;\n  var length = queue.length;\n  var state = this._state;\n  var value = this._value;\n\n  for(var i = 0; i < length; i++){\n    queue[i] && queue[i][state](value);\n    queue[i] = undefined;\n  }\n\n  this._queue = undefined;\n  this._queued = 0;\n};\n\nCache.prototype.crash = function Cache$crash(error){\n  if(this._state > Pending) return;\n  this._value = error;\n  this._state = Crashed;\n  this._drainQueue();\n};\n\nCache.prototype.reject = function Cache$reject(reason){\n  if(this._state > Pending) return;\n  this._value = reason;\n  this._state = Rejected;\n  this._drainQueue();\n};\n\nCache.prototype.resolve = function Cache$resolve(value){\n  if(this._state > Pending) return;\n  this._value = value;\n  this._state = Resolved;\n  this._drainQueue();\n};\n\nCache.prototype.run = function Cache$run(){\n  var _this = this;\n  if(_this._state > Cold) return;\n  _this._state = Pending;\n  _this._cancel = _this.$1._interpret(\n    function Cache$fork$rec(x){ _this.crash(x) },\n    function Cache$fork$rej(x){ _this.reject(x) },\n    function Cache$fork$res(x){ _this.resolve(x) }\n  );\n};\n\nCache.prototype.reset = function Cache$reset(){\n  if(this._state === Cold) return;\n  if(this._state === Pending) this._cancel();\n  this._cancel = noop;\n  this._queue = [];\n  this._queued = 0;\n  this._value = undefined;\n  this._state = Cold;\n};\n\nexport function cache(m){\n  return new Cache(application1(cache, future, arguments), m);\n}\n"
  },
  {
    "path": "src/chain-rej.js",
    "content": "import {call} from './internal/utils.js';\nimport {createTransformation, application1, application, future, func} from './future.js';\n\nexport var ChainRejTransformation = createTransformation(1, 'chainRej', {\n  rejected: function ChainRejTransformation$rejected(x){ return call(this.$1, x) },\n});\n\nexport function chainRej(f){\n  var context1 = application1(chainRej, func, arguments);\n  return function chainRej(m){\n    var context2 = application(2, chainRej, future, arguments, context1);\n    return m._transform(new ChainRejTransformation(context2, f));\n  };\n}\n"
  },
  {
    "path": "src/chain.js",
    "content": "import {FL} from './internal/const.js';\nimport {invalidArgumentOf} from './internal/error.js';\nimport {isChain} from './internal/predicates.js';\nimport {isFuture, application1, application, func, ChainTransformation} from './future.js';\n\nexport var monad = {pred: isChain, error: invalidArgumentOf('have Chain implemented')};\n\nexport function chain(f){\n  var context1 = application1(chain, func, arguments);\n  return function chain(m){\n    var context2 = application(2, chain, monad, arguments, context1);\n    return isFuture(m) ?\n           m._transform(new ChainTransformation(context2, f)) :\n           m[FL.chain](f);\n  };\n}\n"
  },
  {
    "path": "src/coalesce.js",
    "content": "import {call} from './internal/utils.js';\nimport {createTransformation, Resolve, application1, application, func, future} from './future.js';\n\nexport var CoalesceTransformation = createTransformation(2, 'coalesce', {\n  rejected: function CoalesceTransformation$rejected(x){\n    return new Resolve(this.context, call(this.$1, x));\n  },\n  resolved: function CoalesceTransformation$resolved(x){\n    return new Resolve(this.context, call(this.$2, x));\n  },\n});\n\nexport function coalesce(f){\n  var context1 = application1(coalesce, func, arguments);\n  return function coalesce(g){\n    var context2 = application(2, coalesce, func, arguments, context1);\n    return function coalesce(m){\n      var context3 = application(3, coalesce, future, arguments, context2);\n      return m._transform(new CoalesceTransformation(context3, f, g));\n    };\n  };\n}\n"
  },
  {
    "path": "src/done.js",
    "content": "import {application1, application, func, future} from './future.js';\nimport {raise} from './internal/utils.js';\n\nexport function done(callback){\n  var context1 = application1(done, func, arguments);\n  function done$res(x){\n    callback(null, x);\n  }\n  return function done(m){\n    application(2, done, future, arguments, context1);\n    return m._interpret(raise, callback, done$res);\n  };\n}\n"
  },
  {
    "path": "src/encase-p.js",
    "content": "import {wrapException, typeError} from './internal/error.js';\nimport {isThenable} from './internal/predicates.js';\nimport {noop, show} from './internal/utils.js';\nimport {createInterpreter, application1, application, func, any} from './future.js';\n\nfunction invalidPromise(p, f, a){\n  return typeError(\n    'encaseP() expects the function it\\'s given to return a Promise/Thenable'\n    + '\\n  Actual: ' + show(p) + '\\n  From calling: ' + show(f)\n    + '\\n  With: ' + show(a)\n  );\n}\n\nexport var EncaseP = createInterpreter(2, 'encaseP', function EncaseP$interpret(rec, rej, res){\n  var open = true, fn = this.$1, arg = this.$2, p;\n  try{\n    p = fn(arg);\n  }catch(e){\n    rec(wrapException(e, this));\n    return noop;\n  }\n  if(!isThenable(p)){\n    rec(wrapException(invalidPromise(p, fn, arg), this));\n    return noop;\n  }\n  p.then(function EncaseP$res(x){\n    if(open){\n      open = false;\n      res(x);\n    }\n  }, function EncaseP$rej(x){\n    if(open){\n      open = false;\n      rej(x);\n    }\n  });\n  return function EncaseP$cancel(){ open = false };\n});\n\nexport function encaseP(f){\n  var context1 = application1(encaseP, func, arguments);\n  return function encaseP(x){\n    var context2 = application(2, encaseP, any, arguments, context1);\n    return new EncaseP(context2, f, x);\n  };\n}\n"
  },
  {
    "path": "src/encase.js",
    "content": "import {noop} from './internal/utils.js';\nimport {createInterpreter, application1, application, func, any} from './future.js';\n\nexport var Encase = createInterpreter(2, 'encase', function Encase$interpret(rec, rej, res){\n  var fn = this.$1, r;\n  try{ r = fn(this.$2) }catch(e){ rej(e); return noop }\n  res(r);\n  return noop;\n});\n\nexport function encase(f){\n  var context1 = application1(encase, func, arguments);\n  return function encase(x){\n    var context2 = application(2, encase, any, arguments, context1);\n    return new Encase(context2, f, x);\n  };\n}\n"
  },
  {
    "path": "src/extract-left.js",
    "content": "import {application1, future} from './future.js';\n\nexport function extractLeft(m){\n  application1(extractLeft, future, arguments);\n  return m.extractLeft();\n}\n"
  },
  {
    "path": "src/extract-right.js",
    "content": "import {application1, future} from './future.js';\n\nexport function extractRight(m){\n  application1(extractRight, future, arguments);\n  return m.extractRight();\n}\n"
  },
  {
    "path": "src/fork-catch.js",
    "content": "import {application, application1, func, future} from './future.js';\n\nexport function forkCatch(f){\n  var context1 = application1(forkCatch, func, arguments);\n  return function forkCatch(g){\n    var context2 = application(2, forkCatch, func, arguments, context1);\n    return function forkCatch(h){\n      var context3 = application(3, forkCatch, func, arguments, context2);\n      return function forkCatch(m){\n        application(4, forkCatch, future, arguments, context3);\n        return m._interpret(f, g, h);\n      };\n    };\n  };\n}\n"
  },
  {
    "path": "src/fork.js",
    "content": "import {raise} from './internal/utils.js';\nimport {application, application1, func, future} from './future.js';\n\nexport function fork(f){\n  var context1 = application1(fork, func, arguments);\n  return function fork(g){\n    var context2 = application(2, fork, func, arguments, context1);\n    return function fork(m){\n      application(3, fork, future, arguments, context2);\n      return m._interpret(raise, f, g);\n    };\n  };\n}\n"
  },
  {
    "path": "src/future.js",
    "content": "/* eslint no-cond-assign:0, no-constant-condition:0 */\nimport type from 'sanctuary-type-identifiers';\n\nimport {FL, $$type} from './internal/const.js';\nimport {captureContext, captureApplicationContext, captureStackTrace} from './internal/debug.js';\nimport {\n  invalidArgument,\n  invalidArgumentOf,\n  invalidArity,\n  invalidFuture,\n  invalidFutureArgument,\n  typeError,\n  withExtraContext,\n  wrapException,\n} from './internal/error.js';\nimport {Next, Done} from './internal/iteration.js';\nimport {nil, cons, isNil, reverse, toArray} from './internal/list.js';\nimport {isFunction, isUnsigned} from './internal/predicates.js';\nimport {show, noop, call, moop} from './internal/utils.js';\n\nfunction alwaysTrue(){\n  return true;\n}\n\nfunction getArgs(it){\n  var args = new Array(it.arity);\n  for(var i = 1; i <= it.arity; i++){\n    args[i - 1] = it['$' + String(i)];\n  }\n  return args;\n}\n\nfunction showArg(arg){\n  return ' (' + show(arg) + ')';\n}\n\nexport var any = {pred: alwaysTrue, error: invalidArgumentOf('be anything')};\nexport var func = {pred: isFunction, error: invalidArgumentOf('be a Function')};\nexport var future = {pred: isFuture, error: invalidFutureArgument};\nexport var positiveInteger = {pred: isUnsigned, error: invalidArgumentOf('be a positive Integer')};\n\nexport function application(n, f, type, args, prev){\n  if(args.length < 2 && type.pred(args[0])) return captureApplicationContext(prev, n, f);\n  var e = args.length > 1 ? invalidArity(f, args) : type.error(f.name, n - 1, args[0]);\n  captureStackTrace(e, f);\n  throw withExtraContext(e, prev);\n}\n\nexport function application1(f, type, args){\n  return application(1, f, type, args, nil);\n}\n\nexport function Future(computation){\n  var context = application1(Future, func, arguments);\n  return new Computation(context, computation);\n}\n\nexport function isFuture(x){\n  return x instanceof Future || type(x) === $$type;\n}\n\n// Compliance with sanctuary-type-identifiers versions 1 and 2.\n// To prevent sanctuary-type-identifiers version 3 from identifying 'Future'\n// as being of the type denoted by $$type, we ensure that\n// Future.constructor.prototype is equal to Future.\nFuture['@@type'] = $$type;\nFuture.constructor = {prototype: Future};\n\nFuture[FL.of] = resolve;\nFuture[FL.chainRec] = chainRec;\n\nFuture.prototype['@@type'] = $$type;\n\nFuture.prototype['@@show'] = function Future$show(){\n  return this.toString();\n};\n\nFuture.prototype.pipe = function Future$pipe(f){\n  if(!isFunction(f)) throw invalidArgument('Future#pipe', 0, 'be a Function', f);\n  return f(this);\n};\n\nFuture.prototype[FL.ap] = function Future$FL$ap(other){\n  var context = captureContext(nil, 'a Fantasy Land dispatch to ap', Future$FL$ap);\n  return other._transform(new ApTransformation(context, this));\n};\n\nFuture.prototype[FL.map] = function Future$FL$map(mapper){\n  var context = captureContext(nil, 'a Fantasy Land dispatch to map', Future$FL$map);\n  return this._transform(new MapTransformation(context, mapper));\n};\n\nFuture.prototype[FL.bimap] = function Future$FL$bimap(lmapper, rmapper){\n  var context = captureContext(nil, 'a Fantasy Land dispatch to bimap', Future$FL$bimap);\n  return this._transform(new BimapTransformation(context, lmapper, rmapper));\n};\n\nFuture.prototype[FL.chain] = function Future$FL$chain(mapper){\n  var context = captureContext(nil, 'a Fantasy Land dispatch to chain', Future$FL$chain);\n  return this._transform(new ChainTransformation(context, mapper));\n};\n\nFuture.prototype[FL.alt] = function Future$FL$alt(other){\n  var context = captureContext(nil, 'a Fantasy Land dispatch to alt', Future$FL$alt);\n  return this._transform(new AltTransformation(context, other));\n};\n\nFuture.prototype.extractLeft = function Future$extractLeft(){\n  return [];\n};\n\nFuture.prototype.extractRight = function Future$extractRight(){\n  return [];\n};\n\nFuture.prototype._transform = function Future$transform(transformation){\n  return new Transformer(transformation.context, this, cons(transformation, nil));\n};\n\nFuture.prototype.isTransformer = false;\nFuture.prototype.context = nil;\nFuture.prototype.arity = 0;\nFuture.prototype.name = 'future';\n\nFuture.prototype.toString = function Future$toString(){\n  return this.name + getArgs(this).map(showArg).join('');\n};\n\nFuture.prototype.toJSON = function Future$toJSON(){\n  return {$: $$type, kind: 'interpreter', type: this.name, args: getArgs(this)};\n};\n\nexport function createInterpreter(arity, name, interpret){\n  var Interpreter = function(context, $1, $2, $3){\n    this.context = context;\n    this.$1 = $1;\n    this.$2 = $2;\n    this.$3 = $3;\n  };\n\n  Interpreter.prototype = Object.create(Future.prototype);\n  Interpreter.prototype.arity = arity;\n  Interpreter.prototype.name = name;\n  Interpreter.prototype._interpret = interpret;\n\n  return Interpreter;\n}\n\nexport var Computation =\ncreateInterpreter(1, 'Future', function Computation$interpret(rec, rej, res){\n  var computation = this.$1, open = false, cancel = noop, cont = function(){ open = true };\n  try{\n    cancel = computation(function Computation$rej(x){\n      cont = function Computation$rej$cont(){\n        open = false;\n        rej(x);\n      };\n      if(open){\n        cont();\n      }\n    }, function Computation$res(x){\n      cont = function Computation$res$cont(){\n        open = false;\n        res(x);\n      };\n      if(open){\n        cont();\n      }\n    });\n  }catch(e){\n    rec(wrapException(e, this));\n    return noop;\n  }\n  if(!(isFunction(cancel) && cancel.length === 0)){\n    rec(wrapException(typeError(\n      'The computation was expected to return a nullary cancellation function\\n' +\n      '  Actual: ' + show(cancel)\n    ), this));\n    return noop;\n  }\n  cont();\n  return function Computation$cancel(){\n    if(open){\n      open = false;\n      cancel && cancel();\n    }\n  };\n});\n\nexport var Never = createInterpreter(0, 'never', function Never$interpret(){\n  return noop;\n});\n\nNever.prototype._isNever = true;\n\nexport var never = new Never(nil);\n\nexport function isNever(x){\n  return isFuture(x) && x._isNever === true;\n}\n\nexport var Crash = createInterpreter(1, 'crash', function Crash$interpret(rec){\n  rec(this.$1);\n  return noop;\n});\n\nexport function crash(x){\n  return new Crash(application1(crash, any, arguments), x);\n}\n\nexport var Reject = createInterpreter(1, 'reject', function Reject$interpret(rec, rej){\n  rej(this.$1);\n  return noop;\n});\n\nReject.prototype.extractLeft = function Reject$extractLeft(){\n  return [this.$1];\n};\n\nexport function reject(x){\n  return new Reject(application1(reject, any, arguments), x);\n}\n\nexport var Resolve = createInterpreter(1, 'resolve', function Resolve$interpret(rec, rej, res){\n  res(this.$1);\n  return noop;\n});\n\nResolve.prototype.extractRight = function Resolve$extractRight(){\n  return [this.$1];\n};\n\nexport function resolve(x){\n  return new Resolve(application1(resolve, any, arguments), x);\n}\n\n// Note: This function is not curried because it's only used to satisfy the\n//      Fantasy Land ChainRec specification.\nexport function chainRec(step, init){\n  return resolve(Next(init))._transform(new ChainTransformation(nil, function chainRec$recur(o){\n    return o.done ?\n           resolve(o.value) :\n           step(Next, Done, o.value)._transform(new ChainTransformation(nil, chainRec$recur));\n  }));\n}\n\nexport var Transformer =\ncreateInterpreter(2, 'transform', function Transformer$interpret(rec, rej, res){\n  // These are the cold, and hot, transformation stacks. The cold actions are those that\n  // have yet to run parallel computations, and hot are those that have.\n  var cold = nil, hot = nil;\n\n  // These combined variables define our current state.\n  // future         = the future we are currently forking\n  // transformation = the transformation to be informed when the future settles\n  // cancel         = the cancel function of the current future\n  // settled        = a boolean indicating whether a new tick should start\n  // async          = a boolean indicating whether we are awaiting a result asynchronously\n  var future, transformation, cancel = noop, settled, async = true, it;\n\n  // Takes a transformation from the top of the hot stack and returns it.\n  function nextHot(){\n    var x = hot.head;\n    hot = hot.tail;\n    return x;\n  }\n\n  // Takes a transformation from the top of the cold stack and returns it.\n  function nextCold(){\n    var x = cold.head;\n    cold = cold.tail;\n    return x;\n  }\n\n  // This function is called with a future to use in the next tick.\n  // Here we \"flatten\" the actions of another Sequence into our own actions,\n  // this is the magic that allows for infinitely stack safe recursion because\n  // actions like ChainAction will return a new Sequence.\n  // If we settled asynchronously, we call drain() directly to run the next tick.\n  function settle(m){\n    settled = true;\n    future = m;\n    if(future.isTransformer){\n      var tail = future.$2;\n      while(!isNil(tail)){\n        cold = cons(tail.head, cold);\n        tail = tail.tail;\n      }\n      future = future.$1;\n    }\n    if(async) drain();\n  }\n\n  // This function serves as a rejection handler for our current future.\n  // It will tell the current transformation that the future rejected, and it will\n  // settle the current tick with the transformation's answer to that.\n  function rejected(x){\n    settle(transformation.rejected(x));\n  }\n\n  // This function serves as a resolution handler for our current future.\n  // It will tell the current transformation that the future resolved, and it will\n  // settle the current tick with the transformation's answer to that.\n  function resolved(x){\n    settle(transformation.resolved(x));\n  }\n\n  // This function is passed into actions when they are \"warmed up\".\n  // If the transformation decides that it has its result, without the need to await\n  // anything else, then it can call this function to force \"early termination\".\n  // When early termination occurs, all actions which were stacked prior to the\n  // terminator will be skipped. If they were already hot, they will also be\n  // sent a cancel signal so they can cancel their own concurrent computations,\n  // as their results are no longer needed.\n  function early(m, terminator){\n    cancel();\n    cold = nil;\n    if(async && transformation !== terminator){\n      transformation.cancel();\n      while((it = nextHot()) && it !== terminator) it.cancel();\n    }\n    settle(m);\n  }\n\n  // This will cancel the current Future, the current transformation, and all stacked hot actions.\n  function Sequence$cancel(){\n    cancel();\n    transformation && transformation.cancel();\n    while(it = nextHot()) it.cancel();\n  }\n\n  // This function is called when an exception is caught.\n  function exception(e){\n    Sequence$cancel();\n    settled = true;\n    cold = hot = nil;\n    var error = wrapException(e, future);\n    future = never;\n    rec(error);\n  }\n\n  // This function serves to kickstart concurrent computations.\n  // Takes all actions from the cold stack in reverse order, and calls run() on\n  // each of them, passing them the \"early\" function. If any of them settles (by\n  // calling early()), we abort. After warming up all actions in the cold queue,\n  // we warm up the current transformation as well.\n  function warmupActions(){\n    cold = reverse(cold);\n    while(cold !== nil){\n      it = cold.head.run(early);\n      if(settled) return;\n      hot = cons(it, hot);\n      cold = cold.tail;\n    }\n    transformation = transformation.run(early);\n  }\n\n  // This function represents our main execution loop. By \"tick\", we've been\n  // referring to the execution of one iteration in the while-loop below.\n  function drain(){\n    async = false;\n    while(true){\n      settled = false;\n      if(transformation = nextCold()){\n        cancel = future._interpret(exception, rejected, resolved);\n        if(!settled) warmupActions();\n      }else if(transformation = nextHot()){\n        cancel = future._interpret(exception, rejected, resolved);\n      }else break;\n      if(settled) continue;\n      async = true;\n      return;\n    }\n    cancel = future._interpret(exception, rej, res);\n  }\n\n  // Start the execution loop.\n  settle(this);\n\n  // Return the cancellation function.\n  return Sequence$cancel;\n});\n\nTransformer.prototype.isTransformer = true;\n\nTransformer.prototype._transform = function Transformer$_transform(transformation){\n  return new Transformer(transformation.context, this.$1, cons(transformation, this.$2));\n};\n\nTransformer.prototype.toString = function Transformer$toString(){\n  return toArray(reverse(this.$2)).reduce(function(str, action){\n    return action.name + getArgs(action).map(showArg).join('') + ' (' + str + ')';\n  }, this.$1.toString());\n};\n\nfunction BaseTransformation$rejected(x){\n  this.cancel();\n  return new Reject(this.context, x);\n}\n\nfunction BaseTransformation$resolved(x){\n  this.cancel();\n  return new Resolve(this.context, x);\n}\n\nfunction BaseTransformation$toJSON(){\n  return {$: $$type, kind: 'transformation', type: this.name, args: getArgs(this)};\n}\n\nexport var BaseTransformation = {\n  rejected: BaseTransformation$rejected,\n  resolved: BaseTransformation$resolved,\n  run: moop,\n  cancel: noop,\n  context: nil,\n  arity: 0,\n  name: 'transform',\n  toJSON: BaseTransformation$toJSON,\n};\n\nfunction wrapHandler(handler){\n  return function transformationHandler(x){\n    var m;\n    try{\n      m = handler.call(this, x);\n    }catch(e){\n      return new Crash(this.context, e);\n    }\n    if(isFuture(m)){\n      return m;\n    }\n    return new Crash(this.context, invalidFuture(\n      this.name + ' expects the return value from the function it\\'s given', m,\n      '\\n  When called with: ' + show(x)\n    ));\n  };\n}\n\nexport function createTransformation(arity, name, prototype){\n  var Transformation = function(context, $1, $2){\n    this.context = context;\n    this.$1 = $1;\n    this.$2 = $2;\n  };\n\n  Transformation.prototype = Object.create(BaseTransformation);\n  Transformation.prototype.arity = arity;\n  Transformation.prototype.name = name;\n\n  if(typeof prototype.rejected === 'function'){\n    Transformation.prototype.rejected = wrapHandler(prototype.rejected);\n  }\n\n  if(typeof prototype.resolved === 'function'){\n    Transformation.prototype.resolved = wrapHandler(prototype.resolved);\n  }\n\n  if(typeof prototype.run === 'function'){\n    Transformation.prototype.run = prototype.run;\n  }\n\n  return Transformation;\n}\n\nexport var ApTransformation = createTransformation(1, 'ap', {\n  resolved: function ApTransformation$resolved(f){\n    if(isFunction(f)) return this.$1._transform(new MapTransformation(this.context, f));\n    throw typeError(\n      'ap expects the second Future to resolve to a Function\\n' +\n      '  Actual: ' + show(f)\n    );\n  },\n});\n\nexport var AltTransformation = createTransformation(1, 'alt', {\n  rejected: function AltTransformation$rejected(){ return this.$1 },\n});\n\nexport var MapTransformation = createTransformation(1, 'map', {\n  resolved: function MapTransformation$resolved(x){\n    return new Resolve(this.context, call(this.$1, x));\n  },\n});\n\nexport var BimapTransformation = createTransformation(2, 'bimap', {\n  rejected: function BimapTransformation$rejected(x){\n    return new Reject(this.context, call(this.$1, x));\n  },\n  resolved: function BimapTransformation$resolved(x){\n    return new Resolve(this.context, call(this.$2, x));\n  },\n});\n\nexport var ChainTransformation = createTransformation(1, 'chain', {\n  resolved: function ChainTransformation$resolved(x){ return call(this.$1, x) },\n});\n"
  },
  {
    "path": "src/go.js",
    "content": "/* eslint consistent-return: 0 */\n\nimport {typeError, invalidFuture, invalidArgument, wrapException} from './internal/error.js';\nimport {isIteration} from './internal/iteration.js';\nimport {isIterator} from './internal/predicates.js';\nimport {Undetermined, Synchronous, Asynchronous} from './internal/timing.js';\nimport {show, noop} from './internal/utils.js';\nimport {createInterpreter, isFuture, application1, func} from './future.js';\n\nexport function invalidIteration(o){\n  return typeError(\n    'The iterator did not return a valid iteration from iterator.next()\\n' +\n    '  Actual: ' + show(o)\n  );\n}\n\nexport function invalidState(x){\n  return invalidFuture(\n    'go() expects the value produced by the iterator', x,\n    '\\n  Tip: If you\\'re using a generator, make sure you always yield a Future'\n  );\n}\n\nexport var Go = createInterpreter(1, 'go', function Go$interpret(rec, rej, res){\n  var _this = this, timing = Undetermined, cancel = noop, state, value, iterator;\n\n  function crash(e){\n    rec(wrapException(e, _this));\n  }\n\n  try{\n    iterator = _this.$1();\n  }catch(e){\n    crash(e);\n    return noop;\n  }\n\n  if(!isIterator(iterator)){\n    crash(invalidArgument('go', 0, 'return an iterator, maybe you forgot the \"*\"', iterator));\n    return noop;\n  }\n\n  function resolved(x){\n    value = x;\n    if(timing === Asynchronous) return drain();\n    timing = Synchronous;\n  }\n\n  function drain(){\n    // eslint-disable-next-line no-constant-condition\n    while(true){\n      try{\n        state = iterator.next(value);\n      }catch(e){\n        return crash(e);\n      }\n      if(!isIteration(state)) return crash(invalidIteration(state));\n      if(state.done) break;\n      if(!isFuture(state.value)) return crash(invalidState(state.value));\n      timing = Undetermined;\n      cancel = state.value._interpret(crash, rej, resolved);\n      if(timing === Undetermined) return (timing = Asynchronous);\n    }\n    res(state.value);\n  }\n\n  drain();\n\n  return function Go$cancel(){ cancel() };\n});\n\nexport function go(generator){\n  return new Go(application1(go, func, arguments), generator);\n}\n"
  },
  {
    "path": "src/hook.js",
    "content": "import {noop, show, raise} from './internal/utils.js';\nimport {invalidFuture, wrapException} from './internal/error.js';\nimport {createInterpreter, isFuture, application1, application, func, future} from './future.js';\n\nfunction invalidDisposal(m, f, x){\n  return invalidFuture(\n    'hook() expects the return value from the first function it\\'s given', m,\n    '\\n  From calling: ' + show(f) + '\\n  With: ' + show(x)\n  );\n}\n\nfunction invalidConsumption(m, f, x){\n  return invalidFuture(\n    'hook() expects the return value from the second function it\\'s given', m,\n    '\\n  From calling: ' + show(f) + '\\n  With: ' + show(x)\n  );\n}\n\nexport var Hook = createInterpreter(3, 'hook', function Hook$interpret(rec, rej, res){\n  var _this = this, _acquire = this.$1, _dispose = this.$2, _consume = this.$3;\n  var cancel, cancelConsume = noop, resource, value, cont = noop;\n\n  function Hook$done(){\n    cont(value);\n  }\n\n  function Hook$rec(x){\n    rec(wrapException(x, _this));\n  }\n\n  function Hook$dispose(){\n    var disposal;\n    try{\n      disposal = _dispose(resource);\n    }catch(e){\n      return Hook$rec(e);\n    }\n    if(!isFuture(disposal)){\n      return Hook$rec(invalidDisposal(disposal, _dispose, resource));\n    }\n    cancel = Hook$cancelDisposal;\n    disposal._interpret(Hook$rec, Hook$disposalRejected, Hook$done);\n  }\n\n  function Hook$cancelConsumption(){\n    cancelConsume();\n    Hook$dispose();\n    Hook$cancelDisposal();\n  }\n\n  function Hook$cancelDisposal(){\n    cont = noop;\n  }\n\n  function Hook$disposalRejected(x){\n    Hook$rec(new Error('The disposal Future rejected with ' + show(x)));\n  }\n\n  function Hook$consumptionException(x){\n    cont = Hook$rec;\n    value = x;\n    Hook$dispose();\n  }\n\n  function Hook$consumptionRejected(x){\n    cont = rej;\n    value = x;\n    Hook$dispose();\n  }\n\n  function Hook$consumptionResolved(x){\n    cont = res;\n    value = x;\n    Hook$dispose();\n  }\n\n  function Hook$consume(x){\n    resource = x;\n    var consumption;\n    try{\n      consumption = _consume(resource);\n    }catch(e){\n      return Hook$consumptionException(e);\n    }\n    if(!isFuture(consumption)){\n      return Hook$consumptionException(invalidConsumption(consumption, _consume, resource));\n    }\n    cancel = Hook$cancelConsumption;\n    cancelConsume = consumption._interpret(\n      Hook$consumptionException,\n      Hook$consumptionRejected,\n      Hook$consumptionResolved\n    );\n  }\n\n  var cancelAcquire = _acquire._interpret(Hook$rec, rej, Hook$consume);\n  cancel = cancel || cancelAcquire;\n\n  return function Hook$fork$cancel(){\n    rec = raise;\n    cancel();\n  };\n});\n\nexport function hook(acquire){\n  var context1 = application1(hook, future, arguments);\n  return function hook(dispose){\n    var context2 = application(2, hook, func, arguments, context1);\n    return function hook(consume){\n      var context3 = application(3, hook, func, arguments, context2);\n      return new Hook(context3, acquire, dispose, consume);\n    };\n  };\n}\n"
  },
  {
    "path": "src/internal/const.js",
    "content": "export var FL = {\n  alt: 'fantasy-land/alt',\n  ap: 'fantasy-land/ap',\n  bimap: 'fantasy-land/bimap',\n  chain: 'fantasy-land/chain',\n  chainRec: 'fantasy-land/chainRec',\n  map: 'fantasy-land/map',\n  of: 'fantasy-land/of',\n  zero: 'fantasy-land/zero',\n};\n\nexport var ordinal = ['first', 'second', 'third', 'fourth', 'fifth'];\n\nexport var namespace = 'fluture';\nexport var name = 'Future';\nexport var version = 5;\n\nexport var $$type = namespace + '/' + name + '@' + version;\n"
  },
  {
    "path": "src/internal/debug.js",
    "content": "import {ordinal} from './const.js';\nimport {cons} from './list.js';\n\n/* c8 ignore next */\nvar captureStackTrace = Error.captureStackTrace || captureStackTraceFallback;\nvar _debug = debugHandleNone;\n\nexport {captureStackTrace};\n\nexport function debugMode(debug){\n  _debug = debug ? debugHandleAll : debugHandleNone;\n}\n\nexport function debugHandleNone(x){\n  return x;\n}\n\nexport function debugHandleAll(x, fn, a, b, c){\n  return fn(a, b, c);\n}\n\nexport function debug(x, fn, a, b, c){\n  return _debug(x, fn, a, b, c);\n}\n\nexport function captureContext(previous, tag, fn){\n  return debug(previous, debugCaptureContext, previous, tag, fn);\n}\n\nexport function debugCaptureContext(previous, tag, fn){\n  var context = {tag: tag, name: ' from ' + tag + ':'};\n  captureStackTrace(context, fn);\n  return cons(context, previous);\n}\n\nexport function captureApplicationContext(context, n, f){\n  return debug(context, debugCaptureApplicationContext, context, n, f);\n}\n\nexport function debugCaptureApplicationContext(context, n, f){\n  return debugCaptureContext(context, ordinal[n - 1] + ' application of ' + f.name, f);\n}\n\nexport function captureStackTraceFallback(x){\n  var e = new Error;\n  if(typeof e.stack === 'string'){\n    x.stack = x.name + '\\n' + e.stack.split('\\n').slice(1).join('\\n');\n\n  /* c8 ignore next 3 */\n  }else{\n    x.stack = x.name;\n  }\n}\n"
  },
  {
    "path": "src/internal/error.js",
    "content": "import {show} from './utils.js';\nimport {ordinal, namespace, name, version} from './const.js';\nimport type from 'sanctuary-type-identifiers';\nimport {nil, cat} from './list.js';\nimport {captureStackTrace} from './debug.js';\n\nfunction showArg(x){\n  return show(x) + ' :: ' + type.parse(type(x)).name;\n}\n\nexport function error(message){\n  return new Error(message);\n}\n\nexport function typeError(message){\n  return new TypeError(message);\n}\n\nexport function invalidArgument(it, at, expected, actual){\n  return typeError(\n    it + '() expects its ' + ordinal[at] + ' argument to ' + expected + '.' +\n    '\\n  Actual: ' + showArg(actual)\n  );\n}\n\nexport function invalidArgumentOf(expected){\n  return function(it, at, actual){\n    return invalidArgument(it, at, expected, actual);\n  };\n}\n\nexport function invalidContext(it, actual){\n  return typeError(\n    it + '() was invoked outside the context of a Future. You might want to use'\n  + ' a dispatcher instead\\n  Called on: ' + show(actual)\n  );\n}\n\nexport function invalidArity(f, args){\n  return new TypeError(\n    f.name + '() expects to be called with a single argument per invocation\\n' +\n    '  Saw: ' + args.length + ' arguments' +\n    Array.prototype.slice.call(args).map(function(arg, i){\n      return '\\n  ' + (\n        ordinal[i] ?\n        ordinal[i].charAt(0).toUpperCase() + ordinal[i].slice(1) :\n        'Argument ' + String(i + 1)\n      ) + ': ' + showArg(arg);\n    }).join('')\n  );\n}\n\nfunction invalidNamespace(m, x){\n  return (\n    'The Future was not created by ' + namespace + '. '\n  + 'Make sure you transform other Futures to ' + namespace + ' Futures. '\n  + 'Got ' + (x ? ('a Future from ' + x) : 'an unscoped Future') + '.'\n  + '\\n  See: https://github.com/fluture-js/Fluture#casting-futures'\n  );\n}\n\nfunction invalidVersion(m, x){\n  return (\n    'The Future was created by ' + (x < version ? 'an older' : 'a newer')\n  + ' version of ' + namespace + '. '\n  + 'This means that one of the sources which creates Futures is outdated. '\n  + 'Update this source, or transform its created Futures to be compatible.'\n  + '\\n  See: https://github.com/fluture-js/Fluture#casting-futures'\n  );\n}\n\nexport function invalidFuture(desc, m, s){\n  var id = type.parse(type(m));\n  var info = id.name === name ? '\\n' + (\n    id.namespace !== namespace ? invalidNamespace(m, id.namespace)\n  : id.version !== version ? invalidVersion(m, id.version)\n  : 'Nothing seems wrong. Contact the Fluture maintainers.') : '';\n  return typeError(\n    desc + ' to be a valid Future.' + info + '\\n' +\n    '  Actual: ' + show(m) + ' :: ' + id.name + (s || '')\n  );\n}\n\nexport function invalidFutureArgument(it, at, m, s){\n  return invalidFuture(it + '() expects its ' + ordinal[at] + ' argument', m, s);\n}\n\nexport function ensureError(value, fn){\n  var message;\n  try{\n    if(value instanceof Error) return value;\n    message = 'A Non-Error was thrown from a Future: ' + show(value);\n  }catch (_){\n    message = 'Something was thrown from a Future, but it could not be converted to String';\n  }\n  var e = error(message);\n  captureStackTrace(e, fn);\n  return e;\n}\n\nexport function assignUnenumerable(o, prop, value){\n  Object.defineProperty(o, prop, {value: value, writable: true, configurable: true});\n}\n\nexport function wrapException(caught, callingFuture){\n  var origin = ensureError(caught, wrapException);\n  var context = cat(origin.context || nil, callingFuture.context);\n  var e = error(origin.message);\n  assignUnenumerable(e, 'future', origin.future || callingFuture);\n  assignUnenumerable(e, 'reason', origin.reason || origin);\n  assignUnenumerable(e, 'stack', e.reason.stack);\n  return withExtraContext(e, context);\n}\n\nexport function withExtraContext(e, context){\n  assignUnenumerable(e, 'context', context);\n  assignUnenumerable(e, 'stack', e.stack + contextToStackTrace(context));\n  return e;\n}\n\nexport function contextToStackTrace(context){\n  var stack = '', tail = context;\n  while(tail !== nil){\n    stack = stack + '\\n' + tail.head.stack;\n    tail = tail.tail;\n  }\n  return stack;\n}\n"
  },
  {
    "path": "src/internal/iteration.js",
    "content": "import {isObject, isBoolean} from './predicates.js';\n\nexport function Next(x){\n  return {done: false, value: x};\n}\n\nexport function Done(x){\n  return {done: true, value: x};\n}\n\nexport function isIteration(x){\n  return isObject(x) && isBoolean(x.done);\n}\n"
  },
  {
    "path": "src/internal/list.js",
    "content": "export function List(head, tail){\n  this.head = head;\n  this.tail = tail;\n}\n\nList.prototype.toJSON = function(){\n  return toArray(this);\n};\n\nexport var nil = new List(null, null);\nnil.tail = nil;\n\nexport function isNil(list){\n  return list.tail === list;\n}\n\n// cons :: (a, List a) -> List a\n//      -- O(1) append operation\nexport function cons(head, tail){\n  return new List(head, tail);\n}\n\n// reverse :: List a -> List a\n//         -- O(n) list reversal\nexport function reverse(xs){\n  var ys = nil, tail = xs;\n  while(!isNil(tail)){\n    ys = cons(tail.head, ys);\n    tail = tail.tail;\n  }\n  return ys;\n}\n\n// cat :: (List a, List a) -> List a\n//     -- O(n) list concatenation\nexport function cat(xs, ys){\n  var zs = ys, tail = reverse(xs);\n  while(!isNil(tail)){\n    zs = cons(tail.head, zs);\n    tail = tail.tail;\n  }\n  return zs;\n}\n\n// toArray :: List a -> Array a\n//         -- O(n) list to Array\nexport function toArray(xs){\n  var tail = xs, arr = [];\n  while(!isNil(tail)){\n    arr.push(tail.head);\n    tail = tail.tail;\n  }\n  return arr;\n}\n"
  },
  {
    "path": "src/internal/parallel.js",
    "content": "import {noop} from './utils.js';\nimport {createTransformation, Future, crash, reject, resolve} from '../future.js';\n\nfunction Eager(future){\n  var _this = this;\n  _this.rec = noop;\n  _this.rej = noop;\n  _this.res = noop;\n  _this.crashed = false;\n  _this.rejected = false;\n  _this.resolved = false;\n  _this.value = null;\n  _this.cancel = future._interpret(function Eager$crash(x){\n    _this.value = x;\n    _this.crashed = true;\n    _this.cancel = noop;\n    _this.rec(x);\n  }, function Eager$reject(x){\n    _this.value = x;\n    _this.rejected = true;\n    _this.cancel = noop;\n    _this.rej(x);\n  }, function Eager$resolve(x){\n    _this.value = x;\n    _this.resolved = true;\n    _this.cancel = noop;\n    _this.res(x);\n  });\n}\n\nEager.prototype = Object.create(Future.prototype);\n\nEager.prototype._interpret = function Eager$interpret(rec, rej, res){\n  if(this.crashed) rec(this.value);\n  else if(this.rejected) rej(this.value);\n  else if(this.resolved) res(this.value);\n  else{\n    this.rec = rec;\n    this.rej = rej;\n    this.res = res;\n  }\n  return this.cancel;\n};\n\nexport function earlyCrash(early, x){\n  early(crash(x));\n}\n\nexport function earlyReject(early, x){\n  early(reject(x));\n}\n\nexport function earlyResolve(early, x){\n  early(resolve(x));\n}\n\nexport function createParallelTransformation(name, rec, rej, res, prototype){\n  var ParallelTransformation = createTransformation(1, name, Object.assign({\n    run: function Parallel$run(early){\n      var eager = new Eager(this.$1);\n      var transformation = new ParallelTransformation(this.context, eager);\n      function Parallel$early(m){ early(m, transformation) }\n      transformation.cancel = eager._interpret(\n        function Parallel$rec(x){ rec(Parallel$early, x) },\n        function Parallel$rej(x){ rej(Parallel$early, x) },\n        function Parallel$res(x){ res(Parallel$early, x) }\n      );\n      return transformation;\n    },\n  }, prototype));\n  return ParallelTransformation;\n}\n"
  },
  {
    "path": "src/internal/predicates.js",
    "content": "import {FL} from './const.js';\n\nexport function isFunction(f){\n  return typeof f === 'function';\n}\n\nexport function isThenable(m){\n  return m instanceof Promise || m != null && isFunction(m.then);\n}\n\nexport function isBoolean(f){\n  return typeof f === 'boolean';\n}\n\nexport function isNumber(f){\n  return typeof f === 'number';\n}\n\nexport function isUnsigned(n){\n  return (n === Infinity || isNumber(n) && n > 0 && n % 1 === 0);\n}\n\nexport function isObject(o){\n  return o !== null && typeof o === 'object';\n}\n\nexport function isIterator(i){\n  return isObject(i) && isFunction(i.next);\n}\n\nexport function isArray(x){\n  return Array.isArray(x);\n}\n\nexport function hasMethod(method, x){\n  return x != null && isFunction(x[method]);\n}\n\nexport function isFunctor(x){\n  return hasMethod(FL.map, x);\n}\n\nexport function isAlt(x){\n  return isFunctor(x) && hasMethod(FL.alt, x);\n}\n\nexport function isApply(x){\n  return isFunctor(x) && hasMethod(FL.ap, x);\n}\n\nexport function isBifunctor(x){\n  return isFunctor(x) && hasMethod(FL.bimap, x);\n}\n\nexport function isChain(x){\n  return isApply(x) && hasMethod(FL.chain, x);\n}\n"
  },
  {
    "path": "src/internal/timing.js",
    "content": "export var Undetermined = 0;\nexport var Synchronous = 1;\nexport var Asynchronous = 2;\n"
  },
  {
    "path": "src/internal/utils.js",
    "content": "export {default as show} from 'sanctuary-show';\n\n/* c8 ignore next */\nvar setImmediate = typeof setImmediate === 'undefined' ? setImmediateFallback : setImmediate;\n\nexport function noop(){}\nexport function moop(){ return this }\nexport function call(f, x){ return f(x) }\n\nexport function setImmediateFallback(f, x){\n  return setTimeout(f, 0, x);\n}\n\nexport function raise(x){\n  setImmediate(function rethrowErrorDelayedToEscapePromiseCatch(){\n    throw x;\n  });\n}\n"
  },
  {
    "path": "src/lastly.js",
    "content": "import {AndTransformation} from './and.js';\nimport {\n  application,\n  application1,\n  createTransformation,\n  future,\n  Reject,\n  Resolve,\n} from './future.js';\n\nexport var LastlyTransformation = createTransformation(1, 'lastly', {\n  rejected: function LastlyAction$rejected(x){\n    return this.$1._transform(new AndTransformation(this.context, new Reject(this.context, x)));\n  },\n  resolved: function LastlyAction$resolved(x){\n    return this.$1._transform(new AndTransformation(this.context, new Resolve(this.context, x)));\n  },\n});\n\nexport function lastly(cleanup){\n  var context1 = application1(lastly, future, arguments);\n  return function lastly(program){\n    var context2 = application(2, lastly, future, arguments, context1);\n    return program._transform(new LastlyTransformation(context2, cleanup));\n  };\n}\n"
  },
  {
    "path": "src/map-rej.js",
    "content": "import {call} from './internal/utils.js';\nimport {createTransformation, Reject, application1, application, future, func} from './future.js';\n\nexport var MapRejTransformation = createTransformation(1, 'mapRej', {\n  rejected: function MapRejTransformation$rejected(x){\n    return new Reject(this.context, call(this.$1, x));\n  },\n});\n\nexport function mapRej(f){\n  var context1 = application1(mapRej, func, arguments);\n  return function mapRej(m){\n    var context2 = application(2, mapRej, future, arguments, context1);\n    return m._transform(new MapRejTransformation(context2, f));\n  };\n}\n"
  },
  {
    "path": "src/map.js",
    "content": "import {FL} from './internal/const.js';\nimport {invalidArgumentOf} from './internal/error.js';\nimport {isFunctor} from './internal/predicates.js';\nimport {isFuture, MapTransformation, application1, application, func} from './future.js';\n\nexport var functor = {pred: isFunctor, error: invalidArgumentOf('have Functor implemented')};\n\nexport function map(f){\n  var context1 = application1(map, func, arguments);\n  return function map(m){\n    var context2 = application(2, map, functor, arguments, context1);\n    return isFuture(m) ?\n           m._transform(new MapTransformation(context2, f)) :\n           m[FL.map](f);\n  };\n}\n"
  },
  {
    "path": "src/node.js",
    "content": "import {wrapException} from './internal/error.js';\nimport {noop, call} from './internal/utils.js';\nimport {createInterpreter, application1, func} from './future.js';\n\nexport var Node = createInterpreter(1, 'node', function Node$interpret(rec, rej, res){\n  function Node$done(err, val){\n    cont = err ? function EncaseN3$rej(){\n      open = false;\n      rej(err);\n    } : function EncaseN3$res(){\n      open = false;\n      res(val);\n    };\n    if(open){\n      cont();\n    }\n  }\n  var open = false, cont = function(){ open = true };\n  try{\n    call(this.$1, Node$done);\n  }catch(e){\n    rec(wrapException(e, this));\n    open = false;\n    return noop;\n  }\n  cont();\n  return function Node$cancel(){ open = false };\n});\n\nexport function node(f){\n  return new Node(application1(node, func, arguments), f);\n}\n"
  },
  {
    "path": "src/pap.js",
    "content": "import {createParallelTransformation, earlyCrash, earlyReject} from './internal/parallel.js';\nimport {noop} from './internal/utils.js';\nimport {typeError} from './internal/error.js';\nimport {isFunction} from './internal/predicates.js';\nimport {show} from './internal/utils.js';\nimport {MapTransformation, application1, application, future} from './future.js';\n\nexport var ParallelApTransformation =\ncreateParallelTransformation('pap', earlyCrash, earlyReject, noop, {\n  resolved: function ParallelApTransformation$resolved(f){\n    if(isFunction(f)) return this.$1._transform(new MapTransformation(this.context, f));\n    throw typeError(\n      'pap expects the second Future to resolve to a Function\\n' +\n      '  Actual: ' + show(f)\n    );\n  },\n});\n\nexport function pap(mx){\n  var context1 = application1(pap, future, arguments);\n  return function pap(mf){\n    var context2 = application(2, pap, future, arguments, context1);\n    return mf._transform(new ParallelApTransformation(context2, mx));\n  };\n}\n"
  },
  {
    "path": "src/par.js",
    "content": "import type from 'sanctuary-type-identifiers';\n\nimport {FL, namespace, version} from './internal/const.js';\nimport {invalidFutureArgument} from './internal/error.js';\nimport {captureContext} from './internal/debug.js';\nimport {nil} from './internal/list.js';\n\nimport {never, resolve, isFuture, MapTransformation} from './future.js';\nimport {ParallelApTransformation} from './pap.js';\nimport {RaceTransformation} from './race.js';\n\nexport function ConcurrentFuture(sequential){\n  this.sequential = sequential;\n}\n\nConcurrentFuture.prototype = Object.create(Par.prototype);\n\nexport function Par(sequential){\n  if(!isFuture(sequential)) throw invalidFutureArgument(Par.name, 0, sequential);\n  return new ConcurrentFuture(sequential);\n}\n\nvar $$type = namespace + '/ConcurrentFuture@' + version;\nvar zeroInstance = new ConcurrentFuture(never);\n\n// Compliance with sanctuary-type-identifiers versions 1 and 2.\n// To prevent sanctuary-type-identifiers version 3 from identifying\n// 'Par' as being of the type denoted by $$type, we ensure that\n// Par.constructor.prototype is equal to Par.\nPar['@@type'] = $$type;\nPar.constructor = {prototype: Par};\n\nPar[FL.of] = function Par$of(x){\n  return new ConcurrentFuture(resolve(x));\n};\n\nPar[FL.zero] = function Par$zero(){\n  return zeroInstance;\n};\n\nPar.prototype['@@type'] = $$type;\n\nPar.prototype['@@show'] = function Par$show(){\n  return this.toString();\n};\n\nPar.prototype.toString = function Par$toString(){\n  return 'Par (' + this.sequential.toString() + ')';\n};\n\nPar.prototype[FL.map] = function Par$FL$map(f){\n  var context = captureContext(\n    nil,\n    'a Fantasy Land dispatch to map via ConcurrentFuture',\n    Par$FL$map\n  );\n  return new ConcurrentFuture(this.sequential._transform(new MapTransformation(context, f)));\n};\n\nPar.prototype[FL.ap] = function Par$FL$ap(other){\n  var context = captureContext(\n    nil,\n    'a Fantasy Land dispatch to ap via ConcurrentFuture',\n    Par$FL$ap\n  );\n  return new ConcurrentFuture(other.sequential._transform(\n    new ParallelApTransformation(context, this.sequential)\n  ));\n};\n\nPar.prototype[FL.alt] = function Par$FL$alt(other){\n  var context = captureContext(\n    nil,\n    'a Fantasy Land dispatch to alt via ConcurrentFuture',\n    Par$FL$alt\n  );\n  return new ConcurrentFuture(other.sequential._transform(\n    new RaceTransformation(context, this.sequential)\n  ));\n};\n\nexport function isParallel(x){\n  return x instanceof ConcurrentFuture || type(x) === $$type;\n}\n"
  },
  {
    "path": "src/parallel.js",
    "content": "import {wrapException, invalidArgumentOf} from './internal/error.js';\nimport {isArray} from './internal/predicates.js';\nimport {noop} from './internal/utils.js';\nimport {\n  createInterpreter,\n  isFuture,\n  resolve,\n  application1,\n  positiveInteger,\n  application,\n} from './future.js';\n\nfunction isFutureArray(xs){\n  if(!isArray(xs)) return false;\n  for(var i = 0; i < xs.length; i++){\n    if(!isFuture(xs[i])) return false;\n  }\n  return true;\n}\n\nexport var futureArray = {\n  pred: isFutureArray,\n  error: invalidArgumentOf('be an Array of valid Futures'),\n};\n\nexport var Parallel = createInterpreter(2, 'parallel', function Parallel$interpret(rec, rej, res){\n  var _this = this, futures = this.$2, length = futures.length;\n  var max = Math.min(this.$1, length), cancels = new Array(length), out = new Array(length);\n  var cursor = 0, running = 0, blocked = false, cont = noop;\n\n  function Parallel$cancel(){\n    rec = noop;\n    rej = noop;\n    res = noop;\n    cursor = length;\n    for(var n = 0; n < length; n++) cancels[n] && cancels[n]();\n  }\n\n  function Parallel$run(idx){\n    running++;\n    cancels[idx] = futures[idx]._interpret(function Parallel$rec(e){\n      cont = rec;\n      cancels[idx] = noop;\n      Parallel$cancel();\n      cont(wrapException(e, _this));\n    }, function Parallel$rej(reason){\n      cont = rej;\n      cancels[idx] = noop;\n      Parallel$cancel();\n      cont(reason);\n    }, function Parallel$res(value){\n      cancels[idx] = noop;\n      out[idx] = value;\n      running--;\n      if(cursor === length && running === 0) res(out);\n      else if(blocked) Parallel$drain();\n    });\n  }\n\n  function Parallel$drain(){\n    blocked = false;\n    while(cursor < length && running < max) Parallel$run(cursor++);\n    blocked = true;\n  }\n\n  Parallel$drain();\n\n  return Parallel$cancel;\n});\n\nvar emptyArray = resolve([]);\n\nexport function parallel(max){\n  var context1 = application1(parallel, positiveInteger, arguments);\n  return function parallel(ms){\n    var context2 = application(2, parallel, futureArray, arguments, context1);\n    return ms.length === 0 ? emptyArray : new Parallel(context2, max, ms);\n  };\n}\n"
  },
  {
    "path": "src/promise.js",
    "content": "import {application1, future} from './future.js';\n\nexport function promise(m){\n  application1(promise, future, arguments);\n  return new Promise(function promise$computation(res, rej){\n    m._interpret(rej, rej, res);\n  });\n}\n"
  },
  {
    "path": "src/race.js",
    "content": "import {\n  createParallelTransformation,\n  earlyCrash,\n  earlyReject,\n  earlyResolve,\n} from './internal/parallel.js';\nimport {application1, application, future} from './future.js';\n\nexport var RaceTransformation =\ncreateParallelTransformation('race', earlyCrash, earlyReject, earlyResolve, {});\n\nexport function race(left){\n  var context1 = application1(race, future, arguments);\n  return function race(right){\n    var context2 = application(2, race, future, arguments, context1);\n    return right._transform(new RaceTransformation(context2, left));\n  };\n}\n"
  },
  {
    "path": "src/reject-after.js",
    "content": "import {\n  any,\n  application,\n  application1,\n  createInterpreter,\n  never,\n  positiveInteger,\n} from './future.js';\n\nexport var RejectAfter =\ncreateInterpreter(2, 'rejectAfter', function RejectAfter$interpret(rec, rej){\n  var id = setTimeout(rej, this.$1, this.$2);\n  return function RejectAfter$cancel(){ clearTimeout(id) };\n});\n\nRejectAfter.prototype.extractLeft = function RejectAfter$extractLeft(){\n  return [this.$2];\n};\n\nfunction alwaysNever(_){\n  return never;\n}\n\nexport function rejectAfter(time){\n  var context1 = application1(rejectAfter, positiveInteger, arguments);\n  return time === Infinity ? alwaysNever : (function rejectAfter(value){\n    var context2 = application(2, rejectAfter, any, arguments, context1);\n    return new RejectAfter(context2, time, value);\n  });\n}\n"
  },
  {
    "path": "src/seq.js",
    "content": "import {invalidArgumentOf} from './internal/error.js';\nimport {application1} from './future.js';\nimport {isParallel} from './par.js';\n\nvar parallel = {pred: isParallel, error: invalidArgumentOf('be a ConcurrentFuture')};\n\nexport function seq(par){\n  application1(seq, parallel, arguments);\n  return par.sequential;\n}\n"
  },
  {
    "path": "src/swap.js",
    "content": "import {createTransformation, Reject, Resolve, application1, future} from './future.js';\n\nexport var SwapTransformation = createTransformation(0, 'swap', {\n  resolved: function SwapTransformation$resolved(x){\n    return new Reject(this.context, x);\n  },\n  rejected: function SwapTransformation$rejected(x){\n    return new Resolve(this.context, x);\n  },\n});\n\nexport function swap(m){\n  var context = application1(swap, future, arguments);\n  return m._transform(new SwapTransformation(context));\n}\n"
  },
  {
    "path": "src/value.js",
    "content": "import {error} from './internal/error.js';\nimport {raise, show} from './internal/utils.js';\nimport {application1, application, func, future} from './future.js';\n\nexport function value(res){\n  var context1 = application1(value, func, arguments);\n  return function value(m){\n    application(2, value, future, arguments, context1);\n    function value$rej(x){\n      raise(error(\n        'Future#value was called on a rejected Future\\n' +\n        '  Rejection: ' + show(x) + '\\n' +\n        '  Future: ' + show(m)\n      ));\n    }\n    return m._interpret(raise, value$rej, res);\n  };\n}\n"
  },
  {
    "path": "test/arbitraries.js",
    "content": "import jsv from 'jsverify';\nimport {Future, resolve, reject, Par, seq, extractLeft, extractRight} from '../index.js';\n\nconst noop = () => {};\nconst show = m => m.toString();\n\nexport const nil = jsv.elements([null, undefined]);\n\nconst immediatelyResolve = x => {\n  const m = Future((rej, res) => { setImmediate(res, x); return noop });\n  m.extractRight = () => [x];\n  return m;\n};\n\nconst immediatelyReject = x => {\n  const m = Future((rej) => { setImmediate(rej, x); return noop });\n  m.extractLeft = () => [x];\n  return m;\n};\n\nexport function AsyncResolvedFutureArb (arb){\n  return arb.smap(immediatelyResolve, extractRight, show);\n}\n\nexport function AsyncRejectedFutureArb (arb){\n  return arb.smap(immediatelyReject, extractLeft, show);\n}\n\nexport function ResolvedFutureArb (arb){\n  return arb.smap(resolve, extractRight, show);\n}\n\nexport function RejectedFutureArb (arb){\n  return arb.smap(reject, extractLeft, show);\n}\n\nexport function FutureArb (larb, rarb){\n  return jsv.oneof(\n    RejectedFutureArb(larb),\n    ResolvedFutureArb(rarb),\n    AsyncRejectedFutureArb(larb),\n    AsyncResolvedFutureArb(rarb)\n  );\n}\n\nexport const {\n  any,\n  anyFuture,\n  anyRejectedFuture,\n  anyResolvedFuture,\n  anyNonFuture,\n  anyFunction,\n} = jsv.letrec(tie => ({\n  anyRejectedFuture: jsv.oneof(AsyncRejectedFutureArb(tie('any')), RejectedFutureArb(tie('any'))),\n  anyResolvedFuture: jsv.oneof(AsyncResolvedFutureArb(tie('any')), ResolvedFutureArb(tie('any'))),\n  anyFuture: jsv.oneof(tie('anyRejectedFuture'), tie('anyResolvedFuture')),\n  anyFunction: jsv.fn(tie('any')),\n  anyNonFuture: jsv.oneof(\n    jsv.number,\n    jsv.string,\n    jsv.bool,\n    jsv.falsy,\n    jsv.constant(new Error('Kapot')),\n    jsv.constant(Future),\n    jsv.constant(Par),\n    tie('anyFunction')\n  ),\n  any: jsv.oneof(\n    tie('anyNonFuture'),\n    tie('anyFuture')\n  ),\n}));\n\nexport const anyParallel = anyFuture.smap(Par, seq, show);\n"
  },
  {
    "path": "test/assertions.js",
    "content": "import show from 'sanctuary-show';\nimport type from 'sanctuary-type-identifiers';\nimport {Future, isFuture} from '../index.js';\nimport {strictEqual, deepStrictEqual} from 'assert';\n\nconst states = ['pending', 'crashed', 'rejected', 'resolved'];\n\nexport const equality = a => b => {\n  strictEqual(show(a), show(b));\n  deepStrictEqual(a, b);\n  return true;\n};\n\nexport const future = x => {\n  equality(isFuture(x))(true);\n  equality(type(x))(Future['@@type']);\n  return true;\n};\n\nexport function makeEquivalence (equals){\n  return function equivalence (ma){\n    return function (mb){\n      let astate = 0, bstate = 0, val;\n      return new Promise(function (pass, fail){\n        future(ma);\n        future(mb);\n\n        function twice (m, x, s1, s2){\n          fail(new Error(\n            'A Future ' + states[s2] + ' after already having ' + states[s1] + '.\\n' +\n            '  First: Future({ <' + states[s1] + '> ' + show(val) + ' })\\n' +\n            '  Second: Future({ <' + states[s1] + '> ' + show(x) + ' })\\n' +\n            '  Future: ' + m.toString()\n          ));\n        }\n\n        function assertInnerEqual (a, b){\n          if(astate === bstate){\n            if(isFuture(a) && isFuture(b)){\n              equivalence(a)(b).then(pass, fail);\n              return;\n            }\n            try {\n              equals(a)(b);\n              pass(true);\n            } catch (e){\n              inequivalent('The inner values are not equal: ' + e.message);\n            }\n          }else{\n            inequivalent(\n              'One Future ' + states[astate] + ', and the other Future ' + states[bstate]\n            );\n          }\n          function inequivalent (message){\n            fail(new Error(\n              '\\n    ' + ma.toString() +\n              ' :: Future({ <' + states[astate] + '> ' + show(a) + ' })' +\n              '\\n    is not equivalent to:\\n    ' + mb.toString() +\n              ' :: Future({ <' + states[bstate] + '> ' + show(b) + ' })\\n\\n' +\n              message\n            ));\n          }\n        }\n\n        ma._interpret(function (x){\n          if(astate > 0) twice(ma, x, astate, 1);\n          else {\n            astate = 1;\n            if(bstate > 0) assertInnerEqual(x, val);\n            else val = x;\n          }\n        }, function (x){\n          if(astate > 0) twice(ma, x, astate, 2);\n          else {\n            astate = 2;\n            if(bstate > 0) assertInnerEqual(x, val);\n            else val = x;\n          }\n        }, function (x){\n          if(astate > 0) twice(ma, x, astate, 3);\n          else {\n            astate = 3;\n            if(bstate > 0) assertInnerEqual(x, val);\n            else val = x;\n          }\n        });\n\n        mb._interpret(function (x){\n          if(bstate > 0) twice(mb, x, bstate, 1);\n          else {\n            bstate = 1;\n            if(astate > 0) assertInnerEqual(val, x);\n            else val = x;\n          }\n        }, function (x){\n          if(bstate > 0) twice(mb, x, bstate, 2);\n          else {\n            bstate = 2;\n            if(astate > 0) assertInnerEqual(val, x);\n            else val = x;\n          }\n        }, function (x){\n          if(bstate > 0) twice(mb, x, bstate, 3);\n          else {\n            bstate = 3;\n            if(astate > 0) assertInnerEqual(val, x);\n            else val = x;\n          }\n        });\n      });\n    };\n  };\n}\n\nexport const equivalence = makeEquivalence(equality);\n"
  },
  {
    "path": "test/build/main.js",
    "content": "import {noop, eq, test} from '../util/util.js';\nimport * as Fluture from '../../index.js';\nimport require from './require.js';\n\nconst Future = require('../../index.cjs');\n\ntest('exports the Future constructor by default', function (){\n  eq(typeof Future, 'function');\n  eq(Future(noop) instanceof Future, true);\n});\n\ntest('has a Future property that refers to itself for import destructuring', function (){\n  eq(Future.Future, Future);\n});\n\nObject.keys(Fluture).forEach(key => {\n  test('has a ' + key + ' property of type ' + typeof Fluture[key], function (){\n    eq(typeof Future[key], typeof Fluture[key]);\n  });\n});\n\ntest('exports Future with the correct name property', function (){\n  eq(Future.name, Fluture.Future.name);\n});\n"
  },
  {
    "path": "test/build/require.js",
    "content": "import {createRequire} from 'module';\nexport default createRequire(import.meta.url);\n"
  },
  {
    "path": "test/integration/main.js",
    "content": "import {\n  Future,\n  after,\n  ap,\n  both,\n  cache,\n  chain,\n  fork,\n  map,\n  parallel,\n  race,\n  rejectAfter,\n  resolve,\n} from '../../index.js';\n\nimport {noop, error, assertResolved, eq, add, test} from '../util/util.js';\nimport {resolved, resolvedSlow} from '../util/futures.js';\n\nfunction through (x, fs){\n  return fs.reduce(function (y, f){\n    return f(y);\n  }, x);\n}\n\ntest('is capable of joining', function (){\n  var m = through(resolve('a'), [\n    chain(function (x){ return chain(function (x){ return after(5)(x + 'c') })(after(5)(x + 'b')) }),\n    chain(function (x){ return after(5)(x + 'd') }),\n    chain(function (x){ return resolve(x + 'e') }),\n    chain(function (x){ return after(5)(x + 'f') }),\n  ]);\n  return assertResolved(m, 'abcdef');\n});\n\ntest('is capable of early termination', function (done){\n  var slow = Future(function (){\n    var id = setTimeout(done, 20, new Error('Not terminated'));\n    return function (){ return clearTimeout(id) };\n  });\n  var m = through(slow, [race(slow), race(slow), race(slow), race(resolved)]);\n  m._interpret(done, noop, noop);\n  setTimeout(done, 40, null);\n});\n\ntest('cancels running actions when one early-terminates asynchronously', function (done){\n  var slow = Future(function (){\n    var id = setTimeout(done, 50, new Error('Not terminated'));\n    return function (){ return clearTimeout(id) };\n  });\n  var m = through(slow, [race(slow), race(slow), race(slow), race(resolvedSlow)]);\n  m._interpret(done, noop, noop);\n  setTimeout(done, 100, null);\n});\n\ntest('does not run actions unnecessarily when one early-terminates synchronously', function (done){\n  var broken = Future(function (){ done(error) });\n  var m = through(resolvedSlow, [race(broken), race(broken), race(resolved)]);\n  m._interpret(done, noop, function (){ return done() });\n});\n\ntest('resolves the left-hand side first when running actions in parallel', function (){\n  var m = through(resolve(1), [\n    map(function (x){ return x }),\n    chain(function (x){ return resolve(x) }),\n    race(resolve(2)),\n  ]);\n  return assertResolved(m, 1);\n});\n\ntest('does not forget about actions to run after early termination', function (){\n  var m = through('a', [\n    after(100),\n    race(after(20)('b')),\n    map(function (x){ return (x + 'c') }),\n  ]);\n  return assertResolved(m, 'bc');\n});\n\ntest('does not run early terminating actions twice, or cancel them', function (done){\n  var mock = Object.create(Future.prototype);\n  mock._interpret = function (_, l, r){ return r(done()) || (function (){ return done(error) }) };\n  var m = through('a', [\n    after(30),\n    map(function (x){ return (x + 'b') }),\n    race(mock),\n  ]);\n  m._interpret(done, noop, noop);\n});\n\ntest('does not run concurrent computations twice', function (done){\n  var ran = false;\n  var m = through(resolvedSlow, [\n    chain(function (){ return resolvedSlow }),\n    race(Future(function (){ ran ? done(error) : (ran = true); return noop })),\n  ]);\n  m._interpret(done, done, function (){ return done() });\n});\n\ntest('returns a cancel function which cancels all running actions', function (done){\n  var i = 0;\n  var started = function (){ return void i++ };\n  var cancelled = function (){ return --i < 1 && done() };\n  var slow = Future(function (){ return started() || (function (){ return cancelled() }) });\n  var m = through(slow, [race(slow), race(slow), race(slow), race(slow)]);\n  var cancel = m._interpret(done, noop, noop);\n  eq(i, 5);\n  cancel();\n});\n\ntest('returns source when cast to String', function (){\n  const m = ap(resolve(22))(map(add)(resolve(20)));\n  eq(\n    String(m),\n    'ap (resolve (22)) (map (function (a){ return function (b){ return a + b } }) (resolve (20)))'\n  );\n});\n\ntest('returns an AST when cast to JSON', function (){\n  const m = ap(resolve(22))(map(add)(resolve(20)));\n  eq(\n    JSON.stringify(m),\n    '{\"$\":\"fluture/Future@5\",\"kind\":\"interpreter\",\"type\":\"transform\",\"args\":[' +\n      '{\"$\":\"fluture/Future@5\",\"kind\":\"interpreter\",\"type\":\"resolve\",\"args\":[20]},[' +\n        '{\"$\":\"fluture/Future@5\",\"kind\":\"transformation\",\"type\":\"ap\",\"args\":[' +\n          '{\"$\":\"fluture/Future@5\",\"kind\":\"interpreter\",\"type\":\"resolve\",\"args\":[22]}' +\n        ']},' +\n        '{\"$\":\"fluture/Future@5\",\"kind\":\"transformation\",\"type\":\"map\",\"args\":[null]}' +\n      ']' +\n    ']}'\n  );\n});\n\ntest('does not produce issue #362', function (done){\n  const ma = cache(rejectAfter(1)(new Error));\n  const mb = map(noop)(parallel(Infinity)([ma, ma]));\n  fork(() => done())(noop)(mb);\n});\n\ntest('does not produce issue #362 in a regular combinator', function (done){\n  const ma = cache(rejectAfter(1)(new Error));\n  const mb = map(noop)(both(ma)(ma));\n  fork(() => done())(noop)(mb);\n});\n"
  },
  {
    "path": "test/prop/0.algebra.js",
    "content": "import show from 'sanctuary-show';\nimport {assertEqual, I, B, T, K} from '../util/util.js';\nimport {FutureArb, any as _x, anyFuture as _mx, f, g, _of, elements, property} from '../util/props.js';\nimport {\n  alt,\n  and,\n  ap,\n  bichain,\n  bimap,\n  cache,\n  chain,\n  chainRej,\n  hook,\n  lastly,\n  map,\n  mapRej,\n  reject,\n  resolve,\n  swap,\n} from '../../index.js';\n\nvar _f = elements([f, g, I, resolve]);\nvar _mf = _of(_f);\nvar _fm = FutureArb(_f, _f).smap(function (m){\n  return function (x){\n    return bimap(T(x))(T(x))(m);\n  };\n}, function (f){\n  return bimap(K)(K)(f());\n}, show);\n\nfunction eq (x){\n  return function (y){\n    return assertEqual(x, y);\n  };\n}\n\nproperty('alt associativity', _mx, _mx, _mx, function (a, b, c){\n  return eq(alt(a)(alt(b)(c)))(alt(alt(a)(b))(c));\n});\n\nproperty('alt distributivity with map', _mx, _mx, function (a, b){\n  return eq(map(f)(alt(a)(b)))(alt(map(f)(a))(map(f)(b)));\n});\n\nproperty('and associativity', _mx, _mx, _mx, function (a, b, c){\n  return eq(and(a)(and(b)(c)))(and(and(a)(b))(c));\n});\n\nproperty('and distributivity with map', _mx, _mx, function (a, b){\n  return eq(map(f)(and(a)(b)))(and(map(f)(a))(map(f)(b)));\n});\n\nproperty('ap composition using map', _mx, _mf, _mf, function (mx, mf, mg){\n  return eq(ap(mx)(ap(mf)(map(B)(mg))))(ap(ap(mx)(mf))(mg));\n});\n\nproperty('bichain associativity', _mx, _fm, _fm, function (m, f, g){\n  return eq(bichain(g)(g)(bichain(f)(f)(m)))(bichain(B(bichain(g)(g))(f))(B(bichain(g)(g))(f))(m));\n});\n\nproperty('bichain left identity on rejection', _x, _fm, _fm, function (x, f, g){\n  return eq(bichain(f)(g)(reject(x)))(f(x));\n});\n\nproperty('bichain left identity on resolution', _x, _fm, _fm, function (x, f, g){\n  return eq(bichain(f)(g)(resolve(x)))(g(x));\n});\n\nproperty('bichain right identity', _mx, function (m){\n  return eq(bichain(reject)(resolve)(m))(m);\n});\n\nproperty('bimap identity', _mx, function (mx){\n  return eq(bimap(I)(I)(mx))(mx);\n});\n\nproperty('bimap composition', _mx, _f, _f, _f, _f, function (mx, f, g, h, i){\n  return eq(bimap(B(f)(g))(B(h)(i))(mx))(bimap(f)(h)(bimap(g)(i)(mx)));\n});\n\nproperty('cache idempotence', _mx, function (m){\n  return eq(cache(cache(m)))(cache(m));\n});\n\nproperty('chain associativity', _mx, _fm, _fm, function (m, f, g){\n  return eq(chain(g)(chain(f)(m)))(chain(B(chain(g))(f))(m));\n});\n\nproperty('chain left identity', _x, _fm, function (x, f){\n  return eq(chain(f)(resolve(x)))(f(x));\n});\n\nproperty('chain right identity', _mx, function (m){\n  return eq(chain(resolve)(m))(m);\n});\n\nproperty('chainRej associativity', _mx, _fm, _fm, function (m, f, g){\n  return eq(chainRej(g)(chainRej(f)(m)))(chainRej(B(chainRej(g))(f))(m));\n});\n\nproperty('chainRej left identity', _x, _fm, function (x, f){\n  return eq(chainRej(f)(reject(x)))(f(x));\n});\n\nproperty('chainRej right identity', _mx, function (m){\n  return eq(chainRej(reject)(m))(m);\n});\n\nproperty('hook identity', _mx, function (m){\n  return eq(hook(m)(resolve)(resolve))(m);\n});\n\nproperty('lastly associativity', _mx, _mx, _mx, function (a, b, c){\n  return eq(lastly(a)(lastly(b)(c)))(lastly(lastly(a)(b))(c));\n});\n\nproperty('lastly distributivity with map', _mx, _mx, function (a, b){\n  return eq(map(f)(lastly(a)(b)))(lastly(map(f)(a))(map(f)(b)));\n});\n\nproperty('map identity', _mx, function (m){\n  return eq(map(I)(m))(m);\n});\n\nproperty('map composition', _mx, _f, _f, function (m, f, g){\n  return eq(map(B(f)(g))(m))(map(f)(map(g)(m)));\n});\n\nproperty('mapRej identity', _mx, function (m){\n  return eq(mapRej(I)(m))(m);\n});\n\nproperty('mapRej composition', _mx, _f, _f, function (m, f, g){\n  return eq(mapRej(B(f)(g))(m))(mapRej(f)(mapRej(g)(m)));\n});\n\nproperty('resolve identity for ap', _mx, function (mx){\n  return eq(ap(mx)(resolve(I)))(mx);\n});\n\nproperty('resolve homomorphism with ap', _x, function (x){\n  return eq(ap(resolve(x))(resolve(f)))(resolve(f(x)));\n});\n\nproperty('resolve interchange with ap', _x, _mf, function (x, mf){\n  return eq(ap(resolve(x))(mf))(ap(mf)(resolve(T(x))));\n});\n\nproperty('swap self inverse', _mx, function (m){\n  return eq(swap(swap(m)))(m);\n});\n"
  },
  {
    "path": "test/prop/0.fantasy-land.js",
    "content": "import FL from 'fantasy-laws';\nimport Z from 'sanctuary-type-classes';\nimport show from 'sanctuary-show';\nimport {Future, bimap} from '../../index.js';\nimport {assertEqual as eq, I, B, T, K, noop, STACKSIZE, test} from '../util/util.js';\nimport {\n  FutureArb,\n  _of,\n  any as _x,\n  anyFuture as _mx,\n  constant as _k,\n  elements,\n  f,\n  g,\n  nat,\n  property,\n  suchthat,\n} from '../util/props.js';\n\nvar of = function (x){\n  return Z.of(Future, x);\n};\n\nvar _f = elements([f, g, I, of]);\nvar _mf = _of(_f);\nvar _fm = FutureArb(_f, _f).smap(function (m){\n  return function (x){\n    return bimap(T(x))(T(x))(m);\n  };\n}, function (f){\n  return bimap(K)(K)(f());\n}, show);\n\nfunction testLaw (laws, typeclass, name){\n  var args = Array.from(arguments).slice(3);\n  test(`${typeclass} ${name}`, laws[name].apply(null, args));\n}\n\ntestLaw(FL.Functor(eq), 'Functor', 'identity', _mx);\ntestLaw(FL.Functor(eq), 'Functor', 'composition', _mx, _f, _f);\n\ntestLaw(FL.Alt(eq), 'Alt', 'associativity', _mx, _mx, _mx);\ntestLaw(FL.Alt(eq), 'Alt', 'distributivity', _mx, _mx, _f);\n\ntestLaw(FL.Bifunctor(eq), 'Bifunctor', 'identity', _mx);\ntestLaw(FL.Bifunctor(eq), 'Bifunctor', 'composition', _mx, _f, _f, _f, _f);\n\ntestLaw(FL.Apply(eq), 'Apply', 'composition', _mf, _mf, _mx);\n\ntestLaw(FL.Applicative(eq, Future), 'Applicative', 'identity', _mx);\ntestLaw(FL.Applicative(eq, Future), 'Applicative', 'homomorphism', _f, _x);\ntestLaw(FL.Applicative(eq, Future), 'Applicative', 'interchange', _mf, _x);\n\ntestLaw(FL.Chain(eq), 'Chain', 'associativity', _mx, _fm, _fm);\n\ntestLaw(\n  FL.ChainRec(eq, Future),\n  'ChainRec',\n  'equivalence',\n  _k(function (v){ return v < 1 }),\n  _k(B(of)(function (v){ return v - 1 })),\n  _k(of),\n  suchthat(nat, function (x){ return x < 100 })\n);\n\ntest('ChainRec stack-safety', function (){\n  var p = function (v){ return v > (STACKSIZE + 1) };\n  var d = of;\n  var n = B(of)(function (v){ return v + 1 });\n  var a = Z.chainRec(Future, function (l, r, v){ return p(v) ? Z.map(r, d(v)) : Z.map(l, n(v)) }, 0);\n  a._interpret(noop, noop, noop);\n});\n\ntestLaw(FL.Monad(eq, Future), 'Monad', 'leftIdentity', _fm, _mx);\ntestLaw(FL.Monad(eq, Future), 'Monad', 'rightIdentity', _mx);\n\nproperty('map derived from ap and of', _mx, _f, function (m, f){\n  return eq(Z.map(f, m), Z.ap(of(f), m));\n});\n\nproperty('map derived from chain and of', _mx, _f, function (m, f){\n  return eq(Z.map(f, m), Z.chain(B(of)(f), m));\n});\n\nproperty('map derived from bimap', _mx, _f, function (m, f){\n  return eq(Z.map(f, m), Z.bimap(I, f, m));\n});\n\nproperty('ap derived from chain and map', _mx, _mf, function (mx, mf){\n  return eq(Z.ap(mf, mx), Z.chain(function (f){ return Z.map(f, mx) }, mf));\n});\n"
  },
  {
    "path": "test/prop/1.fantasy-libs.js",
    "content": "import * as R from 'ramda';\nimport Z from 'sanctuary-type-classes';\nimport {Future, ap, alt, map, bimap, chain, resolve, reject} from '../../index.js';\n\nimport {assertEqual} from '../util/util.js';\nimport {any, property, FutureArb, string, number, constant, anyFuture, oneof} from '../util/props.js';\n\nfunction bang (x){\n  return x + '!';\n}\n\nfunction compose (f, g){\n  return function (x){\n    return f(g(x));\n  };\n}\n\nfunction square (x){\n  return x * x;\n}\n\nvar stringNumberFuture = FutureArb(string, number);\nvar stringSquareFuture = FutureArb(string, constant(square));\nvar make = oneof(constant(resolve), constant(reject));\n\nproperty('Z.of(Future, x) = resolve(x)', any, function (x){\n  return assertEqual(Z.of(Future, x), resolve(x));\n});\n\nproperty('R.ap(mf, mx) = ap(mx)(mf)', stringSquareFuture, stringNumberFuture, function (mf, mx){\n  return assertEqual(R.ap(mf, mx), ap(mx)(mf));\n});\n\nproperty('Z.ap(mf, mx) = ap(mx)(mf)', stringSquareFuture, stringNumberFuture, function (mf, mx){\n  return assertEqual(Z.ap(mf, mx), ap(mx)(mf));\n});\n\nproperty('Z.alt(a, b) = alt(b)(a)', anyFuture, anyFuture, function (a, b){\n  return assertEqual(Z.alt(a, b), alt(b)(a));\n});\n\nproperty('R.map(f, mx) = map(f)(mx)', stringNumberFuture, function (mx){\n  return assertEqual(R.map(square, mx), map(square)(mx));\n});\n\nproperty('Z.map(f, mx) = map(f, mx)', stringNumberFuture, function (mx){\n  return assertEqual(Z.map(square, mx), map(square)(mx));\n});\n\nproperty('Z.bimap(f, g, mx) = bimap(f)(g)(mx)', stringNumberFuture, function (mx){\n  return assertEqual(Z.bimap(bang, square, mx), bimap(bang)(square)(mx));\n});\n\nproperty('R.chain(f, mx) = chain(f)(mx)', make, stringNumberFuture, function (g, mx){\n  var f = compose(f, square);\n  return assertEqual(R.chain(f, mx), chain(f)(mx));\n});\n\nproperty('Z.chain(f, mx) = chain(f)(mx)', make, stringNumberFuture, function (g, mx){\n  var f = compose(f, square);\n  return assertEqual(Z.chain(f, mx), chain(f)(mx));\n});\n"
  },
  {
    "path": "test/prop/2.arbitrary.js",
    "content": "import {assertEqual, I, B, K} from '../util/util.js';\nimport {\n  any,\n  anyFuture,\n  anyRejectedFuture,\n  anyResolvedFuture,\n  constant,\n  f,\n  g,\n  oneof,\n  property,\n} from '../util/props.js';\nimport {\n  after,\n  and,\n  bichain,\n  bimap,\n  chain,\n  chainRej,\n  coalesce,\n  go,\n  map,\n  mapRej,\n  reject,\n  rejectAfter,\n  resolve,\n  swap,\n} from '../../index.js';\n\nvar make = oneof(constant(resolve), constant(reject));\n\nfunction eq (a){\n  return function (b){\n    return assertEqual(a, b);\n  };\n}\n\nproperty('bichain(reject)(B(mk)(f))(m) = chain(B(mk)(f))(m)', make, anyFuture, function (mk, m){\n  return eq(bichain(reject)(B(mk)(f))(m))(chain(B(mk)(f))(m));\n});\n\nproperty('bichain(B(mk)(f))(resolve)(m) = chainRej(B(mk)(f))(m)', make, anyFuture, function (mk, m){\n  return eq(bichain(B(mk)(f))(resolve)(m))(chainRej(B(mk)(f))(m));\n});\n\nproperty('bichain(B(mk)(f))(B(mk)(g))(m) = chain(I)(coalesce(B(mk)(f))(B(mk)(g))(m))', make, anyFuture, function (mk, m){\n  return eq(bichain(B(mk)(f))(B(mk)(g))(m))(chain(I)(coalesce(B(mk)(f))(B(mk)(g))(m)));\n});\n\nproperty('swap(m) = bichain(resolve)(reject)(m)', anyFuture, function (m){\n  return eq(swap(m))(bichain(resolve)(reject)(m));\n});\n\nproperty('swap(resolve(x)) = reject(x)', any, function (x){\n  return eq(swap(resolve(x)))(reject(x));\n});\n\nproperty('swap(reject(x)) = resolve(x)', any, function (x){\n  return eq(swap(reject(x)))(resolve(x));\n});\n\nproperty('Resolved m => chainRej(B(mk)(f))(m) = m', make, anyResolvedFuture, function (mk, m){\n  return eq(chainRej(B(mk)(f))(m))(m);\n});\n\nproperty('Rejected m => chainRej(B(mk)(f))(m) = chain(B(mk)(f))(swap(m))', make, anyRejectedFuture, function (mk, m){\n  return eq(chainRej(B(mk)(f))(m))(chain(B(mk)(f))(swap(m)));\n});\n\nproperty('Resolved m => chain(B(mk)(f))(m) = chainRej(B(mk)(f))(swap(m))', make, anyResolvedFuture, function (mk, m){\n  return eq(chain(B(mk)(f))(m))(chainRej(B(mk)(f))(swap(m)));\n});\n\nproperty('after(1)(x) = resolve(x)', any, function (x){\n  return eq(after(1)(x))(resolve(x));\n});\n\nproperty('and(a)(b) = chain(K(a))(b)', anyFuture, anyFuture, function (a, b){\n  return eq(and(a)(b))(chain(K(a))(b));\n});\n\nproperty('coalesce(f)(g)(m) = chainRej(B(resolve)(f))(map(g)(m))', anyFuture, function (m){\n  return eq(coalesce(f)(g)(m))(chainRej(B(resolve)(f))(map(g)(m)));\n});\n\nproperty('go(function*(){ return f(yield m) }) = map(f)(m)', anyFuture, function (m){\n  return eq(go(function*(){ return f(yield m) }))(map(f)(m));\n});\n\nproperty('mapRej(f)(m) = chainRej(B(reject)(f))(m)', anyFuture, function (m){\n  return eq(mapRej(f)(m))(chainRej(B(reject)(f))(m));\n});\n\nproperty('mapRej(f)(m) = bimap(f)(I)(m)', anyFuture, function (m){\n  return eq(mapRej(f)(m))(bimap(f)(I)(m));\n});\n\nproperty('mapRej(f)(m) = swap(map(f)(swap(m)))', anyFuture, function (m){\n  return eq(mapRej(f)(m))(swap(map(f)(swap(m))));\n});\n\nproperty('map(f)(m) = swap(mapRej(f)(swap(m)))', anyFuture, function (m){\n  return eq(map(f)(m))(swap(mapRej(f)(swap(m))));\n});\n\nproperty('rejectAfter(1)(x) = reject(x)', any, function (x){\n  return eq(rejectAfter(1)(x))(reject(x));\n});\n"
  },
  {
    "path": "test/types/map.test-d.ts",
    "content": "import {expectType} from 'tsd';\n\nimport * as fl from '../../index.js';\n\nconst resolved = fl.resolve (42);\nconst rejected = fl.reject ('uh-oh');\n\nconst resolvedPar = fl.Par (resolved);\nconst rejectedPar = fl.Par (rejected);\n\n// Standard usage on Future instances.\nexpectType<fl.FutureInstance<never, string>> (fl.map (String) (resolved));\nexpectType<fl.FutureInstance<string, string>> (fl.map (String) (rejected));\n\n// Standard usage on ConcurrentFuture instances.\nexpectType<fl.ConcurrentFutureInstance<never, string>> (fl.map (String) (resolvedPar));\nexpectType<fl.ConcurrentFutureInstance<string, string>> (fl.map (String) (rejectedPar));\n\n// Usage with pipe on Future instances (https://git.io/JLx3F).\nexpectType<fl.FutureInstance<never, string>> (resolved .pipe (fl.map (String)));\nexpectType<fl.FutureInstance<string, string>> (rejected .pipe (fl.map (String)));\n\n// Function parameter inference from the second argument in a pipe (https://git.io/JLxsX).\nexpectType<fl.FutureInstance<never, number>> (resolved .pipe (fl.map (x => x)));\nexpectType<fl.FutureInstance<string, never>> (rejected .pipe (fl.map (x => x)));\n"
  },
  {
    "path": "test/unit/0.debug.js",
    "content": "import {eq, error, assertStackTrace, K, I, test} from '../util/util.js';\nimport {\n  debugMode,\n  debug,\n  captureContext,\n  captureApplicationContext,\n  captureStackTraceFallback,\n} from '../../src/internal/debug.js';\nimport {nil} from '../../src/internal/list.js';\n\ntest('debug does nothing but return its first argument by default', function (done){\n  debugMode(false);\n  eq(debug(null, done, error), null);\n  eq(debug(42, done, error), 42);\n  done();\n});\n\ntest('debug runs the given function when debugMode was enabled', function (){\n  var guard = {};\n  debugMode(true);\n  eq(debug(null, K(guard)), guard);\n  eq(debug(null, I, guard), guard);\n});\n\ntest('captureContext returns previous when debugMode is off', function (){\n  debugMode(false);\n  var previous = {};\n  var x = captureContext(previous, 2, 3);\n  eq(x, previous);\n});\n\ntest('captureContext returns a list with a context object', function (){\n  debugMode(true);\n  var prev = nil;\n  var tag = 'hello world';\n  var expectedName = ' from ' + tag + ':';\n  var ctx = captureContext(prev, tag);\n  eq(typeof ctx, 'object');\n  eq(ctx.tail, prev);\n  eq(typeof ctx.head, 'object');\n  eq(ctx.head.tag, tag);\n  eq(ctx.head.name, expectedName);\n  assertStackTrace(expectedName, ctx.head.stack);\n});\n\ntest('captureApplicationContext returns previous when debugMode is off', function (){\n  debugMode(false);\n  var previous = {};\n  var x = captureApplicationContext(previous, 1, Math.sqrt);\n  eq(x, previous);\n});\n\ntest('captureApplicationContext returns a list with a context object', function (){\n  debugMode(true);\n  var prev = nil;\n  var expectedName = ' from first application of sqrt:';\n  var ctx = captureApplicationContext(prev, 1, Math.sqrt);\n  eq(typeof ctx, 'object');\n  eq(ctx.tail, prev);\n  eq(typeof ctx.head, 'object');\n  eq(ctx.head.tag, 'first application of sqrt');\n  eq(ctx.head.name, expectedName);\n  assertStackTrace(expectedName, ctx.head.stack);\n});\n\ntest('captureStackTraceFallback assigns a stack trace to the given object', function (){\n  debugMode(false);\n  var o = {name: 'test'};\n  captureStackTraceFallback(o);\n  assertStackTrace('test', o.stack);\n});\n"
  },
  {
    "path": "test/unit/0.error.js",
    "content": "import {eq, assertStackTrace, error as mockError, noop, test} from '../util/util.js';\nimport {mock} from '../util/futures.js';\nimport {namespace, name, version} from '../../src/internal/const.js';\nimport {nil, cons, cat} from '../../src/internal/list.js';\nimport {\n  error,\n  typeError,\n  invalidArgument,\n  invalidContext,\n  invalidArity,\n  invalidFutureArgument,\n  wrapException,\n  contextToStackTrace,\n} from '../../src/internal/error.js';\n\nfunction args (){\n  return arguments;\n}\n\ntest('error constructs an Error', function (){\n  eq(error('hello'), new Error('hello'));\n});\n\ntest('typeError constructs a TypeError', function (){\n  eq(typeError('hello'), new TypeError('hello'));\n});\n\ntest('invalidArgument constructs a TypeError', function (){\n  eq(invalidArgument('Test', 1, 'foo', 'bar'), new TypeError(\n    'Test() expects its second argument to foo.\\n  Actual: \"bar\" :: String'\n  ));\n});\n\ntest('invalidContext constructs a TypeError', function (){\n  eq(invalidContext('Test', 'foo'), new TypeError(\n    'Test() was invoked outside the context of a Future. You might want ' +\n    'to use a dispatcher instead\\n  Called on: \"foo\"'\n  ));\n});\n\ntest('invalidArity constructs a TypeError', function (){\n  eq(invalidArity(noop, args('one', 2, 3, 4, 5, 6)), new TypeError(\n    'noop() expects to be called with a single argument per invocation\\n' +\n    '  Saw: 6 arguments\\n' +\n    '  First: \"one\" :: String\\n' +\n    '  Second: 2 :: Number\\n' +\n    '  Third: 3 :: Number\\n' +\n    '  Fourth: 4 :: Number\\n' +\n    '  Fifth: 5 :: Number\\n' +\n    '  Argument 6: 6 :: Number'\n  ));\n});\n\nvar mockType = function (identifier){\n  return {'@@type': identifier, '@@show': function (){\n    return 'mockType(\"' + identifier + '\")';\n  }};\n};\n\ntest('invalidFutureArgument warns us when nothing seems wrong', function (){\n  var actual = invalidFutureArgument('Foo', 0, mockType(namespace + '/' + name + '@' + version));\n  eq(actual, new TypeError(\n    'Foo() expects its first argument to be a valid Future.\\n' +\n    'Nothing seems wrong. Contact the Fluture maintainers.\\n' +\n    '  Actual: mockType(\"fluture/Future@5\") :: Future'\n  ));\n});\n\ntest('invalidFutureArgument warns us about Futures from other sources', function (){\n  var actual = invalidFutureArgument('Foo', 0, mockType('bobs-tinkershop/' + name + '@' + version));\n  eq(actual, new TypeError(\n    'Foo() expects its first argument to be a valid Future.\\n' +\n    'The Future was not created by fluture. ' +\n    'Make sure you transform other Futures to fluture Futures. ' +\n    'Got a Future from bobs-tinkershop.\\n' +\n    '  See: https://github.com/fluture-js/Fluture#casting-futures\\n' +\n    '  Actual: mockType(\"bobs-tinkershop/Future@5\") :: Future'\n  ));\n});\n\ntest('invalidFutureArgument warns us about Futures from unnamed sources', function (){\n  var actual = invalidFutureArgument('Foo', 0, mockType(name));\n  eq(actual, new TypeError(\n    'Foo() expects its first argument to be a valid Future.\\n' +\n    'The Future was not created by fluture. ' +\n    'Make sure you transform other Futures to fluture Futures. ' +\n    'Got an unscoped Future.\\n' +\n    '  See: https://github.com/fluture-js/Fluture#casting-futures\\n' +\n    '  Actual: mockType(\"Future\") :: Future'\n  ));\n});\n\ntest('invalidFutureArgument warns about older versions', function (){\n  var actual = invalidFutureArgument('Foo', 0, mockType(namespace + '/' + name + '@' + (version - 1)));\n  eq(actual, new TypeError(\n    'Foo() expects its first argument to be a valid Future.\\n' +\n    'The Future was created by an older version of fluture. ' +\n    'This means that one of the sources which creates Futures is outdated. ' +\n    'Update this source, or transform its created Futures to be compatible.\\n' +\n    '  See: https://github.com/fluture-js/Fluture#casting-futures\\n' +\n    '  Actual: mockType(\"fluture/Future@4\") :: Future'\n  ));\n});\n\ntest('invalidFutureArgument warns about newer versions', function (){\n  var actual = invalidFutureArgument('Foo', 0, mockType(namespace + '/' + name + '@' + (version + 1)));\n  eq(actual, new TypeError(\n    'Foo() expects its first argument to be a valid Future.\\n' +\n    'The Future was created by a newer version of fluture. ' +\n    'This means that one of the sources which creates Futures is outdated. ' +\n    'Update this source, or transform its created Futures to be compatible.\\n' +\n    '  See: https://github.com/fluture-js/Fluture#casting-futures\\n' +\n    '  Actual: mockType(\"fluture/Future@6\") :: Future'\n  ));\n});\n\ntest('wrapException converts any value to an Error', function (){\n  var evilValue = {};\n  evilValue.__defineGetter__('name', () => { throw new Error });\n  evilValue.__defineGetter__('stack', () => { throw new Error });\n\n  eq(wrapException(new Error('test'), mock) instanceof Error, true);\n  eq(wrapException(new TypeError('test'), mock) instanceof Error, true);\n  eq(wrapException('test', mock) instanceof Error, true);\n  eq(wrapException({foo: 'bar'}, mock) instanceof Error, true);\n  eq(wrapException(evilValue, mock) instanceof Error, true);\n  eq(wrapException(null, mock) instanceof Error, true);\n  eq(wrapException({crash: null}, mock) instanceof Error, true);\n});\n\ntest('wrapException creates an error which encompasses the given error', function (){\n  var m = Object.create(mock);\n  m.context = cons({stack: 'hello'}, cons({stack: 'world'}, nil));\n  var e = wrapException(mockError, m);\n  eq(e.name, 'Error');\n  eq(e.message, mockError.message);\n  eq(e.reason, mockError);\n  eq(e.context, m.context);\n  eq(e.future, m);\n  assertStackTrace('Error: Intentional error for unit testing', e.stack);\n\n  var m2 = Object.create(mock);\n  m2.context = cons({stack: 'foo'}, cons({stack: 'bar'}, nil));\n  var e2 = wrapException(e, m2);\n  eq(e2.name, 'Error');\n  eq(e2.message, mockError.message);\n  eq(e2.reason, mockError);\n  eq(e2.context, cat(m.context, m2.context));\n  eq(e2.future, m);\n  assertStackTrace('Error: Intentional error for unit testing', e2.stack);\n});\n\ntest('contextToStackTrace converts a nested context structure to a stack trace', function (){\n  eq(contextToStackTrace(cons({stack: 'hello'}, cons({stack: 'world'}, nil))), '\\nhello\\nworld');\n});\n"
  },
  {
    "path": "test/unit/0.iteration.js",
    "content": "import chai from 'chai';\nimport {test} from '../util/util.js';\nimport {Next, Done, isIteration} from '../../src/internal/iteration.js';\n\nvar expect = chai.expect;\n\ntest('Next', function (){\n  var actual = Next(42);\n  expect(isIteration(actual)).to.equal(true);\n  expect(actual.done).to.equal(false);\n  expect(actual.value).to.equal(42);\n});\n\ntest('Done', function (){\n  var actual = Done(42);\n  expect(isIteration(actual)).to.equal(true);\n  expect(actual.done).to.equal(true);\n  expect(actual.value).to.equal(42);\n});\n"
  },
  {
    "path": "test/unit/0.list.js",
    "content": "import {eq, test} from '../util/util.js';\nimport {nil, cons, reverse, cat} from '../../src/internal/list.js';\n\ntest('reverse', function (){\n  eq(reverse(nil), nil);\n  eq(reverse(cons('a', nil)), cons('a', nil));\n  eq(reverse(cons('a', cons('b', nil))), cons('b', cons('a', nil)));\n  eq(reverse(cons('a', cons('b', cons('c', nil)))), cons('c', cons('b', cons('a', nil))));\n});\n\ntest('cat', function (){\n  eq(cat(nil, nil), nil);\n  eq(cat(cons('a', nil), nil), cons('a', nil));\n  eq(cat(nil, cons('a', nil)), cons('a', nil));\n  eq(\n    cat(cons('a', cons('b', nil)), cons('c', cons('d', nil))),\n    cons('a', cons('b', cons('c', cons('d', nil))))\n  );\n});\n"
  },
  {
    "path": "test/unit/0.predicates.js",
    "content": "import chai from 'chai';\nimport {test, eq, noop} from '../util/util.js';\nimport Future from '../../index.js';\nimport * as util from '../../src/internal/predicates.js';\n\nvar expect = chai.expect;\n\ntest('isThenable', function (){\n  var ps = [\n    Promise.resolve(1),\n    new Promise(noop),\n    {then: noop},\n    {then (a){ return a }},\n    {then (a, b){ return b }},\n  ];\n\n  var values = [NaN, 1, true, undefined, null, [], {}];\n  var xs = values.concat([noop]).concat(values.map(function (x){ return ({then: x}) }));\n\n  ps.forEach(function (p){ return expect(util.isThenable(p)).to.equal(true) });\n  xs.forEach(function (x){ return expect(util.isThenable(x)).to.equal(false) });\n});\n\ntest('isFunction', function (){\n  var xs = [NaN, 1, true, undefined, null, [], {}];\n  eq(util.isFunction(function (){}), true);\n  eq(util.isFunction(Future), true);\n  xs.forEach(function (x){ return expect(util.isFunction(x)).to.equal(false) });\n});\n\ntest('isUnsigned', function (){\n  var is = [1, 2, 999999999999999, Infinity];\n  var xs = [NaN, 0, -0, -1, -999999999999999, -Infinity, '1', [], {}];\n  is.forEach(function (i){ return expect(util.isUnsigned(i)).to.equal(true) });\n  xs.forEach(function (x){ return expect(util.isUnsigned(x)).to.equal(false) });\n});\n\ntest('isObject', function (){\n  function O (){}\n  var os = [{}, {foo: 1}, Object.create(null), new O, []];\n  var xs = [1, true, NaN, null, undefined, ''];\n  os.forEach(function (i){ return expect(util.isObject(i)).to.equal(true) });\n  xs.forEach(function (x){ return expect(util.isObject(x)).to.equal(false) });\n});\n\ntest('isIterator', function (){\n  var is = [{next (){}}, {next (x){ return x }}, (function*(){}())];\n  var xs = [1, true, NaN, null, undefined, '', {}, {next: 1}];\n  is.forEach(function (i){ return expect(util.isIterator(i)).to.equal(true) });\n  xs.forEach(function (x){ return expect(util.isIterator(x)).to.equal(false) });\n});\n"
  },
  {
    "path": "test/unit/0.utils.js",
    "content": "import chai from 'chai';\nimport {test} from '../util/util.js';\nimport {setImmediateFallback} from '../../src/internal/utils.js';\n\nvar expect = chai.expect;\n\ntest('setImmediateFallback', function (done){\n  var t = setTimeout(done, 25, new Error('Time is up'));\n  setImmediateFallback(function (x){\n    expect(x).to.equal(42);\n    clearTimeout(t);\n    done();\n  }, 42);\n});\n"
  },
  {
    "path": "test/unit/1.future.js",
    "content": "import Future from '../../index.js';\nimport {noop, eq, assertCrashed, assertResolved, error, assertValidFuture, test} from '../util/util.js';\nimport {testFunction, functionArg} from '../util/props.js';\n\ntestFunction('Future', Future, [functionArg], assertValidFuture);\n\ntest('crashes when the computation throws an error', function (){\n  var m = Future(function (){ throw error });\n  return assertCrashed(m, error);\n});\n\ntest('crashes when the computation returns nonsense', function (){\n  var m = Future(function (){ return 1 });\n  return assertCrashed(m, new TypeError(\n    'The computation was expected to return a nullary cancellation function\\n' +\n    '  Actual: 1'\n  ));\n});\n\ntest('does not crash when the computation returns a nullary function', function (){\n  return new Promise((res, rej) => {\n    var m = Future(function (){ return function (){} });\n    m._interpret(rej, noop, noop);\n    setTimeout(res, 20);\n  });\n});\n\ntest('settles using the last synchronously called continuation', function (){\n  var actual = Future(function (rej, res){\n    res(1);\n    rej(2);\n    res(3);\n    return noop;\n  });\n  return assertResolved(actual, 3);\n});\n\ntest('settles using the first asynchronously called continuation', function (){\n  var actual = Future(function (rej, res){\n    setTimeout(res, 10, 1);\n    setTimeout(res, 50, 2);\n    return noop;\n  });\n  return assertResolved(actual, 1);\n});\n\ntest('stops continuations from being called after cancellation', function (){\n  return new Promise((res, rej) => {\n    const fail = () => rej(error);\n    Future(function (rej, res){\n      setTimeout(res, 20, 1);\n      setTimeout(rej, 20, 1);\n      return noop;\n    })\n    ._interpret(rej, fail, fail)();\n    setTimeout(res, 25);\n  });\n});\n\ntest('cannot continue during cancellation (#216)', function (){\n  return new Promise((res, rej) => {\n    const fail = () => rej(error);\n    Future(function (rej, res){\n      return function (){\n        rej();\n        res();\n      };\n    })\n    ._interpret(rej, fail, fail)();\n    setTimeout(res, 20);\n  });\n});\n\ntest('stops cancellation from being called after continuations', function (){\n  return new Promise((res, rej) => {\n    var m = Future(function (rej, res){\n      res(1);\n      return function (){ rej(error) };\n    });\n    var cancel = m._interpret(rej, noop, noop);\n    cancel();\n    res();\n  });\n});\n\ntest('can be cast to String', function (){\n  var m = Future(function (rej, res){ res() });\n  eq(m.toString(), 'Future (function (rej, res){ res() })');\n});\n"
  },
  {
    "path": "test/unit/1.is-future.js",
    "content": "import {isFuture} from '../../index.js';\nimport {property, anyFuture, anyNonFuture} from '../util/props.js';\n\nproperty('returns true about Futures', anyFuture, function (value){\n  return isFuture(value) === true;\n});\n\nproperty('returns false about everything else', anyNonFuture, function (value){\n  return isFuture(value) === false;\n});\n"
  },
  {
    "path": "test/unit/1.is-never.js",
    "content": "import {isNever, never} from '../../index.js';\nimport {any, property} from '../util/props.js';\nimport {eq, test} from '../util/util.js';\n\ntest('returns true about never', function (){\n  eq(isNever(never), true);\n});\n\nproperty('returns false about everything else', any, function (value){\n  return isNever(value) === false;\n});\n"
  },
  {
    "path": "test/unit/1.never.js",
    "content": "import {never} from '../../index.js';\nimport {assertValidFuture, noop, eq, test} from '../util/util.js';\n\ntest('is a Future', function (){\n  assertValidFuture(never);\n});\n\ntest('does nothing and returns a noop cancel function', function (){\n  var m = never;\n  var cancel = m._interpret(noop, noop, noop);\n  cancel();\n});\n\ntest('returns the code to create the Never', function (){\n  var m = never;\n  eq(m.toString(), 'never');\n});\n"
  },
  {
    "path": "test/unit/1.pipe.js",
    "content": "import {mock} from '../util/futures.js';\nimport {eq, throws, test} from '../util/util.js';\n\ntest('throws when not given a function', function (){\n  throws(function (){\n    mock.pipe(42);\n  }, new TypeError(\n    'Future#pipe() expects its first argument to be a Function.\\n' +\n    '  Actual: 42 :: Number'\n  ));\n});\n\ntest('transforms the Future using the given function', function (){\n  eq(mock.pipe(String), '(util.mock)');\n});\n"
  },
  {
    "path": "test/unit/2.done.js",
    "content": "import {done} from '../../index.js';\nimport {testFunction, functionArg, resolvedFutureArg} from '../util/props.js';\nimport {eq, isFunction, test} from '../util/util.js';\nimport {rejected, resolved} from '../util/futures.js';\n\ntestFunction('done', done, [functionArg, resolvedFutureArg], isFunction);\n\ntest('passes the rejection value as first parameter', function (testDone){\n  done(function (x, y){\n    eq(x, 'rejected');\n    eq(y, undefined);\n    testDone();\n  })(rejected);\n});\n\ntest('passes the resolution value as second parameter', function (testDone){\n  done(function (x, y){\n    eq(x, null);\n    eq(y, 'resolved');\n    testDone();\n  })(resolved);\n});\n"
  },
  {
    "path": "test/unit/2.extract-left.js",
    "content": "import {extractLeft} from '../../index.js';\nimport {testFunction, futureArg} from '../util/props.js';\nimport {isArray, test} from '../util/util.js';\nimport {mock} from '../util/futures.js';\n\ntestFunction('extractLeft', extractLeft, [futureArg], isArray);\n\ntest('dispatches to #extractLeft', function (done){\n  var m = Object.create(mock);\n  m.extractLeft = done;\n  extractLeft(m);\n});\n"
  },
  {
    "path": "test/unit/2.extract-right.js",
    "content": "import {extractRight} from '../../index.js';\nimport {testFunction, futureArg} from '../util/props.js';\nimport {isArray, test} from '../util/util.js';\nimport {mock} from '../util/futures.js';\n\ntestFunction('extractRight', extractRight, [futureArg], isArray);\n\ntest('dispatches to #extractRight', function (done){\n  var m = Object.create(mock);\n  m.extractRight = done;\n  extractRight(m);\n});\n"
  },
  {
    "path": "test/unit/2.fork-catch.js",
    "content": "import {forkCatch} from '../../index.js';\nimport {testFunction, functionArg, futureArg} from '../util/props.js';\nimport {eq, isFunction, error, noop, test} from '../util/util.js';\nimport {crashed, rejected, resolved} from '../util/futures.js';\n\ntestFunction('forkCatch', forkCatch, [functionArg, functionArg, functionArg, futureArg], isFunction);\n\ntest('calls the first continuation with the crash exception', function (done){\n  function assertCrash (x){\n    eq(x, error);\n    done();\n  }\n  forkCatch(assertCrash)(noop)(noop)(crashed);\n});\n\ntest('calls the second continuation with the rejection reason', function (done){\n  function assertRejection (x){\n    eq(x, 'rejected');\n    done();\n  }\n  forkCatch(noop)(assertRejection)(noop)(rejected);\n});\n\ntest('calls the third continuation with the resolution value', function (done){\n  function assertResolution (x){\n    eq(x, 'resolved');\n    done();\n  }\n  forkCatch(noop)(noop)(assertResolution)(resolved);\n});\n"
  },
  {
    "path": "test/unit/2.fork.js",
    "content": "import {fork} from '../../index.js';\nimport {testFunction, functionArg, futureArg} from '../util/props.js';\nimport {eq, isFunction, error, noop, itRaises, test} from '../util/util.js';\nimport {crashed, rejected, resolved} from '../util/futures.js';\n\ntestFunction('fork', fork, [functionArg, functionArg, futureArg], isFunction);\n\nitRaises('the crash exception', function (){\n  fork(noop)(noop)(crashed);\n}, error);\n\ntest('calls the first continuation with the rejection reason', function (done){\n  function assertRejection (x){\n    eq(x, 'rejected');\n    done();\n  }\n  fork(assertRejection)(noop)(rejected);\n});\n\ntest('calls the second continuation with the resolution value', function (done){\n  function assertResolution (x){\n    eq(x, 'resolved');\n    done();\n  }\n  fork(noop)(assertResolution)(resolved);\n});\n"
  },
  {
    "path": "test/unit/2.promise.js",
    "content": "import {promise} from '../../index.js';\nimport {testFunction, futureArg} from '../util/props.js';\nimport {noop, isThenable, eq, error, test} from '../util/util.js';\nimport {crashed, rejected, resolved} from '../util/futures.js';\n\nprocess.addListener('unhandledRejection', noop);\n\ntestFunction('promise', promise, [futureArg], isThenable);\n\ntest('returns a Promise', function (){\n  var actual = promise(resolved);\n  eq(actual instanceof Promise, true);\n});\n\ntest('rejects if the Future crashes', function (){\n  return promise(crashed).then(\n    function (){ throw new Error('It resolved') },\n    function (x){ eq(x, error) }\n  );\n});\n\ntest('rejects if the Future rejects', function (){\n  return promise(rejected).then(\n    function (){ throw new Error('It resolved') },\n    function (x){ eq(x, 'rejected') }\n  );\n});\n\ntest('resolves if the Future resolves', function (){\n  return promise(resolved).then(\n    function (x){ eq(x, 'resolved') }\n  );\n});\n"
  },
  {
    "path": "test/unit/2.value.js",
    "content": "import show from 'sanctuary-show';\nimport {value} from '../../index.js';\nimport {testFunction, functionArg, resolvedFutureArg} from '../util/props.js';\nimport {eq, isFunction, noop, itRaises, error, test} from '../util/util.js';\nimport {crashed, rejected, resolved} from '../util/futures.js';\n\ntestFunction('value', value, [functionArg, resolvedFutureArg], isFunction);\n\nitRaises('when the Future crashes', function (){\n  value(noop)(rejected);\n}, error);\n\nitRaises('when the Future rejects', function (){\n  value(noop)(crashed);\n}, new Error(\n  'Future#value was called on a rejected Future\\n' +\n  '  Rejection: \"rejected\"\\n' +\n  '  Future: ' + show(rejected)\n));\n\ntest('calls the continuation with the resolution value', function (done){\n  value(function (x){\n    eq(x, 'resolved');\n    done();\n  })(resolved);\n});\n"
  },
  {
    "path": "test/unit/3.after.js",
    "content": "import {after, never} from '../../index.js';\nimport {eq, assertValidFuture, assertResolved, test, error} from '../util/util.js';\nimport {testFunction, positiveIntegerArg, anyArg} from '../util/props.js';\n\ntestFunction('after', after, [positiveIntegerArg, anyArg], assertValidFuture);\n\ntest('returns Never when given Infinity', function (){\n  eq(after(Infinity)(1), never);\n});\n\ntest('resolves with the given value', function (){\n  return assertResolved(after(20)(1), 1);\n});\n\ntest('clears its internal timeout when cancelled', function (done){\n  const fail = () => done(error);\n  after(20)(1)._interpret(done, fail, fail)();\n  setTimeout(done, 25);\n});\n\ntest('returns array with the value', function (){\n  eq(after(20)(1).extractRight(), [1]);\n});\n\ntest('returns the code to create the After when cast to String', function (){\n  eq(after(20)(1).toString(), 'after (20) (1)');\n});\n"
  },
  {
    "path": "test/unit/3.attempt-p.js",
    "content": "/* eslint prefer-promise-reject-errors: 0 */\n\nimport chai from 'chai';\nimport {attemptP, map, mapRej} from '../../index.js';\nimport {assertCrashed, assertRejected, assertResolved, assertValidFuture, error, noop, test} from '../util/util.js';\nimport {testFunction, functionArg} from '../util/props.js';\n\nvar expect = chai.expect;\n\ntestFunction('encaseP', attemptP, [functionArg], assertValidFuture);\n\ntest('crashes when the Promise generator throws', function (){\n  var m = attemptP(function (){ throw error });\n  return assertCrashed(m, error);\n});\n\ntest('crashes when the Promise generator does not return a Promise', function (){\n  var m = attemptP(noop);\n  return assertCrashed(m, new TypeError(\n    'encaseP() expects the function it\\'s given to return a Promise/Thenable\\n' +\n    '  Actual: undefined\\n' +\n    '  From calling: function (){}\\n' +\n    '  With: undefined'\n  ));\n});\n\ntest('resolves with the resolution value of the returned Promise', function (){\n  var actual = attemptP(function (){ return Promise.resolve(1) });\n  return assertResolved(actual, 1);\n});\n\ntest('rejects with rejection reason of the returned Promise', function (){\n  var actual = attemptP(function (){ return Promise.reject(error) });\n  return assertRejected(actual, error);\n});\n\ntest('ensures no resolution happens after cancel', function (done){\n  const fail = () => done(error);\n  var actual = attemptP(function (){ return Promise.resolve(1) });\n  actual._interpret(done, fail, fail)();\n  setTimeout(done, 20);\n});\n\ntest('ensures no rejection happens after cancel', function (done){\n  const fail = () => done(error);\n  var actual = attemptP(function (){ return Promise.reject(1) });\n  actual._interpret(done, fail, fail)();\n  setTimeout(done, 20);\n});\n\ntest('crashes with errors that occur in rejection continuation', function (){\n  var m = map(function (){ throw error })(attemptP(function (){ return Promise.resolve(1) }));\n  return assertCrashed(m, error);\n});\n\ntest('crashes with errors that occur in resolution continuation', function (){\n  var m = mapRej(function (){ throw error })(attemptP(function (){ return Promise.reject(1) }));\n  return assertCrashed(m, error);\n});\n\ntest('returns the code to create the Future when cast to String', function (){\n  var f = function (){ return Promise.resolve(42) };\n  var m = attemptP(f);\n  expect(m.toString()).to.equal('encaseP (' + f.toString() + ') (undefined)');\n});\n"
  },
  {
    "path": "test/unit/3.attempt.js",
    "content": "import chai from 'chai';\nimport {attempt, map} from '../../index.js';\nimport {test, assertCrashed, assertRejected, assertResolved, assertValidFuture, error} from '../util/util.js';\nimport {testFunction, functionArg} from '../util/props.js';\n\nvar expect = chai.expect;\n\ntestFunction('encase', attempt, [functionArg], assertValidFuture);\n\ntest('resolves with the return value of the function', function (){\n  var actual = attempt(function (){ return 1 });\n  return assertResolved(actual, 1);\n});\n\ntest('rejects with the exception thrown by the function', function (){\n  var actual = attempt(function (){ throw error });\n  return assertRejected(actual, error);\n});\n\ntest('does not swallow errors from subsequent maps and such', function (){\n  var m = map(function (){ throw error })(attempt(function (x){ return x }));\n  return assertCrashed(m, error);\n});\n\ntest('returns the code to create the Future', function (){\n  var f = function (){};\n  var m = attempt(f);\n  expect(m.toString()).to.equal('encase (' + f.toString() + ') (undefined)');\n});\n"
  },
  {
    "path": "test/unit/3.cache.js",
    "content": "import chai from 'chai';\nimport {Future, cache, resolve, reject, after, rejectAfter} from '../../index.js';\nimport {Crashed, Rejected, Resolved} from '../../src/cache.js';\nimport {test, assertCrashed, assertRejected, assertResolved, assertValidFuture, error, noop, onceOrError} from '../util/util.js';\nimport * as F from '../util/futures.js';\nimport {testFunction, futureArg} from '../util/props.js';\n\nvar expect = chai.expect;\n\ntestFunction('cache', cache, [futureArg], assertValidFuture);\n\ntest('interpret crashes if the underlying computation crashes', function (){\n  return assertCrashed(cache(F.crashed), error);\n});\n\ntest('interpret resolves with the resolution value resolve the given Future', function (){\n  return assertResolved(cache(resolve(1)), 1);\n});\n\ntest('interpret rejects with the rejection reason resolve the given Future', function (){\n  return assertRejected(cache(reject(error)), error);\n});\n\ntest('interpret only interprets its given Future once', function (){\n  var m = cache(Future(onceOrError(function (rej, res){ res(1); return noop })));\n  m._interpret(noop, noop, noop);\n  m._interpret(noop, noop, noop);\n  return assertResolved(m, 1);\n});\n\ntest('interpret crashes all consumers once a delayed crash happens', function (){\n  var m = cache(F.crashedSlow);\n  var a = assertCrashed(m, error);\n  var b = assertCrashed(m, error);\n  var c = assertCrashed(m, error);\n  return Promise.all([a, b, c]);\n});\n\ntest('interpret resolves all consumers once a delayed resolution happens', function (){\n  var m = cache(after(200)(1));\n  var a = assertResolved(m, 1);\n  var b = assertResolved(m, 1);\n  var c = assertResolved(m, 1);\n  return Promise.all([a, b, c]);\n});\n\ntest('interpret rejects all consumers once a delayed rejection happens', function (){\n  var m = cache(rejectAfter(20)(error));\n  var a = assertRejected(m, error);\n  var b = assertRejected(m, error);\n  var c = assertRejected(m, error);\n  return Promise.all([a, b, c]);\n});\n\ntest('interpret crashes all new consumers after a crash happened', function (){\n  var m = cache(F.crashed);\n  m._interpret(noop, noop, noop);\n  return assertCrashed(m, error);\n});\n\ntest('interpret rejects all new consumers after a rejection happened', function (){\n  var m = cache(reject('err'));\n  m._interpret(noop, noop, noop);\n  return assertRejected(m, 'err');\n});\n\ntest('interpret it iinterpret nterprets the internal Future again when interpreted after having been cancelled', function (done){\n  var m = cache(Future(function (rej, res){\n    var o = {cancelled: false};\n    var id = setTimeout(res, 20, o);\n    return function (){ o.cancelled = true; clearTimeout(id) };\n  }));\n  var clear = m._interpret(done, noop, noop);\n  setTimeout(function (){\n    clear();\n    m._interpret(done, noop, function (v){ return (expect(v).to.have.property('cancelled', false), done()) });\n  }, 10);\n});\n\ntest('interpret does not reset when one resolve multiple listeners is cancelled', function (done){\n  var m = cache(Future(function (rej, res){\n    setTimeout(res, 5, 1);\n    return function (){ return done(new Error('Reset happened')) };\n  }));\n  var cancel = m._interpret(done, noop, noop);\n  m._interpret(done, noop, noop);\n  cancel();\n  setTimeout(done, 20);\n});\n\ntest('interpret does not change when cancelled after settled', function (done){\n  var m = cache(Future(function (rej, res){\n    res(1);\n    return function (){ return done(new Error('Cancelled after settled')) };\n  }));\n  var cancel = m._interpret(done, noop, noop);\n  setTimeout(function (){\n    cancel();\n    done();\n  }, 5);\n});\n\ntest('crash sets state to Crashed', function (){\n  var m = cache(Future(noop));\n  m.crash(1);\n  expect(m._state).to.equal(Crashed);\n});\n\ntest('crash does nothing when state is resolved', function (){\n  var m = cache(Future(noop));\n  m.resolve(1);\n  m.crash(2);\n  expect(m._state).to.equal(Resolved);\n});\n\ntest('resolve does nothing when state is rejected', function (){\n  var m = cache(Future(noop));\n  m.reject(1);\n  m.resolve(2);\n  expect(m._state).to.equal(Rejected);\n});\n\ntest('reject does nothing when state is resolved', function (){\n  var m = cache(Future(noop));\n  m.resolve(1);\n  m.reject(2);\n  expect(m._state).to.equal(Resolved);\n});\n\ntest('_addToQueue does nothing when state is settled', function (){\n  var m = cache(Future(noop));\n  m.resolve(1);\n  m._addToQueue(noop, noop);\n  expect(m._queued).to.equal(0);\n});\n\ntest('_drainQueue is idempotent', function (){\n  var m = cache(resolve(1));\n  m._drainQueue();\n  m._drainQueue();\n  m._interpret(noop, noop, noop);\n  m._drainQueue();\n  m._drainQueue();\n});\n\ntest('run is idempotent', function (){\n  var m = cache(resolve(1));\n  m.run();\n  m.run();\n});\n\ntest('reset is idempotent', function (){\n  var m = cache(resolve(1));\n  m.reset();\n  m._interpret(noop, noop, noop);\n  m.reset();\n  m.reset();\n});\n\ntest('reset cancels the underlying computation', function (done){\n  var m = cache(Future(function (){ return function (){ done() } }));\n  m.run();\n  m.reset();\n});\n\ntest('returns the code to create the Cache when cast to String', function (){\n  var m = cache(resolve(1));\n  var s = 'cache (resolve (1))';\n  expect(m.toString()).to.equal(s);\n});\n\ntest('extractLeft returns empty array for cold Cacheds', function (){\n  expect(cache(reject(1)).extractLeft()).to.deep.equal([]);\n});\n\ntest('extractLeft returns array with reason for rejected Cacheds', function (){\n  var m = cache(reject(1));\n  m.run();\n  expect(m.extractLeft()).to.deep.equal([1]);\n});\n\ntest('extractRight returns empty array for cold Cacheds', function (){\n  expect(cache(resolve(1)).extractRight()).to.deep.equal([]);\n});\n\ntest('extractRight returns array with value for resolved Cacheds', function (){\n  var m = cache(resolve(1));\n  m.run();\n  expect(m.extractRight()).to.deep.equal([1]);\n});\n"
  },
  {
    "path": "test/unit/3.crash.js",
    "content": "import {crash} from '../../src/future.js';\nimport {eq, assertIsFuture, assertCrashed, test} from '../util/util.js';\nimport {testFunction, anyArg} from '../util/props.js';\n\ntestFunction('crash', crash, [anyArg], assertIsFuture);\n\ntest('returns a crashed Future', function (){\n  return assertCrashed(crash(1), 1);\n});\n\ntest('can be shown as string', function (){\n  eq(crash(1).toString(), 'crash (1)');\n});\n"
  },
  {
    "path": "test/unit/3.encase-p.js",
    "content": "/* eslint prefer-promise-reject-errors: 0 */\n\nimport chai from 'chai';\nimport {encaseP} from '../../index.js';\nimport {test, assertCrashed, assertRejected, assertResolved, assertValidFuture, error, noop} from '../util/util.js';\nimport {testFunction, functionArg, anyArg} from '../util/props.js';\n\nvar expect = chai.expect;\n\ntestFunction('encaseP', encaseP, [functionArg, anyArg], assertValidFuture);\n\ntest('crashes when the Promise generator throws', function (){\n  var m = encaseP(function (){ throw error })(1);\n  return assertCrashed(m, error);\n});\n\ntest('crashes when the Promise generator does not return a Promise', function (){\n  var m = encaseP(noop)(1);\n  return assertCrashed(m, new TypeError(\n    'encaseP() expects the function it\\'s given to return a Promise/Thenable\\n' +\n    '  Actual: undefined\\n' +\n    '  From calling: function (){}\\n' +\n    '  With: 1'\n  ));\n});\n\ntest('resolves with the resolution value of the returned Promise', function (){\n  var actual = encaseP(function (x){ return Promise.resolve(x + 1) })(1);\n  return assertResolved(actual, 2);\n});\n\ntest('rejects with rejection reason of the returned Promise', function (){\n  var actual = encaseP(function (){ return Promise.reject(error) })(1);\n  return assertRejected(actual, error);\n});\n\ntest('ensures no resolution happens after cancel', function (done){\n  const fail = () => done(error);\n  var actual = encaseP(function (x){ return Promise.resolve(x + 1) })(1);\n  actual._interpret(done, fail, fail)();\n  setTimeout(done, 20);\n});\n\ntest('ensures no rejection happens after cancel', function (done){\n  const fail = () => done(error);\n  var actual = encaseP(function (x){ return Promise.reject(x + 1) })(1);\n  actual._interpret(done, fail, fail)();\n  setTimeout(done, 20);\n});\n\ntest('returns the code to create the Future when cast to String', function (){\n  var f = function (a){ return Promise.resolve(a) };\n  var m = encaseP(f)(null);\n  expect(m.toString()).to.equal('encaseP (' + f.toString() + ') (null)');\n});\n"
  },
  {
    "path": "test/unit/3.encase.js",
    "content": "import chai from 'chai';\nimport {encase, map} from '../../index.js';\nimport {test, assertCrashed, assertRejected, assertResolved, assertValidFuture, error} from '../util/util.js';\nimport {testFunction, functionArg, anyArg} from '../util/props.js';\n\nvar expect = chai.expect;\n\ntestFunction('encase', encase, [functionArg, anyArg], assertValidFuture);\n\ntest('resolves with the return value of the function', function (){\n  var actual = encase(function (x){ return x + 1 })(1);\n  return assertResolved(actual, 2);\n});\n\ntest('rejects with the exception thrown by the function', function (){\n  var actual = encase(function (a){ throw a, error })(1);\n  return assertRejected(actual, error);\n});\n\ntest('does not swallow errors from subsequent maps and such', function (){\n  var m = map(function (){ throw error })(encase(function (x){ return x })(1));\n  return assertCrashed(m, error);\n});\n\ntest('returns the code to create the Future when cast to String', function (){\n  var f = function (a){ return void a };\n  var m = encase(f)(null);\n  expect(m.toString()).to.equal('encase (' + f.toString() + ') (null)');\n});\n"
  },
  {
    "path": "test/unit/3.go.js",
    "content": "import chai from 'chai';\nimport {Future, go, resolve, after} from '../../index.js';\nimport {test, assertCrashed, assertResolved, assertValidFuture, error, noop, STACKSIZE} from '../util/util.js';\nimport * as F from '../util/futures.js';\nimport {testFunction, functionArg} from '../util/props.js';\n\nvar expect = chai.expect;\n\ntestFunction('go', go, [functionArg], assertValidFuture);\n\ntest('crashes when the given function throws an error', function (){\n  var m = go(function (){ throw error });\n  return assertCrashed(m, error);\n});\n\ntest('crashes when the given function does not return an interator', function (){\n  var m = go(function (){ return null });\n  return assertCrashed(m, new TypeError(\n    'go() expects its first argument to return an iterator, maybe you forgot the \"*\".\\n' +\n    '  Actual: null :: Null'\n  ));\n});\n\ntest('crashes when iterator.next() throws an error', function (){\n  var m = go(function (){ return {next: () => { throw error }} });\n  return assertCrashed(m, error);\n});\n\ntest('crashes when the returned iterator does not return a valid iteration', function (){\n  var m = go(function (){ return {next: () => { return null }} });\n  return assertCrashed(m, new TypeError(\n    'The iterator did not return a valid iteration from iterator.next()\\n' +\n    '  Actual: null'\n  ));\n});\n\ntest('crashes when the returned iterator produces something other than a Future', function (){\n  var m = go(function (){ return {next: () => { return {done: false, value: null} }} });\n  return assertCrashed(m, new TypeError(\n    'go() expects the value produced by the iterator to be a valid Future.\\n' +\n    '  Actual: null :: Null\\n' +\n    '  Tip: If you\\'re using a generator, make sure you always yield a Future'\n  ));\n});\n\ntest('crashes when the yielded Future crashes', function (){\n  var m = go(function*(){ yield F.crashed });\n  return assertCrashed(m, error);\n});\n\ntest('handles synchronous Futures', function (){\n  return assertResolved(go(function*(){\n    var a = yield resolve(1);\n    var b = yield resolve(2);\n    return a + b;\n  }), 3);\n});\n\ntest('handles asynchronous Futures', function (){\n  return assertResolved(go(function*(){\n    var a = yield after(10)(1);\n    var b = yield after(10)(2);\n    return a + b;\n  }), 3);\n});\n\ntest('does not mix state over multiple interpretations', function (){\n  var m = go(function*(){\n    var a = yield resolve(1);\n    var b = yield after(10)(2);\n    return a + b;\n  });\n  return Promise.all([\n    assertResolved(m, 3),\n    assertResolved(m, 3),\n  ]);\n});\n\ntest('is stack safe', function (){\n  var gen = function*(){\n    var i = 0;\n    while(i < STACKSIZE + 1){ yield resolve(i++) }\n    return i;\n  };\n\n  var m = go(gen);\n  return assertResolved(m, STACKSIZE + 1);\n});\n\ntest('cancels the running operation when cancelled', function (done){\n  var cancel = go(function*(){\n    yield resolve(1);\n    yield Future(function (){ return function (){ return done() } });\n  })._interpret(done, noop, noop);\n  cancel();\n});\n\ntest('returns the code to create the Go when cast to String', function (){\n  var f = function*(){};\n  var m = go(f);\n  var s = 'go (' + f.toString() + ')';\n  expect(m.toString()).to.equal(s);\n});\n"
  },
  {
    "path": "test/unit/3.hook.js",
    "content": "import chai from 'chai';\nimport {Future, hook, resolve, reject} from '../../index.js';\nimport {test, assertCrashed, assertIsFuture, assertRejected, assertResolved, error, itRaises, K, noop} from '../util/util.js';\nimport * as F from '../util/futures.js';\nimport {testFunction, futureArg, functionArg} from '../util/props.js';\n\nvar expect = chai.expect;\n\ntestFunction('hook', hook, [futureArg, functionArg, functionArg], assertIsFuture);\n\ntest('crashes when the disposal function does not return Future', function (){\n  var m = hook(F.resolved)(function (){ return 1 })(function (){ return F.resolved });\n  return assertCrashed(m, new TypeError(\n    'hook() expects the return value from the first function it\\'s given to be a valid Future.\\n' +\n    '  Actual: 1 :: Number\\n' +\n    '  From calling: function (){ return 1 }\\n' +\n    '  With: \"resolved\"'\n  ));\n});\n\ntest('crashes when the disposal function throws', function (){\n  var m = hook(F.resolved)(function (){ throw error })(function (){ return F.resolved });\n  return assertCrashed(m, error);\n});\n\ntest('crashes when the computation function does not return Future', function (){\n  var m = hook(F.resolved)(function (){ return F.resolved })(function (){ return 1 });\n  return assertCrashed(m, new TypeError(\n    'hook() expects the return value from the second function it\\'s given to be a valid Future.\\n' +\n    '  Actual: 1 :: Number\\n' +\n    '  From calling: function (){ return 1 }\\n' +\n    '  With: \"resolved\"'\n  ));\n});\n\ntest('crashes when the computation function throws', function (){\n  var m = hook(F.resolved)(function (){ return F.resolved })(function (){ throw error });\n  return assertCrashed(m, error);\n});\n\ntest('crashes when the disposal Future rejects', function (){\n  var rejected = hook(F.resolved)(function (){ return reject(1) })(function (){ return reject(2) });\n  var resolved = hook(F.resolved)(function (){ return reject(1) })(function (){ return resolve(2) });\n  return Promise.all([\n    assertCrashed(rejected, new Error('The disposal Future rejected with 1')),\n    assertCrashed(resolved, new Error('The disposal Future rejected with 1')),\n  ]);\n});\n\ntest('runs the first computation after the second, both with the resource', function (done){\n  var ran = false;\n  hook(F.resolved)(function (x){\n    expect(x).to.equal('resolved');\n    return Future(function (rej, res){ res(done(ran ? null : new Error('Second did not run'))); return noop });\n  })(function (x){\n    expect(x).to.equal('resolved');\n    return Future(function (rej, res){ res(ran = true); return noop });\n  })._interpret(done, done, noop);\n});\n\ntest('runs the first even if the second rejects', function (done){\n  hook(F.resolved)(function (){\n    return Future(function (){ done(); return noop });\n  })(function (){\n    return reject(2);\n  })._interpret(done, noop, noop);\n});\n\ntest('assumes the state resolve the second if the first resolves', function (){\n  var rejected = hook(F.resolved)(function (){ return resolve(1) })(function (){ return reject(2) });\n  var resolved = hook(F.resolved)(function (){ return resolve(1) })(function (){ return resolve(2) });\n  return Promise.all([\n    assertRejected(rejected, 2),\n    assertResolved(resolved, 2),\n  ]);\n});\n\ntest('does not hook after being cancelled', function (done){\n  const fail = () => done(error);\n  hook(F.resolvedSlow)(function (){ return resolve('dispose') })(fail)._interpret(done, fail, fail)();\n  setTimeout(done, 25);\n});\n\ntest('does not reject after being cancelled', function (done){\n  const fail = () => done(error);\n  hook(F.rejectedSlow)(function (){ return resolve('dispose') })(fail)._interpret(done, fail, fail)();\n  hook(F.resolved)(function (){ return resolve('dispose') })(function (){ return F.rejectedSlow })._interpret(done, fail, fail)();\n  setTimeout(done, 25);\n});\n\ntest('cancels acquire appropriately', function (done){\n  const fail = () => done(error);\n  var acquire = Future(function (){ return function (){ return done() } });\n  var cancel =\n    hook(acquire)(function (){ return resolve('dispose') })(function (){ return resolve('consume') })\n    ._interpret(done, fail, fail);\n  setTimeout(cancel, 10);\n});\n\ntest('cancels consume appropriately', function (done){\n  const fail = () => done(error);\n  var consume = Future(function (){ return function (){ return done() } });\n  var cancel =\n    hook(F.resolved)(function (){ return resolve('dispose') })(function (){ return consume })\n    ._interpret(done, fail, fail);\n  setTimeout(cancel, 10);\n});\n\ntest('cancels delayed consume appropriately', function (done){\n  const fail = () => done(error);\n  var consume = Future(function (){ return function (){ return done() } });\n  var cancel =\n    hook(F.resolvedSlow)(function (){ return resolve('dispose') })(function (){ return consume })\n    ._interpret(done, fail, fail);\n  setTimeout(cancel, 25);\n});\n\ntest('does not cancel disposal', function (done){\n  const fail = () => done(error);\n  var dispose = Future(function (){ return function (){ return done(error) } });\n  var cancel =\n    hook(F.resolved)(function (){ return dispose })(function (){ return resolve('consume') })\n    ._interpret(done, fail, fail);\n  setTimeout(cancel, 10);\n  setTimeout(done, 50);\n});\n\ntest('does not cancel delayed dispose', function (done){\n  const fail = () => done(error);\n  var dispose = Future(function (){ return function (){ return done(error) } });\n  var cancel =\n    hook(F.resolved)(function (){ return dispose })(function (){ return F.resolvedSlow })\n    ._interpret(done, fail, fail);\n  setTimeout(cancel, 50);\n  setTimeout(done, 100);\n});\n\ntest('runs the disposal Future when cancelled after acquire', function (done){\n  const fail = () => done(error);\n  var cancel =\n    hook(F.resolved)(function (){ return Future(function (){ done(); return noop }) })(function (){ return F.resolvedSlow })\n    ._interpret(done, fail, fail);\n  setTimeout(cancel, 10);\n});\n\nitRaises('exceptions that occur after the Future was unsubscribed', function (done){\n  const fail = () => done(error);\n  hook(F.resolved)(K(F.crashedSlow))(K(F.resolved))._interpret(function (){\n    done(new Error('Exception handler called'));\n  }, fail, fail)();\n}, error);\n\ntest('returns the code which creates the same data-structure when cast to String', function (){\n  var a = resolve(1);\n  var d = function (){ return resolve(2) };\n  var c = function (){ return resolve(3) };\n  var m = hook(a)(d)(c);\n  var expected = 'hook (' + a.toString() + ') (' + d.toString() + ') (' + c.toString() + ')';\n  expect(m.toString()).to.equal(expected);\n});\n"
  },
  {
    "path": "test/unit/3.node.js",
    "content": "import chai from 'chai';\nimport {node} from '../../index.js';\nimport {test, assertCrashed, assertRejected, assertResolved, assertValidFuture, error} from '../util/util.js';\nimport {testFunction, functionArg} from '../util/props.js';\n\nvar expect = chai.expect;\n\ntestFunction('node', node, [functionArg], assertValidFuture);\n\ntest('crashes when the function throws', function (){\n  var m = node(function (){ throw error });\n  return assertCrashed(m, error);\n});\n\ntest('rejects when the callback is called with (err)', function (){\n  var f = function (done){ return done(error) };\n  return assertRejected(node(f), error);\n});\n\ntest('resolves when the callback is called with (null, a)', function (){\n  var f = function (done){ return done(null, 'a') };\n  return assertResolved(node(f), 'a');\n});\n\ntest('settles with the last synchronous call to done', function (){\n  var f = function (done){ done(null, 'a'); done(error); done(null, 'b') };\n  return assertResolved(node(f), 'b');\n});\n\ntest('settles with the first asynchronous call to done', function (){\n  var f = function (done){\n    setTimeout(done, 10, null, 'a');\n    setTimeout(done, 50, null, 'b');\n  };\n  return assertResolved(node(f), 'a');\n});\n\ntest('ensures no continuations are called after cancel', function (done){\n  const fail = () => done(error);\n  var f = function (done){ return setTimeout(done, 5) };\n  node(f)._interpret(done, fail, fail)();\n  setTimeout(done, 20);\n});\n\ntest('returns the code to create the Future when cast to String', function (){\n  var f = function (a){ return void a };\n  var m = node(f);\n  expect(m.toString()).to.equal('node (' + f.toString() + ')');\n});\n"
  },
  {
    "path": "test/unit/3.parallel.js",
    "content": "import chai from 'chai';\nimport {Future, parallel, resolve, reject, after} from '../../index.js';\nimport {test, promiseTimeout, assertCrashed, assertRejected, assertResolved, assertValidFuture, error, noop, repeat, STACKSIZE} from '../util/util.js';\nimport * as F from '../util/futures.js';\nimport {testFunction, positiveIntegerArg, futureArrayArg} from '../util/props.js';\n\nvar expect = chai.expect;\n\ntestFunction('parallel', parallel, [positiveIntegerArg, futureArrayArg], assertValidFuture);\n\ntest('crashes when one resolve the Futures crash', function (){\n  return assertCrashed(parallel(2)([F.resolved, F.crashed]), error);\n});\n\ntest('crashes when one resolve the Futures crash', function (){\n  return assertCrashed(parallel(2)([F.resolved, F.resolved, F.resolved, F.resolved, F.resolved, F.crashed]), error);\n});\n\ntest('throws when the Array contains something other than Futures', function (){\n  var xs = [NaN, {}, [], 1, 'a', new Date, undefined, null];\n  var fs = xs.map(function (x){ return function (){ return parallel(1)([x])._interpret(noop, noop, noop) } });\n  fs.forEach(function (f){ return expect(f).to.throw(TypeError, /Future/u) });\n});\n\ntest('parallelizes execution', function (){\n  var actual = parallel(5)([\n    after(20)('a'),\n    after(20)('b'),\n    after(20)('c'),\n    after(20)('d'),\n    after(20)('e'),\n  ]);\n  return promiseTimeout(70, assertResolved(actual, ['a', 'b', 'c', 'd', 'e']));\n});\n\ntest('limits parallelism to the given number', function (){\n  var running = 0;\n  var m = Future(function (rej, res){\n    running++;\n    if(running > 2){ return void rej(new Error('More than two running in parallel')) }\n    setTimeout(function (){\n      running--;\n      res('a');\n    }, 20);\n    return noop;\n  });\n  var actual = parallel(2)(repeat(8, m));\n  return assertResolved(actual, repeat(8, 'a'));\n});\n\ntest('runs all in parallel when given number larger than the array length', function (){\n  var actual = parallel(10)([\n    after(20)('a'),\n    after(20)('b'),\n    after(20)('c'),\n    after(20)('d'),\n    after(20)('e'),\n  ]);\n  return promiseTimeout(70, assertResolved(actual, ['a', 'b', 'c', 'd', 'e']));\n});\n\ntest('can deal with synchronously resolving futures', function (){\n  return assertResolved(parallel(5)(repeat(10, resolve(1))), [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]);\n});\n\ntest('interprets the synchronous futures in the provided sequence', function (done){\n  var ns = Array.from({length: 10}, function (_, i){ return i });\n  var xs = [];\n  var ms = ns.map(function (i){\n    return Future(function (rej, res){\n      xs.push(i);\n      res(i);\n      return noop;\n    });\n  });\n  parallel(5)(ms)._interpret(done, noop, function (out){\n    expect(out).to.deep.equal(ns);\n    expect(xs).to.deep.equal(ns);\n    done();\n  });\n});\n\ntest('interprets the asynchronous futures in the provided sequence', function (done){\n  var ns = Array.from({length: 10}, function (_, i){ return i });\n  var xs = [];\n  var ms = ns.map(function (i){\n    return Future(function (rej, res){\n      xs.push(i);\n      setTimeout(res, 10, i);\n      return noop;\n    });\n  });\n  parallel(5)(ms)._interpret(done, noop, function (out){\n    expect(out).to.deep.equal(ns);\n    expect(xs).to.deep.equal(ns);\n    done();\n  });\n});\n\ntest('resolves to an empty array when given an empty array', function (){\n  return assertResolved(parallel(1)([]), []);\n});\n\ntest('runs all in parallel when given Infinity', function (){\n  var actual = parallel(Infinity)([\n    after(20)('a'),\n    after(20)('b'),\n    after(20)('c'),\n    after(20)('d'),\n    after(20)('e'),\n  ]);\n  return promiseTimeout(70, assertResolved(actual, ['a', 'b', 'c', 'd', 'e']));\n});\n\ntest('rejects if one resolve the input rejects', function (){\n  var actual = parallel(2)([F.resolved, reject('err')]);\n  return assertRejected(actual, 'err');\n});\n\ntest('rejects with the first rejection value', function (){\n  return Promise.all([\n    assertRejected(parallel(2)([F.rejectedSlow, F.rejected]), 'rejected'),\n    assertRejected(parallel(2)([F.rejected, F.rejectedSlow]), 'rejected'),\n  ]);\n});\n\ntest('cancels Futures when cancelled', function (done){\n  var m = Future(function (){ return function (){ return done() } });\n  var cancel = parallel(1)([m])._interpret(done, noop, noop);\n  setTimeout(cancel, 20);\n});\n\ntest('cancels only running Futures when cancelled', function (done){\n  var i = 0, j = 0;\n  var m = Future(function (rej, res){\n    var x = setTimeout(function (x){ j += 1; res(x) }, 20, 1);\n\n    return function (){\n      i += 1;\n      clearTimeout(x);\n    };\n  });\n  var cancel = parallel(2)([m, m, m, m])._interpret(done, noop, noop);\n  setTimeout(function (){\n    cancel();\n    expect(i).to.equal(2);\n    expect(j).to.equal(2);\n    done();\n  }, 30);\n});\n\ntest('does not interpret any computations after one rejects', function (done){\n  var m = Future(function (){ done(error) });\n  parallel(2)([F.rejected, m])._interpret(done, noop, noop);\n  done();\n});\n\ntest('automatically cancels running computations when one rejects', function (done){\n  var m = Future(function (){ return function (){ done() } });\n  parallel(2)([m, F.rejected])._interpret(done, noop, noop);\n});\n\ntest('does not cancel settled computations (#123)', function (done){\n  var m1 = Object.create(F.mock);\n  var m2 = Object.create(F.mock);\n\n  m1._interpret = function (_, rej, res){\n    setTimeout(res, 10, 1);\n    return function (){ return done(error) };\n  };\n\n  m2._interpret = function (_, rej){\n    setTimeout(rej, 50, 2);\n    return function (){ return done(error) };\n  };\n\n  parallel(2)([m1, m2])._interpret(done, noop, noop);\n  setTimeout(done, 100, null);\n});\n\ntest('does not resolve after being cancelled', function (done){\n  const fail = () => done(error);\n  const cancel = parallel(1)([F.resolvedSlow, F.resolvedSlow])\n  ._interpret(done, fail, fail);\n  cancel();\n  setTimeout(done, 100);\n});\n\ntest('does not reject after being cancelled', function (done){\n  const fail = () => done(error);\n  const cancel = parallel(1)([F.rejectedSlow, F.rejectedSlow])\n  ._interpret(done, fail, fail);\n  cancel();\n  setTimeout(done, 100);\n});\n\ntest('is stack safe (#130)', function (){\n  var ms = Array.from({length: STACKSIZE}, (_, i) => resolve(i));\n  var expected = Array.from({length: STACKSIZE}, (_, i) => i);\n  return assertResolved(parallel(1)(ms), expected);\n});\n\ntest('returns the code to create the Parallel when cast to String', function (){\n  var m1 = parallel(Infinity)([resolve(1), resolve(2)]);\n  var m2 = parallel(2)([resolve(1), resolve(2)]);\n  var s1 = 'parallel (Infinity) ([resolve (1), resolve (2)])';\n  var s2 = 'parallel (2) ([resolve (1), resolve (2)])';\n  expect(m1.toString()).to.equal(s1);\n  expect(m2.toString()).to.equal(s2);\n});\n"
  },
  {
    "path": "test/unit/3.reject-after.js",
    "content": "import {rejectAfter, never} from '../../index.js';\nimport {eq, assertValidFuture, assertRejected, test, error} from '../util/util.js';\nimport {testFunction, positiveIntegerArg, anyArg} from '../util/props.js';\n\ntestFunction('rejectAfter', rejectAfter, [positiveIntegerArg, anyArg], assertValidFuture);\n\ntest('returns Never when given Infinity', function (){\n  eq(rejectAfter(Infinity)(1), never);\n});\n\ntest('rejects with the given value', function (){\n  return assertRejected(rejectAfter(20)(1), 1);\n});\n\ntest('clears its internal timeout when cancelled', function (done){\n  const fail = () => done(error);\n  rejectAfter(20)(1)._interpret(done, fail, fail)();\n  setTimeout(done, 25);\n});\n\ntest('returns array with the value', function (){\n  eq(rejectAfter(20)(1).extractLeft(), [1]);\n});\n\ntest('returns the code to create the After when cast to String', function (){\n  eq(rejectAfter(20)(1).toString(), 'rejectAfter (20) (1)');\n});\n"
  },
  {
    "path": "test/unit/3.reject.js",
    "content": "import {reject} from '../../index.js';\nimport {eq, assertValidFuture, assertRejected, test} from '../util/util.js';\nimport {testFunction, anyArg} from '../util/props.js';\n\ntestFunction('reject', reject, [anyArg], assertValidFuture);\n\ntest('returns a rejected Future', function (){\n  return assertRejected(reject(1), 1);\n});\n\ntest('provides its reason to extractLeft()', function (){\n  eq(reject(1).extractLeft(), [1]);\n});\n\ntest('can be shown as string', function (){\n  eq(reject(1).toString(), 'reject (1)');\n});\n"
  },
  {
    "path": "test/unit/3.resolve.js",
    "content": "import {resolve} from '../../index.js';\nimport {eq, assertValidFuture, assertResolved, test} from '../util/util.js';\nimport {testFunction, anyArg} from '../util/props.js';\n\ntestFunction('resolve', resolve, [anyArg], assertValidFuture);\n\ntest('returns a resolved Future', function (){\n  return assertResolved(resolve(1), 1);\n});\n\ntest('provides its reason to extractRight()', function (){\n  eq(resolve(1).extractRight(), [1]);\n});\n\ntest('can be shown as string', function (){\n  eq(resolve(1).toString(), 'resolve (1)');\n});\n"
  },
  {
    "path": "test/unit/4.alt.js",
    "content": "import Either from 'sanctuary-either';\nimport {Future, alt} from '../../index.js';\nimport {assertCrashed, eq, assertValidFuture, noop, assertResolved, assertRejected, error, test} from '../util/util.js';\nimport {crashed, rejected, resolved, rejectedSlow, resolvedSlow} from '../util/futures.js';\nimport {testFunction, altArg, futureArg} from '../util/props.js';\n\ntestFunction('alt', alt, [altArg, futureArg], assertValidFuture);\n\ntest('chooses the resolved over the rejected Future', function (){\n  return Promise.all([\n    assertResolved(alt(crashed)(resolved), 'resolved'),\n    assertResolved(alt(resolved)(resolved), 'resolved'),\n    assertResolved(alt(rejected)(resolved), 'resolved'),\n    assertResolved(alt(resolved)(rejected), 'resolved'),\n    assertRejected(alt(rejected)(rejected), 'rejected'),\n    assertResolved(alt(resolved)(resolvedSlow), 'resolvedSlow'),\n    assertResolved(alt(resolvedSlow)(resolved), 'resolved'),\n    assertRejected(alt(rejected)(rejectedSlow), 'rejected'),\n    assertRejected(alt(rejectedSlow)(rejected), 'rejectedSlow'),\n    assertCrashed(alt(rejected)(crashed), error),\n    assertCrashed(alt(resolved)(crashed), error),\n    assertCrashed(alt(crashed)(rejected), error),\n  ]);\n});\n\ntest('dispatches to Fantasy Land alt', function (){\n  eq(alt(Either.Right(42))(Either.Left(42)), Either.Right(42));\n});\n\ntest('cancels the running Future', function (done){\n  var m = Future(function (){ return function (){ return done() } });\n  var cancel = alt(m)(m)._interpret(done, noop, noop);\n  cancel();\n});\n\ntest('displays correctly as string', function (){\n  eq(alt(rejected)(resolved).toString(), 'alt (reject (\"rejected\")) (resolve (\"resolved\"))');\n});\n\n"
  },
  {
    "path": "test/unit/4.and.js",
    "content": "import {Future, and} from '../../index.js';\nimport {assertCrashed, eq, assertValidFuture, noop, assertResolved, assertRejected, error, test} from '../util/util.js';\nimport {crashed, rejected, resolved, rejectedSlow, resolvedSlow} from '../util/futures.js';\nimport {testFunction, futureArg} from '../util/props.js';\n\ntestFunction('and', and, [futureArg, futureArg], assertValidFuture);\n\ntest('chooses the rejected over the resolved Future', function (){\n  return Promise.all([\n    assertResolved(and(resolved)(resolved), 'resolved'),\n    assertRejected(and(rejected)(resolved), 'rejected'),\n    assertRejected(and(resolved)(rejected), 'rejected'),\n    assertRejected(and(rejected)(rejected), 'rejected'),\n    assertResolved(and(resolved)(resolvedSlow), 'resolved'),\n    assertResolved(and(resolvedSlow)(resolved), 'resolvedSlow'),\n    assertRejected(and(rejected)(rejectedSlow), 'rejectedSlow'),\n    assertRejected(and(rejectedSlow)(rejected), 'rejected'),\n    assertCrashed(and(resolved)(crashed), error),\n    assertCrashed(and(rejected)(crashed), error),\n    assertCrashed(and(crashed)(resolved), error),\n  ]);\n});\n\ntest('cancels the running Future', function (done){\n  var m = Future(function (){ return function (){ return done() } });\n  var cancel = and(m)(m)._interpret(done, noop, noop);\n  cancel();\n});\n\ntest('displays correctly as string', function (){\n  eq(and(rejected)(resolved).toString(), 'and (reject (\"rejected\")) (resolve (\"resolved\"))');\n});\n"
  },
  {
    "path": "test/unit/4.ap.js",
    "content": "import Either from 'sanctuary-either';\nimport {Future, ap, resolve, reject, after} from '../../index.js';\nimport {assertCrashed, assertRejected, assertResolved, assertValidFuture, noop, add, eq, bang, test} from '../util/util.js';\nimport {testFunction, applyArg, futureArg} from '../util/props.js';\n\ntestFunction('ap', ap, [applyArg, futureArg], assertValidFuture);\n\ntest('dispatches to Fantasy Land ap', function (){\n  eq(ap(Either.Right('hello'))(Either.Right(bang)), Either.Right('hello!'));\n});\n\ntest('crashes when the other does not resolve to a Function', function (){\n  var m = ap(resolve(1))(resolve(null));\n  return assertCrashed(m, new TypeError(\n    'ap expects the second Future to resolve to a Function\\n' +\n    '  Actual: null'\n  ));\n});\n\ntest('applies the Function on the right to the value on the left', function (){\n  return Promise.all([\n    assertResolved(ap(resolve(1))(resolve(add(1))), 2),\n    assertRejected(ap(resolve(add(1)))(reject('err')), 'err'),\n    assertRejected(ap(reject('err'))(resolve(add(1))), 'err'),\n    assertResolved(ap(after(20)(1))(resolve(add(1))), 2),\n    assertResolved(ap(resolve(1))(after(20)(add(1))), 2),\n  ]);\n});\n\ntest('cancels the left Future if cancel is called while it is running', function (done){\n  var left = Future(function (){ return function (){ return done() } });\n  var right = resolve(add(1));\n  var cancel = ap(left)(right)._interpret(done, noop, noop);\n  cancel();\n});\n\ntest('cancels the right Future if cancel is called while it is running', function (done){\n  var left = resolve(1);\n  var right = Future(function (){ return function (){ return done() } });\n  var cancel = ap(left)(right)._interpret(done, noop, noop);\n  cancel();\n});\n\ntest('displays correctly as string', function (){\n  eq(ap(resolve(1))(resolve(2)).toString(), 'ap (resolve (1)) (resolve (2))');\n});\n"
  },
  {
    "path": "test/unit/4.bichain.js",
    "content": "import {bichain} from '../../index.js';\nimport {test, assertCrashed, assertRejected, assertResolved, assertValidFuture, eq, throwing, error} from '../util/util.js';\nimport {testFunction, functionArg, futureArg} from '../util/props.js';\nimport {resolvedSlow, resolved, rejected, rejectedSlow} from '../util/futures.js';\nimport {resolve, reject} from '../../index.js';\n\ntestFunction('bichain', bichain, [functionArg, functionArg, futureArg], assertValidFuture);\n\ntest('runs a bichain transformation on Futures', function (){\n  return Promise.all([\n    assertResolved(bichain(reject)(resolve)(resolved), 'resolved'),\n    assertResolved(bichain(reject)(resolve)(resolvedSlow), 'resolvedSlow'),\n    assertRejected(bichain(resolve)(reject)(resolved), 'resolved'),\n    assertRejected(bichain(resolve)(reject)(resolvedSlow), 'resolvedSlow'),\n    assertResolved(bichain(resolve)(reject)(rejected), 'rejected'),\n    assertResolved(bichain(resolve)(reject)(rejectedSlow), 'rejectedSlow'),\n    assertRejected(bichain(reject)(resolve)(rejected), 'rejected'),\n    assertRejected(bichain(reject)(resolve)(rejectedSlow), 'rejectedSlow'),\n    assertCrashed(bichain(throwing)(reject)(rejected), error),\n    assertCrashed(bichain(resolve)(throwing)(resolved), error),\n  ]);\n});\n\ntest('displays correctly as string', function (){\n  eq(bichain(resolve)(reject)(resolved).toString(), 'bichain (' + resolve.toString() + ') (' + reject.toString() + ') (resolve (\"resolved\"))');\n});\n"
  },
  {
    "path": "test/unit/4.bimap.js",
    "content": "import Either from 'sanctuary-either';\nimport {bimap} from '../../index.js';\nimport {test, assertCrashed, assertRejected, assertResolved, assertValidFuture, I, bang, eq, throwing, error} from '../util/util.js';\nimport {testFunction, functionArg, bifunctorArg} from '../util/props.js';\nimport {resolved, rejected} from '../util/futures.js';\n\ntestFunction('bimap', bimap, [functionArg, functionArg, bifunctorArg], assertValidFuture);\n\ntest('runs a bimap transformation on Futures', function (){\n  return Promise.all([\n    assertRejected(bimap(bang)(I)(rejected), 'rejected!'),\n    assertResolved(bimap(I)(bang)(resolved), 'resolved!'),\n    assertCrashed(bimap(throwing)(I)(rejected), error),\n    assertCrashed(bimap(I)(throwing)(resolved), error),\n  ]);\n});\n\ntest('dispatches to Fantasy Land bimap otherwise', function (){\n  eq(bimap(I)(bang)(Either.Right('hello')), Either.Right('hello!'));\n});\n\ntest('displays correctly as string', function (){\n  eq(bimap(I)(bang)(resolved).toString(), 'bimap (' + I.toString() + ') (' + bang.toString() + ') (resolve (\"resolved\"))');\n});\n"
  },
  {
    "path": "test/unit/4.both.js",
    "content": "import {Future, both, node, done} from '../../index.js';\nimport {test, assertCrashed, assertRejected, assertResolved, assertValidFuture, error, noop, eq} from '../util/util.js';\nimport {crashed, rejected, resolved, crashedSlow, rejectedSlow, resolvedSlow} from '../util/futures.js';\nimport {testFunction, futureArg} from '../util/props.js';\n\ntestFunction('both', both, [futureArg, futureArg], assertValidFuture);\n\ntest('resolves to a tuple of both resolution values', function (){\n  return Promise.all([\n    assertCrashed(both(crashed)(crashed), error),\n    assertCrashed(both(rejected)(crashed), error),\n    assertCrashed(both(crashed)(resolved), error),\n    assertCrashed(both(resolved)(crashed), error),\n\n    assertRejected(both(rejected)(rejected), 'rejected'),\n    assertRejected(both(rejected)(rejectedSlow), 'rejected'),\n    assertRejected(both(rejectedSlow)(rejected), 'rejected'),\n    assertRejected(both(crashed)(rejected), 'rejected'),\n    assertRejected(both(rejected)(crashedSlow), 'rejected'),\n    assertRejected(both(resolved)(rejected), 'rejected'),\n    assertRejected(both(rejected)(resolved), 'rejected'),\n\n    assertResolved(both(resolved)(resolved), ['resolved', 'resolved']),\n    assertResolved(both(resolved)(resolvedSlow), ['resolved', 'resolvedSlow']),\n    assertResolved(both(resolvedSlow)(resolved), ['resolvedSlow', 'resolved']),\n    assertResolved(both(resolvedSlow)(resolvedSlow), ['resolvedSlow', 'resolvedSlow']),\n  ]);\n});\n\ntest('[GH #118] does not call the left computation twice', function (cb){\n  var called = false;\n  var left = node(function (f){ called ? cb(error) : setTimeout(f, 20, null, called = true) });\n  return done(cb)(both(left)(resolvedSlow));\n});\n\ntest('[GH #118] does not call the right computation twice', function (cb){\n  var called = false;\n  var right = node(function (f){ called ? cb(error) : setTimeout(f, 20, null, called = true) });\n  return done(cb)(both(resolvedSlow)(right));\n});\n\ntest('cancels the right if the left rejects', function (done){\n  var m = both(rejectedSlow)(Future(function (){ return function (){ return done() } }));\n  m._interpret(done, noop, noop);\n});\n\ntest('cancels the left if the right rejects', function (done){\n  var m = both(Future(function (){ return function (){ return done() } }))(rejectedSlow);\n  m._interpret(done, noop, noop);\n});\n\ntest('creates a cancel function which cancels both Futures', function (done){\n  var cancelled = false;\n  var m = Future(function (){ return function (){ return (cancelled ? done() : (cancelled = true)) } });\n  var cancel = both(m)(m)._interpret(done, noop, noop);\n  cancel();\n});\n\ntest('displays correctly as string', function (){\n  eq(both(rejected)(resolved).toString(), 'both (reject (\"rejected\")) (resolve (\"resolved\"))');\n});\n"
  },
  {
    "path": "test/unit/4.chain-rej.js",
    "content": "import {chainRej, resolve, reject} from '../../index.js';\nimport {test, assertCrashed, assertRejected, assertResolved, assertValidFuture, bang, throwing, error, eq} from '../util/util.js';\nimport {rejected, resolved, rejectedSlow} from '../util/futures.js';\nimport {testFunction, functionArg, futureArg} from '../util/props.js';\n\ntestFunction('chainRej', chainRej, [functionArg, futureArg], assertValidFuture);\n\ntest('crashes when the given function does not return Future', function (){\n  return assertCrashed(chainRej(bang)(rejected), new TypeError(\n    'chainRej expects the return value from the function it\\'s given to be a valid Future.\\n' +\n    '  Actual: \"rejected!\" :: String\\n' +\n    '  When called with: \"rejected\"'\n  ));\n});\n\ntest('calls the function with the rejection reason and sequences the returned Future', function (){\n  return Promise.all([\n    assertResolved(chainRej(resolve)(rejected), 'rejected'),\n    assertResolved(chainRej(resolve)(rejectedSlow), 'rejectedSlow'),\n    assertResolved(chainRej(reject)(resolved), 'resolved'),\n    assertRejected(chainRej(reject)(rejected), 'rejected'),\n    assertCrashed(chainRej(throwing)(rejected), error),\n  ]);\n});\n\ntest('displays correctly as string', function (){\n  eq(chainRej(resolve)(resolved).toString(), 'chainRej (' + resolve.toString() + ') (resolve (\"resolved\"))');\n});\n"
  },
  {
    "path": "test/unit/4.chain.js",
    "content": "import Either from 'sanctuary-either';\nimport {chain, resolve, reject} from '../../index.js';\nimport {test, assertCrashed, assertRejected, assertResolved, assertValidFuture, bang, eq, throwing, error} from '../util/util.js';\nimport {rejected, resolved, resolvedSlow} from '../util/futures.js';\nimport {testFunction, functionArg, chainArg} from '../util/props.js';\n\ntestFunction('chain', chain, [functionArg, chainArg], assertValidFuture);\n\ntest('dispatches to Fantasy Land chain', function (){\n  eq(chain(Either.Left)(Either.Right(42)), Either.Left(42));\n});\n\ntest('crashes when the given function does not return Future', function (){\n  return assertCrashed(chain(bang)(resolved), new TypeError(\n    'chain expects the return value from the function it\\'s given to be a valid Future.\\n' +\n    '  Actual: \"resolved!\" :: String\\n' +\n    '  When called with: \"resolved\"'\n  ));\n});\n\ntest('calls the function with the resolution value and sequences the returned Future', function (){\n  return Promise.all([\n    assertRejected(chain(reject)(resolved), 'resolved'),\n    assertRejected(chain(reject)(resolvedSlow), 'resolvedSlow'),\n    assertResolved(chain(resolve)(resolved), 'resolved'),\n    assertRejected(chain(resolve)(rejected), 'rejected'),\n    assertCrashed(chain(throwing)(resolved), error),\n  ]);\n});\n\ntest('displays correctly as string', function (){\n  eq(chain(resolve)(resolved).toString(), 'chain (' + resolve.toString() + ') (resolve (\"resolved\"))');\n});\n"
  },
  {
    "path": "test/unit/4.coalesce.js",
    "content": "import {coalesce} from '../../index.js';\nimport {test, assertCrashed, assertResolved, assertValidFuture, bang, B, throwing, error, eq} from '../util/util.js';\nimport {resolved, rejected} from '../util/futures.js';\nimport {testFunction, functionArg, futureArg} from '../util/props.js';\n\ntestFunction('coalesce', coalesce, [functionArg, functionArg, futureArg], assertValidFuture);\n\ntest('joins the rejection and resolution values into the resolution branch', function (){\n  return Promise.all([\n    assertResolved(coalesce(bang)(B(bang)(bang))(rejected), 'rejected!'),\n    assertResolved(coalesce(bang)(B(bang)(bang))(resolved), 'resolved!!'),\n    assertCrashed(coalesce(throwing)(B)(rejected), error),\n    assertCrashed(coalesce(B)(throwing)(resolved), error),\n  ]);\n});\n\ntest('displays correctly as string', function (){\n  eq(coalesce(bang)(B)(resolved).toString(), 'coalesce (' + bang.toString() + ') (' + B.toString() + ') (resolve (\"resolved\"))');\n});\n"
  },
  {
    "path": "test/unit/4.lastly.js",
    "content": "import {lastly, resolve, reject, map} from '../../index.js';\nimport {test, assertRejected, assertResolved, assertValidFuture, noop, eq} from '../util/util.js';\nimport {rejected, rejectedSlow, resolved, resolvedSlow} from '../util/futures.js';\nimport {testFunction, futureArg} from '../util/props.js';\n\ntestFunction('lastly', lastly, [futureArg, futureArg], assertValidFuture);\n\ntest('runs the second Future when the first resolves', function (done){\n  lastly(map(done)(resolve(null)))(resolve(1))._interpret(done, noop, noop);\n});\n\ntest('runs the second Future when the first rejects', function (done){\n  lastly(map(done)(resolve(null)))(reject(1))._interpret(done, noop, noop);\n});\n\ntest('resolves with the resolution value of the first', function (){\n  var actual = lastly(resolve(2))(resolve(1));\n  return assertResolved(actual, 1);\n});\n\ntest('rejects with the rejection reason of the first if the second resolves', function (){\n  var actual = lastly(resolve(2))(reject(1));\n  return assertRejected(actual, 1);\n});\n\ntest('always rejects with the rejection reason of the second', function (){\n  var actualResolved = lastly(reject(2))(resolve(1));\n  var actualRejected = lastly(reject(2))(reject(1));\n  return Promise.all([\n    assertRejected(actualResolved, 2),\n    assertRejected(actualRejected, 2),\n  ]);\n});\n\ntest('does nothing after being cancelled', function (done){\n  const fail = () => fail(done);\n  lastly(resolved)(resolvedSlow)._interpret(done, fail, fail)();\n  lastly(resolvedSlow)(resolved)._interpret(done, fail, fail)();\n  lastly(rejected)(rejectedSlow)._interpret(done, fail, fail)();\n  lastly(rejectedSlow)(rejected)._interpret(done, fail, fail)();\n  setTimeout(done, 25);\n});\n\ntest('displays correctly as string', function (){\n  eq(lastly(rejected)(resolved).toString(), 'lastly (reject (\"rejected\")) (resolve (\"resolved\"))');\n});\n"
  },
  {
    "path": "test/unit/4.map-rej.js",
    "content": "import {mapRej} from '../../index.js';\nimport {test, assertCrashed, assertRejected, assertResolved, assertValidFuture, bang, throwing, error, eq} from '../util/util.js';\nimport {rejected, resolved, resolvedSlow, rejectedSlow} from '../util/futures.js';\nimport {testFunction, functionArg, futureArg} from '../util/props.js';\n\ntestFunction('mapRej', mapRej, [functionArg, futureArg], assertValidFuture);\n\ntest('maps the rejection branch with the given function', function (){\n  return Promise.all([\n    assertRejected(mapRej(bang)(rejected), 'rejected!'),\n    assertResolved(mapRej(bang)(resolved), 'resolved'),\n    assertCrashed(mapRej(throwing)(rejected), error),\n  ]);\n});\n\ntest('does not resolve after being cancelled', function (done){\n  const fail = () => done(error);\n  mapRej(fail)(resolvedSlow)._interpret(done, fail, fail)();\n  setTimeout(done, 25);\n});\n\ntest('does not reject after being cancelled', function (done){\n  const fail = () => done(error);\n  mapRej(fail)(rejectedSlow)._interpret(done, fail, fail)();\n  setTimeout(done, 25);\n});\n\ntest('displays correctly as string', function (){\n  eq(mapRej(bang)(rejected).toString(), 'mapRej (' + bang.toString() + ') (reject (\"rejected\"))');\n});\n"
  },
  {
    "path": "test/unit/4.map.js",
    "content": "import Either from 'sanctuary-either';\nimport {map} from '../../index.js';\nimport {test, assertCrashed, assertRejected, assertResolved, assertValidFuture, bang, eq, throwing, error} from '../util/util.js';\nimport {rejected, resolved, resolvedSlow, rejectedSlow} from '../util/futures.js';\nimport {testFunction, functionArg, functorArg} from '../util/props.js';\n\ntestFunction('map', map, [functionArg, functorArg], assertValidFuture);\n\ntest('dispatches to Fantasy Land map', function (){\n  eq(map(bang)(Either.Right('hello')), Either.Right('hello!'));\n});\n\ntest('maps the resolution branch with the given function', function (){\n  return Promise.all([\n    assertRejected(map(bang)(rejected), 'rejected'),\n    assertResolved(map(bang)(resolved), 'resolved!'),\n    assertCrashed(map(throwing)(resolved), error),\n  ]);\n});\n\ntest('does not resolve after being cancelled', function (done){\n  const fail = () => done(error);\n  map(fail)(resolvedSlow)._interpret(done, fail, fail)();\n  setTimeout(done, 25);\n});\n\ntest('does not reject after being cancelled', function (done){\n  const fail = () => done(error);\n  map(fail)(rejectedSlow)._interpret(done, fail, fail)();\n  setTimeout(done, 25);\n});\n\ntest('displays correctly as string', function (){\n  eq(map(bang)(resolved).toString(), 'map (' + bang.toString() + ') (resolve (\"resolved\"))');\n});\n"
  },
  {
    "path": "test/unit/4.pap.js",
    "content": "import {Future, resolve, reject, after} from '../../index.js';\nimport {pap} from '../../src/pap.js';\nimport {test, assertCrashed, assertRejected, assertResolved, assertValidFuture, noop, add} from '../util/util.js';\nimport {testFunction, futureArg} from '../util/props.js';\n\ntestFunction('pap', pap, [futureArg, futureArg], assertValidFuture);\n\ntest('crashes when the other does not resolve to a Function', function (){\n  var m = pap(resolve(1))(resolve(null));\n  return assertCrashed(m, new TypeError(\n    'pap expects the second Future to resolve to a Function\\n' +\n    '  Actual: null'\n  ));\n});\n\ntest('applies the Function on the right to the value on the left', function (){\n  return Promise.all([\n    assertResolved(pap(resolve(1))(resolve(add(1))), 2),\n    assertRejected(pap(resolve(add(1)))(reject('err')), 'err'),\n    assertRejected(pap(reject('err'))(resolve(add(1))), 'err'),\n    assertResolved(pap(after(20)(1))(resolve(add(1))), 2),\n    assertResolved(pap(resolve(1))(after(20)(add(1))), 2),\n  ]);\n});\n\ntest('cancels the left Future if cancel is called while it is running', function (done){\n  var left = Future(function (){ return function (){ return done() } });\n  var right = resolve(add(1));\n  var cancel = pap(left)(right)._interpret(done, noop, noop);\n  cancel();\n});\n\ntest('cancels the right Future if cancel is called while it is running', function (done){\n  var left = resolve(1);\n  var right = Future(function (){ return function (){ return done() } });\n  var cancel = pap(left)(right)._interpret(done, noop, noop);\n  cancel();\n});\n"
  },
  {
    "path": "test/unit/4.race.js",
    "content": "import {Future, race} from '../../index.js';\nimport {test, assertCrashed, assertRejected, assertResolved, assertValidFuture, error, noop, eq} from '../util/util.js';\nimport {crashed, crashedSlow, rejected, rejectedSlow, resolved, resolvedSlow} from '../util/futures.js';\nimport {testFunction, futureArg} from '../util/props.js';\n\ntestFunction('race', race, [futureArg, futureArg], assertValidFuture);\n\ntest('races one Future against another', function (){\n  return Promise.all([\n    assertCrashed(race(crashed)(resolvedSlow), error),\n    assertResolved(race(crashedSlow)(resolved), 'resolved'),\n    assertCrashed(race(crashed)(rejectedSlow), error),\n    assertRejected(race(crashedSlow)(rejected), 'rejected'),\n    assertResolved(race(resolved)(crashedSlow), 'resolved'),\n    assertCrashed(race(resolvedSlow)(crashed), error),\n    assertRejected(race(rejected)(crashedSlow), 'rejected'),\n    assertCrashed(race(rejectedSlow)(crashed), error),\n    assertResolved(race(resolved)(resolvedSlow), 'resolved'),\n    assertResolved(race(resolvedSlow)(resolved), 'resolved'),\n    assertRejected(race(rejectedSlow)(rejected), 'rejected'),\n    assertRejected(race(rejected)(rejectedSlow), 'rejected'),\n    assertResolved(race(rejectedSlow)(resolved), 'resolved'),\n    assertRejected(race(rejected)(resolvedSlow), 'rejected'),\n    assertResolved(race(resolved)(rejectedSlow), 'resolved'),\n    assertRejected(race(resolvedSlow)(rejected), 'rejected'),\n  ]);\n});\n\ntest('cancels the right if the left resolves', function (done){\n  var m = race(resolvedSlow)(Future(function (){ return function (){ return done() } }));\n  m._interpret(done, noop, noop);\n});\n\ntest('cancels the left if the right resolves', function (done){\n  var m = race(Future(function (){ return function (){ return done() } }))(resolvedSlow);\n  m._interpret(done, noop, noop);\n});\n\ntest('cancels the right if the left rejects', function (done){\n  var m = race(rejectedSlow)(Future(function (){ return function (){ return done() } }));\n  m._interpret(done, noop, noop);\n});\n\ntest('cancels the left if the right rejects', function (done){\n  var m = race(Future(function (){ return function (){ return done() } }))(rejectedSlow);\n  m._interpret(done, noop, noop);\n});\n\ntest('creates a cancel function which cancels both Futures', function (done){\n  var cancelled = false;\n  var m = Future(function (){ return function (){ return (cancelled ? done() : (cancelled = true)) } });\n  var cancel = race(m)(m)._interpret(done, noop, noop);\n  cancel();\n});\n\ntest('displays correctly as string', function (){\n  eq(race(rejected)(resolved).toString(), 'race (reject (\"rejected\")) (resolve (\"resolved\"))');\n});\n"
  },
  {
    "path": "test/unit/4.swap.js",
    "content": "import {swap, resolve, reject} from '../../index.js';\nimport {test, assertRejected, assertResolved, assertValidFuture, eq} from '../util/util.js';\nimport {testFunction, futureArg} from '../util/props.js';\n\ntestFunction('swap', swap, [futureArg], assertValidFuture);\n\ntest('rejects with the resolution value', function (){\n  var actual = swap(resolve(1));\n  return assertRejected(actual, 1);\n});\n\ntest('resolves with the rejection reason', function (){\n  var actual = swap(reject(1));\n  return assertResolved(actual, 1);\n});\n\ntest('displays correctly as string', function (){\n  eq(swap(resolve(42)).toString(), 'swap (resolve (42))');\n});\n"
  },
  {
    "path": "test/unit/5.chain-rec.js",
    "content": "import chai from 'chai';\nimport {resolve, after, reject} from '../../index.js';\nimport {chainRec} from '../../src/future.js';\nimport {isIteration} from '../../src/internal/iteration.js';\nimport {test, assertCrashed, assertRejected, assertResolved, error, noop} from '../util/util.js';\n\nvar expect = chai.expect;\n\ntest('is a binary function', function (){\n  expect(chainRec).to.be.a('function');\n  expect(chainRec.length).to.equal(2);\n});\n\ntest('crashes if the iterator throws', function (){\n  var m = chainRec(function (){ throw error });\n  return assertCrashed(m, error);\n});\n\ntest('does not break if the iteration does not contain a value key', function (){\n  var actual = chainRec(function (f, g, x){ return (x, resolve({done: true})) }, 0);\n  return assertResolved(actual, undefined);\n});\n\ntest('calls the function with Next, Done and the initial value', function (){\n  chainRec(function (next, done, x){\n    expect(next).to.be.a('function');\n    expect(next.length).to.equal(1);\n    expect(next(x)).to.satisfy(isIteration);\n    expect(done).to.be.a('function');\n    expect(done.length).to.equal(1);\n    expect(done(x)).to.satisfy(isIteration);\n    expect(x).to.equal(42);\n    return resolve(done(x));\n  }, 42)._interpret(noop, noop, noop);\n});\n\ntest('calls the function with the value from the current iteration', function (){\n  var i = 0;\n  chainRec(function (f, g, x){\n    expect(x).to.equal(i);\n    return x < 5 ? resolve(f(++i)) : resolve(g(x));\n  }, i)._interpret(noop, noop, noop);\n});\n\ntest('works asynchronously', function (){\n  var actual = chainRec(function (f, g, x){ return after(10)(x < 5 ? f(x + 1) : g(x)) }, 0);\n  return assertResolved(actual, 5);\n});\n\ntest('responds to failure', function (){\n  var m = chainRec(function (f, g, x){ return reject(x) }, 1);\n  return assertRejected(m, 1);\n});\n\ntest('responds to failure after chaining async', function (){\n  var m = chainRec(\n    function (f, g, x){ return x < 2 ? after(10)(f(x + 1)) : reject(x) }, 0\n  );\n  return assertRejected(m, 2);\n});\n\ntest('can be cancelled straight away', function (done){\n  const fail = () => done(error);\n  chainRec(function (f, g, x){ return after(10)(g(x)) }, 1)\n  ._interpret(done, fail, fail)();\n  setTimeout(done, 20);\n});\n\ntest('can be cancelled after some iterations', function (done){\n  const fail = () => done(error);\n  var m = chainRec(function (f, g, x){ return after(10)(x < 5 ? f(x + 1) : g(x)) }, 0);\n  var cancel = m._interpret(done, fail, fail);\n  setTimeout(cancel, 25);\n  setTimeout(done, 70);\n});\n"
  },
  {
    "path": "test/unit/5.par.js",
    "content": "import chai from 'chai';\nimport Z from 'sanctuary-type-classes';\nimport {Future, Par, seq, resolve, reject, never, ap, map, alt, and} from '../../index.js';\nimport {test, add, assertCrashed, assertRejected, assertResolved, bang, error, noop, throws} from '../util/util.js';\nimport {rejected, resolved, resolvedSlow} from '../util/futures.js';\n\nvar expect = chai.expect;\n\nvar mf = resolve(bang);\n\ntest('is a unary function', function (){\n  expect(Par).to.be.a('function');\n  expect(Par.length).to.equal(1);\n});\n\ntest('throws when not given a Future', function (){\n  var f = function (){ return Par(1) };\n  throws(f, new TypeError(\n    'Par() expects its first argument to be a valid Future.\\n' +\n    '  Actual: 1 :: Number'\n  ));\n});\n\ntest('of resolves with the value', function (){\n  var m = Z.of(Par, 1);\n  return assertResolved(seq(m), 1);\n});\n\ntest('zero creates a never-ending ConcurrentFuture', function (){\n  var m = Z.zero(Par);\n  expect(seq(m)).to.equal(never);\n});\n\ntest('ap throws TypeError when the Future does not resolve to a Function', function (){\n  var m = seq(ap(Par(resolved))(Par(resolve(1))));\n  return assertCrashed(m, new TypeError(\n    'pap expects the second Future to resolve to a Function\\n' +\n    '  Actual: 1'\n  ));\n});\n\ntest('ap calls the function contained in the given Future to its contained value', function (){\n  var actual = ap(Par(resolved))(Par(mf));\n  return assertResolved(seq(actual), 'resolved!');\n});\n\ntest('ap rejects if one of the two reject', function (){\n  var left = ap(Par(rejected))(Par(mf));\n  var right = ap(Par(resolved))(Par(rejected));\n  return Promise.all([\n    assertRejected(seq(left), 'rejected'),\n    assertRejected(seq(right), 'rejected'),\n  ]);\n});\n\ntest('ap does not matter if either resolves late', function (){\n  var left = ap(Par(resolvedSlow))(Par(mf));\n  var right = ap(Par(resolved))(Par(and(mf)(resolvedSlow)));\n  return Promise.all([\n    assertResolved(seq(left), 'resolvedSlow!'),\n    assertResolved(seq(right), 'resolved!'),\n  ]);\n});\n\ntest('ap cannot reject twice', function (){\n  var actual = ap(Par(rejected))(Par(rejected));\n  return assertRejected(seq(actual), 'rejected');\n});\n\ntest('ap creates a cancel function which cancels both Futures', function (done){\n  var cancelled = false;\n  var m = Par(Future(function (){ return function (){ return (cancelled ? done() : (cancelled = true)) } }));\n  var cancel = seq(ap(m)(m))._interpret(done, noop, noop);\n  cancel();\n});\n\ntest('ap shows a reasonable representation when cast to string', function (){\n  var m = ap(Par(reject(0)))(Par(resolve(1)));\n  var s = 'Par (pap (reject (0)) (resolve (1)))';\n  expect(m.toString()).to.equal(s);\n});\n\ntest('map applies the given function to its inner', function (){\n  var actual = map(add(1))(Par(resolve(1)));\n  return assertResolved(seq(actual), 2);\n});\n\ntest('map does not map rejected state', function (){\n  var actual = map(function (){ return 'mapped' })(Par(rejected));\n  return assertRejected(seq(actual), 'rejected');\n});\n\ntest('map shows a reasonable representation when cast to string', function (){\n  var m = map(noop)(Par(resolved));\n  var expected = 'Par (map (' + noop.toString() + ') (resolve (\"resolved\")))';\n  expect(m.toString()).to.equal(expected);\n});\n\ntest('alt rejects when the first one rejects', function (){\n  var m1 = Par(Future(function (rej, res){ setTimeout(res, 50, 1); return noop }));\n  var m2 = Par(Future(function (rej){ setTimeout(rej, 5, error); return noop }));\n  return assertRejected(seq(alt(m1)(m2)), error);\n});\n\ntest('alt resolves when the first one resolves', function (){\n  var m1 = Par(Future(function (rej, res){ setTimeout(res, 5, 1); return noop }));\n  var m2 = Par(Future(function (rej){ setTimeout(rej, 50, error); return noop }));\n  return assertResolved(seq(alt(m1)(m2)), 1);\n});\n\ntest('alt shows a reasonable representation when cast to string', function (){\n  var m = alt(Par(resolve(1)))(Par(resolve(2)));\n  var s = 'Par (race (resolve (1)) (resolve (2)))';\n  expect(m.toString()).to.equal(s);\n});\n"
  },
  {
    "path": "test/unit/5.seq.js",
    "content": "import {seq} from '../../index.js';\nimport {testFunction, parallelArg} from '../util/props.js';\nimport {assertValidFuture} from '../util/util.js';\n\ntestFunction('seq', seq, [parallelArg], assertValidFuture);\n"
  },
  {
    "path": "test/util/futures.js",
    "content": "import {Future, resolve, reject, after, rejectAfter, and} from '../../index.js';\nimport {crash} from '../../src/future.js';\nimport {error} from '../util/util.js';\n\nexport var mock = Object.create(Future.prototype);\nmock._interpret = function (){ throw new Error('Override _interpret on mock Future') };\nmock.toString = function (){ return '(util.mock)' };\n\nexport var resolved = resolve('resolved');\nexport var rejected = reject('rejected');\nexport var resolvedSlow = after(20)('resolvedSlow');\nexport var rejectedSlow = rejectAfter(20)('rejectedSlow');\nexport var crashed = crash(error);\nexport var crashedSlow = and(crashed)(after(20)(null));\n"
  },
  {
    "path": "test/util/props.js",
    "content": "import type from 'sanctuary-type-identifiers';\nimport show from 'sanctuary-show';\nimport jsc from 'jsverify';\n\nimport {ordinal} from '../../src/internal/const.js';\nimport {eq, error, throws, test} from './util.js';\nimport {\n  any,\n  anyFuture,\n  anyNonFuture,\n  anyParallel,\n  anyFunction,\n  anyResolvedFuture,\n  FutureArb,\n} from '../arbitraries.js';\n\nexport * from '../arbitraries.js';\n\nexport var array = jsc.array;\nexport var nearray = jsc.nearray;\nexport var bool = jsc.bool;\nexport var constant = jsc.constant;\nexport var falsy = jsc.falsy;\nexport var fn = jsc.fn;\nexport var letrec = jsc.letrec;\nexport var nat = jsc.nat;\nexport var number = jsc.number;\nexport var oneof = jsc.oneof;\nexport var string = jsc.string;\nexport var elements = jsc.elements;\nexport var suchthat = jsc.suchthat;\n\nexport function _of (rarb){\n  return FutureArb(string, rarb);\n}\n\nexport function property (name){\n  const args = Array.from(arguments).slice(1);\n  test(name, () => {\n    return jsc.assert(jsc.forall.apply(null, args));\n  });\n}\n\nexport function f (x){\n  return {f: x};\n}\n\nexport function g (x){\n  return {g: x};\n}\n\nexport var altArg = {\n  name: 'have Alt implemented',\n  valid: anyFuture,\n  invalid: anyNonFuture,\n};\n\nexport var applyArg = {\n  name: 'have Apply implemented',\n  valid: anyFuture,\n  invalid: anyNonFuture,\n};\n\nexport var bifunctorArg = {\n  name: 'have Bifunctor implemented',\n  valid: anyFuture,\n  invalid: anyNonFuture,\n};\n\nexport var chainArg = {\n  name: 'have Chain implemented',\n  valid: anyFuture,\n  invalid: anyNonFuture,\n};\n\nexport var functorArg = {\n  name: 'have Functor implemented',\n  valid: anyFuture,\n  invalid: anyNonFuture,\n};\n\nexport var functionArg = {\n  name: 'be a Function',\n  valid: anyFunction,\n  invalid: oneof(number, string, bool, falsy, constant(error)),\n};\n\nexport var futureArg = {\n  name: 'be a valid Future',\n  valid: anyFuture,\n  invalid: anyNonFuture,\n};\n\nexport var resolvedFutureArg = {\n  name: 'be a valid Future',\n  valid: anyResolvedFuture,\n  invalid: anyNonFuture,\n};\n\nexport var positiveIntegerArg = {\n  name: 'be a positive Integer',\n  valid: suchthat(nat, function (x){ return x > 0 }),\n  invalid: oneof(bool, constant(0.5)),\n};\n\nexport var futureArrayArg = {\n  name: 'be an Array of valid Futures',\n  valid: array(anyFuture),\n  invalid: oneof(nearray(anyNonFuture), any),\n};\n\nexport var parallelArg = {\n  name: 'be a ConcurrentFuture',\n  valid: anyParallel,\n  invalid: any,\n};\n\nexport var anyArg = {\n  name: 'be anything',\n  valid: any,\n  invalid: null,\n};\n\nvar getValid = function (x){ return x.valid };\nvar generateValid = function (x){ return getValid(x).generator(1) };\n\nvar capply = function (f, args){\n  return args.reduce(function (g, x){ return g(x) }, f);\n};\n\nexport function testFunction (name, func, args, assert){\n  var validArbs = args.map(getValid);\n  var validArgs = args.map(generateValid);\n\n  test('is a curried ' + args.length + '-ary function', function (){\n    eq(typeof func, 'function');\n    eq(func.length, 1);\n    validArgs.slice(0, -1).forEach(function (_, idx){\n      var partial = capply(func, validArgs.slice(0, idx + 1));\n      eq(typeof partial, 'function');\n      eq(partial.length, 1);\n    });\n  });\n\n  args.forEach(function (arg, idx){\n    var priorArgs = args.slice(0, idx);\n    var followingArgs = args.slice(idx + 1);\n    var validPriorArgs = priorArgs.map(generateValid);\n    var validFollowingArgs = followingArgs.map(generateValid);\n    if(arg !== anyArg){\n      property('throws when the ' + ordinal[idx] + ' argument is invalid', arg.invalid, function (value){\n        throws(function (){\n          capply(func, validPriorArgs.concat([value]).concat(validFollowingArgs));\n        }, new TypeError(\n          name + '() expects its ' + ordinal[idx] + ' argument to ' + arg.name + '.\\n' +\n          '  Actual: ' + show(value) + ' :: ' + type.parse(type(value)).name\n        ));\n        return true;\n      });\n      property('throws when the ' + ordinal[idx] + ' invocation has more than one argument', arg.valid, function (value){\n        throws(function (){\n          var partial = capply(func, validPriorArgs);\n          partial(value, 42);\n        }, new TypeError(\n          name + '() expects to be called with a single argument per invocation\\n' +\n          '  Saw: 2 arguments\\n' +\n          '  First: ' + show(value) + ' :: ' + type.parse(type(value)).name + '\\n' +\n          '  Second: 42 :: Number'\n        ));\n        return true;\n      });\n    }\n  });\n\n  property.apply(null, ['returns valid output when given valid input'].concat(validArbs).concat([function (){\n    return assert(capply(func, Array.from(arguments)));\n  }]));\n}\n"
  },
  {
    "path": "test/util/util.js",
    "content": "import oletus from 'oletus';\nimport show from 'sanctuary-show';\nimport {reject, resolve} from '../../index.js';\nimport {crash} from '../../src/future.js';\nimport * as assert from '../assertions.js';\nexport * from '../../src/internal/predicates.js';\n\nexport var STACKSIZE = (function r (){ try{ return 1 + r() }catch(e){ return 1 } }());\nexport var noop = function (){};\nexport var add = function (a){ return function (b){ return a + b } };\nexport var sub = function (a){ return function (b){ return a - b } };\nexport var bang = function (s){ return (s + '!') };\nexport var I = function (x){ return x };\nexport var B = function (f){ return function (g){ return function (x){ return f(g(x)) } } };\nexport var K = function (x){ return function (){ return x } };\nexport var T = function (x){ return function (f){ return f(x) } };\nexport var error = new Error('Intentional error for unit testing');\nexport var throwing = function (){ throw error };\n\nexport function test (name, impl){\n  oletus(name, () => (\n    impl.length === 0 ? impl() : new Promise((res, rej) => { impl(e => e ? rej(e) : res()) })\n  ));\n}\n\nexport var eq = function eq (actual, expected){\n  assert.equality(actual)(expected);\n};\n\nexport var throws = function throws (f, expected){\n  try{\n    f();\n  }catch(actual){\n    eq(typeof actual, typeof expected);\n    eq(actual.constructor, expected.constructor);\n    eq(actual.name, expected.name);\n    eq(actual.message, expected.message);\n    return;\n  }\n  throw new Error('Expected the function to throw');\n};\n\nexport var itRaises = function itRaises (when, f, e){\n  test('raises ' + when, function (done){\n    var listeners = process.rawListeners('uncaughtException');\n    process.removeAllListeners('uncaughtException');\n    process.once('uncaughtException', function (actual){\n      listeners.forEach(function (f){ process.on('uncaughtException', f) });\n      try {\n        eq(actual.message, e.message);\n      }catch(err){\n        done(err);\n        return;\n      }\n      done();\n    });\n    f();\n  });\n};\n\nexport var isDeepStrictEqual = function isDeepStrictEqual (actual, expected){\n  try{\n    eq(actual, expected);\n    return true;\n  }catch(e){\n    return false;\n  }\n};\n\nexport var repeat = function (n, x){\n  var out = new Array(n);\n  while(n-- > 0){ out[n] = x } //eslint-disable-line\n  return out;\n};\n\nexport var promiseTimeout = function (t, p){\n  return Promise.race([\n    p,\n    new Promise((res, rej) => {\n      setTimeout(rej, t, new Error(`Timeout of ${t}ms reached`));\n    }),\n  ]);\n};\n\nexport var assertIsFuture = function (x){\n  return assert.future(x);\n};\n\nexport var assertValidFuture = function (x){\n  assertIsFuture(x);\n\n  eq(typeof x.extractLeft, 'function');\n  eq(x.extractLeft.length, 0);\n  eq(Array.isArray(x.extractLeft()), true);\n\n  eq(typeof x.extractRight, 'function');\n  eq(x.extractRight.length, 0);\n  eq(Array.isArray(x.extractRight()), true);\n\n  eq(typeof x._transform, 'function');\n  eq(x._transform.length, 1);\n\n  eq(typeof x._interpret, 'function');\n  eq(typeof x._interpret(noop, noop, noop), 'function');\n  eq(x._interpret(noop, noop, noop).length, 0);\n  eq(x._interpret(noop, noop, noop)(), undefined);\n\n  return true;\n};\n\nexport var assertEqual = function (a, b){\n  return assert.equivalence(a)(b);\n};\n\nvar assertEqualByErrorMessage = assert.makeEquivalence(a => b => {\n  return assert.equality(a.message)(b.message);\n});\n\nexport var assertCrashed = function (m, x){\n  return assertEqualByErrorMessage(m)(crash(x));\n};\n\nexport var assertRejected = function (m, x){\n  return assertEqual(m, reject(x));\n};\n\nexport var assertResolved = function (m, x){\n return assertEqual(m, resolve(x));\n};\n\nexport var onceOrError = function (f){\n  var called = false;\n  return function (){\n    if(called){ throw new Error('Function ' + show(f) + ' was called twice') }\n    called = true;\n    return f.apply(null, arguments);\n  };\n};\n\nexport function assertStackTrace (name, x){\n  eq(typeof x, 'string');\n  eq(x.slice(0, name.length), name);\n  var lines = x.slice(name.length).split('\\n');\n  eq(lines.length > 0, true);\n}\n"
  }
]