[
  {
    "path": ".babelrc",
    "content": "{ \"presets\": [\"./.babelrc.js\"] }\n"
  },
  {
    "path": ".babelrc.js",
    "content": "const { BABEL_ENV, NODE_ENV } = process.env;\nconst cjs = BABEL_ENV === 'cjs' || NODE_ENV === 'test';\n\nmodule.exports = {\n  presets: [\n    [\n      'env',\n      {\n        modules: false,\n        loose: true,\n        targets: {\n          browsers: ['last 1 version']\n        }\n      }\n    ],\n    'flow',\n    'react'\n  ],\n  plugins: [\n    'transform-class-properties',\n    cjs && 'transform-es2015-modules-commonjs'\n  ].filter(Boolean)\n};\n"
  },
  {
    "path": ".flowconfig",
    "content": "[ignore]\n\n[include]\n\n[libs]\n\n[lints]\n\n[options]\n\n[strict]\n"
  },
  {
    "path": ".gitignore",
    "content": "node_modules\n*.log\nlib\n.cache\ndist\ncoverage"
  },
  {
    "path": ".prettierrc",
    "content": "{\n  \"singleQuote\": true\n}\n"
  },
  {
    "path": ".travis.yml",
    "content": "git:\n  depth: 1\nsudo: false\nlanguage: node_js\nnode_js:\n  - '8'\ncache:\n  yarn: true\n  directories:\n    - node_modules\nscript:\n  - yarn test --coverage && yarn flow\n  - yarn typescript\n"
  },
  {
    "path": "LICENSE",
    "content": "Copyright (c) 2018-present James Kyle <me@thejameskyle.com>\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, 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": "<div align=\"center\">\n  <br><br><br><br><br>\n  <img src=\"https://raw.githubusercontent.com/thejameskyle/unstated/master/logo.png\" alt=\"Unstated Logo\" width=\"400\">\n  <br><br><br><br><br><br><br><br>\n</div>\n\n# Unstated\n\n> State so simple, it goes without saying\n\n### :wave: [Check out the *-next version of Unstated with an all new React Hooks API &rarr;](https://github.com/jamiebuilds/unstated-next)\n\n## Installation\n\n```sh\nyarn add unstated\n```\n\n## Example\n\n```jsx\n// @flow\nimport React from 'react';\nimport { render } from 'react-dom';\nimport { Provider, Subscribe, Container } from 'unstated';\n\ntype CounterState = {\n  count: number\n};\n\nclass CounterContainer extends Container<CounterState> {\n  state = {\n    count: 0\n  };\n\n  increment() {\n    this.setState({ count: this.state.count + 1 });\n  }\n\n  decrement() {\n    this.setState({ count: this.state.count - 1 });\n  }\n}\n\nfunction Counter() {\n  return (\n    <Subscribe to={[CounterContainer]}>\n      {counter => (\n        <div>\n          <button onClick={() => counter.decrement()}>-</button>\n          <span>{counter.state.count}</span>\n          <button onClick={() => counter.increment()}>+</button>\n        </div>\n      )}\n    </Subscribe>\n  );\n}\n\nrender(\n  <Provider>\n    <Counter />\n  </Provider>,\n  document.getElementById('root')\n);\n```\n\nFor more examples, see the `example/` directory.\n\n## Happy Customers\n\n<h4 align=\"center\">\n  \"Unstated is a breath of fresh air for state management. I rewrote my whole app to use it yesterday.\"\n  <br><br>\n  <a href=\"https://twitter.com/sindresorhus\">Sindre Sorhus</a>\n</h4>\n\n<h4 align=\"center\">\n  \"When people say you don't need Redux most of the time, they actually mean you do need Unstated.<br>It's like setState on fucking horse steroids\"\n  <br><br>\n  <a href=\"https://twitter.com/ken_wheeler\">Ken Wheeler</a> (obviously)\n</h4>\n\n## Guide\n\nIf you're like me, you're sick of all the ceremony around state management in\nReact, you want something that fits in well with the React way of thinking,\nbut doesn't command some crazy architecture and methodology.\n\nSo first off: Component state is nice! It makes sense and people can pick it\nup quickly:\n\n```jsx\nclass Counter extends React.Component {\n  state = { count: 0 };\n  increment = () => {\n    this.setState({ count: this.state.count + 1 });\n  };\n  decrement = () => {\n    this.setState({ count: this.state.count - 1 });\n  };\n  render() {\n    return (\n      <div>\n        <span>{this.state.count}</span>\n        <button onClick={this.decrement}>-</button>\n        <button onClick={this.increment}>+</button>\n      </div>\n    );\n  }\n}\n```\n\nAs a new React developer you might not know exactly how everything works, but\nyou can get a general sense pretty quickly.\n\nThe only problem here is that we can't easily share this state with other\ncomponents in our tree. Which is intentional! React components are designed to\nbe very self-contained.\n\nWhat would be great is if we could replicate the nice parts of React's\ncomponent state API while sharing it across multiple components.\n\nBut how do we share values between components in React? Through \"context\".\n\n> **Note:** The following is part of the new `React.createContext` API\n> [described in this RFC](https://github.com/reactjs/rfcs/blob/master/text/0002-new-version-of-context.md).\n\n```jsx\nconst Amount = React.createContext(1);\n\nclass Counter extends React.Component {\n  state = { count: 0 };\n  increment = amount => { this.setState({ count: this.state.count + amount }); };\n  decrement = amount => { this.setState({ count: this.state.count - amount }); };\n  render() {\n    return (\n      <Amount.Consumer>\n        {amount => (\n          <div>\n            <span>{this.state.count}</span>\n            <button onClick={() => this.decrement(amount)}>-</button>\n            <button onClick={() => this.increment(amount)}>+</button>\n          </div>\n        )}\n      </Amount.Consumer>\n    );\n  }\n}\n\nclass AmountAdjuster extends React.Component {\n  state = { amount: 0 };\n  handleChange = event => {\n    this.setState({\n      amount: parseInt(event.currentTarget.value, 10)\n    });\n  };\n  render() {\n    return (\n      <Amount.Provider value={this.state.amount}>\n        <div>\n          {this.props.children}\n          <input type=\"number\" value={this.state.amount} onChange={this.handleChange}/>\n        </div>\n      </Amount.Provider>\n    );\n  }\n}\n\nrender(\n  <AmountAdjuster>\n    <Counter/>\n  </AmountAdjuster>\n);\n```\n\nThis is already pretty great. Once you get a little bit used to React's way of\nthinking, it makes total sense and it's very predictable.\n\nBut can we build on this pattern to make something even nicer?\n\n### Introducing Unstated\n\nWell this is where Unstated comes in.\n\nUnstated is designed to build on top of the patterns already set out by React\ncomponents and context.\n\nIt has three pieces:\n\n##### `Container`\n\nWe're going to want another place to store our state and some of the logic for\nupdating it.\n\n`Container` is a very simple class which is meant to look just like\n`React.Component` but with only the state-related bits: `this.state` and\n`this.setState`.\n\n```js\nclass CounterContainer extends Container {\n  state = { count: 0 };\n  increment = () => {\n    this.setState({ count: this.state.count + 1 });\n  };\n  decrement = () => {\n    this.setState({ count: this.state.count - 1 });\n  };\n}\n```\n\nBehind the scenes our `Container`s are also event emitters that our app can\nsubscribe to for updates. When you call `setState` it triggers components to\nre-render, be careful not to mutate `this.state` directly or your components\nwon't re-render.\n\n###### `setState()`\n\n`setState()` in `Container` mimics React's `setState()` method as closely as\npossible.\n\n```js\nclass CounterContainer extends Container {\n  state = { count: 0 };\n  increment = () => {\n    this.setState(\n      state => {\n        return { count: state.count + 1 };\n      },\n      () => {\n        console.log('Updated!');\n      }\n    );\n  };\n}\n```\n\nIt's also run asynchronously, so you need to follow the same rules as React.\n\n**Don't read state immediately after setting it**\n\n```js\nclass CounterContainer extends Container {\n  state = { count: 0 };\n  increment = () => {\n    this.setState({ count: 1 });\n    console.log(this.state.count); // 0\n  };\n}\n```\n\n**If you are using previous state to calculate the next state, use the function form**\n\n```js\nclass CounterContainer extends Container {\n  state = { count: 0 };\n  increment = () => {\n    this.setState(state => {\n      return { count: state.count + 1 };\n    });\n  };\n}\n```\n\nHowever, unlike React's `setState()` Unstated's `setState()` returns a promise,\nso you can `await` it like this:\n\n```js\nclass CounterContainer extends Container {\n  state = { count: 0 };\n  increment = async () => {\n    await this.setState({ count: 1 });\n    console.log(this.state.count); // 1\n  };\n}\n```\n\nAsync functions are now available in [all the major browsers](https://caniuse.com/#feat=async-functions),\nbut you can also use [Babel](http://babeljs.io) to compile them down to\nsomething that works in every browser.\n\n##### `<Subscribe>`\n\nNext we'll need a piece to introduce our state back into the tree so that:\n\n* When state changes, our components re-render.\n* We can depend on our container's state.\n* We can call methods on our container.\n\nFor this we have the `<Subscribe>` component which allows us to pass our\ncontainer classes/instances and receive instances of them in the tree.\n\n```jsx\nfunction Counter() {\n  return (\n    <Subscribe to={[CounterContainer]}>\n      {counter => (\n        <div>\n          <span>{counter.state.count}</span>\n          <button onClick={counter.decrement}>-</button>\n          <button onClick={counter.increment}>+</button>\n        </div>\n      )}\n    </Subscribe>\n  );\n}\n```\n\n`<Subscribe>` will automatically construct our container and listen for changes.\n\n##### `<Provider>`\n\nThe final piece that we'll need is something to store all of our instances\ninternally. For this we have `<Provider>`.\n\n```jsx\nrender(\n  <Provider>\n    <Counter />\n  </Provider>\n);\n```\n\nWe can do some interesting things with `<Provider>` as well like dependency\ninjection:\n\n```jsx\nlet counter = new CounterContainer();\n\nrender(\n  <Provider inject={[counter]}>\n    <Counter />\n  </Provider>\n);\n```\n\n### Testing\n\nWhenever we consider the way that we write the state in our apps we should be\nthinking about testing.\n\nWe want to make sure that our state containers have a clean way\n\nWell because our containers are very simple classes, we can construct them in\ntests and assert different things about them very easily.\n\n```js\ntest('counter', async () => {\n  let counter = new CounterContainer();\n  assert(counter.state.count === 0);\n\n  await counter.increment();\n  assert(counter.state.count === 1);\n\n  await counter.decrement();\n  assert(counter.state.count === 0);\n});\n```\n\nIf we want to test the relationship between our container and the component\nwe can again construct our own instance and inject it into the tree.\n\n```js\ntest('counter', async () => {\n  let counter = new CounterContainer();\n  let tree = render(\n    <Provider inject={[counter]}>\n      <Counter />\n    </Provider>\n  );\n\n  await click(tree, '#increment');\n  assert(counter.state.count === 1);\n\n  await click(tree, '#decrement');\n  assert(counter.state.count === 0);\n});\n```\n\nDependency injection is useful in many ways. Like if we wanted to stub out a\nmethod in our state container we can do that painlessly.\n\n```js\ntest('counter', async () => {\n  let counter = new CounterContainer();\n  let inc = stub(counter, 'increment');\n  let dec = stub(counter, 'decrement');\n\n  let tree = render(\n    <Provider inject={[counter]}>\n      <Counter />\n    </Provider>\n  );\n\n  await click(tree, '#increment');\n  assert(inc.calls.length === 1);\n  assert(dec.calls.length === 0);\n});\n```\n\nWe don't even have to do anything to clean up after ourselves because we just\nthrow everything out afterwards.\n\n## FAQ\n\n#### What state should I put into Unstated?\n\nThe React community has focused a lot on trying to put all their state in one\nplace. You could keep doing that with Unstated, but I wouldn't recommend it.\n\nI would recommend a multi-part solution.\n\nFirst, use local component state as much as you possibly can. That counter\nexample from above never should have been refactored away from component\nstate, it was fine before Unstated.\n\nSecond, use libraries to abstract away the bits of state that you'll repeat\nover and over.\n\nLike if form state has you down, you might want to use a library like\n[Final Form](https://github.com/final-form/react-final-form).\n\nIf fetching data is getting to be too much, maybe try out [Apollo](https://www.apollographql.com).\nOr even something uncool but familiar and reliable like [Backbone models and collections](http://backbonejs.org).\nWhat? Are you too cool to use an old framework?\n\nThird, a lot of shared state between components is localized to a few\ncomponents in the tree.\n\n```jsx\n<Tabs>\n  <Tab>One</Tab>\n  <Tab>Two</Tab>\n  <Tab>Three</Tab>\n</Tabs>\n```\n\nFor this, I recommend using React's built-in `React.createContext()` API\nand being careful in designing the API for the base components you create.\n\n> **Note:** If you're on an old version of React and want to use the new\n> context API, [I've got you](https://github.com/thejameskyle/create-react-context/)\n\nFinally, (and only after other things are exhausted), if you really need\nsome global state to be shared throughout your app, you can use Unstated.\n\nI know all of this might sound somehow more complicated, but it's a\nmatter of using the right tool for the job and not forcing a single\nparadigm on the entire universe.\n\nUnstated isn't ambitious, use it as you need it, it's nice and small for\nthat reason. Don't think of it as a \"Redux killer\". Don't go trying to\nbuild complex tools on top of it. Don't reinvent the wheel. Just try it\nout and see how you like it.\n\n#### Passing your own instances directly to `<Subscribe to>`\n\nIf you want to use your own instance of a container directly to `<Subscribe>`\nand you don't care about dependency injection, you can do so:\n\n<!-- prettier-ignore -->\n```jsx\nlet counter = new CounterContainer();\n\nfunction Counter() {\n  return (\n    <Subscribe to={[counter]}>\n      {counter => <div>...</div>}\n    </Subscribe>\n  );\n}\n```\n\nYou just need to keep a couple things in mind:\n\n1. You are opting out of dependency injection, you won't be able to\n   `<Provider inject>` another instance in your tests.\n2. Your instance will be local to whatever `<Subscribe>`'s you pass it to, you\n   will end up with multiple instances of your container if you don't pass the\n   same reference in everywhere.\n\nAlso remember that it is _okay_ to use `<Provider inject>` in your application\ncode, you can pass your instance in there. It's probably better to do that in\nmost scenarios anyways (cause then you get dependency injection and all that\ngood stuff).\n\n#### How can I pass in options to my container?\n\nA good pattern for doing this might be to add a constructor to your container\nwhich accepts `props` sorta like React components. Then create your own\ninstance of your container and pass it into `<Provider inject>`.\n\n```jsx\nclass CounterContainer extends Container {\n  constructor(props = {}) {\n    super();\n    this.state = {\n      amount: props.initialAmount || 1,\n      count: 0\n    };\n  }\n\n  increment = () => {\n    this.setState({ count: this.state.count + this.state.amount });\n  };\n}\n\nlet counter = new CounterContainer({\n  initialAmount: 5\n});\n\nrender(\n  <Provider inject={[counter]}>\n    <Counter />\n  </Provider>\n);\n```\n\n## Related\n\n- [unstated-debug](https://github.com/sindresorhus/unstated-debug) - Debug your Unstated containers with ease\n \n"
  },
  {
    "path": "__tests__/unstated.js",
    "content": "// @flow\nimport React from 'react';\nimport renderer from 'react-test-renderer';\nimport { Provider, Subscribe, Container } from '../src/unstated';\n\nfunction render(element) {\n  return renderer.create(element).toJSON();\n}\n\nasync function click({ children = [] }, id) {\n  const el: any = children.find(({ props = {} }) => props.id === id);\n  el.props.onClick();\n}\n\nclass CounterContainer extends Container<{ count: number }> {\n  state = { count: 0 };\n  increment(amount = 1) {\n    this.setState({ count: this.state.count + amount });\n  }\n  decrement(amount = 1) {\n    this.setState({ count: this.state.count - amount });\n  }\n}\n\nfunction Counter() {\n  return (\n    <Subscribe to={[CounterContainer]}>\n      {counter => (\n        <div>\n          <span>{counter.state.count}</span>\n          <button id=\"decrement\" onClick={() => counter.decrement()}>\n            -\n          </button>\n          <button id=\"increment\" onClick={() => counter.increment()}>\n            +\n          </button>\n        </div>\n      )}\n    </Subscribe>\n  );\n}\n\ntest('should incresase/decrease state counter in container', async () => {\n  let counter = new CounterContainer();\n  let tree = render(\n    <Provider inject={[counter]}>\n      <Counter />\n    </Provider>\n  );\n\n  expect(counter.state.count).toBe(0);\n\n  await click(tree, 'increment');\n  expect(counter.state.count).toBe(1);\n\n  await click(tree, 'decrement');\n  expect(counter.state.count).toBe(0);\n});\n\ntest('should remove subscriber listeners if component is unmounted', () => {\n  let counter = new CounterContainer();\n  let tree = renderer.create(\n    <Provider inject={[counter]}>\n      <Counter />\n    </Provider>\n  );\n  const testInstance = tree.root.findByType(Subscribe)._fiber.stateNode;\n\n  expect(counter._listeners.length).toBe(1);\n  expect(testInstance.unmounted).toBe(false);\n\n  tree.unmount();\n\n  expect(counter._listeners.length).toBe(0);\n  expect(testInstance.unmounted).toBe(true);\n});\n\ntest('should throw an error if <Subscribe> component is not wrapper with <Provider>', () => {\n  spyOn(console, 'error');\n  expect(() => render(<Counter />)).toThrowError(\n    'You must wrap your <Subscribe> components with a <Provider>'\n  );\n});\n"
  },
  {
    "path": "__tests__/unstated.tsx",
    "content": "import * as React from 'react';\nimport { Provider, Subscribe, Container } from '../src/unstated';\n\nclass CounterContainer extends Container<{ count: number }> {\n  state = { count: 0 };\n  increment(amount = 1) {\n    this.setState({ count: this.state.count + amount });\n  }\n  decrement(amount = 1) {\n    this.setState({ count: this.state.count - amount });\n  }\n}\n\nclass AmounterContainer extends Container<{ amount: number }> {\n  state = { amount: 1 };\n  setAmount(amount: number) {\n    this.setState({ amount });\n  }\n}\n\nfunction Counter() {\n  return (\n    <Subscribe to={[CounterContainer]}>\n      {(counter: CounterContainer) => (\n        <div>\n          <span>{counter.state.count}</span>\n          <button onClick={() => counter.decrement()}>-</button>\n          <button onClick={() => counter.increment()}>+</button>\n        </div>\n      )}\n    </Subscribe>\n  );\n}\n\nfunction CounterWithAmount() {\n  return (\n    <Subscribe to={[CounterContainer, AmounterContainer]}>\n      {(counter: CounterContainer, amounter: AmounterContainer) => (\n        <div>\n          <span>{counter.state.count}</span>\n          <button onClick={() => counter.decrement(amounter.state.amount)}>\n            -\n          </button>\n          <button onClick={() => counter.increment(amounter.state.amount)}>\n            +\n          </button>\n        </div>\n      )}\n    </Subscribe>\n  );\n}\n\nfunction CounterWithAmountApp() {\n  return (\n    <Subscribe to={[AmounterContainer]}>\n      {(amounter: AmounterContainer) => (\n        <div>\n          <Counter />\n          <input\n            type=\"number\"\n            value={amounter.state.amount}\n            onChange={event => {\n              amounter.setAmount(parseInt(event.currentTarget.value, 10));\n            }}\n          />\n        </div>\n      )}\n    </Subscribe>\n  );\n}\n\nconst sharedAmountContainer = new AmounterContainer();\n\nfunction CounterWithSharedAmountApp() {\n  return (\n    <Subscribe to={[sharedAmountContainer]}>\n      {(amounter: AmounterContainer) => (\n        <div>\n          <Counter />\n          <input\n            type=\"number\"\n            value={amounter.state.amount}\n            onChange={event => {\n              amounter.setAmount(parseInt(event.currentTarget.value, 10));\n            }}\n          />\n        </div>\n      )}\n    </Subscribe>\n  );\n}\n\nlet counter = new CounterContainer();\nlet render = () => (\n  <Provider inject={[counter]}>\n    <Counter />\n  </Provider>\n);\n"
  },
  {
    "path": "example/complex.js",
    "content": "// @flow\nimport React from 'react';\nimport { render } from 'react-dom';\nimport { Provider, Subscribe, Container } from '../src/unstated';\n\ntype AppState = {\n  amount: number\n};\n\nclass AppContainer extends Container<AppState> {\n  state = {\n    amount: 1\n  };\n\n  setAmount(amount: number) {\n    this.setState({ amount });\n  }\n}\n\ntype CounterState = {\n  count: number\n};\n\nclass CounterContainer extends Container<CounterState> {\n  state = {\n    count: 0\n  };\n\n  increment(amount: number) {\n    this.setState({ count: this.state.count + amount });\n  }\n\n  decrement(amount: number) {\n    this.setState({ count: this.state.count - amount });\n  }\n}\n\nfunction Counter() {\n  return (\n    <Subscribe to={[AppContainer, CounterContainer]}>\n      {(app, counter) => (\n        <div>\n          <span>Count: {counter.state.count}</span>\n          <button onClick={() => counter.decrement(app.state.amount)}>-</button>\n          <button onClick={() => counter.increment(app.state.amount)}>+</button>\n        </div>\n      )}\n    </Subscribe>\n  );\n}\n\nfunction App() {\n  return (\n    <Subscribe to={[AppContainer]}>\n      {app => (\n        <div>\n          <Counter />\n          <label>Amount: </label>\n          <input\n            type=\"number\"\n            value={app.state.amount}\n            onChange={event => {\n              app.setAmount(parseInt(event.currentTarget.value, 10));\n            }}\n          />\n        </div>\n      )}\n    </Subscribe>\n  );\n}\n\nrender(\n  <Provider>\n    <App />\n  </Provider>,\n  window.complex\n);\n"
  },
  {
    "path": "example/index.html",
    "content": "<!DOCTYPE html>\n<html>\n  <head>\n    <meta charset=\"utf-8\">\n    <title>Unstated - Examples</title>\n  </head>\n  <body>\n    <h3>Simple</h3>\n    <div id=\"simple\"></div>\n    <script type=\"text/javascript\" src=\"./simple.js\"></script>\n\n    <h3>Complex</h3>\n    <div id=\"complex\"></div>\n    <script type=\"text/javascript\" src=\"./complex.js\"></script>\n\n    <h3>Shared</h3>\n    <div id=\"shared\"></div>\n    <script type=\"text/javascript\" src=\"./shared.js\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "example/shared.js",
    "content": "// @flow\nimport React from 'react';\nimport { render } from 'react-dom';\nimport { Provider, Subscribe, Container } from '../src/unstated';\n\ntype CounterState = {\n  count: number\n};\n\nclass CounterContainer extends Container<CounterState> {\n  state = { count: 0 };\n\n  increment() {\n    this.setState({ count: this.state.count + 1 });\n  }\n\n  decrement() {\n    this.setState({ count: this.state.count - 1 });\n  }\n}\n\nconst sharedCounterContainer = new CounterContainer();\n\nfunction Counter() {\n  return (\n    <Subscribe to={[sharedCounterContainer]}>\n      {counter => (\n        <div>\n          <button onClick={() => counter.decrement()}>-</button>\n          <span>{counter.state.count}</span>\n          <button onClick={() => sharedCounterContainer.increment()}>+</button>\n        </div>\n      )}\n    </Subscribe>\n  );\n}\n\nrender(\n  <Provider>\n    <Counter />\n  </Provider>,\n  window.shared\n);\n"
  },
  {
    "path": "example/simple.js",
    "content": "// @flow\nimport React from 'react';\nimport { render } from 'react-dom';\nimport { Provider, Subscribe, Container } from '../src/unstated';\n\ntype CounterState = {\n  count: number\n};\n\nclass CounterContainer extends Container<CounterState> {\n  state = { count: 0 };\n\n  increment() {\n    this.setState({ count: this.state.count + 1 });\n  }\n\n  decrement() {\n    this.setState({ count: this.state.count - 1 });\n  }\n}\n\nfunction Counter() {\n  return (\n    <Subscribe to={[CounterContainer]}>\n      {counter => (\n        <div>\n          <button onClick={() => counter.decrement()}>-</button>\n          <span>{counter.state.count}</span>\n          <button onClick={() => counter.increment()}>+</button>\n        </div>\n      )}\n    </Subscribe>\n  );\n}\n\nrender(\n  <Provider>\n    <Counter />\n  </Provider>,\n  window.simple\n);\n"
  },
  {
    "path": "flow-typed/npm/jest_v22.x.x.js",
    "content": "// flow-typed signature: 6e1fc0a644aa956f79029fec0709e597\n// flow-typed version: 07ebad4796/jest_v22.x.x/flow_>=v0.39.x\n\ntype JestMockFn<TArguments: $ReadOnlyArray<*>, TReturn> = {\n  (...args: TArguments): TReturn,\n  /**\n   * An object for introspecting mock calls\n   */\n  mock: {\n    /**\n     * An array that represents all calls that have been made into this mock\n     * function. Each call is represented by an array of arguments that were\n     * passed during the call.\n     */\n    calls: Array<TArguments>,\n    /**\n     * An array that contains all the object instances that have been\n     * instantiated from this mock function.\n     */\n    instances: Array<TReturn>\n  },\n  /**\n   * Resets all information stored in the mockFn.mock.calls and\n   * mockFn.mock.instances arrays. Often this is useful when you want to clean\n   * up a mock's usage data between two assertions.\n   */\n  mockClear(): void,\n  /**\n   * Resets all information stored in the mock. This is useful when you want to\n   * completely restore a mock back to its initial state.\n   */\n  mockReset(): void,\n  /**\n   * Removes the mock and restores the initial implementation. This is useful\n   * when you want to mock functions in certain test cases and restore the\n   * original implementation in others. Beware that mockFn.mockRestore only\n   * works when mock was created with jest.spyOn. Thus you have to take care of\n   * restoration yourself when manually assigning jest.fn().\n   */\n  mockRestore(): void,\n  /**\n   * Accepts a function that should be used as the implementation of the mock.\n   * The mock itself will still record all calls that go into and instances\n   * that come from itself -- the only difference is that the implementation\n   * will also be executed when the mock is called.\n   */\n  mockImplementation(\n    fn: (...args: TArguments) => TReturn\n  ): JestMockFn<TArguments, TReturn>,\n  /**\n   * Accepts a function that will be used as an implementation of the mock for\n   * one call to the mocked function. Can be chained so that multiple function\n   * calls produce different results.\n   */\n  mockImplementationOnce(\n    fn: (...args: TArguments) => TReturn\n  ): JestMockFn<TArguments, TReturn>,\n  /**\n   * Just a simple sugar function for returning `this`\n   */\n  mockReturnThis(): void,\n  /**\n   * Deprecated: use jest.fn(() => value) instead\n   */\n  mockReturnValue(value: TReturn): JestMockFn<TArguments, TReturn>,\n  /**\n   * Sugar for only returning a value once inside your mock\n   */\n  mockReturnValueOnce(value: TReturn): JestMockFn<TArguments, TReturn>\n};\n\ntype JestAsymmetricEqualityType = {\n  /**\n   * A custom Jasmine equality tester\n   */\n  asymmetricMatch(value: mixed): boolean\n};\n\ntype JestCallsType = {\n  allArgs(): mixed,\n  all(): mixed,\n  any(): boolean,\n  count(): number,\n  first(): mixed,\n  mostRecent(): mixed,\n  reset(): void\n};\n\ntype JestClockType = {\n  install(): void,\n  mockDate(date: Date): void,\n  tick(milliseconds?: number): void,\n  uninstall(): void\n};\n\ntype JestMatcherResult = {\n  message?: string | (() => string),\n  pass: boolean\n};\n\ntype JestMatcher = (actual: any, expected: any) => JestMatcherResult;\n\ntype JestPromiseType = {\n  /**\n   * Use rejects to unwrap the reason of a rejected promise so any other\n   * matcher can be chained. If the promise is fulfilled the assertion fails.\n   */\n  rejects: JestExpectType,\n  /**\n   * Use resolves to unwrap the value of a fulfilled promise so any other\n   * matcher can be chained. If the promise is rejected the assertion fails.\n   */\n  resolves: JestExpectType\n};\n\n/**\n *  Plugin: jest-enzyme\n */\ntype EnzymeMatchersType = {\n  toBeChecked(): void,\n  toBeDisabled(): void,\n  toBeEmpty(): void,\n  toBePresent(): void,\n  toContainReact(element: React$Element<any>): void,\n  toHaveClassName(className: string): void,\n  toHaveHTML(html: string): void,\n  toHaveProp(propKey: string, propValue?: any): void,\n  toHaveRef(refName: string): void,\n  toHaveState(stateKey: string, stateValue?: any): void,\n  toHaveStyle(styleKey: string, styleValue?: any): void,\n  toHaveTagName(tagName: string): void,\n  toHaveText(text: string): void,\n  toIncludeText(text: string): void,\n  toHaveValue(value: any): void,\n  toMatchElement(element: React$Element<any>): void,\n  toMatchSelector(selector: string): void\n};\n\ntype JestExpectType = {\n  not: JestExpectType & EnzymeMatchersType,\n  /**\n   * If you have a mock function, you can use .lastCalledWith to test what\n   * arguments it was last called with.\n   */\n  lastCalledWith(...args: Array<any>): void,\n  /**\n   * toBe just checks that a value is what you expect. It uses === to check\n   * strict equality.\n   */\n  toBe(value: any): void,\n  /**\n   * Use .toHaveBeenCalled to ensure that a mock function got called.\n   */\n  toBeCalled(): void,\n  /**\n   * Use .toBeCalledWith to ensure that a mock function was called with\n   * specific arguments.\n   */\n  toBeCalledWith(...args: Array<any>): void,\n  /**\n   * Using exact equality with floating point numbers is a bad idea. Rounding\n   * means that intuitive things fail.\n   */\n  toBeCloseTo(num: number, delta: any): void,\n  /**\n   * Use .toBeDefined to check that a variable is not undefined.\n   */\n  toBeDefined(): void,\n  /**\n   * Use .toBeFalsy when you don't care what a value is, you just want to\n   * ensure a value is false in a boolean context.\n   */\n  toBeFalsy(): void,\n  /**\n   * To compare floating point numbers, you can use toBeGreaterThan.\n   */\n  toBeGreaterThan(number: number): void,\n  /**\n   * To compare floating point numbers, you can use toBeGreaterThanOrEqual.\n   */\n  toBeGreaterThanOrEqual(number: number): void,\n  /**\n   * To compare floating point numbers, you can use toBeLessThan.\n   */\n  toBeLessThan(number: number): void,\n  /**\n   * To compare floating point numbers, you can use toBeLessThanOrEqual.\n   */\n  toBeLessThanOrEqual(number: number): void,\n  /**\n   * Use .toBeInstanceOf(Class) to check that an object is an instance of a\n   * class.\n   */\n  toBeInstanceOf(cls: Class<*>): void,\n  /**\n   * .toBeNull() is the same as .toBe(null) but the error messages are a bit\n   * nicer.\n   */\n  toBeNull(): void,\n  /**\n   * Use .toBeTruthy when you don't care what a value is, you just want to\n   * ensure a value is true in a boolean context.\n   */\n  toBeTruthy(): void,\n  /**\n   * Use .toBeUndefined to check that a variable is undefined.\n   */\n  toBeUndefined(): void,\n  /**\n   * Use .toContain when you want to check that an item is in a list. For\n   * testing the items in the list, this uses ===, a strict equality check.\n   */\n  toContain(item: any): void,\n  /**\n   * Use .toContainEqual when you want to check that an item is in a list. For\n   *\n   *\n   *\n   * ing the items in the list, this matcher recursively checks the\n   * equality of all fields, rather than checking for object identity.\n   */\n  toContainEqual(item: any): void,\n  /**\n   * Use .toEqual when you want to check that two objects have the same value.\n   * This matcher recursively checks the equality of all fields, rather than\n   * checking for object identity.\n   */\n  toEqual(value: any): void,\n  /**\n   * Use .toHaveBeenCalled to ensure that a mock function got called.\n   */\n  toHaveBeenCalled(): void,\n  /**\n   * Use .toHaveBeenCalledTimes to ensure that a mock function got called exact\n   * number of times.\n   */\n  toHaveBeenCalledTimes(number: number): void,\n  /**\n   * Use .toHaveBeenCalledWith to ensure that a mock function was called with\n   * specific arguments.\n   */\n  toHaveBeenCalledWith(...args: Array<any>): void,\n  /**\n   * Use .toHaveBeenLastCalledWith to ensure that a mock function was last called\n   * with specific arguments.\n   */\n  toHaveBeenLastCalledWith(...args: Array<any>): void,\n  /**\n   * Check that an object has a .length property and it is set to a certain\n   * numeric value.\n   */\n  toHaveLength(number: number): void,\n  /**\n   *\n   */\n  toHaveProperty(propPath: string, value?: any): void,\n  /**\n   * Use .toMatch to check that a string matches a regular expression or string.\n   */\n  toMatch(regexpOrString: RegExp | string): void,\n  /**\n   * Use .toMatchObject to check that a javascript object matches a subset of the properties of an object.\n   */\n  toMatchObject(object: Object | Array<Object>): void,\n  /**\n   * This ensures that a React component matches the most recent snapshot.\n   */\n  toMatchSnapshot(name?: string): void,\n  /**\n   * Use .toThrow to test that a function throws when it is called.\n   * If you want to test that a specific error gets thrown, you can provide an\n   * argument to toThrow. The argument can be a string for the error message,\n   * a class for the error, or a regex that should match the error.\n   *\n   * Alias: .toThrowError\n   */\n  toThrow(message?: string | Error | Class<Error> | RegExp): void,\n  toThrowError(message?: string | Error | Class<Error> | RegExp): void,\n  /**\n   * Use .toThrowErrorMatchingSnapshot to test that a function throws a error\n   * matching the most recent snapshot when it is called.\n   */\n  toThrowErrorMatchingSnapshot(): void\n};\n\ntype JestObjectType = {\n  /**\n   *  Disables automatic mocking in the module loader.\n   *\n   *  After this method is called, all `require()`s will return the real\n   *  versions of each module (rather than a mocked version).\n   */\n  disableAutomock(): JestObjectType,\n  /**\n   * An un-hoisted version of disableAutomock\n   */\n  autoMockOff(): JestObjectType,\n  /**\n   * Enables automatic mocking in the module loader.\n   */\n  enableAutomock(): JestObjectType,\n  /**\n   * An un-hoisted version of enableAutomock\n   */\n  autoMockOn(): JestObjectType,\n  /**\n   * Clears the mock.calls and mock.instances properties of all mocks.\n   * Equivalent to calling .mockClear() on every mocked function.\n   */\n  clearAllMocks(): JestObjectType,\n  /**\n   * Resets the state of all mocks. Equivalent to calling .mockReset() on every\n   * mocked function.\n   */\n  resetAllMocks(): JestObjectType,\n  /**\n   * Restores all mocks back to their original value.\n   */\n  restoreAllMocks(): JestObjectType,\n  /**\n   * Removes any pending timers from the timer system.\n   */\n  clearAllTimers(): void,\n  /**\n   * The same as `mock` but not moved to the top of the expectation by\n   * babel-jest.\n   */\n  doMock(moduleName: string, moduleFactory?: any): JestObjectType,\n  /**\n   * The same as `unmock` but not moved to the top of the expectation by\n   * babel-jest.\n   */\n  dontMock(moduleName: string): JestObjectType,\n  /**\n   * Returns a new, unused mock function. Optionally takes a mock\n   * implementation.\n   */\n  fn<TArguments: $ReadOnlyArray<*>, TReturn>(\n    implementation?: (...args: TArguments) => TReturn\n  ): JestMockFn<TArguments, TReturn>,\n  /**\n   * Determines if the given function is a mocked function.\n   */\n  isMockFunction(fn: Function): boolean,\n  /**\n   * Given the name of a module, use the automatic mocking system to generate a\n   * mocked version of the module for you.\n   */\n  genMockFromModule(moduleName: string): any,\n  /**\n   * Mocks a module with an auto-mocked version when it is being required.\n   *\n   * The second argument can be used to specify an explicit module factory that\n   * is being run instead of using Jest's automocking feature.\n   *\n   * The third argument can be used to create virtual mocks -- mocks of modules\n   * that don't exist anywhere in the system.\n   */\n  mock(\n    moduleName: string,\n    moduleFactory?: any,\n    options?: Object\n  ): JestObjectType,\n  /**\n   * Returns the actual module instead of a mock, bypassing all checks on\n   * whether the module should receive a mock implementation or not.\n   */\n  requireActual(moduleName: string): any,\n  /**\n   * Returns a mock module instead of the actual module, bypassing all checks\n   * on whether the module should be required normally or not.\n   */\n  requireMock(moduleName: string): any,\n  /**\n   * Resets the module registry - the cache of all required modules. This is\n   * useful to isolate modules where local state might conflict between tests.\n   */\n  resetModules(): JestObjectType,\n  /**\n   * Exhausts the micro-task queue (usually interfaced in node via\n   * process.nextTick).\n   */\n  runAllTicks(): void,\n  /**\n   * Exhausts the macro-task queue (i.e., all tasks queued by setTimeout(),\n   * setInterval(), and setImmediate()).\n   */\n  runAllTimers(): void,\n  /**\n   * Exhausts all tasks queued by setImmediate().\n   */\n  runAllImmediates(): void,\n  /**\n   * Executes only the macro task queue (i.e. all tasks queued by setTimeout()\n   * or setInterval() and setImmediate()).\n   */\n  runTimersToTime(msToRun: number): void,\n  /**\n   * Executes only the macro-tasks that are currently pending (i.e., only the\n   * tasks that have been queued by setTimeout() or setInterval() up to this\n   * point)\n   */\n  runOnlyPendingTimers(): void,\n  /**\n   * Explicitly supplies the mock object that the module system should return\n   * for the specified module. Note: It is recommended to use jest.mock()\n   * instead.\n   */\n  setMock(moduleName: string, moduleExports: any): JestObjectType,\n  /**\n   * Indicates that the module system should never return a mocked version of\n   * the specified module from require() (e.g. that it should always return the\n   * real module).\n   */\n  unmock(moduleName: string): JestObjectType,\n  /**\n   * Instructs Jest to use fake versions of the standard timer functions\n   * (setTimeout, setInterval, clearTimeout, clearInterval, nextTick,\n   * setImmediate and clearImmediate).\n   */\n  useFakeTimers(): JestObjectType,\n  /**\n   * Instructs Jest to use the real versions of the standard timer functions.\n   */\n  useRealTimers(): JestObjectType,\n  /**\n   * Creates a mock function similar to jest.fn but also tracks calls to\n   * object[methodName].\n   */\n  spyOn(object: Object, methodName: string): JestMockFn<any, any>,\n  /**\n   * Set the default timeout interval for tests and before/after hooks in milliseconds.\n   * Note: The default timeout interval is 5 seconds if this method is not called.\n   */\n  setTimeout(timeout: number): JestObjectType\n};\n\ntype JestSpyType = {\n  calls: JestCallsType\n};\n\n/** Runs this function after every test inside this context */\ndeclare function afterEach(\n  fn: (done: () => void) => ?Promise<mixed>,\n  timeout?: number\n): void;\n/** Runs this function before every test inside this context */\ndeclare function beforeEach(\n  fn: (done: () => void) => ?Promise<mixed>,\n  timeout?: number\n): void;\n/** Runs this function after all tests have finished inside this context */\ndeclare function afterAll(\n  fn: (done: () => void) => ?Promise<mixed>,\n  timeout?: number\n): void;\n/** Runs this function before any tests have started inside this context */\ndeclare function beforeAll(\n  fn: (done: () => void) => ?Promise<mixed>,\n  timeout?: number\n): void;\n\n/** A context for grouping tests together */\ndeclare var describe: {\n  /**\n   * Creates a block that groups together several related tests in one \"test suite\"\n   */\n  (name: string, fn: () => void): void,\n\n  /**\n   * Only run this describe block\n   */\n  only(name: string, fn: () => void): void,\n\n  /**\n   * Skip running this describe block\n   */\n  skip(name: string, fn: () => void): void\n};\n\n/** An individual test unit */\ndeclare var it: {\n  /**\n   * An individual test unit\n   *\n   * @param {string} Name of Test\n   * @param {Function} Test\n   * @param {number} Timeout for the test, in milliseconds.\n   */\n  (\n    name: string,\n    fn?: (done: () => void) => ?Promise<mixed>,\n    timeout?: number\n  ): void,\n  /**\n   * Only run this test\n   *\n   * @param {string} Name of Test\n   * @param {Function} Test\n   * @param {number} Timeout for the test, in milliseconds.\n   */\n  only(\n    name: string,\n    fn?: (done: () => void) => ?Promise<mixed>,\n    timeout?: number\n  ): void,\n  /**\n   * Skip running this test\n   *\n   * @param {string} Name of Test\n   * @param {Function} Test\n   * @param {number} Timeout for the test, in milliseconds.\n   */\n  skip(\n    name: string,\n    fn?: (done: () => void) => ?Promise<mixed>,\n    timeout?: number\n  ): void,\n  /**\n   * Run the test concurrently\n   *\n   * @param {string} Name of Test\n   * @param {Function} Test\n   * @param {number} Timeout for the test, in milliseconds.\n   */\n  concurrent(\n    name: string,\n    fn?: (done: () => void) => ?Promise<mixed>,\n    timeout?: number\n  ): void\n};\ndeclare function fit(\n  name: string,\n  fn: (done: () => void) => ?Promise<mixed>,\n  timeout?: number\n): void;\n/** An individual test unit */\ndeclare var test: typeof it;\n/** A disabled group of tests */\ndeclare var xdescribe: typeof describe;\n/** A focused group of tests */\ndeclare var fdescribe: typeof describe;\n/** A disabled individual test */\ndeclare var xit: typeof it;\n/** A disabled individual test */\ndeclare var xtest: typeof it;\n\n/** The expect function is used every time you want to test a value */\ndeclare var expect: {\n  /** The object that you want to make assertions against */\n  (value: any): JestExpectType & JestPromiseType & EnzymeMatchersType,\n  /** Add additional Jasmine matchers to Jest's roster */\n  extend(matchers: { [name: string]: JestMatcher }): void,\n  /** Add a module that formats application-specific data structures. */\n  addSnapshotSerializer(serializer: (input: Object) => string): void,\n  assertions(expectedAssertions: number): void,\n  hasAssertions(): void,\n  any(value: mixed): JestAsymmetricEqualityType,\n  anything(): void,\n  arrayContaining(value: Array<mixed>): void,\n  objectContaining(value: Object): void,\n  /** Matches any received string that contains the exact expected string. */\n  stringContaining(value: string): void,\n  stringMatching(value: string | RegExp): void\n};\n\n// TODO handle return type\n// http://jasmine.github.io/2.4/introduction.html#section-Spies\ndeclare function spyOn(value: mixed, method: string): Object;\n\n/** Holds all functions related to manipulating test runner */\ndeclare var jest: JestObjectType;\n\n/**\n * The global Jasmine object, this is generally not exposed as the public API,\n * using features inside here could break in later versions of Jest.\n */\ndeclare var jasmine: {\n  DEFAULT_TIMEOUT_INTERVAL: number,\n  any(value: mixed): JestAsymmetricEqualityType,\n  anything(): void,\n  arrayContaining(value: Array<mixed>): void,\n  clock(): JestClockType,\n  createSpy(name: string): JestSpyType,\n  createSpyObj(\n    baseName: string,\n    methodNames: Array<string>\n  ): { [methodName: string]: JestSpyType },\n  objectContaining(value: Object): void,\n  stringMatching(value: string): void\n};\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"unstated\",\n  \"version\": \"2.1.1\",\n  \"description\": \"State so simple, it goes without saying\",\n  \"main\": \"lib/unstated.js\",\n  \"module\": \"lib/unstated.es.js\",\n  \"types\": \"lib/unstated.d.ts\",\n  \"repository\": \"https://github.com/thejameskyle/unstated\",\n  \"author\": \"James Kyle <me@thejameskyle.com>\",\n  \"license\": \"MIT\",\n  \"files\": [\"lib\"],\n  \"scripts\": {\n    \"clean\": \"rm -rf lib\",\n    \"build\":\n      \"rollup -c && flow-copy-source src lib && cp src/unstated.d.ts lib/unstated.d.ts\",\n    \"typecheck\": \"flow\",\n    \"test\": \"jest\",\n    \"format\": \"prettier --write **/*.{js,json,md}\",\n    \"prepublish\": \"yarn clean && yarn build\",\n    \"precommit\": \"lint-staged\",\n    \"example\": \"parcel example/index.html\",\n    \"typescript\": \"tsc -p tsconfig.json\"\n  },\n  \"dependencies\": {\n    \"create-react-context\": \"^0.2.2\"\n  },\n  \"peerDependencies\": {\n    \"react\": \"^15.0.0 || ^16.0.0\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^16.0.36\",\n    \"babel-core\": \"^6.26.0\",\n    \"babel-plugin-transform-class-properties\": \"^6.24.1\",\n    \"babel-preset-env\": \"^1.6.1\",\n    \"babel-preset-flow\": \"^6.23.0\",\n    \"babel-preset-react\": \"^6.24.1\",\n    \"babel-register\": \"^6.26.0\",\n    \"flow-bin\": \"^0.64.0\",\n    \"flow-copy-source\": \"^1.2.2\",\n    \"husky\": \"^0.14.3\",\n    \"jest\": \"^22.1.4\",\n    \"jsdom\": \"^11.6.2\",\n    \"lint-staged\": \"^6.1.0\",\n    \"parcel-bundler\": \"^1.5.1\",\n    \"prettier\": \"^1.10.2\",\n    \"prop-types\": \"^15.6.0\",\n    \"react\": \"^16.2.0\",\n    \"react-dom\": \"^16.2.0\",\n    \"react-test-renderer\": \"^16.2.0\",\n    \"rollup\": \"^0.55.3\",\n    \"rollup-plugin-babel\": \"^3.0.3\",\n    \"typescript\": \"^2.7.1\"\n  },\n  \"lint-staged\": {\n    \"*.{js,json,md}\": [\"prettier --write\", \"git add\"]\n  }\n}\n"
  },
  {
    "path": "rollup.config.js",
    "content": "import babel from 'rollup-plugin-babel';\nimport pkg from './package.json';\n\nexport default {\n  input: 'src/unstated.js',\n  output: [\n    {\n      file: pkg.main,\n      format: 'cjs'\n    },\n    {\n      file: pkg.module,\n      format: 'es'\n    }\n  ],\n  external: [\n    ...Object.keys(pkg.dependencies || {}),\n    ...Object.keys(pkg.peerDependencies || {})\n  ],\n  plugins: [babel()]\n};\n"
  },
  {
    "path": "src/unstated.d.ts",
    "content": "import * as React from 'react';\n\nexport class Container<State extends object> {\n  state: State;\n  setState<K extends keyof State>(\n    state:\n      | ((prevState: Readonly<State>) => Pick<State, K> | State | null)\n      | (Pick<State, K> | State | null),\n    callback?: () => void\n  ): Promise<void>;\n  subscribe(fn: () => any): void;\n  unsubscribe(fn: () => any): void;\n}\n\nexport interface ContainerType<State extends object> {\n  new (...args: any[]): Container<State>;\n}\n\ninterface SubscribeProps {\n  to: (ContainerType<any> | Container<any>)[];\n  children(...instances: Container<any>[]): React.ReactNode;\n}\n\nexport class Subscribe extends React.Component<SubscribeProps> {}\n\nexport interface ProviderProps {\n  inject?: Container<any>[];\n  children: React.ReactNode;\n}\n\nexport const Provider: React.SFC<ProviderProps>;\n"
  },
  {
    "path": "src/unstated.js",
    "content": "// @flow\nimport React, { type Node } from 'react';\nimport createReactContext from 'create-react-context';\n\ntype Listener = () => mixed;\n\nconst StateContext = createReactContext(null);\n\nexport class Container<State: {}> {\n  state: State;\n  _listeners: Array<Listener> = [];\n\n  constructor() {\n    CONTAINER_DEBUG_CALLBACKS.forEach(cb => cb(this));\n  }\n\n  setState(\n    updater: $Shape<State> | ((prevState: $Shape<State>) => $Shape<State>),\n    callback?: () => void\n  ): Promise<void> {\n    return Promise.resolve().then(() => {\n      let nextState;\n\n      if (typeof updater === 'function') {\n        nextState = updater(this.state);\n      } else {\n        nextState = updater;\n      }\n\n      if (nextState == null) {\n        if (callback) callback();\n        return;\n      }\n\n      this.state = Object.assign({}, this.state, nextState);\n\n      let promises = this._listeners.map(listener => listener());\n\n      return Promise.all(promises).then(() => {\n        if (callback) {\n          return callback();\n        }\n      });\n    });\n  }\n\n  subscribe(fn: Listener) {\n    this._listeners.push(fn);\n  }\n\n  unsubscribe(fn: Listener) {\n    this._listeners = this._listeners.filter(f => f !== fn);\n  }\n}\n\nexport type ContainerType = Container<Object>;\nexport type ContainersType = Array<Class<ContainerType> | ContainerType>;\nexport type ContainerMapType = Map<Class<ContainerType>, ContainerType>;\n\nexport type SubscribeProps<Containers: ContainersType> = {\n  to: Containers,\n  children: (\n    ...instances: $TupleMap<Containers, <C>(Class<C> | C) => C>\n  ) => Node\n};\n\ntype SubscribeState = {};\n\nconst DUMMY_STATE = {};\n\nexport class Subscribe<Containers: ContainersType> extends React.Component<\n  SubscribeProps<Containers>,\n  SubscribeState\n> {\n  state = {};\n  instances: Array<ContainerType> = [];\n  unmounted = false;\n\n  componentWillUnmount() {\n    this.unmounted = true;\n    this._unsubscribe();\n  }\n\n  _unsubscribe() {\n    this.instances.forEach(container => {\n      container.unsubscribe(this.onUpdate);\n    });\n  }\n\n  onUpdate: Listener = () => {\n    return new Promise(resolve => {\n      if (!this.unmounted) {\n        this.setState(DUMMY_STATE, resolve);\n      } else {\n        resolve();\n      }\n    });\n  };\n\n  _createInstances(\n    map: ContainerMapType | null,\n    containers: ContainersType\n  ): Array<ContainerType> {\n    this._unsubscribe();\n\n    if (map === null) {\n      throw new Error(\n        'You must wrap your <Subscribe> components with a <Provider>'\n      );\n    }\n\n    let safeMap = map;\n    let instances = containers.map(ContainerItem => {\n      let instance;\n\n      if (\n        typeof ContainerItem === 'object' &&\n        ContainerItem instanceof Container\n      ) {\n        instance = ContainerItem;\n      } else {\n        instance = safeMap.get(ContainerItem);\n\n        if (!instance) {\n          instance = new ContainerItem();\n          safeMap.set(ContainerItem, instance);\n        }\n      }\n\n      instance.unsubscribe(this.onUpdate);\n      instance.subscribe(this.onUpdate);\n\n      return instance;\n    });\n\n    this.instances = instances;\n    return instances;\n  }\n\n  render() {\n    return (\n      <StateContext.Consumer>\n        {map =>\n          this.props.children.apply(\n            null,\n            this._createInstances(map, this.props.to)\n          )\n        }\n      </StateContext.Consumer>\n    );\n  }\n}\n\nexport type ProviderProps = {\n  inject?: Array<ContainerType>,\n  children: Node\n};\n\nexport function Provider(props: ProviderProps) {\n  return (\n    <StateContext.Consumer>\n      {parentMap => {\n        let childMap = new Map(parentMap);\n\n        if (props.inject) {\n          props.inject.forEach(instance => {\n            childMap.set(instance.constructor, instance);\n          });\n        }\n\n        return (\n          <StateContext.Provider value={childMap}>\n            {props.children}\n          </StateContext.Provider>\n        );\n      }}\n    </StateContext.Consumer>\n  );\n}\n\nlet CONTAINER_DEBUG_CALLBACKS = [];\n\n// If your name isn't Sindre, this is not for you.\n// I might ruin your day suddenly if you depend on this without talking to me.\nexport function __SUPER_SECRET_CONTAINER_DEBUG_HOOK__(\n  callback: (container: Container<any>) => mixed\n) {\n  CONTAINER_DEBUG_CALLBACKS.push(callback);\n}\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"module\": \"commonjs\",\n    \"target\": \"es5\",\n    \"lib\": [\"es6\", \"dom\"],\n    \"sourceMap\": true,\n    \"jsx\": \"react\",\n    \"moduleResolution\": \"node\",\n    \"forceConsistentCasingInFileNames\": true,\n    \"strict\": true,\n    \"noEmit\": true\n  },\n  \"include\": [\"src/**/*\", \"__test__/*.tsx\"]\n}\n"
  }
]