Repository: yoshuawuyts/barracks
Branch: master
Commit: e9f2f30d8cc5
Files: 9
Total size: 43.9 KB
Directory structure:
gitextract_tcofq5mj/
├── .gitignore
├── .travis.yml
├── LICENSE
├── README.md
├── apply-hook.js
├── index.js
├── package.json
├── script/
│ └── test-size
└── test.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
# files
*.log
*.pid
*.seed
# folders
logs/
pids/
build/
coverage/
node_modules/
================================================
FILE: .travis.yml
================================================
node_js:
- "4"
- "6"
sudo: false
language: node_js
script: "npm run test:cov"
after_script: "npm install coveralls@2 && cat ./coverage/lcov.info | coveralls"
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) 2014 Yoshua Wuyts
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
================================================
# barracks
[![NPM version][npm-image]][npm-url]
[![build status][travis-image]][travis-url]
[![Test coverage][coveralls-image]][coveralls-url]
[![Downloads][downloads-image]][downloads-url]
Action dispatcher for unidirectional data flows. Creates tiny models of data
that can be accessed with actions through a small API.
## Usage
````js
const barracks = require('barracks')
const store = barracks()
store.use({
onError: (err, state, createSend) => {
console.error(`error: ${err}`)
},
onAction: (state, data, name, caller, createSend) => {
console.log(`data: ${data}`)
},
onStateChange: (state, data, prev, caller, createSend) => {
console.log(`state: ${prev} -> ${state}`)
}
})
store.model({
namespace: 'cakes',
state: {},
effects: {},
reducers: {},
subscriptions: {}
})
const createSend = store.start({ subscriptions: true })
const send = createSend('myDispatcher', true)
document.addEventListener('DOMContentLoaded', () => {
store.start() // fire up subscriptions
const state = store.state()
send('foo:start', { name: 'Loki' })
})
````
## API
### store = barracks(hooks?)
Initialize a new `barracks` instance. Takes an optional object of hooks which
is passed to `.use()`.
### store.use(hooks)
Register new hooks on the store. Hooks are little plugins that can extend
behavior or perform actions at specific points in the life cycle. The following
hooks are possible:
- __models:__ an array of models that will be merged with the store.
- __onError(err, state, createSend):__ called when an `effect` or
`subscription` emit an error; if no hook is passed, the default hook will
`throw` on each error
- __onAction(state, data, name, caller, createSend):__ called when an `action`
is fired
- __onStateChange(state, data, prev, caller, createSend):__ called after a
reducer changes the `state`.
- __wrapSubscriptions(fn):__ wraps a `subscription` to add custom behavior
- __wrapReducers(fn):__ wraps a `reducer` to add custom behavior
- __wrapEffects(fn):__ wraps an `effect` to add custom behavior
- __wrapInitialState(obj):__ mutate the initial `state` to add custom
behavior - useful to mutate the state before starting up
`createSend()` is a special function that allows the creation of a new named
`send()` function. The first argument should be a string which is the name, the
second argument is a boolean `callOnError` which can be set to `true` to call
the `onError` hook instead of a provided callback. It then returns a
`send(actionName, data?)` function.
The `wrap*` hooks are synchronously resolved when the `store.start()` method is
called, and the corresponding values from the models are loaded. All wrap hooks
(or wrappers) are passed the argument that would usually be called, so it can
be wrapped or modified. Say we want to make all our `reducers` print `'golden
pony'` every time they're run, we'd do:
```js
const barracks = require('barracks')
const store = barracks()
store.use({
wrapReducers: function wrapConstructor (reducer) {
return function wrapper (state, data) {
console.log('golden pony')
return reducer(state, data)
}
}
})
```
Hooks should be used with care, as they're the most powerful interface into
the state. For application level code, it's generally recommended to delegate to
actions inside models using the `send()` call, and only shape the actions
inside the hooks.
### store.model()
Register a new model on the store. Models are optionally namespaced objects
with an initial `state` and handlers for dealing with data:
- __namespace:__ namespace the model so that it cannot access any properties
and handlers in other models
- __state:__ initial values of `state` inside the model
- __reducers:__ synchronous operations that modify state; triggered by `actions`
- __effects:__ asynchronous operations that don't modify state directly;
triggered by `actions`, can call `actions`
- __subscriptions:__ asynchronous read-only operations that don't modify state
directly; can call `actions`
`state` within handlers is immutable through `Object.freeze()` and thus cannot
be modified. Return data from `reducers` to modify `state`. See [handler
signatures](#handler-signatures) for more info on the handlers.
For debugging purposes, internal references to values can be inspected through a
series of private accessors:
- `store._subscriptions`
- `store._reducers`
- `store._effects`
- `store._models`
### state = store.state(opts)
Get the current state from the store. Opts can take the following values:
- __freeze:__ default: true; set to false to not freeze state in handlers
using `Object.freeze()`; useful for optimizing performance in production
builds
- __state:__ pass in a state object that will be merged with the state returned
from the store; useful for rendering in Node
### send = createSend(name) = store.start(opts)
Start the store and get a `createSend(name)` function. Pass a unique `name` to
`createSend()` to get a `send()` function. Opts can take the following values:
- __subscriptions:__ default: true; set to false to not register
`subscriptions` when starting the application; useful to delay `init`
functions until the DOM has loaded
- __effects:__ default: true; set to `false` to not register `effects` when
starting the application; useful when only wanting the initial `state`
- __reducers:__ default: true; set to false to not register `reducers` when
starting the application; useful when only wanting the initial `state`
If the store has disabled any of the handlers (e.g. `{ reducers: false }`),
calling `store.start()` a second time will register the remaining values. This
is useful if not everything can be started at the same time (e.g. have
`subscriptions` wait for the `DOMContentLoaded` event).
### send(name, data?)
Send a new action to the models with optional data attached. Namespaced models
can be accessed by prefixing the name with the namespace separated with a `:`,
e.g. `namespace:name`.
### store.stop()
After an app is "stopped" all subsequent `send()` calls become no-ops.
```js
store.stop()
send('trimBeard') // -> does not call a reducer/effect
```
## Handler signatures
These are the signatures for the properties that can be passed into a model.
### namespace
An optional string that causes `state`, `effects` and `reducers` to be
prefixed.
```js
app.model({
namespace: 'users'
})
```
### state
State can either be a value or an object of values that is used as the initial
state for the application. If namespaced the values will live under
`state[namespace]`.
```js
app.model({
namespace: 'hey',
state: { foo: 'bar' }
})
app.model({
namespace: 'there',
state: { bin: [ 'beep', 'boop' ] }
})
app.model({
namespace: 'people',
state: 'oi'
}})
```
### reducers
Reducers are synchronous functions that return a value synchronously. No
eventual values, just values that are relevant for the state. It takes two
arguments of `data` and `state`. `data` is the data that was emitted, and
`state` is the current state. Each action has a name that can be accessed
through `send(name)`, and when under a namespace can be accessed as
`send(namespace:name)`. When operating under a namespace, reducers only have
access to the state within the namespace.
```js
// some model
app.model({
namespace: 'plantcake',
state: {
enums: [ 'veggie', 'potato', 'lettuce' ]
paddie: 'veggie'
}
})
// so this model can't access anything in the 'plantcake' namespace
app.model({
namespace: 'burlybeardos',
state: { count: 1 },
reducers: {
feedPlantcake: (state, data) => {
return { count: state.count + 1 }
},
trimBeard: (state, data) => ({ count: state.count - 1 })
}
})
```
### effects
`effects` are asynchronous methods that can be triggered by `actions` in
`send()`. They never update the state directly, but can instead do thing
asynchronously, and then call `send()` again to trigger a `reducer` that can
update the state. `effects` can also trigger other `effects`, making them fully
composable. Generally, it's recommended to only have `effects` without a
`namespace` call other `effects`, as to keep namespaced models as isolated as
possible.
When an `effect` is done executing, or encounters an error, it should call the
final `done(err)` callback. If the `effect` was called by another `effect` it
will call the callback of the caller. When an error propagates all the way to
the top, the `onError` handler will be called, registered in
`barracks(handlers)`. If no callback is registered, errors will `throw`.
Having callbacks in `effects` means that error handling can be formalized
without knowledge of the rest of the application leaking into the model. This
also causes `effects` to become fully composable, which smooths parallel
development in large teams, and keeps the mental overhead low when developing a
single model.
```js
const http = require('xhr')
const app = barracks({
onError: (state, data, prev, send) => send('app:error', data)
})
app.model({
namespace: 'app',
effects: {
error: (state, data, send, done) => {
// if doing http calls here be super sure not to get lost
// in a recursive error handling loop: remember this IS
// the error handler
console.error(data.message)
done()
}
}
})
app.model({
namespace: 'foo',
state: { foo: 1 },
reducers: {
moreFoo: (state, data) => ({ foo: state.foo + data.count })
}
effects: {
fetch: (state, data, send, done) => {
http('foobar.com', function (err, res, body) {
if (err || res.statusCode !== 200) {
return done(new Error({
message: 'error accessing server',
error: err
}))
} else {
send('moreFoo', { count: foo.count }, done)
}
})
}
}
})
```
### subscriptions
`subscriptions` are read-only sources of data. This means they cannot be
triggered by actions, but can emit actions themselves whenever they want. This
is useful for stuff like listening to keyboard events or incoming websocket
data. They should generally be started when the application is loaded, using
the `DOMContentLoaded` listener.
```js
app.model({
subscriptions: {
emitWoofs: (send, done) => {
// emit a woof every second
setInterval(() => send('printWoofs', { woof: 'meow?' }, done), 1000)
}
},
effects: {
printWoofs: (state, data) => console.log(data.woof)
}
})
```
`done()` is passed as the final argument so if an error occurs in a subscriber,
it can be communicated to the `onError` hook.
## FAQ
### What is an "action dispatcher"?
An action dispatcher gets data from one place to another without tightly
coupling code. The best known use case for this is in the `flux` pattern. Say
you want to update a piece of data (for example a user's name), instead of
directly calling the update logic inside the view, the action calls a function
that updates the user's name for you. Now all the views that need to update a
user's name can call the same action and pass in the relevant data. This
pattern tends to make views more robust and easier to maintain.
### Why did you build this?
Passing messages around should not be complicated. Many `flux` implementations
casually throw restrictions at users without having a clear architecture. I
don't like that. `barracks` is a package that creates a clear flow of data within an
application, concerning itself with state, code separation, and data flow. I
believe that having strong opinions and being transparent in them makes for
better architectures than sprinkles of opinions left and right, without a cohesive
story as to _why_.
### How is this different from choo?
`choo` is a framework that handles views, data and all problems related to
that. This is a package that only concerns itself with data flow, without being
explicitly tied to the DOM.
### This looks like more than five functions!
Welllll, no. It's technically five functions with a high arity, hah. Nah,
you're right - but five functions _sounds_ good. Besides: you don't need to
know all options and toggles to get this working; that only relevant once you
start hitting edge cases like we did in `choo` :sparkles:
## See Also
- [choo](https://github.com/yoshuawuyts/choo) - sturdy frontend framework
- [sheet-router](https://github.com/yoshuawuyts/sheet-router) - fast, modular
client-side router
- [yo-yo](https://github.com/maxogden/yo-yo) - template string based view
framework
- [send-action](https://github.com/sethvincent/send-action) - unidirectional
action emitter
## Installation
```sh
$ npm install barracks
```
## License
[MIT](https://tldrlegal.com/license/mit-license)
[npm-image]: https://img.shields.io/npm/v/barracks.svg?style=flat-square
[npm-url]: https://npmjs.org/package/barracks
[travis-image]: https://img.shields.io/travis/yoshuawuyts/barracks/master.svg?style=flat-square
[travis-url]: https://travis-ci.org/yoshuawuyts/barracks
[coveralls-image]: https://img.shields.io/coveralls/yoshuawuyts/barracks.svg?style=flat-square
[coveralls-url]: https://coveralls.io/r/yoshuawuyts/barracks?branch=master
[downloads-image]: http://img.shields.io/npm/dm/barracks.svg?style=flat-square
[downloads-url]: https://npmjs.org/package/barracks
[flux]: http://facebook.github.io/react/blog/2014/05/06/flux.html
[browserify]: https://github.com/substack/node-browserify
================================================
FILE: apply-hook.js
================================================
module.exports = applyHook
// apply arguments onto an array of functions, useful for hooks
// (arr, any?, any?, any?, any?, any?) -> null
function applyHook (arr, arg1, arg2, arg3, arg4, arg5) {
arr.forEach(function (fn) {
fn(arg1, arg2, arg3, arg4, arg5)
})
}
================================================
FILE: index.js
================================================
var mutate = require('xtend/mutable')
var nanotick = require('nanotick')
var assert = require('assert')
var xtend = require('xtend')
var applyHook = require('./apply-hook')
module.exports = dispatcher
// initialize a new barracks instance
// obj -> obj
function dispatcher (hooks) {
hooks = hooks || {}
assert.equal(typeof hooks, 'object', 'barracks: hooks should be undefined or an object')
var onStateChangeHooks = []
var onActionHooks = []
var onErrorHooks = []
var subscriptionWraps = []
var initialStateWraps = []
var reducerWraps = []
var effectWraps = []
use(hooks)
var reducersCalled = false
var effectsCalled = false
var stateCalled = false
var subsCalled = false
var stopped = false
var subscriptions = start._subscriptions = {}
var reducers = start._reducers = {}
var effects = start._effects = {}
var models = start._models = []
var _state = {}
var tick = nanotick()
start.model = setModel
start.state = getState
start.start = start
start.stop = stop
start.use = use
return start
// push an object of hooks onto an array
// obj -> null
function use (hooks) {
assert.equal(typeof hooks, 'object', 'barracks.use: hooks should be an object')
assert.ok(!hooks.onError || typeof hooks.onError === 'function', 'barracks.use: onError should be undefined or a function')
assert.ok(!hooks.onAction || typeof hooks.onAction === 'function', 'barracks.use: onAction should be undefined or a function')
assert.ok(!hooks.onStateChange || typeof hooks.onStateChange === 'function', 'barracks.use: onStateChange should be undefined or a function')
if (hooks.onStateChange) onStateChangeHooks.push(hooks.onStateChange)
if (hooks.onError) onErrorHooks.push(wrapOnError(hooks.onError))
if (hooks.onAction) onActionHooks.push(hooks.onAction)
if (hooks.wrapSubscriptions) subscriptionWraps.push(hooks.wrapSubscriptions)
if (hooks.wrapInitialState) initialStateWraps.push(hooks.wrapInitialState)
if (hooks.wrapReducers) reducerWraps.push(hooks.wrapReducers)
if (hooks.wrapEffects) effectWraps.push(hooks.wrapEffects)
if (hooks.models) hooks.models.forEach(setModel)
}
// push a model to be initiated
// obj -> null
function setModel (model) {
assert.equal(typeof model, 'object', 'barracks.store.model: model should be an object')
models.push(model)
}
// get the current state from the store
// obj? -> obj
function getState (opts) {
opts = opts || {}
assert.equal(typeof opts, 'object', 'barracks.store.state: opts should be an object')
var state = opts.state
if (!opts.state && opts.freeze === false) return xtend(_state)
else if (!opts.state) return Object.freeze(xtend(_state))
assert.equal(typeof state, 'object', 'barracks.store.state: state should be an object')
var namespaces = []
var newState = {}
// apply all fields from the model, and namespaced fields from the passed
// in state
models.forEach(function (model) {
var ns = model.namespace
namespaces.push(ns)
var modelState = model.state || {}
if (ns) {
newState[ns] = newState[ns] || {}
apply(ns, modelState, newState)
newState[ns] = xtend(newState[ns], state[ns])
} else {
mutate(newState, modelState)
}
})
// now apply all fields that weren't namespaced from the passed in state
Object.keys(state).forEach(function (key) {
if (namespaces.indexOf(key) !== -1) return
newState[key] = state[key]
})
var tmpState = xtend(_state, xtend(state, newState))
var wrappedState = wrapHook(tmpState, initialStateWraps)
return (opts.freeze === false)
? wrappedState
: Object.freeze(wrappedState)
}
// initialize the store hooks, get the send() function
// obj? -> fn
function start (opts) {
opts = opts || {}
assert.equal(typeof opts, 'object', 'barracks.store.start: opts should be undefined or an object')
// register values from the models
models.forEach(function (model) {
var ns = model.namespace
if (!stateCalled && model.state && opts.state !== false) {
var modelState = model.state || {}
if (ns) {
_state[ns] = _state[ns] || {}
apply(ns, modelState, _state)
} else {
mutate(_state, modelState)
}
}
if (!reducersCalled && model.reducers && opts.reducers !== false) {
apply(ns, model.reducers, reducers, function (cb) {
return wrapHook(cb, reducerWraps)
})
}
if (!effectsCalled && model.effects && opts.effects !== false) {
apply(ns, model.effects, effects, function (cb) {
return wrapHook(cb, effectWraps)
})
}
if (!subsCalled && model.subscriptions && opts.subscriptions !== false) {
apply(ns, model.subscriptions, subscriptions, function (cb, key) {
var send = createSend('subscription: ' + (ns ? ns + ':' + key : key))
cb = wrapHook(cb, subscriptionWraps)
cb(send, function (err) {
applyHook(onErrorHooks, err, _state, createSend)
})
return cb
})
}
})
// the state wrap is special because we want to operate on the full
// state rather than indvidual chunks, so we apply it outside the loop
if (!stateCalled && opts.state !== false) {
_state = wrapHook(_state, initialStateWraps)
}
if (!opts.noSubscriptions) subsCalled = true
if (!opts.noReducers) reducersCalled = true
if (!opts.noEffects) effectsCalled = true
if (!opts.noState) stateCalled = true
if (!onErrorHooks.length) onErrorHooks.push(wrapOnError(defaultOnError))
return createSend
// call an action from a view
// (str, bool?) -> (str, any?, fn?) -> null
function createSend (selfName, callOnError) {
assert.equal(typeof selfName, 'string', 'barracks.store.start.createSend: selfName should be a string')
assert.ok(!callOnError || typeof callOnError === 'boolean', 'barracks.store.start.send: callOnError should be undefined or a boolean')
return function send (name, data, cb) {
if (!cb && !callOnError) {
cb = data
data = null
}
data = (typeof data === 'undefined' ? null : data)
assert.equal(typeof name, 'string', 'barracks.store.start.send: name should be a string')
assert.ok(!cb || typeof cb === 'function', 'barracks.store.start.send: cb should be a function')
var done = callOnError ? onErrorCallback : cb
_send(name, data, selfName, done)
function onErrorCallback (err) {
err = err || null
if (err) {
applyHook(onErrorHooks, err, _state, function createSend (selfName) {
return function send (name, data) {
assert.equal(typeof name, 'string', 'barracks.store.start.send: name should be a string')
data = (typeof data === 'undefined' ? null : data)
_send(name, data, selfName, done)
}
})
}
}
}
}
// call an action
// (str, str, any, fn) -> null
function _send (name, data, caller, cb) {
if (stopped) return
assert.equal(typeof name, 'string', 'barracks._send: name should be a string')
assert.equal(typeof caller, 'string', 'barracks._send: caller should be a string')
assert.equal(typeof cb, 'function', 'barracks._send: cb should be a function')
;(tick(function () {
var reducersCalled = false
var effectsCalled = false
var newState = xtend(_state)
if (onActionHooks.length) {
applyHook(onActionHooks, _state, data, name, caller, createSend)
}
// validate if a namespace exists. Namespaces are delimited by ':'.
var actionName = name
if (/:/.test(name)) {
var arr = name.split(':')
var ns = arr.shift()
actionName = arr.join(':')
}
var _reducers = ns ? reducers[ns] : reducers
if (_reducers && _reducers[actionName]) {
if (ns) {
var reducedState = _reducers[actionName](_state[ns], data)
newState[ns] = xtend(_state[ns], reducedState)
} else {
mutate(newState, reducers[actionName](_state, data))
}
reducersCalled = true
if (onStateChangeHooks.length) {
applyHook(onStateChangeHooks, newState, data, _state, actionName, createSend)
}
_state = newState
cb(null, newState)
}
var _effects = ns ? effects[ns] : effects
if (!reducersCalled && _effects && _effects[actionName]) {
var send = createSend('effect: ' + name)
if (ns) _effects[actionName](_state[ns], data, send, cb)
else _effects[actionName](_state, data, send, cb)
effectsCalled = true
}
if (!reducersCalled && !effectsCalled) {
throw new Error('Could not find action ' + actionName)
}
}))()
}
}
// stop an app, essentially turns
// all send() calls into no-ops.
// () -> null
function stop () {
stopped = true
}
}
// compose an object conditionally
// optionally contains a namespace
// which is used to nest properties.
// (str, obj, obj, fn?) -> null
function apply (ns, source, target, wrap) {
if (ns && !target[ns]) target[ns] = {}
Object.keys(source).forEach(function (key) {
var cb = wrap ? wrap(source[key], key) : source[key]
if (ns) target[ns][key] = cb
else target[key] = cb
})
}
// handle errors all the way at the top of the trace
// err? -> null
function defaultOnError (err) {
throw err
}
function wrapOnError (onError) {
return function onErrorWrap (err, state, createSend) {
if (err) onError(err, state, createSend)
}
}
// take a apply an array of transforms onto a value. The new value
// must be returned synchronously from the transform
// (any, [fn]) -> any
function wrapHook (value, transforms) {
transforms.forEach(function (transform) {
value = transform(value)
})
return value
}
================================================
FILE: package.json
================================================
{
"name": "barracks",
"version": "9.3.2",
"description": "Action dispatcher for unidirectional data flows",
"main": "index.js",
"scripts": {
"test": "standard && NODE_ENV=test node test",
"test:cov": "standard && NODE_ENV=test istanbul cover test.js",
"watch": "watch 'npm t'"
},
"repository": "yoshuawuyts/barracks",
"keywords": [
"action",
"dispatcher"
],
"license": "MIT",
"dependencies": {
"nanotick": "^1.1.2",
"xtend": "^4.0.1"
},
"devDependencies": {
"bundle-collapser": "^1.2.1",
"coveralls": "~2.11.12",
"es2020": "^1.1.6",
"istanbul": "~0.4.5",
"noop2": "^2.0.0",
"standard": "^8.0.0",
"tape": "^4.6.0",
"uglifyify": "^3.0.2",
"unassertify": "^2.0.3",
"watch": "^1.0.0"
},
"files": [
"LICENSE",
"README.md",
"index.js",
"apply-hook.js"
]
}
================================================
FILE: script/test-size
================================================
#!/bin/sh
usage () {
cat << USAGE
script/test-size
Commands:
g, gzip (default) Output gzip size
m, minified Output size minified
d, discify Run discify
USAGE
}
gzip_size () {
browserify index.js \
-g unassertify \
-g es2020 \
-g uglifyify \
-p bundle-collapser/plugin \
| uglifyjs \
| gzip-size \
| pretty-bytes
}
min_size () {
browserify index.js \
-g unassertify \
-g es2020 \
-g uglifyify \
-p bundle-collapser/plugin \
| uglifyjs \
| wc -c \
| pretty-bytes
}
run_discify () {
browserify index.js --full-paths \
-g unassertify \
-g es2020 \
-g uglifyify \
| uglifyjs \
| discify --open
}
# set CLI flags
getopt -T > /dev/null
if [ "$?" -eq 4 ]; then
args="$(getopt --long help discify minified --options hmdg -- "$*")"
else args="$(getopt h "$*")"; fi
[ ! $? -eq 0 ] && { usage && exit 2; }
eval set -- "$args"
# parse CLI flags
while true; do
case "$1" in
-h|--help) usage && exit 1 ;;
-- ) shift; break ;;
* ) break ;;
esac
done
case "$1" in
d|discify) shift; run_discify "$@" ;;
m|minified) shift; printf "min: %s\n" "$(min_size)" "$@" ;;
g|gzip|*) shift; printf "gzip: %s\n" "$(gzip_size)" "$@" ;;
esac
================================================
FILE: test.js
================================================
const barracks = require('./')
const xtend = require('xtend')
const noop = require('noop2')
const tape = require('tape')
tape('api: store = barracks(handlers)', (t) => {
t.test('should validate input types', (t) => {
t.plan(3)
t.doesNotThrow(barracks, 'no args does not throw')
t.doesNotThrow(barracks.bind(null, {}), 'object does not throw')
t.throws(barracks.bind(null, 123), 'non-object throws')
})
t.test('should validate hook types', (t) => {
t.plan(3)
t.throws(barracks.bind(null, { onError: 123 }), /function/, 'onError throws')
t.throws(barracks.bind(null, { onAction: 123 }), /function/, 'onAction throws')
t.throws(barracks.bind(null, { onStateChange: 123 }), /function/, 'onStateChange throws')
})
})
tape('api: store.model()', (t) => {
t.test('should validate input types', (t) => {
t.plan(2)
const store = barracks()
t.throws(store.model.bind(null, 123), /object/, 'non-obj should throw')
t.doesNotThrow(store.model.bind(null, {}), 'obj should not throw')
})
})
tape('api: store.use()', (t) => {
t.test('should allow model injection', (t) => {
t.plan(1)
const store = barracks()
store.model({
state: { accessed: false }
})
store.use({
models: [{
namespace: 'namespaced',
state: { 'accessed': false },
reducers: { update: (state, data) => data }
}, {
state: {},
reducers: { update: (state, data) => data }
}]
})
const createSend = store.start()
const send = createSend('test', true)
send('namespaced:update', { accessed: true })
send('update', { accessed: true })
setTimeout(function () {
const expected = { accessed: true, namespaced: { accessed: true } }
t.deepEqual(store.state(), expected, 'models can be injected')
}, 100)
})
t.test('should call multiples', (t) => {
t.plan(1)
const store = barracks()
const called = { first: false, second: false }
store.use({
onAction: (state, data, name, caller, createSend) => {
called.first = true
}
})
store.use({
onAction: (state, data, name, caller, createSend) => {
called.second = true
}
})
store.model({
state: {
count: 0
},
reducers: {
foo: (state, data) => ({ count: state.count + 1 })
}
})
const createSend = store.start()
const send = createSend('test', true)
send('foo', { count: 3 })
setTimeout(function () {
const expected = { first: true, second: true }
t.deepEqual(called, expected, 'all hooks were called')
}, 100)
})
})
tape('api: createSend = store.start(opts)', (t) => {
t.test('should validate input types', (t) => {
t.plan(3)
const store = barracks()
t.throws(store.start.bind(null, 123), /object/, 'non-obj should throw')
t.doesNotThrow(store.start.bind(null, {}), /object/, 'obj should not throw')
t.doesNotThrow(store.start.bind(null), 'undefined should not throw')
})
t.test('opts.state = false should not register state', (t) => {
t.plan(1)
const store = barracks()
store.model({ state: { foo: 'bar' } })
store.start({ state: false })
const state = store.state()
t.deepEqual(state, {}, 'no state returned')
})
t.test('opts.effects = false should not register effects', (t) => {
t.plan(1)
const store = barracks()
store.model({ effects: { foo: noop } })
store.start({ effects: false })
const effects = Object.keys(store._effects)
t.deepEqual(effects.length, 0, 'no effects registered')
})
t.test('opts.reducers = false should not register reducers', (t) => {
t.plan(1)
const store = barracks()
store.model({ reducers: { foo: noop } })
store.start({ reducers: false })
const reducers = Object.keys(store._reducers)
t.deepEqual(reducers.length, 0, 'no reducers registered')
})
t.test('opts.subscriptions = false should not register subs', (t) => {
t.plan(1)
const store = barracks()
store.model({ subscriptions: { foo: noop } })
store.start({ subscriptions: false })
const subscriptions = Object.keys(store._subscriptions)
t.deepEqual(subscriptions.length, 0, 'no subscriptions registered')
})
})
tape('api: state = store.state()', (t) => {
t.test('should return initial state', (t) => {
t.plan(1)
const store = barracks()
store.model({ state: { foo: 'bar' } })
store.start()
const state = store.state()
t.deepEqual(state, { foo: 'bar' })
})
t.test('should initialize state with empty namespace object', (t) => {
t.plan(1)
const store = barracks()
store.model({
namespace: 'beep',
state: {}
})
store.start()
const state = store.state()
const expected = {
beep: {}
}
t.deepEqual(expected, state, 'has initial empty namespace object')
})
t.test('should return the combined state', (t) => {
t.plan(1)
const store = barracks()
store.model({
namespace: 'beep',
state: { foo: 'bar', bin: 'baz' }
})
store.model({
namespace: 'boop',
state: { foo: 'bar', bin: 'baz' }
})
store.model({
state: { hello: 'dog', welcome: 'world' }
})
store.start()
const state = store.state()
const expected = {
beep: { foo: 'bar', bin: 'baz' },
boop: { foo: 'bar', bin: 'baz' },
hello: 'dog',
welcome: 'world'
}
t.deepEqual(expected, state, 'initial state of models is combined')
})
t.test('object should be frozen by default', (t) => {
t.plan(1)
const store = barracks()
store.model({ state: { foo: 'bar' } })
store.start()
const state = store.state()
state.baz = 'bin'
const expected = { foo: 'bar' }
t.deepEqual(state, expected, 'state was frozen')
})
t.test('freeze = false should not freeze objects', (t) => {
t.plan(1)
const store = barracks()
store.model({ state: { foo: 'bar' } })
store.start()
const state = store.state({ freeze: false })
state.baz = 'bin'
const expected = { foo: 'bar', baz: 'bin' }
t.deepEqual(state, expected, 'state was not frozen')
})
t.test('passing a state opts should merge state', (t) => {
t.plan(1)
const store = barracks()
store.model({ state: { foo: 'bar' } })
store.model({
namespace: 'beep',
state: { foo: 'bar', bin: 'baz' }
})
store.start()
const extendedState = {
woof: 'dog',
beep: { foo: 'baz' },
barp: { bli: 'bla' }
}
const state = store.state({ state: extendedState })
const expected = {
foo: 'bar',
woof: 'dog',
beep: { foo: 'baz', bin: 'baz' },
barp: { bli: 'bla' }
}
t.deepEqual(state, expected, 'state was merged')
})
})
tape('api: send(name, data?)', (t) => {
t.test('should validate input types', (t) => {
t.plan(1)
const store = barracks()
const createSend = store.start()
const send = createSend('test')
t.throws(send.bind(null, 123), /string/, 'non-string should throw')
})
})
tape('api: stop()', (t) => {
t.test('should stop executing send() calls', (t) => {
t.plan(1)
const store = barracks()
var count = 0
store.model({ reducers: { foo: (state, action) => { count += 1 } } })
const createSend = store.start()
const send = createSend('test', true)
send('foo')
store.stop()
send('foo')
setTimeout(() => t.equal(count, 1, 'no actions after stop()'), 10)
})
})
tape('handlers: reducers', (t) => {
t.test('should be able to be called', (t) => {
t.plan(6)
const store = barracks()
store.model({
namespace: 'meow',
state: { beep: 'boop' },
reducers: {
woof: (state, data) => t.pass('meow.woof called')
}
})
store.model({
state: {
foo: 'bar',
beep: 'boop'
},
reducers: {
foo: (state, data) => {
t.deepEqual(data, { foo: 'baz' }, 'action is equal')
t.equal(state.foo, 'bar', 'state.foo = bar')
return { foo: 'baz' }
},
sup: (state, data) => {
t.equal(data, 'nope', 'action is equal')
t.equal(state.beep, 'boop', 'state.beep = boop')
return { beep: 'nope' }
}
}
})
const createSend = store.start()
const send = createSend('tester', true)
send('foo', { foo: 'baz' })
send('sup', 'nope')
send('meow:woof')
setTimeout(function () {
const state = store.state()
const expected = {
foo: 'baz',
beep: 'nope',
meow: { beep: 'boop' }
}
t.deepEqual(state, expected, 'state was updated')
}, 10)
})
})
tape('handlers: effects', (t) => {
t.test('should be able to be called', (t) => {
t.plan(5)
const store = barracks()
store.model({
namespace: 'meow',
effects: {
woof: (state, data, send, done) => {
t.pass('woof called')
}
}
})
store.model({
state: { bin: 'baz', beep: 'boop' },
reducers: {
bar: (state, data) => {
t.pass('reducer was called')
return { beep: data.beep }
}
},
effects: {
foo: (state, data, send, done) => {
t.pass('effect was called')
send('bar', { beep: data.beep }, () => {
t.pass('effect callback was called')
done()
})
}
}
})
const createSend = store.start()
const send = createSend('tester', true)
send('foo', { beep: 'woof' })
send('meow:woof')
setTimeout(function () {
const state = store.state()
const expected = { bin: 'baz', beep: 'woof' }
t.deepEqual(state, expected, 'state was updated')
}, 10)
})
t.test('should be able to nest effects and return data', (t) => {
t.plan(12)
const store = barracks()
store.model({
effects: {
foo: (state, data, send, done) => {
t.pass('foo was called')
send('bar', { beep: 'boop' }, () => {
t.pass('foo:bar effect callback was called')
send('baz', (err, res) => {
t.ifError(err, 'no error')
t.equal(res, 'yay', 'res is equal')
t.pass('foo:baz effect callback was called')
done()
})
})
},
bar: (state, data, send, done) => {
t.pass('bar was called')
t.deepEqual(data, { beep: 'boop' }, 'action is equal')
send('baz', (err, res) => {
t.ifError(err, 'no error')
t.equal(res, 'yay', 'res is equal')
t.pass('bar:baz effect callback was called')
done()
})
},
baz: (state, data, send, done) => {
t.pass('baz effect was called')
done(null, 'yay')
}
}
})
const createSend = store.start()
const send = createSend('tester', true)
send('foo')
})
t.test('should be able to propagate nested errors', (t) => {
t.plan(7)
const store = barracks()
store.model({
effects: {
foo: (state, data, send, done) => {
t.pass('foo was called')
send('bar', (err, res) => {
t.ok(err, 'error detected')
t.pass('foo:bar effect callback was called')
done()
})
},
bar: (state, data, send, done) => {
t.pass('bar was called')
send('baz', (err, res) => {
t.ok(err, 'error detected')
t.pass('bar:baz effect callback was called')
done(err)
})
},
baz: (state, data, send, done) => {
t.pass('baz effect was called')
done(new Error('oh noooo'))
}
}
})
const createSend = store.start()
const send = createSend('tester', true)
send('foo')
})
})
tape('handlers: subscriptions', (t) => {
t.test('should be able to call', (t) => {
t.plan(9)
const store = barracks()
store.model({
namespace: 'foo',
subscriptions: {
mySub: (send, done) => {
t.pass('namespaced sub initiated')
}
}
})
store.model({
reducers: {
bar: () => t.pass('reducer called')
},
effects: {
foo: (state, data, send, done) => {
t.pass('foo was called')
done(new Error('oh no!'), 'hello')
}
},
subscriptions: {
mySub: (send, done) => {
t.pass('mySub was initiated')
send('foo', (err, res) => {
t.ok(err, 'error detected')
t.equal(res, 'hello', 'res was passed')
t.pass('mySub:foo effect callback was called')
send('bar', (err, res) => {
t.error(err, 'no error detected')
t.pass('mySub:bar effect callback was called')
})
})
}
}
})
store.start()
})
t.test('should be able to emit an error', (t) => {
t.plan(4)
const store = barracks({
onError: (err, state, createSend) => {
t.equal(err.message, 'oh no!', 'err was received')
t.equal((state || {}).a, 1, 'state was passed')
t.equal(typeof createSend, 'function', 'createSend is a function')
}
})
store.model({
state: { a: 1 },
subscriptions: {
mySub: (send, done) => {
t.pass('sub initiated')
done(new Error('oh no!'))
}
}
})
store.start()
})
})
tape('hooks: onStateChange', (t) => {
t.test('should be called whenever state changes', (t) => {
t.plan(4)
const store = barracks({
onStateChange: (state, data, prev, caller, createSend) => {
t.deepEqual(data, { count: 3 }, 'action is equal')
t.deepEqual(state, { count: 4 }, 'state is equal')
t.deepEqual(prev, { count: 1 }, 'prev is equal')
t.equal(caller, 'increment', 'caller is equal')
}
})
store.model({
state: { count: 1 },
reducers: {
increment: (state, data) => ({ count: state.count + data.count })
}
})
const createSend = store.start()
const send = createSend('test', true)
send('increment', { count: 3 })
})
t.test('should allow triggering other actions', (t) => {
t.plan(2)
const store = barracks({
onStateChange: function (state, data, prev, caller, createSend) {
t.pass('onStateChange called')
const send = createSend('test:onStateChange', true)
send('foo')
}
})
store.model({
state: { count: 1 },
effects: {
foo: (state, data, send, done) => {
t.pass('called')
done()
}
},
reducers: {
increment: (state, data) => ({ count: state.count + data.count })
}
})
const createSend = store.start()
const send = createSend('test', true)
send('increment', { count: 3 })
})
t.test('previous state should not be mutated', (t) => {
t.plan(2)
const storeNS = barracks({
onStateChange: (state, data, prev, caller, createSend) => {
t.equal(state.ns.items.length, 3, 'state was updated')
t.equal(prev.ns.items.length, 0, 'prev was left as-is')
}
})
storeNS.model({
namespace: 'ns',
state: { items: [] },
reducers: {
add: (_, state) => ({ items: [1, 2, 3] })
}
})
const createSendNS = storeNS.start()
const sendNS = createSendNS('testNS', true)
sendNS('ns:add')
})
})
tape('hooks: onAction', (t) => {
t.test('should be called whenever an action is emitted', (t) => {
t.plan(5)
const store = barracks({
onAction: (state, data, actionName, caller, createSend) => {
t.deepEqual(data, { count: 3 }, 'action is equal')
t.deepEqual(state, { count: 1 }, 'state is equal')
t.deepEqual(actionName, 'foo', 'actionName is equal')
t.equal(caller, 'test', 'caller is equal')
}
})
store.model({
state: { count: 1 },
effects: {
foo: (state, data, send, done) => {
t.pass('effect called')
done()
}
}
})
const createSend = store.start()
const send = createSend('test', true)
send('foo', { count: 3 })
})
})
tape('hooks: onError', (t) => {
t.test('should have a default err handler')
t.test('should not call itself')
})
tape('wrappers: wrapSubscriptions')
tape('wrappers: wrapReducers')
tape('wrappers: wrapEffects')
tape('wrappers: wrapInitialState', (t) => {
t.test('should wrap initial state in start', (t) => {
t.plan(2)
const store = barracks()
store.use({
wrapInitialState: (state) => {
t.deepEqual(state, { foo: 'bar' }, 'initial state is correct')
return xtend(state, { beep: 'boop' })
}
})
store.model({
state: { foo: 'bar' }
})
store.start()
process.nextTick(() => {
const state = store.state()
t.deepEqual(state, { foo: 'bar', beep: 'boop' }, 'wrapped state correct')
})
})
t.test('should wrap initial state in getState', (t) => {
t.plan(1)
const store = barracks()
store.use({
wrapInitialState: (state) => {
return xtend(state, { beep: 'boop' })
}
})
store.model({
state: { foo: 'bar' }
})
process.nextTick(() => {
const opts = {
state: { bin: 'baz' }
}
const expected = {
foo: 'bar',
beep: 'boop',
bin: 'baz'
}
const state = store.state(opts)
t.deepEqual(state, expected, 'wrapped state correct')
})
})
})
gitextract_tcofq5mj/ ├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── apply-hook.js ├── index.js ├── package.json ├── script/ │ └── test-size └── test.js
SYMBOL INDEX (6 symbols across 2 files)
FILE: apply-hook.js
function applyHook (line 5) | function applyHook (arr, arg1, arg2, arg3, arg4, arg5) {
FILE: index.js
function dispatcher (line 12) | function dispatcher (hooks) {
function apply (line 275) | function apply (ns, source, target, wrap) {
function defaultOnError (line 286) | function defaultOnError (err) {
function wrapOnError (line 290) | function wrapOnError (onError) {
function wrapHook (line 299) | function wrapHook (value, transforms) {
Condensed preview — 9 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (47K chars).
[
{
"path": ".gitignore",
"chars": 80,
"preview": "# files\n*.log\n*.pid\n*.seed\n\n# folders\nlogs/\npids/\nbuild/\ncoverage/\nnode_modules/"
},
{
"path": ".travis.yml",
"chars": 158,
"preview": "node_js:\n- \"4\"\n- \"6\"\nsudo: false\nlanguage: node_js\nscript: \"npm run test:cov\"\nafter_script: \"npm install coveralls@2 && "
},
{
"path": "LICENSE",
"chars": 1078,
"preview": "The MIT License (MIT)\n\nCopyright (c) 2014 Yoshua Wuyts\n\nPermission is hereby granted, free of charge, to any person obta"
},
{
"path": "README.md",
"chars": 13396,
"preview": "# barracks\n[![NPM version][npm-image]][npm-url]\n[![build status][travis-image]][travis-url]\n[![Test coverage][coveralls-"
},
{
"path": "apply-hook.js",
"chars": 270,
"preview": "module.exports = applyHook\n\n// apply arguments onto an array of functions, useful for hooks\n// (arr, any?, any?, any?, a"
},
{
"path": "index.js",
"chars": 10169,
"preview": "var mutate = require('xtend/mutable')\nvar nanotick = require('nanotick')\nvar assert = require('assert')\nvar xtend = requ"
},
{
"path": "package.json",
"chars": 866,
"preview": "{\n \"name\": \"barracks\",\n \"version\": \"9.3.2\",\n \"description\": \"Action dispatcher for unidirectional data flows\",\n \"mai"
},
{
"path": "script/test-size",
"chars": 1260,
"preview": "#!/bin/sh\n\nusage () {\ncat << USAGE\nscript/test-size\n Commands:\n g, gzip (default) Output gzip size\n m, minifie"
},
{
"path": "test.js",
"chars": 17630,
"preview": "const barracks = require('./')\nconst xtend = require('xtend')\nconst noop = require('noop2')\nconst tape = require('tape')"
}
]
About this extraction
This page contains the full source code of the yoshuawuyts/barracks GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 9 files (43.9 KB), approximately 12.0k tokens, and a symbol index with 6 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.