forked from swagger-api/swagger-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsystem.js
483 lines (402 loc) · 13 KB
/
system.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
import React from "react"
import { createStore, applyMiddleware, bindActionCreators, compose } from "redux"
import Im, { fromJS, Map } from "immutable"
import deepExtend from "deep-extend"
import { combineReducers } from "redux-immutable"
import serializeError from "serialize-error"
import assignDeep from "@kyleshockey/object-assign-deep"
import { NEW_THROWN_ERR } from "corePlugins/err/actions"
import win from "core/window"
import { systemThunkMiddleware, isFn, objMap, objReduce, isObject, isArray, isFunc } from "core/utils"
const idFn = a => a
// Apply middleware that gets sandwitched between `dispatch` and the reducer function(s)
function createStoreWithMiddleware(rootReducer, initialState, getSystem) {
let middlwares = [
// createLogger( {
// stateTransformer: state => state && state.toJS()
// } ),
systemThunkMiddleware( getSystem )
]
const composeEnhancers = win.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose
return createStore(rootReducer, initialState, composeEnhancers(
applyMiddleware( ...middlwares )
))
}
export default class Store {
constructor(opts={}) {
deepExtend(this, {
state: {},
plugins: [],
system: {
configs: {},
fn: {},
components: {},
rootInjects: {},
statePlugins: {}
},
boundSystem: {},
toolbox: {}
}, opts)
this.getSystem = this._getSystem.bind(this)
// Bare system (nothing in it, besides the state)
this.store = configureStore(idFn, fromJS(this.state), this.getSystem )
// will be the system + Im, we can add more tools when we need to
this.buildSystem(false)
// Bootstrap plugins
this.register(this.plugins)
}
getStore() {
return this.store
}
register(plugins, rebuild=true) {
var pluginSystem = combinePlugins(plugins, this.getSystem())
systemExtend(this.system, pluginSystem)
if(rebuild) {
this.buildSystem()
}
const needAnotherRebuild = callAfterLoad.call(this.system, plugins, this.getSystem())
if(needAnotherRebuild) {
this.buildSystem()
}
}
buildSystem(buildReducer=true) {
let dispatch = this.getStore().dispatch
let getState = this.getStore().getState
this.boundSystem = Object.assign({},
this.getRootInjects(),
this.getWrappedAndBoundActions(dispatch),
this.getWrappedAndBoundSelectors(getState, this.getSystem),
this.getStateThunks(getState),
this.getFn(),
this.getConfigs()
)
if(buildReducer)
this.rebuildReducer()
}
_getSystem() {
return this.boundSystem
}
getRootInjects() {
return Object.assign({
getSystem: this.getSystem,
getStore: this.getStore.bind(this),
getComponents: this.getComponents.bind(this),
getState: this.getStore().getState,
getConfigs: this._getConfigs.bind(this),
Im,
React
}, this.system.rootInjects || {})
}
_getConfigs(){
return this.system.configs
}
getConfigs() {
return {
configs: this.system.configs
}
}
setConfigs(configs) {
this.system.configs = configs
}
rebuildReducer() {
this.store.replaceReducer(buildReducer(this.system.statePlugins))
}
/**
* Generic getter from system.statePlugins
*
*/
getType(name) {
let upName = name[0].toUpperCase() + name.slice(1)
return objReduce(this.system.statePlugins, (val, namespace) => {
let thing = val[name]
if(thing)
return {[namespace+upName]: thing}
})
}
getSelectors() {
return this.getType("selectors")
}
getActions() {
let actionHolders = this.getType("actions")
return objMap(actionHolders, (actions) => {
return objReduce(actions, (action, actionName) => {
if(isFn(action))
return {[actionName]: action}
})
})
}
getWrappedAndBoundActions(dispatch) {
let actionGroups = this.getBoundActions(dispatch)
return objMap(actionGroups, (actions, actionGroupName) => {
let wrappers = this.system.statePlugins[actionGroupName.slice(0,-7)].wrapActions
if(wrappers) {
return objMap(actions, (action, actionName) => {
let wrap = wrappers[actionName]
if(!wrap) {
return action
}
if(!Array.isArray(wrap)) {
wrap = [wrap]
}
return wrap.reduce((acc, fn) => {
let newAction = (...args) => {
return fn(acc, this.getSystem())(...args)
}
if(!isFn(newAction)) {
throw new TypeError("wrapActions needs to return a function that returns a new function (ie the wrapped action)")
}
return wrapWithTryCatch(newAction)
}, action || Function.prototype)
})
}
return actions
})
}
getWrappedAndBoundSelectors(getState, getSystem) {
let selectorGroups = this.getBoundSelectors(getState, getSystem)
return objMap(selectorGroups, (selectors, selectorGroupName) => {
let stateName = [selectorGroupName.slice(0, -9)] // selectors = 9 chars
let wrappers = this.system.statePlugins[stateName].wrapSelectors
if(wrappers) {
return objMap(selectors, (selector, selectorName) => {
let wrap = wrappers[selectorName]
if(!wrap) {
return selector
}
if(!Array.isArray(wrap)) {
wrap = [wrap]
}
return wrap.reduce((acc, fn) => {
let wrappedSelector = (...args) => {
return fn(acc, this.getSystem())(getState().getIn(stateName), ...args)
}
if(!isFn(wrappedSelector)) {
throw new TypeError("wrapSelector needs to return a function that returns a new function (ie the wrapped action)")
}
return wrappedSelector
}, selector || Function.prototype)
})
}
return selectors
})
}
getStates(state) {
return Object.keys(this.system.statePlugins).reduce((obj, key) => {
obj[key] = state.get(key)
return obj
}, {})
}
getStateThunks(getState) {
return Object.keys(this.system.statePlugins).reduce((obj, key) => {
obj[key] = ()=> getState().get(key)
return obj
}, {})
}
getFn() {
return {
fn: this.system.fn
}
}
getComponents(component) {
const res = this.system.components[component]
if(Array.isArray(res)) {
return res.reduce((ori, wrapper) => {
return wrapper(ori, this.getSystem())
})
}
if(typeof component !== "undefined") {
return this.system.components[component]
}
return this.system.components
}
getBoundSelectors(getState, getSystem) {
return objMap(this.getSelectors(), (obj, key) => {
let stateName = [key.slice(0, -9)] // selectors = 9 chars
const getNestedState = ()=> getState().getIn(stateName)
return objMap(obj, (fn) => {
return (...args) => {
let res = wrapWithTryCatch(fn).apply(null, [getNestedState(), ...args])
// If a selector returns a function, give it the system - for advanced usage
if(typeof(res) === "function")
res = wrapWithTryCatch(res)(getSystem())
return res
}
})
})
}
getBoundActions(dispatch) {
dispatch = dispatch || this.getStore().dispatch
const actions = this.getActions()
const process = creator =>{
if( typeof( creator ) !== "function" ) {
return objMap(creator, prop => process(prop))
}
return ( ...args )=>{
var action = null
try{
action = creator( ...args )
}
catch( e ){
action = {type: NEW_THROWN_ERR, error: true, payload: serializeError(e) }
}
finally{
return action // eslint-disable-line no-unsafe-finally
}
}
}
return objMap(actions, actionCreator => bindActionCreators( process( actionCreator ), dispatch ) )
}
getMapStateToProps() {
return () => {
return Object.assign({}, this.getSystem())
}
}
getMapDispatchToProps(extras) {
return (dispatch) => {
return deepExtend({}, this.getWrappedAndBoundActions(dispatch), this.getFn(), extras)
}
}
}
function combinePlugins(plugins, toolbox) {
if(isObject(plugins) && !isArray(plugins)) {
return assignDeep({}, plugins)
}
if(isFunc(plugins)) {
return combinePlugins(plugins(toolbox), toolbox)
}
if(isArray(plugins)) {
return plugins
.map(plugin => combinePlugins(plugin, toolbox))
.reduce(systemExtend, {})
}
return {}
}
function callAfterLoad(plugins, system, { hasLoaded } = {}) {
let calledSomething = hasLoaded
if(isObject(plugins) && !isArray(plugins)) {
if(typeof plugins.afterLoad === "function") {
calledSomething = true
wrapWithTryCatch(plugins.afterLoad).call(this, system)
}
}
if(isFunc(plugins))
return callAfterLoad.call(this, plugins(system), system, { hasLoaded: calledSomething })
if(isArray(plugins)) {
return plugins.map(plugin => callAfterLoad.call(this, plugin, system, { hasLoaded: calledSomething }))
}
return calledSomething
}
// Wraps deepExtend, to account for certain fields, being wrappers.
// Ie: we need to convert some fields into arrays, and append to them.
// Rather than overwrite
function systemExtend(dest={}, src={}) {
if(!isObject(dest)) {
return {}
}
if(!isObject(src)) {
return dest
}
// Wrap components
// Parses existing components in the system, and prepares them for wrapping via getComponents
if(src.wrapComponents) {
objMap(src.wrapComponents, (wrapperFn, key) => {
const ori = dest.components && dest.components[key]
if(ori && Array.isArray(ori)) {
dest.components[key] = ori.concat([wrapperFn])
delete src.wrapComponents[key]
} else if(ori) {
dest.components[key] = [ori, wrapperFn]
delete src.wrapComponents[key]
}
})
if(!Object.keys(src.wrapComponents).length) {
// only delete wrapComponents if we've matched all of our wrappers to components
// this handles cases where the component to wrap may be out of our scope,
// but a higher recursive `combinePlugins` call will be able to handle it.
delete src.wrapComponents
}
}
// Account for wrapActions, make it an array and append to it
// Modifies `src`
// 80% of this code is just safe traversal. We need to address that ( ie: use a lib )
const { statePlugins } = dest
if(isObject(statePlugins)) {
for(let namespace in statePlugins) {
const namespaceObj = statePlugins[namespace]
if(!isObject(namespaceObj) || !isObject(namespaceObj.wrapActions)) {
continue
}
const { wrapActions } = namespaceObj
for(let actionName in wrapActions) {
let action = wrapActions[actionName]
// This should only happen if dest is the first plugin, since invocations after that will ensure its an array
if(!Array.isArray(action)) {
action = [action]
wrapActions[actionName] = action // Put the value inside an array
}
if(src && src.statePlugins && src.statePlugins[namespace] && src.statePlugins[namespace].wrapActions && src.statePlugins[namespace].wrapActions[actionName]) {
src.statePlugins[namespace].wrapActions[actionName] = wrapActions[actionName].concat(src.statePlugins[namespace].wrapActions[actionName])
}
}
}
}
return deepExtend(dest, src)
}
function buildReducer(states) {
let reducerObj = objMap(states, (val) => {
return val.reducers
})
return allReducers(reducerObj)
}
function allReducers(reducerSystem) {
let reducers = Object.keys(reducerSystem).reduce((obj, key) => {
obj[key] = makeReducer(reducerSystem[key])
return obj
},{})
if(!Object.keys(reducers).length) {
return idFn
}
return combineReducers(reducers)
}
function makeReducer(reducerObj) {
return (state = new Map(), action) => {
if(!reducerObj)
return state
let redFn = (reducerObj[action.type])
if(redFn) {
const res = wrapWithTryCatch(redFn)(state, action)
// If the try/catch wrapper kicks in, we'll get null back...
// in that case, we want to avoid making any changes to state
return res === null ? state : res
}
return state
}
}
function wrapWithTryCatch(fn, {
logErrors = true
} = {}) {
if(typeof fn !== "function") {
return fn
}
return function(...args) {
try {
return fn.call(this, ...args)
} catch(e) {
if(logErrors) {
console.error(e)
}
return null
}
}
}
function configureStore(rootReducer, initialState, getSystem) {
const store = createStoreWithMiddleware(rootReducer, initialState, getSystem)
// if (module.hot) {
// // Enable Webpack hot module replacement for reducers
// module.hot.accept("reducers/index", () => {
// const nextRootReducer = require("reducers/index")
// store.replaceReducer(nextRootReducer)
// })
// }
return store
}