Full Code of tj/co for AI

master 249bbdc72da2 cached
19 files
32.2 KB
8.9k tokens
17 symbols
1 requests
Download .txt
Repository: tj/co
Branch: master
Commit: 249bbdc72da2
Files: 19
Total size: 32.2 KB

Directory structure:
gitextract_p95l60cs/

├── .gitignore
├── .travis.yml
├── History.md
├── LICENSE
├── Readme.md
├── component.json
├── index.js
├── package.json
└── test/
    ├── arguments.js
    ├── arrays.js
    ├── context.js
    ├── generator-functions.js
    ├── generators.js
    ├── invalid.js
    ├── objects.js
    ├── promises.js
    ├── recursion.js
    ├── thunks.js
    └── wrap.js

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
node_modules
coverage
co-browser.js

================================================
FILE: .travis.yml
================================================
node_js:
- "stable"
- "4"
- "iojs"
- "0.12"
language: node_js
script: "npm run-script test-travis"
after_script: "npm install coveralls@2 && cat ./coverage/lcov.info | coveralls"


================================================
FILE: History.md
================================================
4.6.0 / 2015-07-09
==================

 * support passing the rest of the arguments to co into the generator

 ```js
 function *gen(...args) { }
 co(gen, ...args);
 ```

4.5.0 / 2015-03-17
==================

 * support regular functions (that return promises)

4.4.0 / 2015-02-14
==================

 * refactor `isGeneratorFunction`
 * expose generator function from `co.wrap()`
 * drop support for node < 0.12

4.3.0 / 2015-02-05
==================

 * check for generator functions in a ES5-transpiler-friendly way

4.2.0 / 2015-01-20
==================

 * support comparing generator functions with ES6 transpilers

4.1.0 / 2014-12-26
==================

 * fix memory leak #180

4.0.2 / 2014-12-18
==================

 * always return a global promise implementation

4.0.1 / 2014-11-30
==================

 * friendlier ES6 module exports

4.0.0 / 2014-11-15
==================

 * co now returns a promise and uses promises underneath
 * `co.wrap()` for wrapping generator functions

3.1.0 / 2014-06-30
==================

 * remove `setImmediate()` shim for node 0.8. semi-backwards breaking.
   Users are expected to shim themselves. Also returns CommonJS browser support.
 * added key order preservation for objects. thanks @greim
 * replace `q` with `bluebird` in benchmarks and tests

3.0.6 / 2014-05-03
==================

 * add `setImmediate()` fallback to `process.nextTick`
 * remove duplicate code in toThunk
 * update thunkify

3.0.5 / 2014-03-17
==================

 * fix object/array test failure which tries to enumerate dates. Closes #98
 * fix final callback error propagation. Closes #92

3.0.4 / 2014-02-17
==================

 * fix toThunk object check regression. Closes #89

3.0.3 / 2014-02-08
==================

 * refactor: arrayToThunk @AutoSponge #88

3.0.2 / 2014-01-01
==================

 * fixed: nil arguments replaced with error fn

3.0.1 / 2013-12-19
==================

 * fixed: callback passed as an argument to generators

3.0.0 / 2013-12-19
==================

 * fixed: callback passed as an argument to generators
 * change: `co(function *(){})` now returns a reusable thunk
 * change: `this` must now be passed through the returned thunk, ex. `co(function *(){}).call(this)`
 * fix "generator already finished" errors

2.3.0 / 2013-11-12
==================

 * add `yield object` support

2.2.0 / 2013-11-05
==================

 * change: make the `isGenerator()` function more generic

2.1.0 / 2013-10-21
==================

 * add passing of arguments into the generator. closes #33.

2.0.0 / 2013-10-14
==================

 * remove callback in favour of thunk-only co(). Closes #30 [breaking change]
 * remove `co.wrap()` [breaking change]

1.5.2 / 2013-09-02
==================

 * fix: preserve receiver with co.wrap()

1.5.1 / 2013-08-11
==================

 * remove setImmediate() usage - ~110% perf increase. Closes #14

0.5.0 / 2013-08-10
==================

 * add receiver propagation support
 * examples: update streams.js example to use `http.get()` and streams2 API

1.4.1 / 2013-07-01
==================

 * fix gen.next(val) for latest v8. Closes #8

1.4.0 / 2013-06-21
==================

 * add promise support to joins
 * add `yield generatorFunction` support
 * add `yield generator` support
 * add nested join support

1.3.0 / 2013-06-10
==================

 * add passing of arguments

1.2.1 / 2013-06-08
==================

 * fix join() of zero thunks

1.2.0 / 2013-06-08
==================

 * add array yielding support. great suggestion by @domenic

1.1.0 / 2013-06-06
==================

 * add promise support
 * change nextTick to setImmediate


================================================
FILE: LICENSE
================================================
(The MIT License)

Copyright (c) 2014 TJ Holowaychuk &lt;tj@vision-media.ca&gt;

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


================================================
FILE: Readme.md
================================================
# co

[![Gitter][gitter-image]][gitter-url]
[![NPM version][npm-image]][npm-url]
[![Build status][travis-image]][travis-url]
[![Test coverage][coveralls-image]][coveralls-url]
[![Downloads][downloads-image]][downloads-url]

  Generator based control flow goodness for nodejs and the browser,
  using promises, letting you write non-blocking code in a nice-ish way.

## Co v4

  `co@4.0.0` has been released, which now relies on promises.
  It is a stepping stone towards the [async/await proposal](https://github.com/lukehoban/ecmascript-asyncawait).
  The primary API change is how `co()` is invoked.
  Before, `co` returned a "thunk", which you then called with a callback and optional arguments.
  Now, `co()` returns a promise.

```js
co(function* () {
  var result = yield Promise.resolve(true);
  return result;
}).then(function (value) {
  console.log(value);
}, function (err) {
  console.error(err.stack);
});
```

  If you want to convert a `co`-generator-function into a regular function that returns a promise,
  you now use `co.wrap(fn*)`.

```js
var fn = co.wrap(function* (val) {
  return yield Promise.resolve(val);
});

fn(true).then(function (val) {

});
```

## Platform Compatibility

  `co@4+` requires a `Promise` implementation.
  For versions of node `< 0.11` and for many older browsers,
  you should/must include your own `Promise` polyfill.

  When using node 0.10.x and lower or browsers without generator support,
  you must use [gnode](https://github.com/TooTallNate/gnode) and/or [regenerator](http://facebook.github.io/regenerator/).

  When using node 0.11.x, you must use the `--harmony-generators`
  flag or just `--harmony` to get access to generators.

  Node v4+ is supported out of the box, you can use `co` without flags or polyfills.

## Installation

```
$ npm install co
```

## Associated libraries

Any library that returns promises work well with `co`.

- [mz](https://github.com/normalize/mz) - wrap all of node's code libraries as promises.

View the [wiki](https://github.com/visionmedia/co/wiki) for more libraries.

## Examples

```js
var co = require('co');

co(function *(){
  // yield any promise
  var result = yield Promise.resolve(true);
}).catch(onerror);

co(function *(){
  // resolve multiple promises in parallel
  var a = Promise.resolve(1);
  var b = Promise.resolve(2);
  var c = Promise.resolve(3);
  var res = yield [a, b, c];
  console.log(res);
  // => [1, 2, 3]
}).catch(onerror);

// errors can be try/catched
co(function *(){
  try {
    yield Promise.reject(new Error('boom'));
  } catch (err) {
    console.error(err.message); // "boom"
 }
}).catch(onerror);

function onerror(err) {
  // log any uncaught errors
  // co will not throw any errors you do not handle!!!
  // HANDLE ALL YOUR ERRORS!!!
  console.error(err.stack);
}
```

## Yieldables

  The `yieldable` objects currently supported are:

  - promises
  - thunks (functions)
  - array (parallel execution)
  - objects (parallel execution)
  - generators (delegation)
  - generator functions (delegation)

Nested `yieldable` objects are supported, meaning you can nest
promises within objects within arrays, and so on!

### Promises

[Read more on promises!](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)

### Thunks

Thunks are functions that only have a single argument, a callback.
Thunk support only remains for backwards compatibility and may
be removed in future versions of `co`.

### Arrays

`yield`ing an array will resolve all the `yieldables` in parallel.

```js
co(function* () {
  var res = yield [
    Promise.resolve(1),
    Promise.resolve(2),
    Promise.resolve(3),
  ];
  console.log(res); // => [1, 2, 3]
}).catch(onerror);
```

### Objects

Just like arrays, objects resolve all `yieldable`s in parallel.

```js
co(function* () {
  var res = yield {
    1: Promise.resolve(1),
    2: Promise.resolve(2),
  };
  console.log(res); // => { 1: 1, 2: 2 }
}).catch(onerror);
```

### Generators and Generator Functions

Any generator or generator function you can pass into `co`
can be yielded as well. This should generally be avoided
as we should be moving towards spec-compliant `Promise`s instead.

## API

### co(fn*).then( val => )

Returns a promise that resolves a generator, generator function,
or any function that returns a generator.

```js
co(function* () {
  return yield Promise.resolve(true);
}).then(function (val) {
  console.log(val);
}, function (err) {
  console.error(err.stack);
});
```

### var fn = co.wrap(fn*)

Convert a generator into a regular function that returns a `Promise`.

```js
var fn = co.wrap(function* (val) {
  return yield Promise.resolve(val);
});

fn(true).then(function (val) {

});
```

## License

  MIT

[npm-image]: https://img.shields.io/npm/v/co.svg?style=flat-square
[npm-url]: https://npmjs.org/package/co
[travis-image]: https://img.shields.io/travis/tj/co.svg?style=flat-square
[travis-url]: https://travis-ci.org/tj/co
[coveralls-image]: https://img.shields.io/coveralls/tj/co.svg?style=flat-square
[coveralls-url]: https://coveralls.io/r/tj/co
[downloads-image]: http://img.shields.io/npm/dm/co.svg?style=flat-square
[downloads-url]: https://npmjs.org/package/co
[gitter-image]: https://badges.gitter.im/Join%20Chat.svg
[gitter-url]: https://gitter.im/tj/co?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge


================================================
FILE: component.json
================================================
{
  "name": "co",
  "version": "4.4.0",
  "description": "generator async control flow goodness",
  "keywords": [
    "async",
    "flow",
    "generator",
    "coro",
    "coroutine"
  ],
  "repo": "tj/co",
  "scripts": ["index.js"],
  "licence": "MIT"
}


================================================
FILE: index.js
================================================

/**
 * slice() reference.
 */

var slice = Array.prototype.slice;

/**
 * Expose `co`.
 */

module.exports = co['default'] = co.co = co;

/**
 * Wrap the given generator `fn` into a
 * function that returns a promise.
 * This is a separate function so that
 * every `co()` call doesn't create a new,
 * unnecessary closure.
 *
 * @param {GeneratorFunction} fn
 * @return {Function}
 * @api public
 */

co.wrap = function (fn) {
  createPromise.__generatorFunction__ = fn;
  return createPromise;
  function createPromise() {
    return co.call(this, fn.apply(this, arguments));
  }
};

/**
 * Execute the generator function or a generator
 * and return a promise.
 *
 * @param {Function} fn
 * @return {Promise}
 * @api public
 */

function co(gen) {
  var ctx = this;
  var args = slice.call(arguments, 1);

  // we wrap everything in a promise to avoid promise chaining,
  // which leads to memory leak errors.
  // see https://github.com/tj/co/issues/180
  return new Promise(function(resolve, reject) {
    if (typeof gen === 'function') gen = gen.apply(ctx, args);
    if (!gen || typeof gen.next !== 'function') return resolve(gen);

    onFulfilled();

    /**
     * @param {Mixed} res
     * @return {Promise}
     * @api private
     */

    function onFulfilled(res) {
      var ret;
      try {
        ret = gen.next(res);
      } catch (e) {
        return reject(e);
      }
      next(ret);
      return null;
    }

    /**
     * @param {Error} err
     * @return {Promise}
     * @api private
     */

    function onRejected(err) {
      var ret;
      try {
        ret = gen.throw(err);
      } catch (e) {
        return reject(e);
      }
      next(ret);
    }

    /**
     * Get the next value in the generator,
     * return a promise.
     *
     * @param {Object} ret
     * @return {Promise}
     * @api private
     */

    function next(ret) {
      if (ret.done) return resolve(ret.value);
      var value = toPromise.call(ctx, ret.value);
      if (value && isPromise(value)) return value.then(onFulfilled, onRejected);
      return onRejected(new TypeError('You may only yield a function, promise, generator, array, or object, '
        + 'but the following object was passed: "' + String(ret.value) + '"'));
    }
  });
}

/**
 * Convert a `yield`ed value into a promise.
 *
 * @param {Mixed} obj
 * @return {Promise}
 * @api private
 */

function toPromise(obj) {
  if (!obj) return obj;
  if (isPromise(obj)) return obj;
  if (isGeneratorFunction(obj) || isGenerator(obj)) return co.call(this, obj);
  if ('function' == typeof obj) return thunkToPromise.call(this, obj);
  if (Array.isArray(obj)) return arrayToPromise.call(this, obj);
  if (isObject(obj)) return objectToPromise.call(this, obj);
  return obj;
}

/**
 * Convert a thunk to a promise.
 *
 * @param {Function}
 * @return {Promise}
 * @api private
 */

function thunkToPromise(fn) {
  var ctx = this;
  return new Promise(function (resolve, reject) {
    fn.call(ctx, function (err, res) {
      if (err) return reject(err);
      if (arguments.length > 2) res = slice.call(arguments, 1);
      resolve(res);
    });
  });
}

/**
 * Convert an array of "yieldables" to a promise.
 * Uses `Promise.all()` internally.
 *
 * @param {Array} obj
 * @return {Promise}
 * @api private
 */

function arrayToPromise(obj) {
  return Promise.all(obj.map(toPromise, this));
}

/**
 * Convert an object of "yieldables" to a promise.
 * Uses `Promise.all()` internally.
 *
 * @param {Object} obj
 * @return {Promise}
 * @api private
 */

function objectToPromise(obj){
  var results = new obj.constructor();
  var keys = Object.keys(obj);
  var promises = [];
  for (var i = 0; i < keys.length; i++) {
    var key = keys[i];
    var promise = toPromise.call(this, obj[key]);
    if (promise && isPromise(promise)) defer(promise, key);
    else results[key] = obj[key];
  }
  return Promise.all(promises).then(function () {
    return results;
  });

  function defer(promise, key) {
    // predefine the key in the result
    results[key] = undefined;
    promises.push(promise.then(function (res) {
      results[key] = res;
    }));
  }
}

/**
 * Check if `obj` is a promise.
 *
 * @param {Object} obj
 * @return {Boolean}
 * @api private
 */

function isPromise(obj) {
  return 'function' == typeof obj.then;
}

/**
 * Check if `obj` is a generator.
 *
 * @param {Mixed} obj
 * @return {Boolean}
 * @api private
 */

function isGenerator(obj) {
  return 'function' == typeof obj.next && 'function' == typeof obj.throw;
}

/**
 * Check if `obj` is a generator function.
 *
 * @param {Mixed} obj
 * @return {Boolean}
 * @api private
 */
 
function isGeneratorFunction(obj) {
  var constructor = obj.constructor;
  if (!constructor) return false;
  if ('GeneratorFunction' === constructor.name || 'GeneratorFunction' === constructor.displayName) return true;
  return isGenerator(constructor.prototype);
}

/**
 * Check for plain object.
 *
 * @param {Mixed} val
 * @return {Boolean}
 * @api private
 */

function isObject(val) {
  return Object == val.constructor;
}


================================================
FILE: package.json
================================================
{
  "name": "co",
  "version": "4.6.0",
  "description": "generator async control flow goodness",
  "keywords": [
    "async",
    "flow",
    "generator",
    "coro",
    "coroutine"
  ],
  "devDependencies": {
    "browserify": "^10.0.0",
    "istanbul-harmony": "0",
    "mocha": "^2.0.0",
    "mz": "^1.0.2"
  },
  "scripts": {
    "test": "mocha --harmony",
    "test-cov": "node --harmony node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha -- --reporter dot",
    "test-travis": "node --harmony node_modules/.bin/istanbul cover ./node_modules/.bin/_mocha --report lcovonly -- --reporter dot",
    "prepublish": "npm run browserify",
    "browserify": "browserify index.js -o ./co-browser.js -s co"
  },
  "files": [
    "co-browser.js",
    "index.js"
  ],
  "license": "MIT",
  "repository": "tj/co",
  "engines": {
    "iojs": ">= 1.0.0",
    "node": ">= 0.12.0"
  }
}


================================================
FILE: test/arguments.js
================================================

var assert = require('assert');

var co = require('..');

describe('co(gen, args)', function () {
  it('should pass the rest of the arguments', function () {
    return co(function *(num, str, arr, obj, fun){
      assert(num === 42);
      assert(str === 'forty-two');
      assert(arr[0] === 42);
      assert(obj.value === 42);
      assert(fun instanceof Function)
    }, 42, 'forty-two', [42], { value: 42 }, function () {});
  })
})


================================================
FILE: test/arrays.js
================================================

var read = require('mz/fs').readFile;
var assert = require('assert');

var co = require('..');

describe('co(* -> yield [])', function(){
  it('should aggregate several promises', function(){
    return co(function *(){
      var a = read('index.js', 'utf8');
      var b = read('LICENSE', 'utf8');
      var c = read('package.json', 'utf8');

      var res = yield [a, b, c];
      assert.equal(3, res.length);
      assert(~res[0].indexOf('exports'));
      assert(~res[1].indexOf('MIT'));
      assert(~res[2].indexOf('devDependencies'));
    });
  })

  it('should noop with no args', function(){
    return co(function *(){
      var res = yield [];
      assert.equal(0, res.length);
    });
  })

  it('should support an array of generators', function(){
    return co(function*(){
      var val = yield [function*(){ return 1 }()]
      assert.deepEqual(val, [1])
    })
  })
})


================================================
FILE: test/context.js
================================================

var assert = require('assert');

var co = require('..');

var ctx = {
  some: 'thing'
};

describe('co.call(this)', function () {
  it('should pass the context', function () {
    return co.call(ctx, function *(){
      assert(ctx == this);
    });
  })
})


================================================
FILE: test/generator-functions.js
================================================

var assert = require('assert');
var co = require('..');

function sleep(ms) {
  return function(done){
    setTimeout(done, ms);
  }
}

function *work() {
  yield sleep(50);
  return 'yay';
}

describe('co(fn*)', function(){
  describe('with a generator function', function(){
    it('should wrap with co()', function(){
      return co(function *(){
        var a = yield work;
        var b = yield work;
        var c = yield work;

        assert('yay' == a);
        assert('yay' == b);
        assert('yay' == c);

        var res = yield [work, work, work];
        assert.deepEqual(['yay', 'yay', 'yay'], res);
      });
    })

    it('should catch errors', function(){
      return co(function *(){
        yield function *(){
          throw new Error('boom');
        };
      }).then(function () {
        throw new Error('wtf')
      }, function (err) {
        assert(err);
        assert(err.message == 'boom');
      });
    })
  })
})


================================================
FILE: test/generators.js
================================================

var assert = require('assert');
var co = require('..');

function sleep(ms) {
  return function(done){
    setTimeout(done, ms);
  }
}

function *work() {
  yield sleep(50);
  return 'yay';
}

describe('co(*)', function(){
  describe('with a generator function', function(){
    it('should wrap with co()', function(){
      return co(function *(){
        var a = yield work;
        var b = yield work;
        var c = yield work;

        assert('yay' == a);
        assert('yay' == b);
        assert('yay' == c);

        var res = yield [work, work, work];
        assert.deepEqual(['yay', 'yay', 'yay'], res);
      });
    })

    it('should catch errors', function(){
      return co(function *(){
        yield function *(){
          throw new Error('boom');
        };
      }).then(function () {
        throw new Error('wtf')
      }, function (err) {
        assert(err);
        assert(err.message == 'boom');
      });
    })
  })
})


================================================
FILE: test/invalid.js
================================================

var assert = require('assert');

var co = require('..');

describe('yield <invalid>', function () {
  it('should throw an error', function () {
    return co(function* () {
      try {
        yield null;
        throw new Error('lol');
      } catch (err) {
        assert(err instanceof TypeError);
        assert(~err.message.indexOf('You may only yield'));
      }
    })
  })
})


================================================
FILE: test/objects.js
================================================

var read = require('mz/fs').readFile;
var assert = require('assert');

var co = require('..');

describe('co(* -> yield {})', function(){
  it('should aggregate several promises', function(){
    return co(function *(){
      var a = read('index.js', 'utf8');
      var b = read('LICENSE', 'utf8');
      var c = read('package.json', 'utf8');

      var res = yield {
        a: a,
        b: b,
        c: c
      };

      assert.equal(3, Object.keys(res).length);
      assert(~res.a.indexOf('exports'));
      assert(~res.b.indexOf('MIT'));
      assert(~res.c.indexOf('devDependencies'));
    });
  })

  it('should noop with no args', function(){
    return co(function *(){
      var res = yield {};
      assert.equal(0, Object.keys(res).length);
    });
  })

  it('should ignore non-thunkable properties', function(){
    return co(function *(){
      var foo = {
        name: { first: 'tobi' },
        age: 2,
        address: read('index.js', 'utf8'),
        tobi: new Pet('tobi'),
        now: new Date(),
        falsey: false,
        nully: null,
        undefiney: undefined,
      };

      var res = yield foo;

      assert.equal('tobi', res.name.first);
      assert.equal(2, res.age);
      assert.equal('tobi', res.tobi.name);
      assert.equal(foo.now, res.now);
      assert.equal(false, foo.falsey);
      assert.equal(null, foo.nully);
      assert.equal(undefined, foo.undefiney);
      assert(~res.address.indexOf('exports'));
    });
  })

  it('should preserve key order', function(){
    function timedThunk(time){
      return function(cb){
        setTimeout(cb, time);
      }
    }

    return co(function *(){
      var before = {
        sun: timedThunk(30),
        rain: timedThunk(20),
        moon: timedThunk(10)
      };

      var after = yield before;

      var orderBefore = Object.keys(before).join(',');
      var orderAfter = Object.keys(after).join(',');
      assert.equal(orderBefore, orderAfter);
    });
  })
})

function Pet(name) {
  this.name = name;
  this.something = function(){};
}


================================================
FILE: test/promises.js
================================================

var assert = require('assert');

var co = require('..');

function getPromise(val, err) {
  return new Promise(function (resolve, reject) {
    if (err) reject(err);
    else resolve(val);
  });
}

describe('co(* -> yield <promise>', function(){
  describe('with one promise yield', function(){
    it('should work', function(){
      return co(function *(){
        var a = yield getPromise(1);
        assert.equal(1, a);
      });
    })
  })

  describe('with several promise yields', function(){
    it('should work', function(){
      return co(function *(){
        var a = yield getPromise(1);
        var b = yield getPromise(2);
        var c = yield getPromise(3);

        assert.deepEqual([1, 2, 3], [a, b, c]);
      });
    })
  })

  describe('when a promise is rejected', function(){
    it('should throw and resume', function(){
      var error;

      return co(function *(){
        try {
          yield getPromise(1, new Error('boom'));
        } catch (err) {
          error = err;
        }

        assert('boom' == error.message);
        var ret = yield getPromise(1);
        assert(1 == ret);
      });
    })
  })

  describe('when yielding a non-standard promise-like', function(){
    it('should return a real Promise', function() {
      assert(co(function *(){
        yield { then: function(){} };
      }) instanceof Promise);
    });
  })
})

describe('co(function) -> promise', function(){
  it('return value', function(done){
    co(function(){
      return 1;
    }).then(function(data){
      assert.equal(data, 1);
      done();
    })
  })

  it('return resolve promise', function(){
    return co(function(){
      return Promise.resolve(1);
    }).then(function(data){
      assert.equal(data, 1);
    })
  })

  it('return reject promise', function(){
    return co(function(){
      return Promise.reject(1);
    }).catch(function(data){
      assert.equal(data, 1);
    })
  })

  it('should catch errors', function(){
    return co(function(){
      throw new Error('boom');
    }).then(function () {
      throw new Error('nope');
    }).catch(function (err) {
      assert.equal(err.message, 'boom');
    });
  })
})


================================================
FILE: test/recursion.js
================================================

var read = require('mz/fs').readFile;
var assert = require('assert');

var co = require('..');

describe('co() recursion', function(){
  it('should aggregate arrays within arrays', function(){
    return co(function *(){
      var a = read('index.js', 'utf8');
      var b = read('LICENSE', 'utf8');
      var c = read('package.json', 'utf8');

      var res = yield [a, [b, c]];
      assert.equal(2, res.length);
      assert(~res[0].indexOf('exports'));
      assert.equal(2, res[1].length);
      assert(~res[1][0].indexOf('MIT'));
      assert(~res[1][1].indexOf('devDependencies'));
    });
  })

  it('should aggregate objects within objects', function(){
    return co(function *(){
      var a = read('index.js', 'utf8');
      var b = read('LICENSE', 'utf8');
      var c = read('package.json', 'utf8');

      var res = yield {
        0: a,
        1: {
          0: b,
          1: c
        }
      };

      assert(~res[0].indexOf('exports'));
      assert(~res[1][0].indexOf('MIT'));
      assert(~res[1][1].indexOf('devDependencies'));
    });
  })
})


================================================
FILE: test/thunks.js
================================================

var assert = require('assert');

var co = require('..');

function get(val, err, error) {
  return function(done){
    if (error) throw error;
    setTimeout(function(){
      done(err, val);
    }, 10);
  }
}

describe('co(* -> yield fn(done))', function () {
  describe('with no yields', function(){
    it('should work', function(){
      return co(function *(){});
    })
  })

  describe('with one yield', function(){
    it('should work', function(){
      return co(function *(){
        var a = yield get(1);
        assert.equal(1, a);
      });
    })
  })

  describe('with several yields', function(){
    it('should work', function(){
      return co(function *(){
        var a = yield get(1);
        var b = yield get(2);
        var c = yield get(3);

        assert.deepEqual([1, 2, 3], [a, b, c]);
      });
    })
  })

  describe('with many arguments', function(){
    it('should return an array', function(){
      function exec(cmd) {
        return function(done){
          done(null, 'stdout', 'stderr');
        }
      }

      return co(function *(){
        var out = yield exec('something');
        assert.deepEqual(['stdout', 'stderr'], out);
      });
    })
  })

  describe('when the function throws', function(){
    it('should be caught', function(){
      return co(function *(){
        try {
          var a = yield get(1, null, new Error('boom'));
        } catch (err) {
          assert.equal('boom', err.message);
        }
      });
    })
  })

  describe('when an error is passed then thrown', function(){
    it('should only catch the first error only', function(){
      return co(function *() {
        yield function (done){
          done(new Error('first'));
          throw new Error('second');
        }
      }).then(function () {
        throw new Error('wtf')
      }, function(err){
        assert.equal('first', err.message);
      });
    })
  })

  describe('when an error is passed', function(){
    it('should throw and resume', function(){
      var error;

      return co(function *(){
        try {
          yield get(1, new Error('boom'));
        } catch (err) {
          error = err;
        }

        assert('boom' == error.message);
        var ret = yield get(1);
        assert(1 == ret);
      });
    })
  })

  describe('with nested co()s', function(){
    it('should work', function(){
      var hit = [];

      return co(function *(){
        var a = yield get(1);
        var b = yield get(2);
        var c = yield get(3);
        hit.push('one');

        assert.deepEqual([1, 2, 3], [a, b, c])

        yield co(function *(){
          hit.push('two');
          var a = yield get(1);
          var b = yield get(2);
          var c = yield get(3);

          assert.deepEqual([1, 2, 3], [a, b, c])

          yield co(function *(){
            hit.push('three');
            var a = yield get(1);
            var b = yield get(2);
            var c = yield get(3);

            assert.deepEqual([1, 2, 3], [a, b, c])
          });
        });

        yield co(function *(){
          hit.push('four');
          var a = yield get(1);
          var b = yield get(2);
          var c = yield get(3);

          assert.deepEqual([1, 2, 3], [a, b, c])
        });

        assert.deepEqual(['one', 'two', 'three', 'four'], hit);
      });
    })
  })

  describe('return values', function(){
    describe('with a callback', function(){
      it('should be passed', function(){
        return co(function *(){
          return [
            yield get(1),
            yield get(2),
            yield get(3)
          ];
        }).then(function (res) {
          assert.deepEqual([1, 2, 3], res);
        });
      })
    })

    describe('when nested', function(){
      it('should return the value', function(){
        return co(function *(){
          var other = yield co(function *(){
            return [
              yield get(4),
              yield get(5),
              yield get(6)
            ]
          });

          return [
            yield get(1),
            yield get(2),
            yield get(3)
          ].concat(other);
        }).then(function (res) {
          assert.deepEqual([1, 2, 3, 4, 5, 6], res);
        });
      })
    })
  })

  describe('when yielding neither a function nor a promise', function(){
    it('should throw', function(){
      var errors = [];

      return co(function *(){
        try {
          var a = yield 'something';
        } catch (err) {
          errors.push(err.message);
        }

        try {
          var a = yield 'something';
        } catch (err) {
          errors.push(err.message);
        }

        assert.equal(2, errors.length);
        var msg = 'yield a function, promise, generator, array, or object';
        assert(~errors[0].indexOf(msg));
        assert(~errors[1].indexOf(msg));
      });
    })
  })

  describe('with errors', function(){
    it('should throw', function(){
      var errors = [];

      return co(function *(){
        try {
          var a = yield get(1, new Error('foo'));
        } catch (err) {
          errors.push(err.message);
        }

        try {
          var a = yield get(1, new Error('bar'));
        } catch (err) {
          errors.push(err.message);
        }

        assert.deepEqual(['foo', 'bar'], errors);
      });
    })

    it('should catch errors on .send()', function(){
      var errors = [];

      return co(function *(){
        try {
          var a = yield get(1, null, new Error('foo'));
        } catch (err) {
          errors.push(err.message);
        }

        try {
          var a = yield get(1, null, new Error('bar'));
        } catch (err) {
          errors.push(err.message);
        }

        assert.deepEqual(['foo', 'bar'], errors);
      });
    })

    it('should pass future errors to the callback', function(){
      return co(function *(){
        yield get(1);
        yield get(2, null, new Error('fail'));
        assert(false);
        yield get(3);
      }).catch(function(err){
        assert.equal('fail', err.message);
      });
    })

    it('should pass immediate errors to the callback', function(){
      return co(function *(){
        yield get(1);
        yield get(2, new Error('fail'));
        assert(false);
        yield get(3);
      }).catch(function(err){
        assert.equal('fail', err.message);
      });
    })

    it('should catch errors on the first invocation', function(){
      return co(function *(){
        throw new Error('fail');
      }).catch(function(err){
        assert.equal('fail', err.message);
      });
    })
  })
})


================================================
FILE: test/wrap.js
================================================

var assert = require('assert');

var co = require('..');

describe('co.wrap(fn*)', function () {
  it('should pass context', function () {
    var ctx = {
      some: 'thing'
    };

    return co.wrap(function* () {
      assert.equal(ctx, this);
    }).call(ctx);
  })

  it('should pass arguments', function () {
    return co.wrap(function* (a, b, c) {
      assert.deepEqual([1, 2, 3], [a, b, c]);
    })(1, 2, 3);
  })

  it('should expose the underlying generator function', function () {
    var wrapped = co.wrap(function* (a, b, c) {});
    var source = Object.toString.call(wrapped.__generatorFunction__);
    assert(source.indexOf('function*') === 0);
  })
})
Download .txt
gitextract_p95l60cs/

├── .gitignore
├── .travis.yml
├── History.md
├── LICENSE
├── Readme.md
├── component.json
├── index.js
├── package.json
└── test/
    ├── arguments.js
    ├── arrays.js
    ├── context.js
    ├── generator-functions.js
    ├── generators.js
    ├── invalid.js
    ├── objects.js
    ├── promises.js
    ├── recursion.js
    ├── thunks.js
    └── wrap.js
Download .txt
SYMBOL INDEX (17 symbols across 6 files)

FILE: index.js
  function createPromise (line 29) | function createPromise() {
  function co (line 43) | function co(gen) {
  function toPromise (line 116) | function toPromise(obj) {
  function thunkToPromise (line 134) | function thunkToPromise(fn) {
  function arrayToPromise (line 154) | function arrayToPromise(obj) {
  function objectToPromise (line 167) | function objectToPromise(obj){
  function isPromise (line 198) | function isPromise(obj) {
  function isGenerator (line 210) | function isGenerator(obj) {
  function isGeneratorFunction (line 222) | function isGeneratorFunction(obj) {
  function isObject (line 237) | function isObject(val) {

FILE: test/generator-functions.js
  function sleep (line 5) | function sleep(ms) {

FILE: test/generators.js
  function sleep (line 5) | function sleep(ms) {

FILE: test/objects.js
  function timedThunk (line 61) | function timedThunk(time){
  function Pet (line 83) | function Pet(name) {

FILE: test/promises.js
  function getPromise (line 6) | function getPromise(val, err) {

FILE: test/thunks.js
  function get (line 6) | function get(val, err, error) {
  function exec (line 45) | function exec(cmd) {
Condensed preview — 19 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (35K chars).
[
  {
    "path": ".gitignore",
    "chars": 35,
    "preview": "node_modules\ncoverage\nco-browser.js"
  },
  {
    "path": ".travis.yml",
    "chars": 179,
    "preview": "node_js:\n- \"stable\"\n- \"4\"\n- \"iojs\"\n- \"0.12\"\nlanguage: node_js\nscript: \"npm run-script test-travis\"\nafter_script: \"npm in"
  },
  {
    "path": "History.md",
    "chars": 3629,
    "preview": "4.6.0 / 2015-07-09\n==================\n\n * support passing the rest of the arguments to co into the generator\n\n ```js\n fu"
  },
  {
    "path": "LICENSE",
    "chars": 1104,
    "preview": "(The MIT License)\n\nCopyright (c) 2014 TJ Holowaychuk &lt;tj@vision-media.ca&gt;\n\nPermission is hereby granted, free of c"
  },
  {
    "path": "Readme.md",
    "chars": 5383,
    "preview": "# co\n\n[![Gitter][gitter-image]][gitter-url]\n[![NPM version][npm-image]][npm-url]\n[![Build status][travis-image]][travis-"
  },
  {
    "path": "component.json",
    "chars": 256,
    "preview": "{\n  \"name\": \"co\",\n  \"version\": \"4.4.0\",\n  \"description\": \"generator async control flow goodness\",\n  \"keywords\": [\n    \"a"
  },
  {
    "path": "index.js",
    "chars": 5058,
    "preview": "\n/**\n * slice() reference.\n */\n\nvar slice = Array.prototype.slice;\n\n/**\n * Expose `co`.\n */\n\nmodule.exports = co['defaul"
  },
  {
    "path": "package.json",
    "chars": 886,
    "preview": "{\n  \"name\": \"co\",\n  \"version\": \"4.6.0\",\n  \"description\": \"generator async control flow goodness\",\n  \"keywords\": [\n    \"a"
  },
  {
    "path": "test/arguments.js",
    "chars": 440,
    "preview": "\nvar assert = require('assert');\n\nvar co = require('..');\n\ndescribe('co(gen, args)', function () {\n  it('should pass the"
  },
  {
    "path": "test/arrays.js",
    "chars": 888,
    "preview": "\nvar read = require('mz/fs').readFile;\nvar assert = require('assert');\n\nvar co = require('..');\n\ndescribe('co(* -> yield"
  },
  {
    "path": "test/context.js",
    "chars": 258,
    "preview": "\nvar assert = require('assert');\n\nvar co = require('..');\n\nvar ctx = {\n  some: 'thing'\n};\n\ndescribe('co.call(this)', fun"
  },
  {
    "path": "test/generator-functions.js",
    "chars": 954,
    "preview": "\nvar assert = require('assert');\nvar co = require('..');\n\nfunction sleep(ms) {\n  return function(done){\n    setTimeout(d"
  },
  {
    "path": "test/generators.js",
    "chars": 952,
    "preview": "\nvar assert = require('assert');\nvar co = require('..');\n\nfunction sleep(ms) {\n  return function(done){\n    setTimeout(d"
  },
  {
    "path": "test/invalid.js",
    "chars": 385,
    "preview": "\nvar assert = require('assert');\n\nvar co = require('..');\n\ndescribe('yield <invalid>', function () {\n  it('should throw "
  },
  {
    "path": "test/objects.js",
    "chars": 2050,
    "preview": "\nvar read = require('mz/fs').readFile;\nvar assert = require('assert');\n\nvar co = require('..');\n\ndescribe('co(* -> yield"
  },
  {
    "path": "test/promises.js",
    "chars": 2170,
    "preview": "\nvar assert = require('assert');\n\nvar co = require('..');\n\nfunction getPromise(val, err) {\n  return new Promise(function"
  },
  {
    "path": "test/recursion.js",
    "chars": 1070,
    "preview": "\nvar read = require('mz/fs').readFile;\nvar assert = require('assert');\n\nvar co = require('..');\n\ndescribe('co() recursio"
  },
  {
    "path": "test/thunks.js",
    "chars": 6624,
    "preview": "\nvar assert = require('assert');\n\nvar co = require('..');\n\nfunction get(val, err, error) {\n  return function(done){\n    "
  },
  {
    "path": "test/wrap.js",
    "chars": 673,
    "preview": "\nvar assert = require('assert');\n\nvar co = require('..');\n\ndescribe('co.wrap(fn*)', function () {\n  it('should pass cont"
  }
]

About this extraction

This page contains the full source code of the tj/co GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 19 files (32.2 KB), approximately 8.9k tokens, and a symbol index with 17 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!