UNPKG

122 kBSource Map (JSON)View Raw
1{"version":3,"file":"monadHelpers-e0c6950d.js","sources":["../src/errorHelpers.js","../src/monadHelpers.js"],"sourcesContent":["/**\n * Created by Andy Likuski on 2020.02.21\n * Copyright (c) 2020 Andy Likuski\n *\n * 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:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * 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.\n */\nimport * as R from 'ramda';\n\n/**\n * Stringify an error with a stack trace\n * https://stackoverflow.com/questions/18391212/is-it-not-possible-to-stringify-an-error-using-json-stringify\n * @param {Object} err Error\n * @return {string} The json stringified error\n */\nexport const stringifyError = err => {\n // If the error isn't an Error object, wrap it\n const wrappedError = wrapError(err);\n\n const obj = R.fromPairs(R.map(\n key => [key, wrappedError[key]],\n Object.getOwnPropertyNames(wrappedError)\n ));\n // Use replace to convert escaped in stack \\\\n to \\n\n return R.replace(/\\\\n/g, '\\n', JSON.stringify(\n // Put message and stack first\n R.merge(R.pick(['message', 'stack'], obj), R.omit(['message', 'stack'])),\n null,\n 2\n ));\n};\n\n/**\n * Wraps an error in Error unless it already is an Error. Useful for Result.Error strings that need to be\n * converted to errors\n * @param {*} error The value to wrap if needed\n * @return {Error} The wrapped error\n */\nexport const wrapError = error => {\n return R.unless(\n R.is(Error),\n e => new Error(e)\n )(error);\n};\n","/**\n * Created by Andy Likuski on 2018.05.10\n * Copyright (c) 2018 Andy Likuski\n *\n * 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:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n *\n * 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.\n */\n\nimport {fromPromised, of, rejected, task, waitAll} from 'folktale/concurrency/task';\nimport * as R from 'ramda';\nimport * as Result from 'folktale/result';\nimport {reqStrPathThrowing} from './throwingFunctions';\nimport {Just} from 'folktale/maybe';\nimport {stringifyError} from './errorHelpers';\nimport {compact, isObject, toArrayIfNot} from './functions';\nimport {inspect} from 'util';\n\n/**\n * Default handler for Task rejections when an error is unexpected and should halt execution\n * with a useful error message\n * @param {[Object]} Errors that are accumulated\n * @param {*} reject Rejection value from a Task\n * @returns {void} No return\n */\nexport const defaultOnRejected = R.curry((errors, reject) => {\n // Combine reject and errors\n const errorsAsArray = toArrayIfNot(errors);\n const allErrors = R.uniq(R.concat(errorsAsArray, [reject]));\n // Wrap each error in an Error object if it isn't already one\n console.error('Accumulated task errors:\\n', // eslint-disable-line no-console\n R.join('\\n', R.map(error => stringifyError(error), allErrors)\n )\n );\n});\nconst _onRejected = defaultOnRejected;\n\n/**\n * Default behavior for task listener defaultOnCancelled, which simply logs\n * @returns {void} No return\n */\nexport const defaultOnCancelled = () => {\n console.log('The task was cancelled. This is the default action'); // eslint-disable-line no-console\n};\nconst _onCanceled = defaultOnCancelled;\n\nconst whenDone = (errors, done) => {\n if (done) {\n done(\n R.when(\n R.identity,\n errs => R.map(\n stringifyError,\n errs || []\n )\n )(errors)\n );\n }\n};\n\n\n/**\n * Defaults the defaultOnRejected and defaultOnCancelled to throw or log, respectively, when neither is expected to occur.\n * Pass the onResolved function with the key onResolved pointing to a unary function with the result. Example:\n * task.run().listen(defaultRunConfig({\n * onResolved: value => ... do something with value ...\n * }))\n * @param {Object} obj Object of callbacks\n * @param {Function} obj.onResolved Unary function expecting the resolved value\n * @param {Function} obj.onCancelled optional cancelled handler. Default is to log\n * @param {Function} obj.onRejected optional rejected handler. Default is to throw. This function is first\n * passed the errors that have accumulated and then the final error. You should make a curried function\n * or similarly that expects two arguments, error and error\n * @param {[Object]} errors Optional list of errors that accumulated\n * @param {Function} done Optional or tests. Will be called after rejecting, canceling or resolving\n * @returns {Object} Run config with defaultOnCancelled, defaultOnRejected, and onReolved handlers\n */\nexport const defaultRunConfig = ({onResolved, onCancelled, onRejected, _whenDone}, errors, done) => {\n return ({\n onCancelled: () => {\n (onCancelled || _onCanceled)();\n whenDone(null, done);\n },\n onRejected: error => {\n _handleReject(onRejected, done, errors, error);\n },\n onResolved: value => {\n let errs = null;\n try {\n // Wrap in case anything goes wrong with the assertions\n onResolved(value);\n } catch (e) {\n // I can't import this but we don't want to process assertion errors\n if (e.constructor.name === 'JestAssertionError') {\n errs = [e];\n throw e;\n }\n const error = new Error('Assertion threw error');\n errs = [e, error];\n const reject = onRejected || _onRejected;\n reject(errs, error);\n } finally {\n (_whenDone || whenDone)(errs, done);\n }\n }\n });\n};\n\n/**\n * Given a rejection in runDefaultConfig or runDefaultToResultConfig, calls the given rejected or the default.\n * if no onRejected is given or it throws an error when called, then done is called with the errors to make the\n * test fail\n * @param {Function} onRejected Expects errors and error\n * @param {Function} done Done function\n * @param {[Object]} errs Accumulated error\n * @param {Object} error Error that caused the oReject\n * @returns {void} No return\n * @private\n */\nconst _handleReject = (onRejected, done, errs, error) => {\n let noThrow = true;\n let caughtError = null;\n try {\n (onRejected || _onRejected)(errs, error);\n } catch (e) {\n noThrow = false;\n caughtError = e;\n } finally {\n // If we didn't define onRejected or our onRejected threw, pass errors so jest fails\n whenDone(\n onRejected && noThrow ?\n null :\n R.concat(errs, compact([error, caughtError])),\n done\n );\n }\n};\n\n/**\n * For a task that returns a Result.\n * Defaults the defaultOnRejected and defaultOnCancelled to fail the test or log, respectively, when neither is expected to occur.\n * Pass the onResolved function with the key onResolved pointing to a unary function with the result.\n * If the task resolves to an Result.Ok, resolves the underlying value and passes it to the onResolved function\n * that you define. If the task resolves ot an Result.Error, the underlying value is passed to on Rejected.\n * rejection and cancellation resolves the underlying value of the Result.Ok or Result.Error. In practice defaultOnRejected shouldn't\n * get called directly. Rather a Result.Error should be resolved and then this function calls defaultOnRejected. cancellation\n * should probably ignores the value.\n * If you don't define onRejected an a rejection occurs or your onRejected throws an exception, the test will fail\n * Example:\n * task.run().listen(defaultRunConfig({\n * onResolved: value => ... do something with value ...\n * }))\n * @param {Object} obj Object of callbacks\n * @param {Function} obj.onResolved Unary function expecting the resolved value\n * @param {Function} [obj.onRejected] Optional expects a list of accumulated errors and the final error. This function\n * will be called for normal task rejection and also if the result of the task is a result.Error, in which\n * case errors will be R.concat(errors || [], [result.Error]) and error will be result.Error\n * @param {Function} [obj.onCancelled] Optional cancelled function\n * @param {[Object]} errors Empty array to collect errors\n * @param {Function} done Done function from test definition\n * @returns {Object} Run config with defaultOnCancelled, defaultOnRejected, and onReolved handlers\n */\nexport const defaultRunToResultConfig = ({onResolved, onCancelled, onRejected}, errors, done) => {\n // We have to do this here instead of using defaultRunConfig's version\n const reject = (errs, error) => {\n _handleReject(onRejected, done, errs, error);\n };\n\n return defaultRunConfig({\n onResolved: result => {\n return result.map(value => {\n try {\n // Wrap in case anything goes wrong with the assertions\n onResolved(value);\n } catch (error) {\n reject(R.concat(onCancelled || [], [error]), error);\n }\n // don't finalize here, defaultRunConfig.onResolved does that\n }).mapError(\n error => reject(onCancelled || [], error)\n );\n },\n onRejected: error => reject([], error),\n onCancelled: onCancelled\n },\n errors,\n done\n );\n};\n\n/**\n * Wraps a Task in a Promise.\n * @param {Task} tsk The Task\n * @returns {Promise} The Task as a Promise\n */\nexport const taskToPromise = (tsk) => {\n if (!tsk.run) {\n throw new TypeError(`Expected a Task, got ${typeof tsk}`);\n }\n return tsk.run().promise();\n};\n\n\n/**\n * @deprecated Use fromPromised from folktale/concurrency/task\n * Wraps a Promise in a Task\n * @param {Promise} promise The promise\n * @param {boolean} expectReject default false. Set true for testing to avoid logging rejects\n * @returns {Task} The promise as a Task\n */\nexport const promiseToTask = promise => {\n return fromPromised(() => promise)();\n};\n\n/**\n * Natural transformation of a Result to a Task. This is useful for chained tasks that return Results.\n * If the Result is a Result.Error, a Task.reject is called with the value. If the Result is a Result.Ok,\n * a Task.of is created with the value\n * @param {Result} result A Result.Ok or Result.Error\n * @returns {Task} The Task.of or Task.reject\n */\nexport const resultToTask = result => result.matchWith({\n Ok: ({value}) => of(value),\n Error: ({value}) => rejected(value)\n});\n\n/**\n * Passes a result to a function that returns a Task an maps the successful Task value to a Result.Ok\n * and erroneous task to a Result.Error. If result is an error it is wrapped in a Task.Of\n * @param {Function} f Function that receives a Result.Ok value and returns a Task. This should not return a task\n * with a result. If it does then you don't need resultToTaskNeedingResult.\n * @param {Object} result A Result.Ok or Result.Error\n * @returns {Object} Task with Result.Ok or Result.Error inside.\n * @sig resultToTaskNeedingResult:: Result r, Task t => (r -> t) -> r -> t r\n */\nexport const resultToTaskNeedingResult = R.curry((f, result) => result.matchWith({\n Ok: ({value}) => f(value).map(Result.Ok).mapRejected(Result.Error),\n Error: of\n}));\n\n/**\n * Passes a result to a function that returns a Task containing a Result\n * and erroneous task maps converts a Result.Ok to a Result.Error. If result is an error it is wrapped in a Task.Of\n * @param {Function} f Function that receives result and returns a Task with a Result in it.\n * @param {Object} result A Result.Ok or Result.Error\n * @returns {Object} Task with Result.Ok or Result.Error inside.\n * @sig resultToTaskNeedingResult:: Result r, Task t => (r -> t r) -> r -> t r\n */\nexport const resultToTaskWithResult = R.curry((f, result) => {\n return result.matchWith({\n Ok: ({value}) => f(value).mapRejected(\n r => {\n return R.cond([\n // Chain Result.Ok to Result.Error\n [Result.Ok.hasInstance, R.chain(v => Result.Error(v))],\n // Leave Result.Error alone\n [Result.Error.hasInstance, R.identity],\n // If the rejected function didn't produce a Result then wrap it in a Result.Error\n [R.T, Result.Error]\n ])(r);\n }\n ),\n Error: of\n });\n});\n\n/**\n * Wraps the value of a successful task in a Result.Ok if it isn't already a Result\n * Converts a rejected task to a resolved task and\n * wraps the value of a rejected task in a Result.Error if it isn't already a Result.Error or converts\n * Result.Ok to Result.Error.\n * @param {Task} tsk The task to map\n * @returns {Task} The task whose resolved or rejected value is wrapped in a Result and is always resolved\n */\nexport const taskToResultTask = tsk => {\n return tsk.map(v => {\n return R.cond([\n // Leave Result.Ok alone\n [Result.Ok.hasInstance, R.identity],\n // Leave Result.Error alone\n [Result.Error.hasInstance, R.identity],\n // If the rejected function didn't produce a Result then wrap it in a Result.Ok\n [R.T, Result.Ok]\n ])(v);\n }).orElse(v => {\n return of(R.cond([\n // Chain Result.Ok to Result.Error\n [Result.Ok.hasInstance, R.chain(e => Result.Error(e))],\n // Leave Result.Error alone\n [Result.Error.hasInstance, R.identity],\n // If the rejected function didn't produce a Result then wrap it in a Result.Error\n [R.T, Result.Error]\n ])(v));\n });\n};\n\n/**\n * A version of traverse that also reduces. I'm sure there's something in Ramda for this, but I can't find it.\n * Same arguments as reduce, but the initialValue must be an applicative, like task.of({}) or Result.of({})\n * f is called with the underlying value of accumulated applicative and the underlying value of each list item,\n * which must be an applicative\n * @param {Function} accumulator Accepts the value of the reduced container and each result of sequencer,\n * then returns a value that will be wrapped in a container for the subsequent interation\n * Container C v => v -> v -> v\n * @param {Object} initialValue A container to be the initial reduced value of accumulator\n * @param {[Object]} list List of contianer\n * @returns {Object} The value resulting from traversing and reducing\n * @sig traverseReduce:: Container C v => (v -> v -> v) -> C v -> [C v] -> C v\n */\nexport const traverseReduce = (accumulator, initialValue, list) => R.reduce(\n (containerResult, container) => {\n return R.chain(\n res => {\n return R.map(\n v => {\n return accumulator(res, v);\n },\n container\n );\n },\n containerResult\n );\n },\n initialValue,\n list\n);\n\n/**\n * Same as traverseReduce but uses mapError to handle Result.Error or anything else that implements mapError\n * @param {function} join It's necessary to pass a join function to instruct how to extract the embedded value,\n * since Result.Error and similar don't implement chain or join. For Result.Error, join would be:\n * const join = error => error.matchWith({Error: ({value}) => value}) or simply error => error.value\n * @param {function} accumulator Accumulates the values of the monads\n * @param {object} initialValue The initial value should match an empty error monad\n * @param {[object]} list The list of error monads\n * @returns {Object} The reduced error monad\n */\nexport const traverseReduceError = (join, accumulator, initialValue, list) => R.reduce(\n (containerResult, container) => join(containerResult.mapError(\n res => container.mapError(v => accumulator(res, v))\n )),\n initialValue,\n list\n);\n\n/**\n * traverseReduceError specifically for Result.Error\n * @param {function} accumulator Accumulates the values of the monads\n * @param {object} initialValue The initial value should match an empty error monad\n * @param {[object]} list The list of error monads\n * @returns {Object} The reduced error monad\n */\nexport const traverseReduceResultError = (accumulator, initialValue, list) => {\n return traverseReduceError(\n error => {\n return error.matchWith(\n {\n Error: ({value}) => value,\n Ok: ({value}) => value\n }\n );\n },\n accumulator,\n initialValue,\n list\n );\n};\n\n/**\n * A version of traverse that also reduces. I'm sure there's something in Ramda for this, but I can't find it.\n * The first argument specify the depth of the container (monad). So a container of R.compose(Task.of Result.Ok(1)) needs\n * a depth or 2. A container of R.compose(Task.of, Result.Ok)([1,2,3]) needs a depth of 3, where the array is the 3rd container\n * if you are operating on individual items. If you're treating the array as an singular entity then it remains level 2.\n * After that Same arguments as reduce, but the initialValue must be an applicative,\n * like task.of({}) or Result.of({}) (both level 1) or R.compose(Task.of, Result.Ok(0)) if adding values (level 2)\n * or R.compose(Task.of, Result.Ok, Array.of)() (level 3) if combining each array item somehow.\n * @param {Function} accumulator Accepts a reduced applicative and each result of sequencer, then returns the new reduced applicative\n * Container C v => v -> v -> v\n * @param {Object} initialValue A conatiner to be the initial reduced value of accumulator. This must match the\n * expected container type\n * @param {[Object]} list List of containers. The list does not itself count as a container toward containerDepth. So a list of Tasks of Results is still level containerDepth: 2\n * @returns {Object} The value resulting from traversing and reducing\n * @sig traverseReduceDeep:: Number N, N-Depth-Container C v => N -> (v -> v -> v) -> C v -> [C v] -> C v\n */\nexport const traverseReduceDeep = R.curry((containerDepth, accumulator, initialValue, deepContainers) =>\n R.reduce(\n (applicatorRes, applicator) => R.compose(\n // This composes the number of R.lift2 calls we need. We need one per container level\n // The first one (final step of compose) is the call to the accumulator function with the lifted values\n ...R.times(R.always(R.liftN(2)), containerDepth)\n )(accumulator)(applicatorRes, applicator),\n initialValue,\n deepContainers\n )\n);\n\n/**\n * Export chains a monad to a reducedMonad with the given function\n * @param {Function} f Expects the reducedMonad and the monad, returns a new reducedMonad\n * @param {Object} reducedMonad THe monad that is already reduced\n * @param {Object} monad The monad to reduce\n * @param {Number} index The index of the monad\n * @return {Object} The monad result of calling f\n */\nconst _chainTogetherWith = (f, reducedMonad, monad, index) => {\n return f(reducedMonad, monad, index);\n};\n\n/**\n * Version of _chainTogetherWith for task that composes a timeout every 100 calls into the chain to prevent stack overflow\n * @param {Function} f Expects the reducedMonad and the monad and an optional index, returns a new reducedMonad\n * @param {Object} reducedMonad THe monad that is already reduced\n * @param {Object} monad The monad to reduce\n * @param {Object} index So we don't break the chain all the time\n * @return {Object} The monad result of calling f\n * @private\n */\nconst _chainTogetherWithTaskDelay = (f, reducedMonad, monad, index) => {\n const n = 100;\n // console.log(`${index} trace: ${stackTrace.get().length}`);\n return composeWithChainMDeep(1, [\n i => f(reducedMonad, monad, i),\n // Timeout every n calls\n R.ifElse(\n i => R.not(R.modulo(i, n)),\n timeoutTask,\n of\n )\n ])(index);\n};\n\nexport const timeoutTask = (...args) => {\n return task(\n (resolver) => {\n const timerId = setTimeout(() => {\n return resolver.resolve(...args);\n }, 0);\n resolver.cleanup(() => {\n clearTimeout(timerId);\n });\n }\n );\n};\n\n/**\n * Reduces a list of monads using buckets to prevent stack overflow\n * @param {Object} config\n * @param {Object} [config.buckets] Defaults to Math.max(100, R.length(monads) / 100). Divides the chained reductions into\n * @param {function} f Reduce function, expects the reducedMonad and the monad and chains them togther\n * buckets to prevent stack overflow.\n * @param {Object} initialValue The monad with the empty value, e.g. Maybe.Just([]) or Task.of(Result.Ok({}))\n * @param {[Object]} monads The list of monads\n */\nconst _reduceMonadsChainedBucketed = R.curry((\n {buckets},\n f,\n initialValue,\n monads\n) => {\n // Bucket the tasks so each task set has up to bucketSize monads If these are still too big we'll recursively\n // break them up later. Minimum 100 per bucket\n const bucketSize = buckets || Math.max(100, Math.floor(R.length(monads) / 100));\n const monadSets = bucketedMonadSets(bucketSize, monads);\n\n // Process each bucket of monads with traverseReduceWhileBucketed (end case) or\n // recurse with _reduceMonadsChainedBucketed with smaller bucket size\n // The first item of each set expects the accumulation of the previous set.\n // This means we can't actually evaluate the sets yet, rather return functions\n // Monad m:: [m[a]] -> m[b]\n const reducedMonadSetFuncs = R.map(\n mSet =>\n (previousSetAccumulationMonad) => {\n return R.ifElse(\n // If we have more than 100 monads recurse, limiting the bucket size to 1 / 10 the current bucket size\n mmSet => R.compose(R.lt(100), R.length)(mmSet),\n // Take the bucketSize number of monads and recurse, this will divide into more buckets\n mmSet => {\n return _reduceMonadsChainedBucketed({buckets}, f, previousSetAccumulationMonad, mmSet);\n },\n // Small enough, do a normal R.reduce for each bucket of tasks\n // Monad m:: [[m a]] -> [b -> m [c]]\n mmSet => {\n return R.reduce(f, previousSetAccumulationMonad, mmSet);\n }\n )(mSet);\n },\n monadSets\n );\n\n // Reduce the buckets. We pass the previous bucket result to the next monadSetFunc to kick off the processing\n // of each monadSet\n return R.reduce(\n // Chain the resultSets together\n // Monad m:: m[[a]] -> m[a]\n (accumulatedMonadSets, monadSetFunc) => {\n return monadSetFunc(accumulatedMonadSets);\n },\n // Initial value\n initialValue,\n reducedMonadSetFuncs\n );\n});\n\n\n/**\n * A version of traverseReduce that also reduces until a boolean condition is met.\n * Same arguments as reduceWhile, but the initialValue must be an applicative, like task.of({}) or Result.of({})\n * f is called with the underlying value of accumulated applicative and the underlying value of each list item,\n * which must be an applicative\n * @param {Object|Function} predicateOrObj Like ramda's reduceWhile predicate. Accepts the accumulated value and next value.\n * These are the values of the container. If false is returned the accumulated value is returned without processing\n * more values. Be aware that for Tasks the task must run to predicate on the result, so plan to check the previous\n * task to prevent a certain task from running\n @param {Boolean} [predicateOrObj.accumulateAfterPredicateFail] Default false. Because of Tasks, we have a boolean here to allow accumulation after\n * the predicate fails. The default behavior is to not accumulate the value of a failed predicate. This makes\n * sense for things like Result where there is no consequence of evaluating them. But we have to run a Task to\n * evaluate it so we might want to quit after the previous task but also add that task result to the accumulation.\n * In that case set this true\n * @param {Function} [predicateOrObj.mappingFunction] Defaults to R.map. The function used to each monad result from list.\n * If the accumulator does not create a new monad then R.map is sufficient. However if the accumulator does create\n * a new monad this should be set to R.chain so that the resulting monad isn't put inside the monad result\n * @param {Function} [predicateOrObj.chainTogetherWith] Defaults to _chainTogetherWith. Only needs to be overridden\n * for high stack count chaining that needs to be broken up to avoid max stack trace\n * @param {Function} [predicateOrObj.monadConstructor] Default to R.identity. Function to create a monad if mappingFunction uses R.chain. This\n * would be a task of function for task monads, an Result,Ok monad for Results, etc.\n * @param {Function} [predicateOrObj.reducer] Default R.Reduce. An alternative reducer function to use, for\n * instnace for stack handling by traverseReduceWhileBucketed\n * @param {Function} accumulator Accepts a reduced applicative and each result of sequencer, then returns the new reduced applicative\n * false it \"short-circuits\" the iteration and returns teh current value of the accumulator\n * @param {Object} initialValueMonad An applicative to be the intial reduced value of accumulator\n * @param {[Object]} list List of applicatives\n * @returns {Object} The value resulting from traversing and reducing\n */\nexport const traverseReduceWhile = (predicateOrObj, accumulator, initialValueMonad, list) => {\n // Configure the reduce function. It returns a reduce function expecting the two monads, the accumulated monad\n // and each in list\n const _reduceMonadsWithWhilst = _reduceMonadsWithWhile({predicateOrObj, accumulator, initialValueMonad});\n // Use R.reduce for processing each monad unless an alternative is specified.\n const reduceFunction = R.ifElse(R.both(isObject, R.prop('reducer')), R.prop('reducer'), () => R.reduce)(predicateOrObj);\n\n // By default we call\n const chainWith = R.propOr(_chainTogetherWith, 'chainTogetherWith', predicateOrObj);\n\n // Call the reducer. After it finishes strip out @@transducer/reduced if we aborted with it at some point\n return composeWithChain([\n reducedMonadValue => {\n // Using the initial value to get the right monad type, strip reduced if if was returned on the last iteration\n return R.map(\n () => {\n return R.ifElse(\n R.prop('@@transducer/reduced'),\n res => R.prop('@@transducer/value', res),\n R.identity\n )(reducedMonadValue);\n },\n initialValueMonad\n );\n },\n // Reduce each monad. This reducer operate on the monad level.\n // The reducer function _reduceMonadsWithWhilst. It is called with the two monads and either chains\n // them together if if the predicate passes or returns the accMonad unchanged each time once the predicate\n // fails.\n () => {\n return R.addIndex(reduceFunction)(\n (accumulatedMonad, currentMonad, index) => {\n return chainWith(\n (accMonad, app, i) => {\n return _reduceMonadsWithWhilst(accMonad, app, i);\n },\n accumulatedMonad,\n currentMonad,\n index\n );\n },\n // The monad with the empty value, e.g. Maybe.Just([]) or Task.of(Result.Ok({}))\n initialValueMonad,\n // The list of monads\n list\n );\n }\n ])();\n};\n\n\n/**\n * A version of traverseReduceWhile that prevents maximum call stack exceeded by breaking chains into buckets\n * Normally long lists of chained tasks keep calling a new function. We need to break this up after some number\n * of calls to prevent the maximum call stack\n * @param {Object} config The config\n * @param {Object} config.predicateOrObj Like ramda's reduceWhile predicate. Accepts the accumulated value and next value.\n * These are the values of the container. If false is returned the accumulated value is returned without processing\n * more values. Be aware that for Tasks the task must run to predicate on the result, so plan to check the previous\n * task to prevent a certain task from running\n * @param {Boolean} [config.accumulateAfterPredicateFail] Default false. Because of Tasks, we have a boolean here to allow accumulation after\n * the predicate fails. The default behavior is to not accumulate the value of a failed predicate. This makes\n * sense for things like Result where there is no consequence of evaluating them. But we have to run a Task to\n * evaluate it so we might want to quit after the previous task but also add that task result to the accumulation.\n * In that case set this true\n * @param {Function} [config.mappingFunction] Defaults to R.map. The function used to each monad result from list.\n * If the accumulator does not create a new monad then R.map is sufficient. However if the accumulator does create\n * a new monad this should be set to R.chain so that the resulting monad isn't put inside the monad result\n * @param {Function} [config.chainTogetherWith] Defaults to _chainTogetherWith. Only needs to be overridden\n * for high stack count chaining that needs to be broken up to avoid max stack trace\n * @param {Function} accumulator The accumulator function expecting the reduced monad and nonad\n * @param {Object} initialValue The initial value monad\n * @param {[Object]} list The list of monads\n * @return {Object} The reduced monad\n */\nexport const traverseReduceWhileBucketed = (config, accumulator, initialValue, list) => {\n return traverseReduceWhile(\n R.merge(config, {reducer: _reduceMonadsChainedBucketed({})}),\n accumulator,\n initialValue,\n list\n );\n};\n\n/**\n * Version of traverseReduceWhileBucketed that breaks tasks chaining with timeouts to prevent max stack trace errors\n * @param {Object} config The config\n * @param {Boolean} [config.accumulateAfterPredicateFail] Default false. Because of Tasks, we have a boolean here to allow accumulation after\n * the predicate fails. The default behavior is to not accumulate the value of a failed predicate. This makes\n * sense for things like Result where there is no consequence of evaluating them. But we have to run a Task to\n * evaluate it so we might want to quit after the previous task but also add that task result to the accumulation.\n * In that case set this true\n * @param {Function} [config.mappingFunction] Defaults to R.map. The function used to each monad result from list.\n * If the accumulator does not create a new monad then R.map is sufficient. However if the accumulator does create\n * a new monad this should be set to R.chain so that the resulting monad isn't put inside the monad result\n * @param {Function} [config.chainTogetherWith] Defaults to _chainTogetherWithTaskDelay\n * @param {Function} accumulator The accumulator function expecting the reduced task and task\n * @param {Object} initialValue The initial value task\n * @param {[Object]} list The list of tasks\n * @return {Object} The reduced task\n * @return {Object} The reduced monad\n */\nexport const traverseReduceWhileBucketedTasks = (config, accumulator, initialValue, list) => {\n // If config.mappingFunction is already R.chain, we can compose with chain since the accumulator is returning\n // a monad. If not the use composeWithMapMDeep so that the given accumulator can returns its value but our\n // composed accumulator returns a task\n const accumulatorComposeChainOrMap = R.ifElse(\n R.equals(R.chain),\n () => composeWithChainMDeep,\n () => composeWithMapMDeep\n )(R.propOr(null, 'mappingFunction', config));\n return traverseReduceWhileBucketed(\n R.merge(\n config,\n {\n monadConstructor: of,\n // This has to be chain so we can return a task in our accumulator\n mappingFunction: R.chain,\n // This adds a timeout in the chaining process to avoid max stack trace problems\n chainTogetherWith: _chainTogetherWithTaskDelay\n }\n ),\n // Call the timeout task to break the stacktrace chain. Then call the accumulator with the normal inputs.\n // Always returns a task no matter if the accumulator does or not\n (accum, current) => {\n return accumulatorComposeChainOrMap(1, [\n ([a, c]) => accumulator(a, c),\n ([a, c]) => timeoutTask([a, c])\n ])([accum, current]);\n },\n initialValue,\n list\n );\n};\n\n/**\n * Used by traverseReduceWhile to chain the accumulated monad with each subsequent monad.\n * If the value of the accumulated monad is @@transducer/reduced. The chaining is short-circuited so that\n * all subsequent values are ignored\n * @param {Object} config The config\n * @param {Function|Object} config.predicateOrObj See traverseReduceWhile\n * @param {Function} config.accumulator The accumulator\n * @returns {Function} A function expecting (accumulatedMonad, applicator, index) This function is called with\n * each accumulatedMonad and applicator by traverseReduceWhile. The index is the monad index\n * @private\n */\nconst _reduceMonadsWithWhile = ({predicateOrObj, accumulator, initialValueMonad}) => {\n // Determine if predicateOrObj is just a function or also an object\n const {predicate, accumulateAfterPredicateFail} = R.ifElse(\n R.is(Function),\n () => ({predicate: predicateOrObj, accumulateAfterPredicateFail: false}),\n R.identity\n )(predicateOrObj);\n\n // Map the applicator below with R.map unless an override like R.chain is specified\n const mappingFunction = R.propOr(R.map, 'mappingFunction', predicateOrObj);\n const monadConstructor = R.propOr(R.identity, 'monadConstructor', predicateOrObj);\n const chainTogetherWith = R.propOr(_chainTogetherWith, 'chainTogetherWith', predicateOrObj);\n\n return (accumulatedMonad, applicator, index) => {\n return R.chain(\n accumulatedValue => {\n return R.ifElse(\n R.prop('@@transducer/reduced'),\n // Done, we can't quit reducing since we're chaining monads. Instead we keep chaining the initialValueMonad\n // and always return the same accumulatedMonad, meaning the @@transducer/reduced valued monad\n // We use chainWith to allow breaks in chains for tasks that would otherwise cause a stack overflow\n accValue => {\n // Always returns the same thing, but break the chain occasionally to prevent stack overflow\n return chainTogetherWith(\n () => {\n return initialValueMonad.map(() => accValue);\n },\n null,\n null,\n index\n );\n },\n accValue => mappingFunction(\n value => {\n // If the applicator's value passes the predicate, accumulate it and process the next item\n // Otherwise we stop reducing by returning R.reduced()\n return R.ifElse(\n v => {\n return predicate(accValue, v);\n },\n v => {\n return accumulator(accValue, v);\n },\n // We have to detect this above ourselves. R.reduce can't see it for deferred types like Task\n // IF the user wants to add v to the accumulation after predicate failure, do it.\n v => {\n // Use monadConstructor if is false so we return the right monad type if specified\n return (accumulateAfterPredicateFail ? R.identity : monadConstructor)(\n R.reduced(accumulateAfterPredicateFail ? accumulator(accValue, v) : accValue)\n );\n }\n )(value);\n },\n // map or chain this\n applicator\n )\n )(accumulatedValue);\n },\n // Chain this\n accumulatedMonad\n );\n };\n};\n/**\n * Like traverseReduceDeep but also accepts an accumulate to deal with Result.Error objects.\n * Like traverseReduceDeep accumulator is called on Result.Ok values, but Result.Error values are passed to\n * accumulatorError. The returned value is within the outer container(s): {Ok: accumulator result, Error: errorAccumulator result}\n *\n * Example:\n * traverseReduceDeepResults(2, R.flip(R.append), R.concat, Task.of({Ok: Result.Ok([]), Error: Result.Error('')}), [Task.of(Result.Ok(1))), Task.of(Result.Error('a')),\n * Task.of(Result.Ok(2)), Task.of(Result.Error('b')])\n * returns Task.of({Ok: Result.Ok([1, 2]), Error: Result.Error('ab')})\n *\n * @param {Function} accumulator Accepts a reduced applicative and each result that is a Result.Ok of reducer, then returns the new reduced applicative\n * Container C v => v -> v -> v where the Container at containerDepth must be a Result\n * @param {Function} accumulatorForErrors Accepts a reduced applicative and each result that is a Result.Error of reducer, then returns the new reduced applicative\n * Container C v => v -> v -> v where the Container at containerDepth must be a Result\n * @param {Object} initialValue A container to be the initial reduced values of accumulators. This must match the\n * expected container type up to the Result and have an object with two initial Results: {Ok: initial Result.Ok, Error: initial Result.Error}\n * @param {[Object]} list List of containers. The list does not itself count as a container toward containerDepth. So a list of Tasks of Results is still level containerDepth: 2\n * @returns {Object} The value resulting from traversing and reducing\n * @sig traverseReduceDeep:: Number N, N-Depth-Container C v => N -> (v -> v -> v) -> C v -> [C v] -> C v\n */\nexport const traverseReduceDeepResults = R.curry((containerDepth, accumulator, accumulatorForErrors, initialValue, deepContainers) =>\n R.reduce(\n (applicatorRes, applicator) => {\n const f = R.ifElse(\n d => R.gt(d, 1),\n // Compose levels\n () => R.compose,\n // Just 1 level, no need to lift\n () => () => R.identity\n )(containerDepth);\n const composed = f(\n // This composes the number of R.lift2 calls we need. We need one per container level,\n // but the penultimate level must determine which accumulator to call, so it handles the final level by calling\n // accumulator or accumulatorForErrors\n // This is containerDept - 1 because our accumulator below handles the last level\n ...R.times(R.always(R.liftN(2)), containerDepth - 1)\n );\n return composed(\n (accumulatedObj, result) => result.matchWith({\n Ok: ({value}) => ({\n Ok: accumulator(accumulatedObj.Ok, value),\n Error: accumulatedObj.Error\n }),\n Error: ({value}) => ({\n Error: accumulatorForErrors(accumulatedObj.Error, value),\n Ok: accumulatedObj.Ok\n })\n })\n )(applicatorRes, applicator);\n },\n initialValue,\n deepContainers\n )\n);\n\n\n/**\n * Converts objects with monad values into list of [M [k,v]]\n * @param {Function} monadConstructor Constructs the one-level monad, e.g. Result.Ok\n * @param {Object} objOfMonads Object with String keys and value that are monads matching that of the constructor\n * e.g. {a: Result.Ok(1), b: Result.Ok(2)}\n * @returns {[Object]} A list of the same type of Monads but containing an array with one key value pair\n * e.g. [Result.Ok([['a',1]]), Result.Ok(['b', 2])]\n * @sig objOfMLevelDeepMonadsToListWithPairs:: Monad M, String k => <k, M v> -> [M [k, v] ]\n */\nexport const objOfMLevelDeepMonadsToListWithPairs = R.curry((monadDepth, monadConstructor, objOfMonads) => {\n // Lifts k, which is not a monad, to the level of the monad v, then combines them into a single pair array,\n // which is returned wrapped with the monad constructor\n const liftKeyIntoMonad = lift1stOf2ForMDeepMonad(monadDepth, monadConstructor, (k, v) => [k, v]);\n // Here we map each key into a monad with its value, converting the k, v to an array with one pair\n // Object <k, (Result (Maybe v))> -> [Result (Maybe [[k, v]]) ]\n return R.map(\n ([k, v]) => liftKeyIntoMonad(k, v),\n R.toPairs(objOfMonads)\n );\n});\n\n/**\n * Handles objects whose values are lists of monads by sequencing each list of monads into a single monad\n * and then packaging the keys into the monad as well\n * @param {Number} monadDepth The depth of the monad for each item of the array for each value.\n * @param {Function} monadConstructor Constructs the monad so that the key can be combined with the values monad\n * @param {Function} objOfMonads Objects whose values are list of monads\n * @returns {[Monad]} A list of monads each containing and origianl key value in the form monad [[k, values]]].\n * This is thus an array with one pair, where the pair contains a key and values\n * @sig objOfMLevelDeepListOfMonadsToListWithPairs:: Monad M, String k => [<k, [M<v>]>] -> [M [k, [v]]]\n * Example {a: [Maybe.Just(1), Maybe.Just(2)], b: [Maybe.Just(3), Maybe.Just(4)]} becomes\n * [Maybe.Just(['a', [1, 2]]], Maybe.Just(['b', [3, 4]])]\n */\nexport const objOfMLevelDeepListOfMonadsToListWithPairs = R.curry((monadDepth, monadConstructor, objOfMonads) => {\n // Here String k:: k -> [v] -> monadConstructor [k, [v]]\n // So we lift k to the monad level and create a pair with the array of values\n const liftKeyIntoMonad = lift1stOf2ForMDeepMonad(monadDepth, monadConstructor, (k, values) => R.prepend(k, [values]));\n return R.compose(\n R.map(([k, v]) => liftKeyIntoMonad(k, v)),\n R.toPairs,\n // Map each value and then sequence each monad of the value into a single monad containing an array of values\n // Monad m:: <k, [m v]> -> <k, m [v]>\n R.map(monadValues => traverseReduceDeep(\n monadDepth,\n // Prev is an array of previous monad values. Next is a value from monadValues\n (prev, next) => R.append(next, prev),\n monadConstructor([]),\n monadValues\n ))\n )(objOfMonads);\n});\n\n/**\n * Like objOfMLevelDeepListOfMonadsToListWithPairs but where the input is already pairs\n * The monad depth should be the depth of each monad in each list + 1 where 1 accounts for each list, which we\n * want to treat as a monad layer.\n */\nexport const pairsOfMLevelDeepListOfMonadsToListWithPairs = R.curry((monadDepth, monadConstructor, pairsOfMonads) => {\n // Here String k:: k -> [v] -> monadConstructor [k, [v]]\n // So we lift k to the monad level and create a pair with the array of values\n const liftKeyIntoMonad = lift1stOf2ForMDeepMonad(monadDepth, monadConstructor, (k, values) => R.prepend(k, [values]));\n return R.compose(\n R.map(([k, v]) => liftKeyIntoMonad(k, v)),\n // Map each value and then sequence each monad of the value into a single monad containing an array of values\n // Monad m:: [k, [m v]> -> [k, m [v]]\n pairs => R.map(([k, monadValues]) => [\n k,\n traverseReduceDeep(\n monadDepth,\n // Prev is an array of previous monad values. Next is a value from monadValues\n (prev, next) => R.append(next, prev),\n monadConstructor(),\n monadValues\n )\n ], pairs)\n )(pairsOfMonads);\n});\n\n/**\n * Lifts an M level deep monad using the given M-level monad constructor and applies a 2 argument function f\n * The given value is called as the first argument of f, the second argument if the unwrapped value of the monad\n * The value returned by f is converted back to a monad. So this is essentially monad.chain(v => f(value, v)\n * but the chaining works on the given depth. This is useful for key value pairs when the key and value\n * need to be packaged into the monad that is the value.\n *\n * Inspiration: https://github.com/MostlyAdequate/mostly-adequate-guide (Ch 10)\n * const tOfM = compose(Task.of, Maybe.of);\n liftA2(liftA2(concat), tOfM('Rainy Days and Mondays'), tOfM(' always get me down'));\n * Task(Maybe(Rainy Days and Mondays always get me down))\n *\n * @param {Number} The monad depth to process values at. Note that the given monads can be deeper than\n * this number but the processing will occur at the depth given here\n * @param {Function} constructor M-level deep monad constructor\n * @param {Function} 2-arity function to combine value with the value of the last argument\n * @param {*} value Unwrapped value as the first argument of the function\n * @param {Object} monad Monad matching that of the constructor to apply the function(value) to\n * @returns {Object} the mapped monad\n * Example:\n * const constructor = R.compose(Result.Ok, Result.Just)\n * const myLittleResultWithMaybeAdder = lift1stOf2ForMDeepMonad(2, constructor, R.add);\n * myLittleResultWithMaybeAdder(5)(constructor(1))) -> constructor(6);\n * f -> Result (Just (a) ) -> Result (Just (f (value, a)))\n */\nexport const lift1stOf2ForMDeepMonad = R.curry((monadDepth, constructor, f, value, monad) => R.compose(\n // This composes the number of R.liftN(N) calls we need. We need one per monad level\n ...R.times(R.always(R.liftN(2)), monadDepth)\n)(f)(constructor(value))(monad));\n\n/**\n * Map based on the depth of the monad\n * @param {Number} monadDepth 1 or greater. [1] is 1, [[1]] is 2, Result.Ok(Maybe.Just(1)) is 2\n * @param {Function} Mapping function that operates at the given depth.\n * @param {Object} Monad of a least the given depth\n * @returns {Object} The mapped monad value\n */\nexport const mapMDeep = R.curry((monadDepth, f, monad) => {\n return doMDeep(\n monadDepth,\n // Wrapping for debugging visibility\n R.curry((fn, functor) => R.map(fn, functor)),\n f,\n monad);\n});\n\n/**\n * composeWith using mapMDeep Each function of compose will receive the object monadDepth levels deep.\n * The function should transform the value without wrapping in monads\n * @param {Number} monadDepth 1 or greater. [1] is 1, [[1]] is 2, Result.Ok(Maybe.Just(1)) is 2\n * @param {*} list List of functions that expects the unwrapped value and returns an unwrapped value\n * @returns {Object} A function expecting the input value(s), which is/are passed to the last function of list\n * The value returned by the first function of list wrapped in the monadDepth levels of monads\n */\nexport const composeWithMapMDeep = (monadDepth, list) => {\n // Each function, last to first, in list receives an unwrapped object and returns an unwrapped object.\n // mapMDeep is called with each of these functions. The result of each mapMDeep is given to the next function\n return R.composeWith(mapMDeep(monadDepth))(list);\n};\n\n/**\n * composeWith using map. The final function in list (first run) must return a monad that can be mapped to the\n * subsequent functions. The subsequent functions map the incoming value but do not return a monad.\n * @param {*} list List of functions that expects the unwrapped value and returns an unwrapped value\n * @returns {Object} A function expecting the input value(s), which is/are passed to the last function of list\n */\nexport const composeWithMap = list => {\n return composeWithMapMDeep(1, list);\n};\n\n/**\n * Chain based on the depth of the monad\n * @param {Number} monadDepth 1 or greater. [1] is 1, [[1]] is 2, Result.Ok(Maybe.Just(1)) is 2\n * @param {Function} Mapping function that operates at the given depth.\n * @param {Object} Monad of a least the given depth\n * @returns {Object} The mapped monad value\n */\nexport const chainMDeep = R.curry((monadDepth, f, monad) => {\n // This prevents common error types from continuing to chain to prevent a partially chained result\n // Add more as needed\n const errorPredicate = mm => R.anyPass([\n Result.Error.hasInstance\n ])(mm);\n return doMDeep(\n monadDepth,\n // Wrapping for debugging visibility\n R.curry((fn, m) => {\n // If the error predicate returns true revert to the monad for the remaining\n return R.ifElse(\n errorPredicate,\n () => monad,\n mm => R.chain(fn, mm)\n )(m);\n }),\n f,\n monad\n );\n});\n\n/**\n * chains at each level excepts maps the deepest level\n * @param monadDepth\n * @param f\n * @param monad\n * @return {*}\n */\nexport const chainExceptMapDeepestMDeep = R.curry((monadDepth, f, monad) => {\n return doMDeepExceptDeepest(monadDepth, [R.chain, R.map], f, monad);\n});\n\n/**\n * Map based on the depth of the monad-1 and chain the deepest level monad\n * @param {Number} monadDepth 1 or greater. [1] is 1, [[1]] is 2, Result.Ok(Maybe.Just(1)) is 2\n * @param {Function} Chaining function that operates at the given depth.\n * @param {Object} Monad of a least the given depth\n * @returns {Object} The mapped then chained monad value\n */\nexport const mapExceptChainDeepestMDeep = R.curry((monadDepth, f, monad) => {\n return doMDeepExceptDeepest(monadDepth, [R.map, R.chain], f, monad);\n});\n\n/**\n * composeWith using chainMDeep Each function of compose will receive the object monadDepth levels deep.\n * The function should transform the value without wrapping in monads\n * @param {Number} monadDepth 1 or greater. [1] is 1, [[1]] is 2, Result.Ok(Maybe.Just(1)) is 2\n * @param {*} list List of functions that expects the unwrapped value and returns an unwrapped value\n * @returns {Object} A function expecting the input value(s), which is/are passed to the last function of list\n * The value returned by the first function of list wrapped in the monadDepth levels of monads\n */\nexport const composeWithChainMDeep = (monadDepth, list) => {\n // Each function, last to first, in list receives an unwrapped object and returns the monadDepth level deep monad\n // chainMDeep is called with each of these functions. The result of each chainMDeep is given to the next function\n return R.composeWith(\n (f, res) => {\n return chainMDeep(monadDepth, f, res);\n }\n )(list);\n};\n\n/**\n * Composes with chain\n * The function should transform the value without wrapping in monads\n * @param {*} list List of functions that expects the unwrapped value and returns an unwrapped value\n * @returns {Object} A function expecting the input value(s), which is/are passed to the last function of list\n * The value returned by the first function of list wrapped in a monad\n */\nexport const composeWithChain = list => {\n return composeWithChainMDeep(1, list);\n};\n\n/**\n * composeWith using mapMDeep but chain the lowest level so that each function of list must return the deepest monad.\n * Each function of compose will receive the object monadDepth levels deep.\n * The last function (first called) must returned the monadDepth deep wrapped monad but subsequent ones must only\n * return a type of the deepest monad.\n * For example:\n * const test = composeWithMapExceptChainDeepestMDeep(2, [\n * // Subsequent function will only process Result.Ok\n * deliciousFruitOnly => Result.Ok(R.concat('still ', deliciousFruitOnly)),\n * // Subsequent function returns the deepest monad\n * testFruit => R.ifElse(R.contains('apple'), f => Result.Ok(R.concat('delicious ', f)), f => Result.Error(R.concat('disgusting ', f)))(testFruit),\n * // Initial function returns 2-levels deep\n * fruit => task.of(Result.Ok(R.concat('test ', fruit)))\n *])\n * test('apple') => task.of(Result.Ok('still delicious test apple'))\n * test('kumquat') => task.of(Result.Error('disgusting test kumquat'))\n * @param {Number} monadDepth 1 or greater. [1] is 1, [[1]] is 2, Result.Ok(Maybe.Just(1)) is 2\n * @param {*} list List of functions that expects the unwrapped value and returns an unwrapped value\n * @returns {Object} A function expecting the input value(s), which is/are passed to the last function of list\n * The value returned by the first function of list wrapped in the monadDepth levels of monads\n */\nexport const composeWithMapExceptChainDeepestMDeep = (monadDepth, list) => {\n return R.composeWith(mapExceptChainDeepestMDeep(monadDepth))(list);\n};\n\n/**\n * Map/Chain/Filter etc based on the depth of the monad and the iterFunction\n * @param {Number} monadDepth 1 or greater. [1] is 1, [[1]] is 2, Result.Ok(Maybe.Just(1)) is 2\n * @param {Function} func R.map, R.chain, R.filter or similar\n * @param {Function} f Mapping function that operates at the given depth.\n * @param {Object} Monad of a least the given depth\n * @returns {Object} The mapped monad value\n */\nexport const doMDeep = R.curry((monadDepth, func, f, monad) => R.compose(\n // This composes the number of R.liftN(N) calls we need. We need one per monad level\n ...R.times(R.always(func), monadDepth)\n)(f)(monad));\n\n\n/**\n * Map/Chain/Filter etc based on the depth of the monad and the funcPair. The deepest monad is processed\n * with funcPair[1] and all higher level monads are processed with funcPair[0]. This allows for a combination\n * such as [R.map, R.chain] to chain the deepest value but map the higher values so that the caller can\n * change the deepest monad type without having to wrap the unchanging outer monad types. For instance\n * the caller might have a monad task.of(Result.Ok) and want to convert it conditionally to task.of(Result.Error):\n * const test = doMDeepExceptDeepest(2, [R.map, R.chain], R.ifElse(R.equals('pear'), Result.Error, Result.Ok)(of(result)))\n * test(of(Result.Ok('apple'))) => of(Result.Ok('apple'))\n * test(of(Result.Ok('pear'))) => of(Result.Error('pear'))\n * Note that in this example task.of doesn't have to be used again to wrap the result\n * @param {Number} monadDepth 1 or greater. [1] is 1, [[1]] is 2, Result.Ok(Maybe.Just(1)) is 2\n * @param {[Function]} funcPair Two functions R.map, R.chain, R.filter or similar.\n * The first function is composed monadDepth-1 times and the last function is composed once after the others\n * @param {Function} f Mapping function that operates at the given depth.\n * @param {Object} Monad of a least the given depth\n * @returns {Object} The mapped monad value\n */\nexport const doMDeepExceptDeepest = R.curry((monadDepth, funcPair, f, monad) => {\n return R.compose(\n // This composes the number of R.liftN(N) calls we need. We need one per monad level\n ...R.times(\n R.always(\n func => value => funcPair[0](func, value)\n ),\n monadDepth - 1\n ),\n // funcPair[1] gets called with the deepest level of monad\n func => value => funcPair[1](func, value)\n )(f)(monad);\n});\n\n/**\n * Given a monad whose return value can be mapped and a single input object,\n * map the monad return value to return an obj with the value at 'value', merged with input object in its original form\n * of the function. Example: mapToResponseAndInputs(({a, b, c}) => task.of(someValue))({a, b, c}) -> task.of({a, b, c, value: someValue})\n * @param {Function} f Function expecting an object and returning a monad that can be mapped\n * @param {Object} arg The object containing the incoming named arguments that f is called with. If null defaults to {}.\n * @return {Object} The value of the monad at the value key merged with the input args\n */\nexport const mapToResponseAndInputs = f => arg => {\n return mapMonadByConfig({name: 'value'}, f)(arg);\n};\n\n/**\n * Applies f to arg returning a monad that is at least level deep. mapMDeep(level) is then used to map the value\n * of the monad at that level\n * @param {Number} level Monadic level of 1 or greater. For instance 1 would map the 'apple' of task.of('apple'),\n * 2 would map the 'apple' of task.of(Result.Ok('apple')) etc. The mapped value is merged with arg and returned\n * @param {Function} f The function applied to arg\n * @param {*} arg Argument passed to f\n * @return {Object} The monad that result from the deep mapping\n */\nexport const mapToMergedResponseAndInputsMDeep = (level, f) => arg => {\n return mapMonadByConfig({mappingFunction: mapMDeep(level)}, f)(arg);\n};\n\n/**\n * Given a monad whose return value can be mapped and a single input object,\n * map the monad return value to return an obj merged with input object in its original form\n * of the function. Example: mapToResponseAndInputs(({a, b, c}) => task.of({d: true, e: true}))({a, b, c}) -> task.of({a, b, c, d, e})\n * @param {Function} f Function expecting an object and returning a monad that can be mapped to an object\n * @param {Object} arg The object containing the incoming named arguments that f is called with. If null defaults to {}.\n * @return {Object} The value of the monad merged with the input args\n */\nexport const mapToMergedResponseAndInputs = f => arg => mapToMergedResponseAndInputsMDeep(1, f)(arg);\n\n/**\n * Given a monad whose return value can be mapped and a single input object,\n * map the monad return value to return an obj with the value at 'value', merged with input object in its original form\n * of the function. Example: mapToNamedResponseAndInputs('foo', ({a, b, c}) => task.of(someValue))({a, b, c}) -> task.of({a, b, c, foo: someValue})\n * @param {String} name The key name for the output\n * @param {Function} f Function expecting an object and returning a monad that can be mapped\n * @param {Object} arg The object containing the incoming named arguments that f is called with. If null defaults to {}.\n * @return {Object} The value of the monad at the value key merged with the input args\n */\nexport const mapToNamedResponseAndInputs = (name, f) => arg => {\n return mapMonadByConfig({name}, f)(arg);\n};\n\n/**\n * Given a monad the specified levels deep whose return value can be mapped and a single input object,\n * map the monad return value to return an obj with the value at 'value', merged with input object in its original form\n * of the function. Example: mapToNamedResponseAndInputs(2, 'foo', ({a, b, c}) => task.of(Result.Ok(someValue)))({a, b, c}) -> task.of(Result.Ok({a, b, c, foo: someValue}))\n * @param {String} name The key name for the output\n * @param {Function} f Function expecting an object and returning a monad that can be mapped\n * @param {Object} arg The object containing the incoming named arguments that f is called with. If null defaults to {}.\n * @return {Object} The value of the monad at the value key merged with the input args\n */\nexport const mapToNamedResponseAndInputsMDeep = R.curry((level, name, f, arg) => {\n return mapMonadByConfig({mappingFunction: mapMDeep(level), name}, f)(arg);\n});\n\n/**\n * Same as mapToNamedResponseAndInputs but works with a non-monad\n * @param {String} name The key name for the output\n * @param {Function} f Function expecting an object and returning an value that is directly merged with the other args\n * @param {Object} arg The object containing the incoming named arguments that f is called with. If null defaults to {}.\n * @return {Object} The output of f named named and merged with arg\n */\nexport const toNamedResponseAndInputs = (name, f) => arg => {\n const monadF = _arg => Just(f(_arg));\n const just = mapToNamedResponseAndInputs(name, monadF)(R.when(R.isNil, () => ({}))(arg));\n return just.unsafeGet();\n};\n\n/**\n * Hybrid version of mapToNamedResponseAndInputs and toNamedResponseAndInputs.\n * Handles mapping a monad containing an object or straight object\n * @param {String} name The name for the key of the output value\n * @param {Function} f mapping function\n * @return {*} The monad if f(_arg) is a monad, other wise an object\n */\nexport const mapOrObjToNamedResponseAndInputs = (name, f) => arg => {\n // Wrap in a monad unless there is a map property, meaning it's already a monad\n let isMonad = null;\n const monadF = _arg => {\n const maybeMonad = f(_arg);\n isMonad = R.hasIn('map', maybeMonad);\n // Wrap if it wasn't a monad\n return R.unless(() => isMonad, Just)(f(_arg));\n };\n const just = mapToNamedResponseAndInputs(name, monadF)(R.when(R.isNil, () => ({}))(arg));\n // Unwrap if it wasn't a monad\n return R.unless(() => isMonad, j => j.unsafeGet())(just);\n};\n\n/**\n * Same as toMergedResponseAndInputs but works with a non-monad\n * @param {Function} f Function expecting an object and returning an value that is directly merged with the other args\n * @param {Object} arg The object containing the incoming named arguments that f is called with. If null defaults to {}.\n * @return {Object} The output of f named named and merged with arg\n */\nexport const toMergedResponseAndInputs = f => arg => {\n const monadF = _arg => Just(f(_arg));\n const just = mapToMergedResponseAndInputs(monadF)(arg);\n return just.unsafeGet();\n};\n\n/**\n * Internal method to place a Result instance at the key designated by resultOutputKey merged with an\n * object remainingInputObj. This is used by mapResultMonadWithOtherInputs and for task error handling by\n * mapResultTaskWithOtherInputs\n * @param {String} [resultOutputKey] The key to use for the output Result instance. If not specified,\n * The result is instead merged with the remainingInputObj\n * @param {Object} remainingInputObj Input object that does not include the resultInputKey Result\n * @param {Object} result The Result instance to output\n * @returns {Object} remainingInputObject merged with {resultOutputKey: result} or result\n * @private\n */\nconst _mapResultToOutputKey = (resultOutputKey, remainingInputObj, result) => R.ifElse(\n R.always(resultOutputKey),\n // Leave the remainingInputObj out\n _result => R.merge(remainingInputObj, {[resultOutputKey]: _result}),\n // If there is anything in the remainingInputObj, merge it with the result.value\n _result => R.map(R.merge(remainingInputObj), _result)\n)(result);\n\n/**\n * For mapResultMonadWithOtherInputs separates the resultInputKey value from the other input values in inputObj\n * @param {String} [resultInputKey] Key indicating a Result instance in inputObj. If null then the entire inputObj\n * is assumed to be a Result\n * @param {Object} inputObj Input object containing a Result at inputObj\n * @returns {{remainingInputObj: *, inputResult: *}|{remainingInputObj: {}, inputResult: *}}\n * remainingInputObj is inputObject without resultInputKey, inputResult is the value of resultInputKey or simply\n * inputObject if resultInputKey is not specified\n * @private\n */\nconst _separateResultInputFromRemaining = (resultInputKey, inputObj) => {\n if (resultInputKey) {\n // Omit resultInputKey since we need to process it separately\n return {\n remainingInputObj: R.omit([resultInputKey], inputObj),\n // inputObj[resultInputKey] must exist\n inputResult: reqStrPathThrowing(resultInputKey, inputObj)\n };\n }\n // No resultInputKey, so the the entire input is an inputObj\n return {\n remainingInputObj: {},\n inputResult: inputObj\n };\n};\n\n/**\n * Like mapToNamedResponseAndInputs but operates on one incoming Result.Ok|Error and outputs a monad with it's internal\n * value containing a Result along with the other unaltered input keys. If the incoming instance is a Result.Ok, it's\n * value is passed to f. Otherwise f is skipped.\n * The f function must produce monad whose internal value may or may not be a Result\n * If the f does not produce its own Result.Ok/Result.Error, use the flag needsFunctionOutputWrapped=true.\n * The logic for this function is that often we are composing a monad like a Task whose returned value might or\n * might not be a Result. But for the sake of composition, we always want to get a Result wrapped in a monad back\n * from each call of the composition. We also want to keep passing unaltered input parameters to each call in the composition\n *\n * @param {Object} inputOutputConfig\n * @param {String} [inputOutputConfig.resultInputKey] A key of arg that is a Result.Ok.\n * The value of this is passed to f with the key inputKey. If not specified all of inputObj is expected to be a result\n * and it's value is passed to f\n * @param {String} [inputOutputConfig.inputKey] A key name to use to pass arg[resultInputKey]'s value in to f. Only\n * specify if resultInputKey is\n * @param {String} [inputOutputConfig.resultOutputKey] The key name for the output,\n * it should have a suffix 'Result' since the output is always a Result. If not specified then the result of f\n * is returned instead of assigning it to resultOutputKey\n * @param {String} inputOutputConfig.monad Specify the outer monad, such as Task.of, in case the incoming\n * Result is a Result.Error and we therefore can't run f on its mapped value. This is not used on the Result that is\n * returned by f, since even if that is a Result.Error f will have it wrapped in the monad.\n * @param {Boolean} [inputOutputConfig.needsFunctionOutputWrapped] Default false. Set true if the value of the monad produced\n * by f is not a Result. This will map the monad's value to a Result.Ok producing a Result within a Monad\n * @param {Function} f Function expecting arg merged with the underlying value of result at and returning a monad that can be mapped\n * @param {Object} inputObj The object containing the incoming named arguments that f is called with in addition to the Result\n * at obj[resultInputKey] that has been mapped to its underlying value at key inputKey. obj[resultInputKey] is omitted from the\n * object passed to f since it's underlying value is being passed. The output of f must be a monad such as a Task but it's underlying\n * value must NOT be a Result, because the value will be mapped automatically to a result. If you want f to produce a\n * Monad<Result> instead of a Monad<value>, use chainResultToNamedResponseAndInputs\n * @return {Object} The value produced by f mapped to a result and assigned to resultOutputKey and the rest of the key/values\n * from inputObj unchanged. Note that only the value at resultOutputKey is a Result.Ok|Error\n * Example: See unit test\n *\n */\nexport const mapResultMonadWithOtherInputs = R.curry(\n // Map Result inputObj[resultInputKey] to a merge of its value at key inputKey with inputObj (inputObj omits resultInputKey)\n // Monad M, Result R: R a -> R M b\n ({resultInputKey, inputKey, resultOutputKey, wrapFunctionOutputInResult, monad}, f, inputObj) => {\n const {remainingInputObj, inputResult} = _separateResultInputFromRemaining(resultInputKey, inputObj);\n\n // If our incoming Result is a Result.Error, just wrap it in the monad with the expected resultOutputKey\n // This is the same resulting structure if the f produces a Result.Error\n if (Result.Error.hasInstance(inputResult)) {\n return inputResult.orElse(\n error => monad(_mapResultToOutputKey(resultOutputKey, remainingInputObj, inputResult))\n );\n }\n return R.chain(\n value => R.compose(\n resultMonad => R.map(result => _mapResultToOutputKey(resultOutputKey, remainingInputObj, result), resultMonad),\n // Wrap the monad value from f in a Result if needed (if f didn't produce one)\n // Monad M: Result R: M b | M R b -> M R b\n outputMonad => R.when(\n R.always(wrapFunctionOutputInResult),\n mon => R.map(\n m => Result.Ok(m),\n mon\n )\n )(outputMonad),\n // Call f on the merged object\n // Monad M: Result R: R <k, v> -> M b | M R b\n obj => f(obj),\n // Merge the inputObj with the valued value\n // Assign the value to inputKey if it's specified\n // Result R: R a -> <k, v>\n v => R.merge(remainingInputObj, R.when(R.always(inputKey), vv => ({[inputKey]: vv}))(v))\n )(value),\n inputResult\n );\n }\n);\n\n/**\n * Version of mapResultMonadWithOtherInputs for Tasks as the monad and expects\n * resultInputKey to end in the word 'Result' so inputKey can be the same key without that ending.\n * If a task error occurs then a Result.Error is returned in a task with the error\n */\nexport const mapResultTaskWithOtherInputs = R.curry(\n ({resultInputKey, resultOutputKey, wrapFunctionOutputInResult}, f, inputObj) => {\n // assign inputKey to resultInputKey value minus Result if resultInputKey is specified\n const inputKey = R.when(\n R.identity,\n rik => {\n const key = R.replace(/Result$/, '', rik);\n if (R.concat(key, 'Result') !== rik) {\n throw new Error(`Expected resultInputKey to end with 'Result' but got ${resultInputKey}`);\n }\n return key;\n }\n )(resultInputKey);\n return mapResultMonadWithOtherInputs(\n {resultInputKey, inputKey, resultOutputKey, wrapFunctionOutputInResult, monad: of},\n f,\n inputObj\n ).orElse(\n // If the task itself fails, put the error in the resultOutputKey\n error => {\n // Separate the inputResult from the other input values\n const {remainingInputObj, inputResult} = _separateResultInputFromRemaining(resultInputKey, inputObj);\n // Create a Result.Error at resultOutputKey and wrap the object in a task. This matches the successful\n // outcome but with a Result.Error\n return of((_mapResultToOutputKey(resultOutputKey, remainingInputObj, Result.Error(error))));\n }\n );\n }\n);\n\n/**\n * Like mapToResponseAndInputs, but resolves the value of the monad to a certain path and gives it a name .\n * Given a monad whose return value can be mapped and a single input object,\n * map the monad return value, getting its value at strPath and giving it the key name, them merge it with the input object in its original form\n * of the function.\n * Example: mapToResponseAndInputs('billy', 'is.1.goat', ({a, b, c}) => task.of({is: [{cow: 'grass'}, {goat: 'can'}]}))({a, b, c}) ->\n * task.of({a, b, c, billy: 'can'})\n * @param {String} name The key name for the output\n * @param {String} strPath dot-separated path with strings and indexes\n * @param {Function} f Function that returns a monad\n * @returns {Object} The resulting monad containing the strPath value of the monad at the named key merged with the input args\n */\nexport const mapToNamedPathAndInputs = R.curry(\n (name, strPath, f) => arg => {\n return mapMonadByConfig({name, strPath}, f)(arg);\n }\n);\n\n/**\n * A generalized form of mapToNamedPathAndInputs and mapToNamedResponse\n * @param {Object} config The configuration\n * @param {Function} [config.mappingFunction]. Defaults to R.map, the mapping function to use to map the monad\n * returned by f(arg). For example R.mapMDeep(2) to map 2-level monad\n * @param {String} [config.name] The name to assign the result of applying the monadic function f to arg. This\n * name/value is merged with the incoming object arg. If omitted\n * @param {String} [config.strPath] Optional string path to extract a value with the value that the monad that f(arg) returns\n * @param {Function} [config.isMonadType] Optionaly accepts f(arg) and tests if it matches the desired monad, such\n * as task.of, Result.of, Array.of. Returns true or false accordingly\n * f(arg).\n * @param {Function} [config.errorMonad] Optional. If the monad returned by f(arg) doesn't match the monad,\n * then the errorMonad is returned containing an {f, arg, value, message} where value is the return value and message\n * is an error message. If config.successMonad isn't specified, this value is used if the the return value of f(arg)\n * lacks a .map function\n * @param {Function} f The monadic function to apply to arg\n * @param {Object} arg The argument to pass to f. No that this argument must be called on the result of such as:\n * mapMonadByConfig(config, f)(arg)\n * @return {Object} The monad or error monad value or throws\n */\nexport const mapMonadByConfig = (\n {mappingFunction, name, strPath, isMonadType, errorMonad},\n f\n) => arg => {\n return R.defaultTo(R.map, mappingFunction)(\n // Container value\n value => {\n // If name is not specified, value must be an object\n // If strPath is specified, value must be an object\n if (R.both(\n v => R.not(R.is(Object, v)),\n () => {\n return R.either(\n ({name: n}) => R.isNil(n),\n ({strPath: s}) => s\n )({name, strPath});\n }\n )(value)) {\n let message;\n message = `value ${inspect(value)} is not an object. arg: ${inspect(arg)}, f: ${f}`;\n if (errorMonad) {\n // return the errorMonad if defined\n return errorMonad({f, arg, value, message});\n }\n throw new Error(message);\n }\n // Merge the current args with the value object, or the value at name,\n // first optionally extracting what is at strPath\n const resolvedValue = R.when(\n () => strPath,\n v => {\n try {\n return reqStrPathThrowing(strPath, v);\n } catch (e) {\n console.error(`Function ${f} did not produce a value at ${strPath}`); // eslint-disable-line no-console\n throw e;\n }\n }\n )(value);\n return R.merge(\n arg,\n R.when(\n () => name,\n v => {\n return {[name]: v};\n }\n )(resolvedValue)\n );\n },\n // Call f(arg), raising an exception if it doesn't return a monad\n applyMonadicFunction({isMonadType, errorMonad}, f, arg)\n );\n};\n\n/**\n *\n * @param {Object} config The configuration\n * @param {Function} [config.isMonadType] if specified the result of f(arg) is applied to it to see if f(arg) returns\n * the right type. Returns a boolean\n * @param {Object} [config.errorMonad] if f(arg) doesn't match the type of config.successMonad or if config.successMonad\n * is not specified but the returned value of f(arg) lacks a map method, this type is called with the given values:\n * {f, arg, value, message} where value is the return value of f(arg) and message is an error message\n * @param {Function} f Expects a single argument and returns a monad\n * @param {*} arg The argument. If this is mistakenly null it will be made {}\n * @return {*} The monad\n */\nexport const applyMonadicFunction = ({isMonadType, errorMonad}, f, arg) => {\n return R.unless(\n value => R.both(\n v => R.is(Object, v),\n v => R.ifElse(\n () => isMonadType,\n // If successMonad is specified check that the value matches its type\n vv => isMonadType(vv),\n // Otherwise just check that it has a map function\n vv => R.hasIn('map', vv)\n )(v)\n )(value),\n value => {\n const message = `mapToNamedPathAndInputs: function f with args: ${\n inspect(arg)\n } returned value ${\n inspect(value)\n }, which lacks a .map() function, meaning it is not a monad. Make sure the return value is the desired monad type: task, array, etc`;\n\n if (errorMonad) {\n return errorMonad({f, arg, value, message});\n }\n throw new TypeError(message);\n }\n // Default arg to {} if null\n )(f(R.when(R.isNil, () => ({}))(arg)));\n};\n\n\n/**\n * Calls a function that returns a monad and maps the result to the given string path\n * @param {String} strPath dot-separated path with strings and indexes\n * @param {Function} f Function that returns a monad\n * @returns {*} The monad containing the value at the string path\n */\nexport const mapToPath = R.curry(\n (strPath, monad) => R.map(\n // Container value\n value => {\n // Find the path in the returned value\n return reqStrPathThrowing(strPath, value);\n },\n monad\n )\n);\n\n/**\n * Calls a function with arg that returns a monad and maps the result to the given string path.\n * The input values are not returned, just the mapped value\n * @param {String} strPath dot-separated path with strings and indexes\n * @param {Function} f Function that returns a monad\n * @param {*} arg Passed to f\n * @returns {*} The monad containing the value at the string path\n */\nexport const mapWithArgToPath = R.curry(\n (strPath, f) => arg => R.map(\n // Container value\n value => {\n // Find the path in the returned value\n return reqStrPathThrowing(strPath, value);\n },\n // Call f(arg), raising an exception if it doesn't return a monad\n applyMonadicFunction({}, f, arg)\n )\n);\n\n/**\n * Versions of task.waitAll that divides tasks into 100 buckets to prevent stack overflow since waitAll\n * chains all tasks together\n * @param {Task} tasks A list of tasks\n * @param {Number} [buckets] Default to 100. If there are 1 million tasks we probably need 100,000 buckets to\n * keep stacks to 100 lines\n * @returns {*} The list of tasks to be processed without blowing the stack limit\n */\nexport const waitAllBucketed = (tasks, buckets = 100) => {\n const taskSets = R.reduceBy(\n (acc, [tsk, i]) => R.concat(acc, [tsk]),\n [],\n ([_, i]) => i.toString(),\n R.addIndex(R.map)((tsk, i) => [tsk, i % buckets], tasks)\n );\n\n return R.map(\n // Chain the resultSets together\n // Task t:: t[[a]] -> t[a]\n resultSets => R.chain(R.identity, resultSets),\n // Task t:: [t[a]] -> t[[a]]\n R.traverse(\n of,\n // Do a normal waitAll for each bucket of tasks\n // to run them all in parallel\n // Task t:: [t] -> t [a]\n R.ifElse(\n // If we have more than 100 buckets recurse on a tenth\n ts => R.compose(R.lt(100), R.length)(ts),\n ts => waitAllBucketed(ts, buckets / 10),\n ts => waitAll(ts)\n ),\n // Remove the bucket keys\n // Task t:: <k, [t]> -> [[t]]\n R.values(taskSets)\n )\n );\n};\n\n/**\n *\n * Buckets the given monads into bucketCount number buckets\n * @param {Number} bucketSize The number of moands in each bucket\n * @param {[Object]} monads The monads to bucket\n * @return {[[Object]]} Lists of monads\n */\nconst bucketedMonadSets = (bucketSize, monads) => {\n return R.compose(\n // Remove the keys\n R.values,\n ms => {\n return R.reduceBy(\n (acc, [mms, i]) => R.concat(acc, [mms]),\n [],\n ([_, i]) => i.toString(),\n // Create pairs where the second value is the index / bucketCount\n // This lets us dived the first bucketCount monads into once bucket, the next bucketCounts into the next\n // bucket, etc\n R.addIndex(R.map)((monad, monadIndex) => {\n return [monad, Math.floor(monadIndex / bucketSize)];\n }, ms)\n );\n }\n )(monads);\n};\n/**\n * Versions of R.sequence that divides tasks into 100 buckets to prevent stack overflow since waitAll\n * chains all tasks together. waitAllSequentiallyBucketed runs tasks sequentially not concurrently\n * @param {Object} config The configuration\n * @param {Number} [config.buckets] Default to R.length(monads) / 100 The number of buckets to divide monads into\n * @param {Object} [config.monadType] The monad type to pass to R.traverse. E.g. Task.of, Result.Ok, Maybe.Just\n * @param {[Object]} monads A list of monads\n * @returns {*} The list of monads to be processed without blowing the stack limit\n */\nexport const sequenceBucketed = ({buckets, monadType}, monads) => {\n const bucketSize = buckets || Math.floor(R.length(monads) / 100);\n const monadSets = bucketedMonadSets(bucketSize, monads);\n if (!monadType) {\n throw new Error('config.monadType is not specified. It is required for sequencing');\n }\n\n return R.map(\n // Chain the resultSets together\n // Monad m:: m[[a]] -> m[a]\n resultSets => R.chain(R.identity, resultSets),\n // Process each set of monads with R.sequence (end case) or recurse with sequenceBucket with smaller bucket size\n // Monad m:: [m[a]] -> m[[a]]\n R.traverse(\n monadType,\n // Monad m:: [m] -> m [a]\n R.ifElse(\n // If we have more than 100 monads recurse, limiting the bucket size to 1 / 10 the current bucket size\n m => R.compose(R.lt(100), R.length)(m),\n m => sequenceBucketed({monadType, buckets: bucketSize / 10}, m),\n // Do a normal R.sequence for each bucket of monads\n // to run them all in sequence\n m => R.sequence(monadType, m)\n ),\n monadSets\n )\n );\n};\n\n// given an array of something and a transform function that takes an item from\n// the array and turns it into a task, run all the tasks in sequence.\n// inSequence :: (a -> Task) -> Array<a> -> Task\n/* export const chainInSequence = R.curry((chainedTasks, task) => {\n let log = [];\n\n R.chain(\n reducedValue => task\n chainedTasks;\n)\n\n return items.reduce((pipe, item, i) => {\n // build up a chain of tasks\n return (\n pipe\n // transform this item to a task\n .chain(() => transform(item))\n // after it's done, push the result to and return the log\n .map(result => {\n log.push(result);\n return log;\n })\n );\n }, Task.of(\"start\"));\n})*/\n\n/*\nexport function liftObjDeep(obj, keys = []) {\n if (R.anyPass([Array.isArray, R.complement(R.is)(Object)])(obj)) {\n return R.cond([\n [Array.isArray,\n a => R.liftN(R.length(keys) + 1, (...args) => args)(R.addIndex(R.map)(\n (v, k) => v,\n a\n ))\n ],\n [R.T,\n o => R.liftN(R.length(keys) + 1, (...args) => args)([o])\n ]\n ])(obj);\n }\n\n // Get all combinations at this level. To do this we look at array values and scalars\n // We put the scalar in a single array\n return R.compose(\n R.when(\n pairs => {\n return R.compose(R.lt(1), R.length)(pairs);\n },\n pairs => R.liftN(R.length(pairs), (...args) => [...args])(...R.map(R.compose(Array.of, R.last), pairs))\n ),\n //R.toPairs,\n //R.map(R.unless(Array.isArray, Array.of)),\n o => chainObjToValues(\n (v, k) => liftObjDeep(v, R.concat(keys, [k])),\n o\n )\n )(obj);\n};\n*/\n\n/**\n * Converts a list of result tasks to a single task containing {Ok: objects, Error: objects}\n * @param {[Task<Result<Object>>]} resultTasks List of Tasks resolving to a Result.Ok or Result.Error\n * @return {Task<Object>} The Task that resolves to {Ok: objects, Error: objects}\n */\nexport const resultTasksToResultObjTask = resultTasks => {\n return traverseReduceWhileBucketedTasks(\n {predicate: R.always(true)},\n // The accumulator\n ({Ok: oks, Error: errors}, result) => {\n return result.matchWith({\n Ok: ({value}) => {\n return {Ok: R.concat(oks, [value]), Error: errors};\n },\n Error: ({value}) => {\n return {Ok: oks, Error: R.concat(errors, [value])};\n }\n });\n },\n of({Ok: [], Error: []}),\n resultTasks\n );\n};\n\n/**\n * Converts a list of results to a single result containing {Ok: objects, Error: objects}\n * @param {[Result<Object>]} results List of Tasks resolving to a Result.Ok or Result.Error\n * @return {Object} The Task that resolves to {Ok: objects, Error: objects}\n */\nexport const resultsToResultObj = results => {\n return traverseReduceDeepResults(1,\n // The accumulator\n (res, location) => R.concat(\n res,\n [location]\n ),\n // The accumulator of errors\n (res, errorObj) => R.concat(\n res,\n [errorObj]\n ),\n {Ok: [], Error: []},\n results\n );\n};\n\n/**\n * Run the given task the given number of times until it succeeds. If after the give times it still rejects then\n * reject with the accumulated errors of each failed run\n * @param {Object} tsk Task to run multiply times\n * @param {Number} times The number of times to run the tasks\n * @param {[Object]} [errors] Optional place to push errors\n * @return {Task <Object>} Returns a task that resolves task or rejects\n */\nexport const retryTask = (tsk, times, errors) => {\n const errs = errors || [];\n const _retryTask = _times => {\n return tsk.orElse(reason => {\n errs.push(reason);\n if (_times > 1) {\n return _retryTask(_times - 1);\n }\n return rejected(`Task failed after ${_times} tries ${\n R.join('\\n', R.map(error => stringifyError(error), errs))\n }`);\n });\n };\n return _retryTask(times);\n};\n\n"],"names":["stringifyError","err","wrappedError","wrapError","obj","R","key","Object","getOwnPropertyNames","JSON","stringify","error","Error","e","defaultOnRejected","errors","reject","errorsAsArray","toArrayIfNot","allErrors","console","_onRejected","defaultOnCancelled","log","_onCanceled","whenDone","done","errs","defaultRunConfig","onResolved","onCancelled","onRejected","_whenDone","_handleReject","value","constructor","name","noThrow","caughtError","compact","defaultRunToResultConfig","result","map","mapError","taskToPromise","tsk","run","TypeError","promise","promiseToTask","fromPromised","resultToTask","matchWith","Ok","of","rejected","resultToTaskNeedingResult","f","Result","mapRejected","resultToTaskWithResult","r","hasInstance","v","taskToResultTask","orElse","traverseReduce","accumulator","initialValue","list","containerResult","container","res","traverseReduceError","join","traverseReduceResultError","traverseReduceDeep","containerDepth","deepContainers","applicatorRes","applicator","_chainTogetherWith","reducedMonad","monad","index","_chainTogetherWithTaskDelay","n","composeWithChainMDeep","i","timeoutTask","args","task","resolver","timerId","setTimeout","resolve","cleanup","clearTimeout","_reduceMonadsChainedBucketed","monads","buckets","bucketSize","Math","max","floor","monadSets","bucketedMonadSets","reducedMonadSetFuncs","mSet","previousSetAccumulationMonad","mmSet","accumulatedMonadSets","monadSetFunc","traverseReduceWhile","predicateOrObj","initialValueMonad","_reduceMonadsWithWhilst","_reduceMonadsWithWhile","reduceFunction","isObject","chainWith","composeWithChain","reducedMonadValue","accumulatedMonad","currentMonad","accMonad","app","traverseReduceWhileBucketed","config","reducer","traverseReduceWhileBucketedTasks","accumulatorComposeChainOrMap","composeWithMapMDeep","monadConstructor","mappingFunction","chainTogetherWith","accum","current","a","c","Function","predicate","accumulateAfterPredicateFail","accumulatedValue","accValue","traverseReduceDeepResults","accumulatorForErrors","d","composed","accumulatedObj","objOfMLevelDeepMonadsToListWithPairs","monadDepth","objOfMonads","liftKeyIntoMonad","lift1stOf2ForMDeepMonad","k","objOfMLevelDeepListOfMonadsToListWithPairs","values","monadValues","prev","next","pairsOfMLevelDeepListOfMonadsToListWithPairs","pairsOfMonads","pairs","mapMDeep","doMDeep","fn","functor","composeWithMap","chainMDeep","errorPredicate","mm","m","chainExceptMapDeepestMDeep","doMDeepExceptDeepest","mapExceptChainDeepestMDeep","composeWithMapExceptChainDeepestMDeep","func","funcPair","mapToResponseAndInputs","arg","mapMonadByConfig","mapToMergedResponseAndInputsMDeep","level","mapToMergedResponseAndInputs","mapToNamedResponseAndInputs","mapToNamedResponseAndInputsMDeep","toNamedResponseAndInputs","monadF","_arg","Just","just","unsafeGet","mapOrObjToNamedResponseAndInputs","isMonad","maybeMonad","j","toMergedResponseAndInputs","_mapResultToOutputKey","resultOutputKey","remainingInputObj","_result","_separateResultInputFromRemaining","resultInputKey","inputObj","inputResult","reqStrPathThrowing","mapResultMonadWithOtherInputs","inputKey","wrapFunctionOutputInResult","resultMonad","outputMonad","mon","vv","mapResultTaskWithOtherInputs","rik","mapToNamedPathAndInputs","strPath","isMonadType","errorMonad","s","message","inspect","resolvedValue","applyMonadicFunction","mapToPath","mapWithArgToPath","waitAllBucketed","tasks","taskSets","acc","_","toString","resultSets","ts","waitAll","ms","mms","monadIndex","sequenceBucketed","monadType","resultTasksToResultObjTask","resultTasks","oks","resultsToResultObj","results","location","errorObj","retryTask","times","_retryTask","_times","reason","push"],"mappings":";;;;;;;;;;AAAA;;;;;;;;;;AAYA;;;;;;;IAMaA,cAAc,GAAG,SAAjBA,cAAiB,CAAAC,GAAG,EAAI;AACnC;AACA,MAAMC,YAAY,GAAGC,SAAS,CAACF,GAAD,CAA9B;AAEA,MAAMG,GAAG,GAAGC,WAAA,CAAYA,KAAA,CACtB,UAAAC,GAAG;AAAA,WAAI,CAACA,GAAD,EAAMJ,YAAY,CAACI,GAAD,CAAlB,CAAJ;AAAA,GADmB,EAEtBC,MAAM,CAACC,mBAAP,CAA2BN,YAA3B,CAFsB,CAAZ,CAAZ,CAJmC;;AASnC,SAAOG,SAAA,CAAU,MAAV,EAAkB,IAAlB,EAAwBI,IAAI,CAACC,SAAL;AAE7BL,EAA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