`):\n *\n * ```javascript\n * var hljs = require('highlight.js') // https://highlightjs.org/\n *\n * // Actual default values\n * var md = require('markdown-it')({\n * highlight: function (str, lang) {\n * if (lang && hljs.getLanguage(lang)) {\n * try {\n * return '' +\n * hljs.highlight(str, { language: lang, ignoreIllegals: true }).value +\n * '
';\n * } catch (__) {}\n * }\n *\n * return '' + md.utils.escapeHtml(str) + '
';\n * }\n * });\n * ```\n *\n **/\nfunction MarkdownIt(presetName, options) {\n if (!(this instanceof MarkdownIt)) {\n return new MarkdownIt(presetName, options);\n }\n\n if (!options) {\n if (!utils.isString(presetName)) {\n options = presetName || {};\n presetName = 'default';\n }\n }\n\n /**\n * MarkdownIt#inline -> ParserInline\n *\n * Instance of [[ParserInline]]. You may need it to add new rules when\n * writing plugins. For simple rules control use [[MarkdownIt.disable]] and\n * [[MarkdownIt.enable]].\n **/\n this.inline = new ParserInline();\n\n /**\n * MarkdownIt#block -> ParserBlock\n *\n * Instance of [[ParserBlock]]. You may need it to add new rules when\n * writing plugins. For simple rules control use [[MarkdownIt.disable]] and\n * [[MarkdownIt.enable]].\n **/\n this.block = new ParserBlock();\n\n /**\n * MarkdownIt#core -> Core\n *\n * Instance of [[Core]] chain executor. You may need it to add new rules when\n * writing plugins. For simple rules control use [[MarkdownIt.disable]] and\n * [[MarkdownIt.enable]].\n **/\n this.core = new ParserCore();\n\n /**\n * MarkdownIt#renderer -> Renderer\n *\n * Instance of [[Renderer]]. Use it to modify output look. Or to add rendering\n * rules for new token types, generated by plugins.\n *\n * ##### Example\n *\n * ```javascript\n * var md = require('markdown-it')();\n *\n * function myToken(tokens, idx, options, env, self) {\n * //...\n * return result;\n * };\n *\n * md.renderer.rules['my_token'] = myToken\n * ```\n *\n * See [[Renderer]] docs and [source code](https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.js).\n **/\n this.renderer = new Renderer();\n\n /**\n * MarkdownIt#linkify -> LinkifyIt\n *\n * [linkify-it](https://github.com/markdown-it/linkify-it) instance.\n * Used by [linkify](https://github.com/markdown-it/markdown-it/blob/master/lib/rules_core/linkify.js)\n * rule.\n **/\n this.linkify = new LinkifyIt();\n\n /**\n * MarkdownIt#validateLink(url) -> Boolean\n *\n * Link validation function. CommonMark allows too much in links. By default\n * we disable `javascript:`, `vbscript:`, `file:` schemas, and almost all `data:...` schemas\n * except some embedded image types.\n *\n * You can change this behaviour:\n *\n * ```javascript\n * var md = require('markdown-it')();\n * // enable everything\n * md.validateLink = function () { return true; }\n * ```\n **/\n this.validateLink = validateLink;\n\n /**\n * MarkdownIt#normalizeLink(url) -> String\n *\n * Function used to encode link url to a machine-readable format,\n * which includes url-encoding, punycode, etc.\n **/\n this.normalizeLink = normalizeLink;\n\n /**\n * MarkdownIt#normalizeLinkText(url) -> String\n *\n * Function used to decode link url to a human-readable format`\n **/\n this.normalizeLinkText = normalizeLinkText;\n\n\n // Expose utils & helpers for easy acces from plugins\n\n /**\n * MarkdownIt#utils -> utils\n *\n * Assorted utility functions, useful to write plugins. See details\n * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/common/utils.js).\n **/\n this.utils = utils;\n\n /**\n * MarkdownIt#helpers -> helpers\n *\n * Link components parser functions, useful to write plugins. See details\n * [here](https://github.com/markdown-it/markdown-it/blob/master/lib/helpers).\n **/\n this.helpers = utils.assign({}, helpers);\n\n\n this.options = {};\n this.configure(presetName);\n\n if (options) { this.set(options); }\n}\n\n\n/** chainable\n * MarkdownIt.set(options)\n *\n * Set parser options (in the same format as in constructor). Probably, you\n * will never need it, but you can change options after constructor call.\n *\n * ##### Example\n *\n * ```javascript\n * var md = require('markdown-it')()\n * .set({ html: true, breaks: true })\n * .set({ typographer, true });\n * ```\n *\n * __Note:__ To achieve the best possible performance, don't modify a\n * `markdown-it` instance options on the fly. If you need multiple configurations\n * it's best to create multiple instances and initialize each with separate\n * config.\n **/\nMarkdownIt.prototype.set = function (options) {\n utils.assign(this.options, options);\n return this;\n};\n\n\n/** chainable, internal\n * MarkdownIt.configure(presets)\n *\n * Batch load of all options and compenent settings. This is internal method,\n * and you probably will not need it. But if you will - see available presets\n * and data structure [here](https://github.com/markdown-it/markdown-it/tree/master/lib/presets)\n *\n * We strongly recommend to use presets instead of direct config loads. That\n * will give better compatibility with next versions.\n **/\nMarkdownIt.prototype.configure = function (presets) {\n var self = this, presetName;\n\n if (utils.isString(presets)) {\n presetName = presets;\n presets = config[presetName];\n if (!presets) { throw new Error('Wrong `markdown-it` preset \"' + presetName + '\", check name'); }\n }\n\n if (!presets) { throw new Error('Wrong `markdown-it` preset, can\\'t be empty'); }\n\n if (presets.options) { self.set(presets.options); }\n\n if (presets.components) {\n Object.keys(presets.components).forEach(function (name) {\n if (presets.components[name].rules) {\n self[name].ruler.enableOnly(presets.components[name].rules);\n }\n if (presets.components[name].rules2) {\n self[name].ruler2.enableOnly(presets.components[name].rules2);\n }\n });\n }\n return this;\n};\n\n\n/** chainable\n * MarkdownIt.enable(list, ignoreInvalid)\n * - list (String|Array): rule name or list of rule names to enable\n * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found.\n *\n * Enable list or rules. It will automatically find appropriate components,\n * containing rules with given names. If rule not found, and `ignoreInvalid`\n * not set - throws exception.\n *\n * ##### Example\n *\n * ```javascript\n * var md = require('markdown-it')()\n * .enable(['sub', 'sup'])\n * .disable('smartquotes');\n * ```\n **/\nMarkdownIt.prototype.enable = function (list, ignoreInvalid) {\n var result = [];\n\n if (!Array.isArray(list)) { list = [ list ]; }\n\n [ 'core', 'block', 'inline' ].forEach(function (chain) {\n result = result.concat(this[chain].ruler.enable(list, true));\n }, this);\n\n result = result.concat(this.inline.ruler2.enable(list, true));\n\n var missed = list.filter(function (name) { return result.indexOf(name) < 0; });\n\n if (missed.length && !ignoreInvalid) {\n throw new Error('MarkdownIt. Failed to enable unknown rule(s): ' + missed);\n }\n\n return this;\n};\n\n\n/** chainable\n * MarkdownIt.disable(list, ignoreInvalid)\n * - list (String|Array): rule name or list of rule names to disable.\n * - ignoreInvalid (Boolean): set `true` to ignore errors when rule not found.\n *\n * The same as [[MarkdownIt.enable]], but turn specified rules off.\n **/\nMarkdownIt.prototype.disable = function (list, ignoreInvalid) {\n var result = [];\n\n if (!Array.isArray(list)) { list = [ list ]; }\n\n [ 'core', 'block', 'inline' ].forEach(function (chain) {\n result = result.concat(this[chain].ruler.disable(list, true));\n }, this);\n\n result = result.concat(this.inline.ruler2.disable(list, true));\n\n var missed = list.filter(function (name) { return result.indexOf(name) < 0; });\n\n if (missed.length && !ignoreInvalid) {\n throw new Error('MarkdownIt. Failed to disable unknown rule(s): ' + missed);\n }\n return this;\n};\n\n\n/** chainable\n * MarkdownIt.use(plugin, params)\n *\n * Load specified plugin with given params into current parser instance.\n * It's just a sugar to call `plugin(md, params)` with curring.\n *\n * ##### Example\n *\n * ```javascript\n * var iterator = require('markdown-it-for-inline');\n * var md = require('markdown-it')()\n * .use(iterator, 'foo_replace', 'text', function (tokens, idx) {\n * tokens[idx].content = tokens[idx].content.replace(/foo/g, 'bar');\n * });\n * ```\n **/\nMarkdownIt.prototype.use = function (plugin /*, params, ... */) {\n var args = [ this ].concat(Array.prototype.slice.call(arguments, 1));\n plugin.apply(plugin, args);\n return this;\n};\n\n\n/** internal\n * MarkdownIt.parse(src, env) -> Array\n * - src (String): source string\n * - env (Object): environment sandbox\n *\n * Parse input string and return list of block tokens (special token type\n * \"inline\" will contain list of inline tokens). You should not call this\n * method directly, until you write custom renderer (for example, to produce\n * AST).\n *\n * `env` is used to pass data between \"distributed\" rules and return additional\n * metadata like reference info, needed for the renderer. It also can be used to\n * inject data in specific cases. Usually, you will be ok to pass `{}`,\n * and then pass updated object to renderer.\n **/\nMarkdownIt.prototype.parse = function (src, env) {\n if (typeof src !== 'string') {\n throw new Error('Input data should be a String');\n }\n\n var state = new this.core.State(src, this, env);\n\n this.core.process(state);\n\n return state.tokens;\n};\n\n\n/**\n * MarkdownIt.render(src [, env]) -> String\n * - src (String): source string\n * - env (Object): environment sandbox\n *\n * Render markdown string into html. It does all magic for you :).\n *\n * `env` can be used to inject additional metadata (`{}` by default).\n * But you will not need it with high probability. See also comment\n * in [[MarkdownIt.parse]].\n **/\nMarkdownIt.prototype.render = function (src, env) {\n env = env || {};\n\n return this.renderer.render(this.parse(src, env), this.options, env);\n};\n\n\n/** internal\n * MarkdownIt.parseInline(src, env) -> Array\n * - src (String): source string\n * - env (Object): environment sandbox\n *\n * The same as [[MarkdownIt.parse]] but skip all block rules. It returns the\n * block tokens list with the single `inline` element, containing parsed inline\n * tokens in `children` property. Also updates `env` object.\n **/\nMarkdownIt.prototype.parseInline = function (src, env) {\n var state = new this.core.State(src, this, env);\n\n state.inlineMode = true;\n this.core.process(state);\n\n return state.tokens;\n};\n\n\n/**\n * MarkdownIt.renderInline(src [, env]) -> String\n * - src (String): source string\n * - env (Object): environment sandbox\n *\n * Similar to [[MarkdownIt.render]] but for single paragraph content. Result\n * will NOT be wrapped into `` tags.\n **/\nMarkdownIt.prototype.renderInline = function (src, env) {\n env = env || {};\n\n return this.renderer.render(this.parseInline(src, env), this.options, env);\n};\n\n\nmodule.exports = MarkdownIt;\n", "'use strict';\n\n\nmodule.exports = require('./lib/');\n", "/**\n * Is it empty (stolen from Underscore)\n * @param {Object|String|?} obj some type of things\n * @return {Boolean} is it empty?\n */\nconst isEmpty = function (obj) {\n if (obj === null || obj === undefined) {\n return true;\n }\n if (Array.isArray(obj) || isString(obj)) {\n return obj.length === 0;\n }\n return Object.keys(obj).length === 0;\n};\n/**\n * Is it a String (stolen from Underscore)\n * @param {Object|String|?} obj some type of things\n * @return {Boolean} is it an string?\n */\nconst isString = function (obj) {\n return toString.call(obj) === '[object String]';\n};\n/**\n * Is it an Object (stolen from Underscore).\n * Note: This will return True for an Array also.\n * @param {Object|String|?} obj some type of things\n * @return {Boolean} is it an object?\n */\nconst isObject = function (obj) {\n const type = typeof obj;\n return (type === 'function' || type === 'object') && !!obj;\n};\n/**\n * Is a given variable undefined?\n * @param {Object|String|?} obj object to test\n * @return {Boolean} is it undefined\n */\nconst isUndefined = function (obj) {\n return obj === undefined;\n};\n/**\n * Capitalize a string\n * @param {String} string a string\n * @return {String} string with first letter capitalized\n */\nconst capitalize = function (string) {\n return isEmpty(string) ? string : string.charAt(0).toUpperCase() + string.slice(1);\n};\n\n/**\n * Convert a value for serialization.\n * @param {Any} value\n * @returns {Any} Though not Map or any class/object with a toJSON method.\n */\nconst serializeValue = function (value) {\n if (value === null || typeof value === 'undefined') {\n return;\n }\n if (isString(value)) {\n return value;\n }\n if (typeof value === 'number') {\n return value;\n }\n if (Array.isArray(value)) {\n return value.map((el) => serializeValue(el));\n }\n if (typeof value.toJSON === 'function') {\n return value.toJSON();\n }\n if (value instanceof Map) {\n const obj = {};\n value.forEach(function (val, key) {\n obj[key] = serializeValue(val);\n });\n return obj;\n }\n if (typeof value === 'function') {\n return;\n }\n if (typeof value === 'undefined') {\n return;\n }\n // a plain Object would just return itself, no matter its property values\n // not sure if I use any in the classes that it is a concern\n return value;\n};\n/**\n * Default toJSON for classes.\n * Bind this to the class instance when calling.\n * @returns {Object}\n */\nconst defaultToJSON = function () {\n // We save the objects class name as a property\n // so we can recreate the right structure later\n // but it is done in each class as I can't find a good way\n // to consistent get the class name.\n const returnObj = {};\n for (const property in this) {\n const value = this[property];\n\n const value2 = serializeValue(value);\n if (typeof value2 === 'undefined') {\n continue;\n }\n returnObj[property] = value2;\n }\n return returnObj;\n};\n\nexport {\n isEmpty,\n isString,\n isObject,\n isUndefined,\n capitalize,\n defaultToJSON\n};\n", "/**\n * Display options for subtable results. Used in RandomTable and RandomTableResultSet\n */\nexport default class DisplayOptions {\n /**\n *\n * @property {String} table Subtable name.\n * @property {Boolean} hide_table Hide the subtable name.\n * @property {Boolean} hide_result Hide the result.\n * @property {Boolean} hide_desc Hide the description field.\n */\n constructor ({\n table = '',\n hide_table = false,\n hide_result = false,\n hide_desc = false\n }) {\n this.table = table;\n /** Accept true, 1, or '1' to set these properties */\n this.hide_table = (hide_table === true || hide_table === '1' || hide_table === 1);\n this.hide_result = (hide_result === true || hide_result === '1' || hide_result === 1);\n this.hide_desc = (hide_desc === true || hide_desc === '1' || hide_desc === 1);\n }\n /**\n * Custom JSON handler to strip defaults.\n * @returns {Object}\n */\n toJSON () {\n const returnObj = {\n className: 'DisplayOptions',\n table: this.table\n };\n if (this.hide_table) {\n returnObj.hide_table = true;\n }\n if (this.hide_result) {\n returnObj.hide_result = true;\n }\n if (this.hide_desc) {\n returnObj.hide_desc = true;\n }\n return returnObj;\n }\n}\n", "import { isString, defaultToJSON } from './r_helpers.js';\n\n/**\n * Class for entries in a random (sub)table.\n * This normalizes the various options into a class that makes the other code simpler.\n */\nexport default class RandomTableEntry {\n /**\n *\n * @property {String} label Basic string label. Only required field. Can include tokens.\n * @property {Boolean} [print=true] Should the result be included in the output.\n * @property {String} [description] Extra description for the label.\n * @property {String[]} [subtable] Other tables to roll on.\n * @property {Number} [weight=1] Number to weight entry relative to other entries.\n */\n constructor ({\n label = '',\n print = true,\n description = '',\n subtable = [],\n weight = 1\n }) {\n this.label = label;\n this.print = !(print === false || print === '0' || print === 0);\n this.description = description;\n this.weight = parseInt(weight, 10);\n if (this.weight <= 0) {\n this.weight = 1;\n }\n // Make sure it's an array of string.\n if (isString(subtable)) {\n this.subtable = [subtable];\n } else if (Array.isArray(subtable)) {\n this.subtable = subtable.map((el) => { return el.toString(); });\n }\n }\n /**\n * Custom JSON handler because Map doesn't JSON stringify automatically.\n * @returns {Object}\n */\n toJSON () {\n const obj = defaultToJSON.call(this);\n obj.className = 'RandomTableEntry';\n return obj;\n }\n}\n", "/**\n * Sum an array\n * @param {Array} arr an array of numbers\n * @returns {Number} Total value of numbers in array\n */\nconst arraySum = function (arr) {\n let total = 0;\n for (let i = 0; i < arr.length; i++) {\n const v = parseFloat(arr[i]);\n if (!isNaN(v)) {\n total += v;\n }\n }\n return total;\n};\n\n/**\n * Random integer between two numbers (stolen from underscorejs)\n * @param {Number} [min=0] mininum value\n * @param {Number} [max=null] maximum value\n * @returns {Number} random value\n */\nconst randomInteger = function (min = 0, max = null) {\n if (max == null) {\n max = min;\n min = 0;\n }\n return min + Math.floor(Math.random() * (max - min + 1));\n};\n\n/**\n * Random value selection\n * @param {Array} values an array of objects from which to choose\n * @param {Array} weights a matching array of integers to weight the values (i.e. values and weights are in the same order)\n * @returns {String} the randomly selected Array element from values param\n */\nconst getWeightedRandom = function (values, weights) {\n let n = 0;\n const num = randomInteger(1, arraySum.call(this, weights));\n let i = 0;\n for (i; i < values.length; i++) {\n n = n + weights[i];\n if (n >= num) {\n break;\n }\n }\n return values[i];\n};\n/**\n * Random value selection, wrapper for getWeightedRandom that processes the data into values/weights arrays\n * @param {String[]} data values\n * @returns {String|null} the randomly selected string\n */\nconst randomString = function (data) {\n const values = [];\n const weights = [];\n\n if (!Array.isArray(data) || data.length === 0) {\n return null;\n }\n data.forEach((entry) => {\n weights.push(1);\n values.push(entry);\n });\n\n return getWeightedRandom(values, weights);\n};\n\nexport {\n randomInteger,\n getWeightedRandom,\n randomString\n};\n", "import { isEmpty, isString, isObject, defaultToJSON } from './r_helpers.js';\nimport DisplayOptions from './DisplayOptions.js';\nimport RandomTableEntry from './RandomTableEntry.js';\nimport { getWeightedRandom } from './randomizer.js';\n\n/**\n * RandomTable: Model for tables used by TableRoller\n */\nexport default class RandomTable {\n /**\n * The primary attributes of this table\n * @property {String} id id for the table, primary key for database if used\n * @property {String} key identifier for the table\n * @property {String} [title] title of the table\n * @property {String} [author] author of the table\n * @property {String} [description] description of the table\n * @property {String} [source] source of the table\n * @property {String[]} [tags] subject tags\n * @property {String[]} [sequence] tables to roll on as default.\n * @property {String[]|Object[]} [table] default table. array of strings or objects. removed after initialization.\n * @property {Object} [tables] a property for each subtables.\n * @property {RandomTableEntries[]} tables[subtablename] Entries for subtables.\n * @property {String[]} [macro] for tables that are only used to aggregate result from other tables, this array consists of table keys and optionsl subtables to be rolled on in order\n * @property {Map[DisplayOptions]} [display_opt] Display options for the subtables.\n * @property {Array} [dependencies] table keys that are needed to get full results from this table\n *\n * Note the Constructor args are not exactly the same as the properties. Some type changes are made to convert data.\n */\n constructor ({\n id = 0,\n key = null,\n title = '',\n author = '',\n description = '',\n source = '',\n tags = [],\n sequence = [],\n tables = {},\n macro = [],\n dependencies = null,\n table = null,\n display_opt = []\n }) {\n this.id = id;\n this.key = key || this.id; // default to the id.\n this.title = title;\n this.author = author;\n this.description = description;\n this.source = source;\n this.tags = tags;\n this.sequence = sequence;\n this.macro = macro;\n this.dependencies = dependencies;\n\n this._normalizeTables(tables, table);\n\n this.display_opt = new Map();\n display_opt.forEach((data) => {\n const key = data.table || '';\n if (key) {\n if (data instanceof DisplayOptions) {\n this.display_opt.set(key, data);\n return;\n }\n const opt = new DisplayOptions(data);\n this.display_opt.set(key, opt);\n }\n });\n }\n toString () {\n return this.title;\n }\n /**\n * Make sure table entries are all RandomTableEntry objects.\n * @param {Array} data\n * @returns RandomTableEntry[]\n */\n _normalizeTable (data) {\n const entries = [];\n data.forEach((d) => {\n if (isEmpty(d)) {\n return;\n }\n if (isString(d)) {\n entries.push(new RandomTableEntry({\n label: d\n }));\n return;\n }\n if (d instanceof RandomTableEntry) {\n entries.push(d);\n return;\n }\n if (isObject(d)) {\n entries.push(new RandomTableEntry(d));\n }\n });\n return entries;\n }\n /**\n * Normalize the tables/table constructor data.\n * @param {Object} tables\n * @param {Array} table\n * @returns\n */\n _normalizeTables (tables, table) {\n if (isEmpty(tables) && isEmpty(table)) {\n return;\n }\n this.tables = {};\n // put default table in first.\n if (!isEmpty(table) && Array.isArray(table)) {\n this.tables.default = this._normalizeTable(table);\n }\n if (isObject(tables)) {\n const subtableNames = Object.keys(tables);\n subtableNames.forEach((name) => {\n const data = tables[name];\n if (!Array.isArray(data)) {\n return;\n }\n this.tables[name] = this._normalizeTable(data);\n });\n }\n }\n /**\n * Basic sequence of table rolls.\n * Either the start, the default sequence, the default table, or just the first one.\n * @param {String} start Subtable name to start with.\n * @returns {String[]}\n */\n getSequence (start = '') {\n if (start !== '') {\n return [start];\n }\n if (this.sequence.length === 0) {\n if (this.tables.default) {\n return ['default'];\n }\n return [this.subtableNames[0]];\n }\n if (this.sequence[0] === 'rollall') {\n return this.subtableNames;\n }\n return this.sequence;\n }\n /**\n * All the subtable names.\n * @returns {String[]}\n */\n get subtableNames () {\n return Object.keys(this.tables);\n }\n /**\n * Get entries for a specific subtable.\n * @param {String} [name=default] Subtable name.\n * @returns {RandomTableEntry[]}\n */\n getSubtableEntries (name = 'default') {\n return this.tables[name] || [];\n }\n /**\n * Get a random entry from a subtable.\n * @param {String} subtableName\n * @returns {RandomTableEntry|null}\n */\n getRandomEntry (subtableName) {\n const entries = this.getSubtableEntries(subtableName);\n if (entries.length === 0) {\n return null;\n }\n const values = [];\n const weights = [];\n entries.forEach((entry, k, l) => {\n weights.push(entry.weight);\n values.push(entry);\n });\n return getWeightedRandom(values, weights);\n }\n /**\n * Get an entry in case we only have the label and need other data from it\n * @param {String} label The item we are looking for\n * @param {String} [table=default] the table to search\n * @returns {RandomTableEntry|null}\n */\n findEntry (label, table = 'default') {\n const t = this.tables[table];\n if (!t) {\n return null;\n }\n const entry = t.find((e) => {\n return e.label === label;\n });\n if (!entry) {\n return null;\n }\n return entry;\n }\n /**\n * Find the dependent tables to get full results for this table\n * @return {Array} table keys\n */\n findDependencies () {\n // check field first, if it's not null we'll trust it...?\n if (this.dependencies !== null) {\n return this.dependencies;\n }\n // iterate over the tables and look for table tokens\n let dep = [];\n\n // Check macro\n this.macro.forEach((macro) => {\n const parts = macro.split(':');\n if (parts.length > 0 && parts[0] !== 'this') {\n dep.push(parts[0]);\n }\n });\n const tokenRegExp = /({{2}.+?}{2})/g;\n const tnames = Object.keys(this.tables);\n tnames.forEach((n) => {\n // n is sub/table name\n const table = this.tables[n];\n table.forEach((result) => {\n const tokens = result.label.match(tokenRegExp);\n if (tokens !== null) {\n tokens.forEach((token) => {\n const parts = token.replace('{{', '').replace('}}', '').split(':');\n if (parts.length > 1 && parts[0] === 'table' && parts[1] !== 'this') {\n dep.push(parts[1]);\n }\n });\n }\n });\n });\n dep = dep.reduce((a, b) => {\n if (a.indexOf(b) < 0) { a.push(b); }\n return a;\n }, []);\n this.dependencies = dep;\n return dep;\n }\n /**\n * Custom JSON handler because Map doesn't JSON stringify automatically.\n * @returns {Object}\n */\n toJSON () {\n const obj = defaultToJSON.call(this);\n obj.className = 'RandomTable';\n return obj;\n }\n}\n", "import { defaultToJSON } from './r_helpers.js';\n\n/**\n * Class for results from RandomTable\n */\nexport default class RandomTableResult {\n /**\n * @property {String} table Title of subtable.\n * @property {String} result Randomized result label.\n * @property {String} desc Extra result description.\n */\n constructor ({\n table = '',\n result = '',\n desc = ''\n }) {\n this.table = table;\n this.result = result;\n this.desc = desc;\n }\n /**\n * Is this from the \"default\" table.\n */\n get isDefault () {\n return this.table === 'default';\n }\n /**\n * Is this an error result.\n */\n get isError () {\n return false;\n }\n toString () {\n return this.result;\n }\n /**\n * Custom JSON handler to strip empty props.\n * @returns {Object}\n */\n toJSON () {\n const obj = defaultToJSON.call(this);\n obj.className = 'RandomTableResult';\n return obj;\n }\n}\n", "import RandomTableResult from './RandomTableResult.js';\n\n/**\n * Class for results from RandomTable\n */\nexport default class TableErrorResult extends RandomTableResult {\n /**\n * Is this an error result.\n */\n get isError () {\n return true;\n }\n /**\n * Custom JSON handler to strip empty props.\n * @returns {Object}\n */\n toJSON () {\n const obj = super.toJSON();\n obj.className = 'TableErrorResult';\n return obj;\n }\n}\n", "import { capitalize, defaultToJSON } from './r_helpers.js';\nimport RandomTableResult from './RandomTableResult.js';\nimport TableErrorResult from './TableErrorResult.js';\nimport DisplayOptions from './DisplayOptions.js';\n\n/**\n * Set of table results.\n */\nexport default class RandomTableResultSet {\n /**\n * @property {String} title Title from the RandomTable parent\n * @property {RandomTableResult[]} results Randomized results.\n * @property {Map[DisplayOptions]|Object} displayOptions Display settings from the RandomTable parent.\n */\n constructor ({\n title = '',\n results = [],\n displayOptions = new Map()\n }) {\n this.title = title;\n this.results = [];\n results.forEach((r) => {\n this.addResult(r);\n });\n if (displayOptions instanceof Map) {\n this.displayOptions = displayOptions;\n } else {\n this.displayOptions = new Map();\n Object.keys(displayOptions).forEach((key) => {\n const data = displayOptions[key];\n const tableName = data.table || '';\n if (tableName) {\n if (data instanceof DisplayOptions) {\n this.displayOptions.set(tableName, data);\n return;\n }\n this.displayOptions.set(tableName, new DisplayOptions(data));\n }\n });\n }\n }\n /**\n * Add a result to the set.\n * @param {RandomTableResult|TableErrorResult|object} data\n * @returns\n */\n addResult (data) {\n if (data instanceof RandomTableResult || data instanceof TableErrorResult) {\n this.results.push(data);\n return;\n }\n if (data.className === 'TableErrorResult') {\n this.results.push(new TableErrorResult(data));\n return;\n }\n this.results.push(new RandomTableResult(data));\n }\n\n get isSimple () {\n return this.results.length === 1;\n }\n\n /**\n * Find the result for a specific table/subtable\n * @param {String} table The table to look for\n * @returns {RandomTableResult|null}\n */\n findResultByTable (table = 'default') {\n const obj = this.results.find((v) => {\n return v.table === table;\n });\n return !obj ? null : obj;\n }\n /**\n * Output the set as a string.\n * @param {Boolean} simple Simplify the output (just the result labels)\n * @returns\n */\n niceString (simple = false) {\n if (this.results.length === 0) {\n return '';\n }\n\n if (simple) {\n return this.results.map((r) => { return r.toString(); }).join(' ');\n }\n\n let output = '';\n this.results.forEach((result) => {\n if (result.isError) {\n output += `Error: ${result.result}\\n`;\n return;\n }\n const displayOpt = this.displayOptions.get(result.table);\n if (displayOpt) {\n if (!displayOpt.hide_table) {\n output += `${capitalize(result.table)}: `;\n }\n if (!displayOpt.hide_result) {\n output += `${capitalize(result.result)}\\n`;\n }\n if (!displayOpt.hide_desc) {\n if (result.desc !== '') {\n output += `(${result.desc})\\n`;\n }\n }\n return;\n }\n if (result.isDefault) {\n output += `${capitalize(result.result)}\\n`;\n } else {\n output += `${capitalize(result.table)}: ${capitalize(result.result)}\\n`;\n }\n if (result.desc !== '') {\n output += `${result.desc}\\n`;\n }\n });\n return output.trim(); // trim off final linebreak\n }\n /**\n * Simple base output of result set.\n */\n toString () {\n return this.niceString();\n }\n /**\n * Custom JSON handler because Map doesn't JSON stringify automatically.\n * @returns {Object}\n */\n toJSON () {\n const obj = defaultToJSON.call(this);\n obj.className = 'RandomTableResultSet';\n return obj;\n }\n}\n", "/* eslint-disable no-useless-escape */\nimport { randomInteger } from './randomizer.js';\n\n/**\n * @prop {String} die Die notation.\n * @prop {Number} value Random roll for the die notation.\n */\nclass DiceResult {\n constructor ({\n die = '',\n value = 0\n }) {\n this.die = die;\n this.value = value;\n }\n toString () {\n return this.value;\n }\n toJSON () {\n return {\n className: 'DiceResult',\n die: this.die,\n value: this.value\n };\n }\n}\n\n/**\n * Dice rolling simulator\n * @param {Number} [die=6] Die type\n * @param {Number} [number=1] Number of times to roll the die\n * @param {Number} [modifier=0] Numeric modifier to dice total\n * @param {String} [mod_op=+] Operator for the modifier (+,-,/,*)\n * @returns {Number} Number rolled (die*number [mod_op][modifier])\n */\nconst parseDiceNotation = function (die = 6, number = 1, modifier = 0, mod_op = '+') {\n modifier = parseInt(modifier, 10);\n die = parseInt(die, 10);\n\n if (number <= 0) {\n number = 1;\n } else {\n number = parseInt(number, 10);\n }\n\n let sum = 0;\n for (let i = 1; i <= number; i++) {\n sum = sum + randomInteger(1, die);\n }\n if (modifier === 0) {\n return sum;\n }\n\n switch (mod_op) {\n case '*':\n sum = sum * modifier;\n break;\n case '-':\n sum = sum - modifier;\n break;\n case '/':\n sum = sum / modifier;\n break;\n case '+':\n default:\n sum = sum + modifier;\n break;\n }\n return Math.round(sum);\n};\n\n/**\n * takes a string like '3d6+2', 'd6', '2d6', parses it, and puts it through roll\n * @params {String} string a die roll notation\n * @returns {Number} the result of the roll\n */\nconst rollDie = function (string = '') {\n string = string.trim();\n const m = string.match(/^([0-9]*)d([0-9]+)(?:([\\+\\-\\*\\/])([0-9]+))*$/);\n if (!m) {\n return '';\n }\n return parseDiceNotation(m[2], m[1], m[4], m[3]);\n};\n\n/**\n * Return a dice result.\n * @param {String} die Die roll notation.\n * @returns {DiceResult}\n */\nconst getDiceResult = function (die = '') {\n return new DiceResult({\n die,\n value: rollDie(die)\n });\n};\n\nexport {\n rollDie,\n DiceResult,\n getDiceResult\n};\n", "/**\n * Custom error for handling known errors in the table roller.\n */\nclass TableError extends Error {\n constructor (message) {\n super(message);\n this.name = 'TableError';\n }\n}\n\nexport default TableError;\n", "/* eslint-disable no-useless-escape */\nimport { isEmpty, isUndefined } from './r_helpers.js';\nimport RandomTable from './RandomTable.js';\nimport RandomTableEntry from './RandomTableEntry.js';\nimport RandomTableResult from './RandomTableResult.js';\nimport RandomTableResultSet from './RandomTableResultSet.js';\nimport { getDiceResult } from './dice_roller.js';\nimport TableError from './TableError.js';\nimport TableErrorResult from './TableErrorResult.js';\n\n/**\n * Define the regex to find tokens\n * This looks for anything between double brackets.\n * Note: this is duplicated in RandomTable.findDependencies() so if updated, update it there too\n */\nconst tokenRegExp = /({{2}.+?}{2})/g;\n\n/**\n * TableRoller\n * Handles rolling on tables and tokens in tables/results.\n * @constructor\n */\nclass TableRoller {\n constructor ({\n token_types = {}\n }) {\n this.token_types = {\n roll: this._defaultRollToken.bind(this),\n table: this._defaultTableToken.bind(this)\n };\n Object.keys(token_types).forEach((token) => {\n this.token_types[token] = token_types[token];\n });\n }\n /**\n * Return an error result\n * @param {String} error Error message\n * @param {String} table Sub/table name if relevant.\n * @returns {TableErrorResult}\n */\n _getErrorResult (error = '', table = '') {\n return new TableErrorResult({\n table: table,\n result: error\n });\n }\n /**\n * Return a result set with an error.\n * @param {String} error Error message\n * @returns {RandomTableResultSet}\n */\n _getErrorResultSet (error = '') {\n return new RandomTableResultSet({\n results: [\n this._getErrorResult(error)\n ]\n });\n }\n /**\n * Get a result from a table/subtable in a RandomTable object\n * DANGER: you could theoretically put yourself in an endless loop if the data were poorly planned\n * Calling method try to catch RangeError to handle that possibility.\n * @param {RandomTable} rtable the RandomTable object\n * @param {String} table table to roll on\n * @returns {RandomTableResult[]}\n */\n _selectFromTable (rtable, table) {\n if (!(rtable instanceof RandomTable)) {\n return [this._getErrorResult('Invalid table.')];\n }\n\n let o = []; // Results\n const entry = rtable.getRandomEntry(table);\n if (entry === null || !(entry instanceof RandomTableEntry)) {\n return [this._getErrorResult('Invalid subtable name.', table)];\n }\n // if print is false we suppress the output from this table\n // (good for top-level tables that have subtables prop set)\n if (entry.print) {\n // replace any tokens\n const t_result = this.findToken(entry.label, rtable);\n o.push(new RandomTableResult({ table: table, result: t_result, desc: entry.description }));\n }\n\n // are there subtables to roll on?\n if (entry.subtable.length === 0) {\n // no subtables\n return o;\n }\n\n // Select from each subtable and add to results.\n entry.subtable.forEach((subtableName) => {\n const subresult = this._selectFromTable(rtable, subtableName);\n // concat because subresult is an array.\n o = o.concat(subresult);\n });\n return o;\n }\n /**\n * Get results array for macro setting of a table.\n * @param {RandomTable} rtable Table with macro set.\n * @returns {RandomTableResult[]}\n */\n _getTableMacroResult (rtable) {\n let results = [];\n try {\n rtable.macro.forEach((macroKey) => {\n const parts = macroKey.split(':');\n const tableKey = parts[0];\n const subtable = parts[1] || '';\n if (tableKey === rtable.key) {\n throw new TableError(`Macros can't self reference.`);\n }\n try {\n const mtable = this.getTableByKey(tableKey);\n const result = this.getTableResult(mtable, subtable);\n // concat because result is an array.\n results = results.concat(result);\n } catch (e) {\n if (e instanceof TableError) {\n results.push(this._getErrorResult(e.message, tableKey));\n } else {\n // Rethrow unexpected errors\n throw e;\n }\n }\n });\n } catch (e) {\n if (e instanceof RangeError) {\n // This could be an infinite loop of table results referencing each other.\n results.push(this._getErrorResult(e.message));\n } else {\n throw e;\n }\n }\n return results;\n }\n /**\n * Generate a result from a RandomTable object\n * @param {RandomTable} rtable the RandomTable\n * @param {String} [start=''] subtable to roll on\n * @return {RandomTableResult[]}\n */\n getTableResult (rtable, start = '') {\n if (!(rtable instanceof RandomTable)) {\n return [\n this._getErrorResult('No table found to roll on.')\n ];\n }\n let results = [];\n\n // if macro is set then we ignore a lot of stuff\n if (rtable.macro.length > 0) {\n return this._getTableMacroResult(rtable);\n }\n\n const sequence = rtable.getSequence(start);\n if (sequence.length === 0) {\n return results;\n }\n try {\n sequence.forEach((seqKey) => {\n const r = this._selectFromTable(rtable, seqKey);\n results = results.concat(r);\n });\n } catch (e) {\n // In case of infinite recursion\n if (e instanceof RangeError) {\n results.push(this._getErrorResult(e.message));\n } else {\n throw e;\n }\n }\n return results;\n }\n /**\n * Get result set from a table based on the key.\n * @param {String} tableKey\n * @param {String} table\n * @returns {RandomTableResultSet}\n */\n getTableResultSetByKey (tableKey, table = '') {\n try {\n const rtable = this.getTableByKey(tableKey);\n const results = this.getTableResult(rtable, table);\n return new RandomTableResultSet({\n title: rtable.title,\n results: results,\n displayOptions: rtable.display_opt\n });\n } catch (e) {\n if (e instanceof TableError) {\n return this._getErrorResultSet(e.message);\n } else {\n // Rethrow unexpected errors\n throw e;\n }\n }\n }\n /**\n * Get result set from a table based on the key.\n * @param {RandomTable} rtable Main table object.\n * @param {String} [table] Subtable\n * @returns {RandomTableResultSet}\n */\n getResultSetForTable (rtable, table = '') {\n if (!(rtable instanceof RandomTable)) {\n return this._getErrorResultSet(`Invalid table data.`);\n }\n const results = this.getTableResult(rtable, table);\n return new RandomTableResultSet({\n title: rtable.title,\n results: results,\n displayOptions: rtable.display_opt\n });\n }\n /**\n * Perform token replacement. Only table and roll actions are accepted\n * @param {String} token A value passed from findToken containing a token(s) {{SOME OPERATION}} Tokens are {{table:SOMETABLE}} {{table:SOMETABLE:SUBTABLE}} {{table:SOMETABLE*3}} (roll that table 3 times) {{roll:1d6+2}} (etc) (i.e. {{table:colonial_occupations:laborer}} {{table:color}} also generate names with {{name:flemish}} (surname only) {{name:flemish:male}} {{name:dutch:female}}\n * @param {RandomTable|null} curtable RandomTable the string is from (needed for \"this\" tokens) or null\n * @returns {RandomTableResultSet|RandomTableResultSet[]|DiceResult|String|Any} The result of the token or else just the token (in case it was a mistake or at least to make the error clearer)\n */\n convertToken (token, curtable = null) {\n let parts = token.replace('{{', '').replace('}}', '').split(':');\n parts = parts.map((el) => {\n return el.trim();\n });\n if (parts.length === 0) {\n return token;\n }\n\n // look for a token type we can run\n try {\n if (this.token_types[parts[0]]) {\n return this.token_types[parts[0]](parts, token, curtable);\n } else {\n return token;\n }\n } catch (e) {\n if (e instanceof RangeError) {\n // This could be an infinite loop of table results referencing each other.\n return this._getErrorResultSet(e.message);\n } else {\n throw e;\n }\n }\n }\n /**\n * Look for tokens to perform replace action on them.\n * @param {String} entryLabel Usually a label from a RandomTableEntry\n * @param {RandomTable|null} curtable RandomTable the string is from (needed for \"this\" tokens) or null\n * @returns {String} String with tokens replaced (if applicable)\n */\n findToken (entryLabel, curtable = null) {\n if (isEmpty(entryLabel)) {\n return '';\n }\n const newstring = entryLabel.replace(tokenRegExp, (token) => {\n return this.convertToken(token, curtable).toString();\n });\n return newstring;\n }\n /**\n * Since tables are stored outside of this module, this function allows for the setting of a function which will be used to lookup a table by it's key\n * @param {Function} lookup a function that takes a table key and returns a RandomTable or null\n */\n setTableKeyLookup (lookup) {\n this._customGetTableByKey = lookup;\n }\n /**\n * Placeholder that should be replaced by a function outside this module\n * @param {String} key human readable table identifier\n * @return {null} nothing, when replaced this function should return a table object\n */\n _customGetTableByKey (key) {\n return null;\n }\n /**\n * Return a table based on it's key.\n * This requires calling setTableKeyLookup and setting a lookup method\n * That returns a RandomTable object or null.\n * @param {String} key human readable table identifier\n * @returns {RandomTable}\n * @throws {TableError}\n */\n getTableByKey (key) {\n if (!key) {\n throw new TableError('No table key.');\n }\n const table = this._customGetTableByKey(key);\n if (!table || !(table instanceof RandomTable)) {\n throw new TableError(`No table found for key: ${key}`);\n }\n return table;\n }\n /**\n * Add a token variable\n * @param {String} name Name of the token (used as first element).\n * @param {Function} process Function to return token replacement value function is passed the token_parts (token split by \":\"), original full_token, current table name\n */\n registerTokenType (name, process) {\n this.token_types[name] = process;\n }\n /**\n * Dice roll token.\n * @returns {DiceResult}\n */\n _defaultRollToken (token_parts, full_token = '', curtable = null) {\n return getDiceResult(token_parts[1]);\n }\n /**\n * Table token lookup in the form:\n * {{table:SOMETABLE}} {{table:SOMETABLE:SUBTABLE}} {{table:SOMETABLE*3}} (roll that table 3 times) {{table:SOMETABLE:SUBTABLE*2}} (roll subtable 2 times)\n * @param {String[]} token_parts Token split by :\n * @param {String} full_token Original token\n * @param {RandomTable|null} curtable Current table or null.\n * @returns {RandomTableResultSet|RandomTableResultSet[]} One or more result sets.\n */\n _defaultTableToken (token_parts, full_token, curtable = null) {\n if (isUndefined(token_parts[1])) {\n return full_token;\n }\n let multiplier = 1;\n if (token_parts[1].indexOf('*') !== -1) {\n const x = token_parts[1].split('*');\n token_parts[1] = x[0];\n multiplier = x[1];\n }\n\n // what table do we roll on\n let rtable = null;\n if (token_parts[1] === 'this') {\n if (!curtable) {\n return full_token;\n }\n // reroll on same table\n rtable = curtable;\n } else {\n // Table lookup\n try {\n rtable = this.getTableByKey(token_parts[1]);\n } catch (e) {\n if (e instanceof TableError) {\n return full_token;\n } else {\n // Rethrow unexpected errors\n throw e;\n }\n }\n }\n\n if (typeof token_parts[2] !== 'undefined' && token_parts[2].indexOf('*') !== -1) {\n const x = token_parts[2].split('*');\n token_parts[2] = x[0];\n multiplier = x[1];\n }\n const subtable = (isUndefined(token_parts[2])) ? '' : token_parts[2];\n\n const results = [];\n for (let i = 1; i <= multiplier; i++) {\n results.push(this.getResultSetForTable(rtable, subtable));\n }\n return results.length === 1 ? results[0] : results;\n }\n}\n\nexport default TableRoller;\n", "/**\n * Adapted from http://blog.javascriptroom.com/2013/01/21/markov-chains/\n */\nclass MarkovGenerator {\n /**\n *\n * @param {Object} memory the \"memory\" where the language parts go\n * @param {String} separator If you want to delimit the generated parts\n * @param {Number} order How many... something... to something.... oh it's been too long I don't remember how this works...\n */\n constructor ({\n memory = {},\n separator = '',\n order = 2\n }) {\n this.memory = memory;\n this.separator = separator;\n this.order = order;\n }\n /**\n * Is the memory key already set.\n * @param {String} key\n */\n isMemoryKeySet (key) {\n return !!this.memory[key];\n }\n /**\n * Generate a starting array for the chain based on the order number\n * @return {Array} just an empty array of length=order\n */\n genInitial () {\n return Array(this.order).fill('');\n }\n /**\n * Get a random array element\n * @param {Array} arr an array\n * @return {String|Object} random value\n */\n getRandomValue (arr) {\n return arr[Math.floor(Math.random() * arr.length)];\n }\n /**\n * Chunk the word or phrase\n * @param {String} txt the text to chunk\n * @param {Function} cb callback function\n * @return {null} null\n */\n breakText (txt, cb) {\n const parts = txt.split(this.separator);\n const prev = this.genInitial();\n\n parts.forEach((v) => {\n v = v.toLowerCase();\n cb(prev, v);\n prev.shift();\n prev.push(v);\n });\n cb(prev, '');\n }\n /**\n * Feed text to memory\n * @param {String} key key for the chain (so we can store multiple memories)\n * @param {String} txt word or phrase\n * @return {null} null\n */\n learn (key, txt) {\n const mem = (this.memory[key]) ? this.memory[key] : {};\n // split up text then add the calculated parts to the memory for this key\n this.breakText(txt, (key, value) => {\n if (!mem[key]) {\n mem[key] = [];\n }\n mem[key].push(value);\n return mem;\n });\n this.memory[key] = mem;\n }\n /**\n * Iterate through, calls self\n * @param {Array} state array of most recent x(x=order) elements in chain\n * @param {Array} ret the chain\n * @return {Array}\n */\n step (state, ret) {\n const nextAvailable = this.memory[this.cur_key][state] || [''];\n const next = this.getRandomValue(nextAvailable);\n // we don't have anywhere to go\n if (!next) {\n return ret;\n }\n ret.push(next);\n const nextState = state.slice(1);\n nextState.push(next);\n return this.step(nextState, ret);\n }\n /**\n * Return a generated response\n * @param {String} key key for the chain (so we can store multiples\n * @param {Array} seed letters to start the response (?)\n */\n generate (key, seed) {\n if (!seed) {\n seed = this.genInitial();\n }\n this.cur_key = key;\n return seed.concat(this.step(seed, [])).join(this.separator);\n }\n}\n\nexport default MarkovGenerator;\n", "/**\n * Custom error for handling known errors in the name generator.\n */\nclass RandomNameError extends Error {\n constructor (message) {\n super(message);\n this.name = 'RandomNameError';\n }\n}\n\nexport default RandomNameError;\n", "import { randomString } from './randomizer.js';\nimport { defaultToJSON } from './r_helpers.js';\n\n/**\n * Class for name data.\n */\nexport default class RandomNameType {\n /**\n *\n * @param {String} key Key to identify uniquely in tokens and methods.\n * @param {String} label Human readable label.\n * @param {String[]} male Names.\n * @param {String[]} female Names.\n * @param {String[]} surname Names.\n */\n constructor ({\n key = '',\n label = '',\n male = [],\n female = [],\n surname = []\n }) {\n this.key = key;\n this.label = label || key;\n this.male = Array.isArray(male) ? male : [];\n this.female = Array.isArray(female) ? female : [];\n this.surname = Array.isArray(surname) ? surname : [];\n }\n /**\n * Returns all personal names.\n * @returns {String[]}\n */\n getAllPersonalNames () {\n return Array.prototype.concat(this.male, this.female);\n }\n /**\n * Return a personal name list.\n * @param {String} gender Mixed, random, male, female\n * @returns {String[]}\n */\n getPersonalNameList (gender = 'random') {\n // Mixed gets all the personal names.\n if (gender === 'mixed' || gender === '') {\n return this.getAllPersonalNames();\n }\n // If specific gender is requested\n // return regardless of if it's empty\n if (gender === 'male') {\n return this.male;\n }\n if (gender === 'female') {\n return this.female;\n }\n // Else return a random list\n const randomList = [];\n if (this.male.length > 0) {\n randomList.push('male');\n }\n if (this.female.length > 0) {\n randomList.push('female');\n }\n if (randomList.length === 0) {\n return [];\n }\n gender = randomString(randomList);\n return this[gender];\n }\n /**\n * Custom JSON handler because Map doesn't JSON stringify automatically.\n * @returns {Object}\n */\n toJSON () {\n const obj = defaultToJSON.call(this);\n obj.className = 'RandomNameType';\n return obj;\n }\n}\n", "import { capitalize } from './r_helpers.js';\nimport MarkovGenerator from './MarkovGenerator.js';\nimport { randomString } from './randomizer.js';\nimport RandomNameError from './RandomNameError.js';\nimport RandomNameType from './RandomNameType.js';\n\n/** Capitalize names, account for multiword lastnames like \"Van Hausen\"\n * @param {String} name a name\n * @return {String} name capitalized\n */\nconst capitalizeName = function (name) {\n if (!name) {\n return '';\n }\n const leave_lower = ['of', 'the', 'from', 'de', 'le', 'la'];\n // need to find spaces in name and capitalize letter after space\n const parts = name.split(' ');\n const upper_parts = parts.map((w) => {\n return (leave_lower.indexOf(w) >= 0) ? w : `${capitalize(w)}`;\n });\n return upper_parts.join(' ');\n};\n\n/**\n * @prop {Map} nameTypes\n * @prop {MarkovGenerator} _markov\n */\nclass RandomNameGenerator {\n /**\n * Random name generation.\n * @param {RandomNameType[]} namedata\n * @param {Number} [markovOrder=3] Markov generator settings.\n */\n constructor ({\n namedata = [],\n markovOrder = 3\n }) {\n this.nameTypes = new Map();\n if (Array.isArray(namedata)) {\n namedata.forEach((type) => {\n this.registerNameType(type);\n });\n }\n this._markov = new MarkovGenerator({ order: markovOrder });\n }\n /**\n * Add some name data\n * Note: you can overwrite existing name_types if you want\n * @param {RandomNameType} type\n * @throws {RandomNameError}\n */\n registerNameType (type) {\n if (!(type instanceof RandomNameType)) {\n throw new RandomNameError('Must be instance of RandomNameType');\n }\n if (!type.key) {\n throw new RandomNameError('RandomNameType must have key set.');\n }\n if (type.key === 'random') {\n throw new RandomNameError(`RandomNameType key ${type.key} is reserved.`);\n }\n if (type.male.length === 0 && type.female.length === 0 && type.surname.length === 0) {\n throw new RandomNameError(`RandomNameType ${type.key} must include male, female, or surname lists.`);\n }\n this.nameTypes.set(type.key, type);\n }\n /**\n * Make sure namedata is set.\n * @param {String} name_type\n * @param {String} [subtype=''] Subtype like a gender or 'surname'\n * @throws RandomNameError\n */\n _validateNameType (name_type, subtype = '') {\n const type = this.nameTypes.get(name_type);\n if (!type) {\n throw new RandomNameError('Invalid name type.');\n }\n if (!subtype) {\n return;\n }\n if (!Array.isArray(type[subtype]) || type[subtype].length === 0) {\n throw new RandomNameError(`${name_type} type does not have subtype ${subtype}`);\n }\n }\n /**\n * Keys of the name types that are set.\n * @returns {String[]}\n */\n getValidNameTypes () {\n return Array.from(this.nameTypes.keys());\n }\n /**\n * Get a random name type from the available types.\n * @returns {String}\n */\n getRandomNameType () {\n return randomString(Array.from(this.nameTypes.keys())) || '';\n }\n /**\n * Get the name type\n * @param {String} name_type Name type key or random.\n * @returns {RandomNameType}\n * @throws {RandomNameError}\n */\n _getNameType (name_type) {\n if (name_type === 'random') {\n // randomize a type...\n name_type = this.getRandomNameType();\n }\n const nameType = this.nameTypes.get(name_type);\n if (!nameType) {\n throw new RandomNameError('Invalid name type.');\n }\n return nameType;\n }\n /**\n * Get a name list\n * @param {String} name_type\n * @param {String} subtype\n * @returns {String[]}\n */\n _getNameList (name_type = 'random', subtype = 'mixed') {\n const nameType = this._getNameType(name_type);\n if (subtype === 'surname') {\n if (nameType.surname.length === 0) {\n throw new RandomNameError(`${name_type} type does not have subtype ${subtype}`);\n }\n return nameType.surname;\n }\n const list = nameType.getPersonalNameList(subtype);\n if (list.length === 0) {\n throw new RandomNameError(`${name_type} type does not have subtype ${subtype}`);\n }\n return list;\n }\n /**\n * Select a personal name from one of the lists.\n * @param {String} name_type what list/process to use, else random\n * @param {String} gender\n * @returns {String}\n * @throws {RandomNameError}\n */\n selectPersonalName (name_type = 'random', gender = 'random') {\n const nameList = this._getNameList(name_type, gender);\n return capitalizeName(randomString(nameList));\n }\n /**\n * Select a sur/last name only from one of the lists\n * @param {String} name_type what list/process to use, else random\n * @returns {String} a name\n * @throws {RandomNameError}\n */\n selectSurname (name_type = 'random') {\n const nameList = this._getNameList(name_type, 'surname');\n return capitalizeName(randomString(nameList));\n }\n /**\n * Select a name from one of the lists\n * @param {String} name_type What name list/process to use else random\n * @param {String} gender male, female, random, ''\n * @param {String} style first=first name only, else full name\n * @returns {String} a name\n * @throws {RandomNameError}\n */\n selectName (name_type = 'random', gender = 'random', style = '') {\n const nameType = this._getNameType(name_type);\n const personalNameList = nameType.getPersonalNameList(gender);\n if (personalNameList.length === 0) {\n throw new RandomNameError(`${nameType.key} does not have list for ${gender}`);\n }\n let name = capitalizeName(randomString(personalNameList));\n if (style !== 'first' && nameType.surname.length > 0) {\n name += ` ${capitalizeName(randomString(nameType.surname))}`;\n }\n return name.trim();\n }\n /**\n * Create a personal name using markov chains.\n * @param {String} name_type what list/process to use, else random\n * @param {String} gender\n * @returns {String}\n * @throws {RandomNameError}\n */\n createPersonalName (name_type = 'random', gender = 'random') {\n const nameType = this._getNameType(name_type);\n const namelist = nameType.getPersonalNameList(gender);\n if (namelist.length === 0) {\n throw new RandomNameError('Starting name list is empty.');\n }\n const mkey = `${nameType.key}_${gender}`;\n if (!this._markov.isMemoryKeySet(mkey)) {\n namelist.forEach((v) => {\n this._markov.learn(mkey, v);\n });\n }\n return capitalizeName(this._markov.generate(mkey).trim());\n }\n /**\n * Create a sur/last name using markov chains.\n * @param {String} name_type what list/process to use, else random\n * @returns {String} a name\n * @throws {RandomNameError}\n */\n createSurName (name_type = 'random') {\n const nameType = this._getNameType(name_type);\n const namelist = nameType.surname;\n if (namelist.length === 0) {\n throw new RandomNameError('Starting name list is empty.');\n }\n const skey = `${nameType.key}_surname`;\n if (!this._markov.isMemoryKeySet(skey)) {\n namelist.forEach((v) => {\n this._markov.learn(skey, v);\n });\n }\n return capitalizeName(this._markov.generate(skey).trim());\n }\n /**\n * Create a name using Markov chains\n * @param {String} [name_type=random] what list/process to use\n * @param {String} [gender=random] male or female or both\n * @param {String} style first=first name only, else full name\n * @returns {String} a name\n * @throws {RandomNameError}\n */\n createName (name_type = 'random', gender = 'random', style = '') {\n if (name_type === 'random') {\n name_type = this.getRandomNameType();\n }\n let name = this.createPersonalName(name_type, gender);\n if (style !== 'first') {\n name = `${name} ${this.createSurName(name_type)}`;\n }\n return name.trim();\n }\n /**\n * Generate a bunch of names, half male, half female\n * @param {Number} [number=10] number of names in the list (half will be male, half will be female)\n * @param {String} [name_type] type of name or else it will randomly select\n * @param {Bool} [create=false] new names or just pick from list\n * @return {Object} arrays of names inside male/female property\n * @throws {RandomNameError}\n */\n generateList (number = 10, name_type = 'random', create = false) {\n const names = { male: [], female: [] };\n\n for (let i = 1; i <= number; i++) {\n const gender = (i <= Math.ceil(number / 2)) ? 'male' : 'female';\n if (create) {\n names[gender].push(this.createName(name_type, gender));\n } else {\n names[gender].push(this.selectName(name_type, gender));\n }\n }\n return names;\n }\n /**\n * Callback for the TableRoller to generate names from a token.\n * Token parts will be:\n * 0: \"name\" literally\n * 1: type of name (often a nationality/language/ethnicity/etc)\n * 2: gender (\"male\"/\"female\" for which name list to pick from, defaults to randomizing between them).\n * 3: style (\"first\" for a first name, else a full name will be returned)\n * @param {String[]} token_parts Parts of a token: 0 will be the action (name in most cases.)\n * @param {String} full_token Full token wrapped in double braces.\n * @param {RandomTable|null} curtable Current table token was found in (helpful if `this` token is found) or null\n * @returns {String}\n */\n nameTokenCallback (token_parts, full_token = '', curtable = null) {\n let string = '';\n if (!token_parts[1]) {\n token_parts[1] = 'random';\n }\n if (!token_parts[3] || token_parts[3] !== 'first') {\n token_parts[3] = '';\n }\n if (!token_parts[2]) {\n token_parts[2] = 'random';\n }\n try {\n string = this.selectName(token_parts[1], token_parts[2], token_parts[3]);\n } catch (e) {\n if (e instanceof RandomNameError) {\n return '';\n } else {\n throw e;\n }\n }\n return string;\n }\n}\n\nexport default RandomNameGenerator;\n", "export default [\n {\n id: 3,\n key: 'npcs',\n title: 'NPC Characteristics',\n sequence: ['size', 'manner', 'physical_trait', 'quirk', 'speech'],\n tables: {\n size: [\n 'Short',\n 'Thin',\n 'Average',\n 'Tall',\n 'Large',\n 'Pick Two'\n ],\n dress: [\n 'Cleancut',\n 'Filthy',\n 'Fancy',\n 'Practical',\n 'Rich',\n 'Uniform'\n ],\n manner: [\n 'Gregarious',\n 'Icy',\n 'Pious',\n 'Flirtacious / Obsequious',\n 'Aggressive / Critical',\n 'Reserved'\n ],\n physical_trait: [\n 'Missing Limb',\n 'Hairy',\n 'Unusual hair',\n 'Muscular',\n 'Unusually Attractive',\n 'Unusually Ugly'\n ],\n quirk: [\n 'Touchy',\n 'Fingers Talisman [crucifix/ring/gun]',\n 'Ticket/Fidgety',\n 'Bad Sense [sight/hearing]',\n 'Drinks/Smokes Profusely',\n 'Gestures a lot'\n ],\n speech: [\n 'Stutters',\n 'Florid',\n 'Terse',\n 'Curses excessively',\n 'Laughs a lot',\n 'Meandering'\n ]\n }\n },\n {\n id: 4,\n key: 'jobs',\n title: 'NPC Jobs',\n display_opt: [\n { table: 'worker', hide_table: true },\n { table: 'merchant', hide_table: true },\n { table: 'craftsman', hide_table: true },\n { table: 'professional', hide_table: true },\n { table: 'wealthy', hide_table: true },\n { table: 'neer_do_well', hide_table: true }\n ],\n tables: {\n default: [\n { label: 'Worker', subtable: 'worker', print: false },\n { label: 'Merchant', subtable: 'merchant', print: false },\n { label: 'Craftsman', subtable: 'craftsman', print: false },\n { label: 'Professional', subtable: 'professional', print: false },\n { label: 'Wealthy', subtable: 'wealthy', print: false },\n { label: 'Ne\\'er Do Well', subtable: 'neer_do_well', print: false }\n ],\n worker: [\n 'Farmer',\n 'Bartender',\n 'Clerk',\n 'Cowboy',\n 'Soldier',\n 'Laundress',\n 'Prostitute',\n 'Logger',\n 'Parent',\n 'Miner',\n 'Trapper',\n 'Unemployed'\n ],\n merchant: [\n 'General Store',\n 'Bathhouse',\n 'Hotel/Boarding',\n 'Saloon',\n 'Pimp',\n 'Hardware',\n 'Livery',\n 'Foreman/Manager',\n 'Food/Cafe',\n 'Freight',\n 'Haberdasher',\n 'Feed Barn'\n ],\n craftsman: [\n 'Blacksmith',\n 'Wainwright',\n 'Brewer/Distiller',\n 'Saddler',\n 'Tailor',\n 'Barber',\n 'Cook',\n 'Butcher',\n 'Gunsmith',\n 'Sawmill',\n 'Carpenter',\n '?'\n ],\n professional: [\n 'Doctor',\n 'Lawyer',\n 'Newspaper Editor',\n 'Teacher',\n 'Sheriff',\n 'Army Officer',\n 'Preacher',\n 'Telegraph Operator',\n 'Conductor',\n 'Assayer',\n 'Surveyor',\n 'Marshal'\n ],\n wealthy: [\n 'Mine Owner',\n 'Cattle Baron',\n 'Trust Fund Child',\n 'Banker',\n 'Politician',\n 'Nouveau Riche'\n ],\n neer_do_well: [\n 'Gambler',\n 'Addict',\n 'Gunfighter',\n 'Actor',\n 'Musician',\n 'Dancer',\n 'Thug',\n 'Gossip',\n 'Thief',\n 'Gigolo',\n 'Hermit',\n 'Vigilante'\n ]\n }\n },\n {\n id: 5,\n key: 'goals',\n title: 'NPC Goals',\n display_opt: [\n { table: 'long_term', hide_table: true },\n { table: 'short_term', hide_table: true },\n { table: 'secrets', hide_table: true }\n ],\n tables: {\n long_term: [\n 'Wealth',\n 'Safety [family/self]',\n 'Civic Good',\n 'Knowledge/Skill/Craft',\n 'Piety/Charity',\n 'Status/Power',\n 'Peace & Quiet',\n 'Passion'\n ],\n short_term: [\n 'Business Deal',\n 'Pleasure/Addiction',\n 'Property',\n 'Specific Object',\n 'Money',\n 'Job/Work',\n 'Love/Lust/Desire',\n 'Revenge/Hate'\n ],\n secrets: [\n 'Love\u2019s another\u2019s spouse [mutual/unrequited/unexpressed]',\n 'Fled a murder rap [innocent/guilty]',\n 'Fraud at profession',\n 'Hidden vice [dope/alcohol/sex]',\n 'Secret child in town',\n 'Ran with a bad bunch of hombres',\n 'Owes a lot of money / Broke',\n 'Hallucinatory visions [religious/psychotic]'\n ]\n }\n },\n {\n id: 6,\n key: 'relationships',\n title: 'NPC Relationships',\n tables: {\n default: [\n { label: 'Hate', weight: 1 },\n { label: 'Dislike', weight: 5 },\n { label: 'Suspicious', weight: 7 },\n { label: 'Neutral', weight: 10 },\n { label: 'Like', weight: 7 },\n { label: 'Friend', weight: 5 },\n { label: 'Love', weight: 1 }\n ],\n specific: [\n 'Lovers [current/former]',\n 'Enemies [long term/recent/former]',\n 'Rivalry [business/love]',\n 'Loaner/Debtor',\n 'Comrades [current/former] [business/army/mines/banditry/cowboys]',\n 'Employer/Employee [current/former]',\n 'Family [happy/secret/estranged]'\n ],\n faction: [\n 'Community leaders (business owners)',\n 'Pious church goers',\n 'Miners/Loggers [union]',\n 'Ranchers',\n 'The Law (sheriff, deputies, judges, posse members, etc.)',\n 'Homesteaders',\n 'Bandits'\n ]\n }\n },\n {\n id: 7,\n key: 'events',\n title: 'Events',\n tables: {\n regular: [\n 'Wedding [jealousy/drunken revelry]',\n 'Funeral [murder/inheritance]',\n 'Market day [theft/rivalry/strangers]',\n 'Holiday',\n 'Arrival [stage/train]',\n 'Sunday services',\n 'Payday at the [mine/ranch/camp]'\n ],\n crimes: [\n 'Drunken brawl',\n 'Murder',\n 'Theft',\n 'Kidnapping',\n 'Bandit raid',\n 'Shootout',\n '[Stage/train] ambushed',\n 'Arson'\n ],\n natural: [\n 'Resource Depletion',\n 'Sickness',\n 'Rainstorm',\n 'Windstorm',\n 'Fire',\n 'Wild animals'\n ],\n other: [\n 'Territorial dispute [ranchers/farmers/both]',\n 'Heartless capitalist tries to run thing',\n 'A dark past catches up with someone',\n 'Mine collapse/Logging accident',\n 'Election',\n 'Workers strike',\n 'Lynch mob',\n 'New business opens',\n 'Square dance'\n ]\n }\n },\n {\n id: 8,\n key: 'stranger',\n title: 'A Stranger Comes to Town',\n tables: {\n default: [\n 'Gunslinger',\n 'Pinkerton Detective',\n 'Itinerant Preacher',\n '[Son/father/daughter/lover] thought to be dead',\n 'Family member with a [problem/past/secret]',\n 'Ex-con [stranger/relative/old friend]',\n 'Snake Oil Salesman',\n 'Rabblerouser',\n 'Swindler [man/woman/couple/family]',\n 'Rich [worldly/naive] [man/couple/woman] from back East',\n 'Bandit [with/out] his gang',\n 'Family looking to settle',\n 'Destitute men looking for work',\n 'Former soldiers [hungry/crazed/in pursuit/pursued]',\n 'Bounty hunter with a [recent/old] warrant for [townsperson/bandit/gunslinger]',\n 'Traveling salesman',\n '[Troublesome/pitiful] [man/woman] comes to get [family/friend] out of jail',\n 'Politician [campaigning/canvassing]',\n 'Woman fleeing [fiance/husband]',\n 'Travelling Troupe of Actors'\n ]\n }\n },\n {\n id: 10,\n key: 'items',\n title: 'Items',\n tables: {\n default: [\n { label: 'weapons', subtable: 'weapons', print: true },\n { label: 'valuables', subtable: 'valuables', print: true },\n { label: 'clothes', subtable: 'clothes', print: true },\n { label: 'consumables', subtable: 'consumables', print: true },\n { label: 'papers', subtable: 'papers', print: true },\n { label: 'other', subtable: 'other', print: true }\n ],\n weapons: [\n 'Famous gunslinger\u2019s pistol',\n 'Knife',\n 'Gun [shotgun/pistol/rifle]',\n 'Bandolier of bullets',\n 'Cavalry Sword',\n 'Ax',\n 'Whip'\n ],\n valuables: [\n 'Wedding band of [live/dead] spouse',\n 'Thoroughbred horse',\n 'Unopened bottle of imported liquor',\n 'Wallet of bills',\n 'Pouch of gold',\n 'Combination to safe on a photo',\n 'Crucifix'\n ],\n clothes: [\n 'Hat [lady\u2019s/man\u2019s] [fine/plain]',\n 'Boots [new/muddy/decorative]',\n 'Dress [fancy/torn/bloodied]',\n 'Shirt [fancy/bloodstained/torn]',\n 'Gun belt',\n 'Earrings [plain/bejeweled]'\n ],\n consumables: [\n 'Bottle of whisky',\n 'Jerky',\n 'Tobacco pouch and rolling papers',\n 'Canned peaches',\n 'Sweet buns',\n 'Wine bottle'\n ],\n papers: [\n 'Newspaper [local/nearby /far]',\n 'Deed to mines',\n 'Arrest warrant',\n 'Letter [incriminating/sentimental]',\n 'Dime novel',\n 'Daguerrotype'\n ],\n other: [\n 'Dice [loaded]',\n 'Playing cards [fresh/used]',\n 'Keys to [house/business/lockbox/jail]',\n 'Hammer [nails]',\n 'Pipe and matches',\n 'Lantern'\n ]\n }\n },\n {\n id: 9,\n key: 'town_landscape',\n title: 'Landscape Prominent Feature',\n tables: {\n default: [\n 'Town build on the banks of a winding stream crossed by makeshift bridges.',\n 'Town build upon rocky outcrops, street(s) wind back and forth, buildings are all at different levels.',\n 'Town grew around a single giant tree, the rest of the land is flat and barren.',\n 'Town sits in a narrow valley, overlooked by ridges, main road snakes down to town and then back up and out.',\n 'Town built at foot of cliff where the first mine was found.',\n 'Town expanded from a small waterfall and pool amongst tall evergreens.'\n ]\n }\n },\n {\n id: 11,\n key: 'dressing',\n title: 'Set Dressing',\n display_opt: [\n { table: 'outside', hide_table: true },\n { table: 'inside', hide_table: true }\n ],\n tables: {\n outside: [\n 'Balconies',\n 'Boardwalks',\n 'Hitching posts',\n 'Water troughs',\n 'Fences',\n 'Barrels',\n 'Mud Puddles',\n 'Hand scrawled signs',\n 'Water wagon',\n 'Log bridges',\n 'Water wheels',\n 'Framed out buildings',\n 'Tents',\n 'Horses and Wagons',\n 'Posters (Wanted, Ads, Broadsheets)'\n ],\n inside: [\n 'Piano',\n 'Billiard table',\n 'Dart board',\n 'Music box',\n 'Spittoons',\n 'Bed pans',\n 'Paintings [landscape/pretty woman/historical figure]',\n 'Mismatched chairs',\n 'Makeshift tables',\n 'Ladders',\n 'Heavy curtains',\n 'Wash tubs',\n 'Valise filled with dresses',\n 'Old Clock',\n 'Brightly upholstered chair/couch',\n 'Crystal decanter filled with whiskey'\n ]\n }\n },\n {\n id: 1,\n key: 'locations',\n title: 'Locations Outside of Town',\n tables: {\n default: [\n 'Train [in motion/broken down/stopped by blocked tracks]',\n 'Family Farm [abandoned/prospering/failing]',\n 'Cattle Ranch',\n 'Mine [abandoned/active]',\n 'Grazing land [disputed]',\n 'River [rapids]',\n 'Rocky hills',\n 'Deep woods',\n 'Religious camp',\n 'Bandit camp',\n 'Log cabin [abandoned/hideout/hermit]'\n ]\n }\n },\n {\n id: 2,\n key: 'resources',\n title: 'Settlement Resources',\n tables: {\n default: [\n 'Gold',\n 'Lumber',\n 'Farmland',\n 'Water',\n 'Railway',\n 'Furs/Game'\n ]\n }\n },\n {\n id: 12,\n key: 'town_name',\n title: 'Town Names',\n display_opt: [\n { table: 'main', hide_table: true },\n { table: 'ending1', hide_table: true },\n { table: 'ending2', hide_table: true }\n ],\n tables: {\n default: [\n { label: '{{table:this:main}}{{table:this:ending1}}', weight: 4 },\n { label: '{{table:this:main}} {{table:this:ending2}}', weight: 4 },\n { label: 'Fort {{table:this:main}}', weight: 1 }\n ],\n main: [\n 'Hadley',\n 'Smith',\n 'Adams',\n 'Snake',\n 'Elk',\n 'Fire',\n 'Coal',\n 'Oak',\n 'Maple',\n 'Elm',\n 'Wilder',\n 'Jackson',\n 'Washington',\n 'Revere',\n 'Franklin',\n 'Shallow',\n 'Rapid',\n 'Gold',\n 'Summer',\n 'Spring',\n 'Nugget',\n 'Mary'\n ],\n ending1: [\n 'ville',\n 'town',\n 'berg',\n 'woods'\n ],\n ending2: [\n 'Hollow',\n 'Hills',\n 'City',\n 'Falls',\n 'Rapids'\n ]\n }\n }\n];\n", "export default [\n {\n key: 'western',\n label: 'Western',\n male: [\n 'Alan',\n 'Conan',\n 'Daveth',\n 'Denzel',\n 'Derrick',\n 'Hammitt',\n 'Jermyn',\n 'Jory',\n 'Merryn',\n 'Pasco',\n 'Tomas',\n 'Trelawney',\n 'Tremayne',\n 'Tristan',\n 'Abel',\n 'Abraham',\n 'Adam',\n 'Alan',\n 'Albert',\n 'Alex',\n 'Alexandre',\n 'Alfred',\n 'Alphonse',\n 'Anatole',\n 'Andr\u00E9',\n 'Anselme',\n 'Armand',\n 'Arthur',\n 'Auguste',\n 'Barnabus',\n 'Benjamin',\n 'Bernard',\n 'Bertrand',\n 'Blaise',\n 'Brice',\n 'Bruno',\n 'C\u00E9sar',\n 'Charles',\n 'Christian',\n 'Christophe',\n 'Claude',\n 'Cyril',\n 'Damien',\n 'Dan',\n 'Daniel',\n 'David',\n 'Denis',\n 'Didier',\n 'Dorian',\n 'Edgar',\n '\u00C9mile',\n 'Emmanuel',\n 'Ernest',\n 'Ethan',\n '\u00C9tienne',\n 'Eug\u00E8ne',\n 'Fabien',\n 'F\u00E9lix',\n 'Ferdinand',\n 'Florent',\n 'Francis',\n 'Frank',\n 'Fred',\n 'Gabriel',\n 'Gaspard',\n 'Geoffrey',\n 'Georges',\n 'G\u00E9rard',\n 'Gilbert',\n 'Guillaume',\n 'Gustave',\n 'Guy',\n 'Hector',\n 'Hercule',\n 'Horace',\n 'Jason',\n 'Jean',\n 'J\u00E9r\u00E9mie',\n 'J\u00E9r\u00F4me',\n 'Jess\u00E9',\n 'Jonathan',\n 'Joseph',\n 'Jules',\n 'Kevin',\n 'Laurent',\n 'L\u00E9o',\n 'L\u00E9on',\n 'L\u00E9onard',\n 'Lionel',\n 'Lou',\n 'Louis',\n 'Lucas',\n 'Manuel',\n 'Marc',\n 'Marcel',\n 'Martin',\n 'Maurice',\n 'Maxime',\n 'Micha\u00EBl',\n 'Morgan',\n 'Nathan',\n 'Nicolas',\n 'Odilon',\n 'Oscar',\n 'Pascal',\n 'Patrick',\n 'Paul',\n 'Philippe',\n 'Pierre',\n 'Raoul',\n 'Rapha\u00EBl',\n 'Raymond',\n 'R\u00E9gis',\n 'Richard',\n 'Robert',\n 'Roger',\n 'Roland',\n 'Ruben',\n 'Samson',\n 'Samuel',\n 'S\u00E9bastien',\n 'Serge',\n 'Simon',\n 'Th\u00E9o',\n 'Th\u00E9odore',\n 'Th\u00E9ophile',\n 'Thomas',\n 'Tristan',\n 'Ulysse',\n 'Valentin',\n 'Victor',\n 'Vincent',\n 'Xavier',\n 'Yves',\n 'Abe',\n 'Abraham',\n 'Adam',\n 'Albert',\n 'Alex',\n 'Alexander',\n 'Alfred',\n 'Aloysius',\n 'Andreas',\n 'Anton',\n 'Arthur',\n 'Augustus',\n 'Bart',\n 'Ben',\n 'Benjamin',\n 'Bernhard',\n 'Bert',\n 'Bob',\n 'Bram',\n 'Brecht',\n 'Casper',\n 'Chris',\n 'Christiaan',\n 'Cornelius',\n 'Damian',\n 'Dani\u00EBl',\n 'David',\n 'Dennis',\n 'Dick',\n 'Dirk',\n 'Ed',\n 'Edwin',\n 'Erik',\n 'Ernst',\n 'Erwin',\n 'Fabian',\n 'Felix',\n 'Ferdinand',\n 'Filip',\n 'Frank',\n 'Fred',\n 'Frederik',\n 'Gerard',\n 'Gerhard',\n 'Gerrit',\n 'Gerry',\n 'Gilbert',\n 'Gustaaf',\n 'Hans',\n 'Hendrik',\n 'Herman',\n 'Hieronymus',\n 'Hubert',\n 'Hugo',\n 'Jacob',\n 'Jan',\n 'Jasper',\n 'Jef',\n 'Jesse',\n 'Jonas',\n 'Jonathan',\n 'Jordan',\n 'Karel',\n 'Kasper',\n 'Kevin',\n 'Lambert',\n 'Lars',\n 'Leo',\n 'Leonard',\n 'Leopold',\n 'Levi',\n 'Louis',\n 'Lucas',\n 'Marcel',\n 'Marco',\n 'Mark',\n 'Martin',\n 'Max',\n 'Michael',\n 'Mick',\n 'Nick',\n 'Nico',\n 'Olaf',\n 'Oliver',\n 'Otto',\n 'Pascal',\n 'Paul',\n 'Peter',\n 'Philip',\n 'Rembrandt',\n 'Richard',\n 'Rob',\n 'Robert',\n 'Robin',\n 'Roy',\n 'Ruben',\n 'Rudolf',\n 'Rupert',\n 'Rutger',\n 'Sebastian',\n 'Simon',\n 'Stefan',\n 'Steven',\n 'Sven',\n 'Theo',\n 'Thomas',\n 'Tim',\n 'Tom',\n 'Vincent',\n 'Werner',\n 'Willem',\n 'Willy',\n 'Xander',\n 'Adam',\n 'Adolf',\n 'Arnold',\n 'Bern',\n 'Baldwin',\n 'Conrad',\n 'Constantin',\n 'Egmund',\n 'Eric',\n 'Finn',\n 'Franco',\n 'Gerald',\n 'Gregorio',\n 'Gunther',\n 'Henryk',\n 'Herman',\n 'Hubert',\n 'Isaac',\n 'Johannes',\n 'Knut',\n 'Norbert',\n 'Otto',\n 'Rainer',\n 'Richard',\n 'Rupert',\n 'Rutger',\n 'Simon',\n 'Stefan',\n 'Waldo',\n 'Walther',\n 'Willem',\n 'akira',\n 'goro',\n 'haruki',\n 'ichiro',\n 'jiro',\n 'ken',\n 'ren',\n 'shin',\n 'shiro',\n 'takashi',\n 'Aar\u00F3n',\n 'Abel',\n 'Alberto',\n 'Albino',\n 'Alcides',\n 'Alejandro',\n 'Alejo',\n '\u00C1lex',\n 'Alexis',\n 'Alfonso',\n 'Alfredo',\n 'Alonso',\n '\u00C1lvaro',\n 'Amado',\n 'Amador',\n 'Anastacio',\n 'Andr\u00E9s',\n '\u00C1ngel',\n 'Armando',\n 'Arsenio',\n 'Arturo',\n 'Baldo',\n 'Bartolom\u00E9',\n 'Bautista',\n 'Benito',\n 'Benjam\u00EDn',\n 'Bernardo',\n 'Berto',\n 'Bol\u00EDvar',\n 'Bonifacio',\n 'Bruno',\n 'Buenaventura',\n 'Carlito',\n 'Carlos',\n 'Carmelo',\n 'C\u00E9sar',\n 'Che',\n 'Chuy',\n 'Clemente',\n 'Crist\u00F3bal',\n 'Dar\u00EDo',\n 'Diego',\n 'Domingo',\n 'Edgardo',\n 'Eduardo',\n 'Eladio',\n 'El\u00EDas',\n 'Emiliano',\n 'Emilio',\n 'Enrique',\n 'Esteban',\n 'Evaristo',\n 'Fabio',\n 'Fabricio',\n 'Faustino',\n 'Feliciano',\n 'Felipe',\n 'F\u00E9lix',\n 'Fernando',\n 'Fidel',\n 'Flavio',\n 'Flori\u00E1n',\n 'Francisco',\n 'Gabriel',\n 'Gast\u00F3n',\n 'Geraldo',\n 'Gerardo',\n 'Gonzalo',\n 'Guadalupe',\n 'Guillermo',\n 'Gustavo',\n 'Gutierre',\n 'H\u00E9ctor',\n 'Hern\u00E1n',\n 'Hernando',\n 'Hugo',\n 'Ignacio',\n 'Isaac',\n 'Isidoro',\n 'Jaime',\n 'Javier',\n 'Jes\u00FAs',\n 'Joaquin',\n 'Joel',\n 'Jorge',\n 'Jose',\n 'Jos\u00E9 Antonio',\n 'Jos\u00E9 Luis',\n 'Jos\u00E9 Manuel',\n 'Juan',\n 'Juan Carlos',\n 'Juan Manuel',\n 'Juan Pablo',\n 'Julio',\n 'Leonardo',\n 'Lorenzo',\n 'Luciano',\n 'Lucio',\n 'Luis',\n 'Lupe',\n 'Manolo',\n 'Manuel',\n 'Marco',\n 'Mariano',\n 'Mario',\n 'Mateo',\n 'Miguel',\n 'Nacho',\n 'N\u00E9stor',\n 'Octavio',\n '\u00D3scar',\n 'Pablo',\n 'Paco',\n 'Pancho',\n 'Pedro',\n 'Pepe',\n 'Pl\u00E1cido',\n 'Rafael',\n 'Ram\u00F3n',\n 'Ra\u00FAl',\n 'Reynaldo',\n 'Ricardo',\n 'Roberto',\n 'Rodrigo',\n 'Salvador',\n 'Samuel',\n 'Sancho',\n 'Santos',\n 'Sergio',\n 'Severino',\n 'Silvio',\n 'Sim\u00F3n',\n 'Tito',\n 'Tom\u00E1s',\n 'Valent\u00EDn',\n 'Vicente',\n 'V\u00EDctor',\n 'Wilfredo'\n ],\n female: [\n 'Adela',\n 'Agatha',\n 'Agnes',\n 'Ava',\n 'Benedicta',\n 'Berta',\n 'Gertrude',\n 'Helena',\n 'Olge',\n 'Sophia',\n 'Susanne',\n 'Yolande',\n 'Agnes',\n 'Albertina',\n 'Alexandra',\n 'Amanda',\n 'Amber',\n 'Amelia',\n 'Angela',\n 'Angelina',\n 'Angelique',\n 'Anita',\n 'Anna',\n 'Annabel',\n 'Anne',\n 'Annemarie',\n 'Antonia',\n 'Augusta',\n 'Beatrix',\n 'Brigitta',\n 'Carla',\n 'Caroline',\n 'Catharina',\n 'Cecilia',\n 'Charlotte',\n 'Christina',\n 'Christine',\n 'Claudia',\n 'C\u00E9cile',\n 'Daphne',\n 'Debora',\n 'Denise',\n 'Diana',\n 'Dora',\n 'Dorothea',\n 'Edith',\n 'Elisabeth',\n 'Elise',\n 'Ellen',\n 'Emma',\n 'Esther',\n 'Eva',\n 'Eveline',\n 'Felicia',\n 'Georgina',\n 'Gertie',\n 'Gertrude',\n 'Hanna',\n 'Hannah',\n 'Helena',\n 'Henrietta',\n 'Henriette',\n 'Hilda',\n 'Hilde',\n 'Ida',\n 'Irena',\n 'Iris',\n 'Isabella',\n 'Isabelle',\n 'Jetta',\n 'Johanna',\n 'Julia',\n 'Juliana',\n 'Justine',\n 'Karen',\n 'Katrina',\n 'Lara',\n 'Laura',\n 'Laurie',\n 'Linda',\n 'Lisa',\n 'Louisa',\n 'Louise',\n 'Magda',\n 'Magdalena',\n 'Maria',\n 'Marianne',\n 'Marilou',\n 'Maud',\n 'Melissa',\n 'Mia',\n 'Michelle',\n 'Mina',\n 'Nicole',\n 'Nicolet',\n 'Nora',\n 'Paula',\n 'Petra',\n 'Rachel',\n 'Rebekka',\n 'Renate',\n 'Ren\u00E9e',\n 'Rosa',\n 'Rosanne',\n 'Samantha',\n 'Sandra',\n 'Sara',\n 'Saskia',\n 'Sophie',\n 'Susanna',\n 'Tina',\n 'Trudy',\n 'Ursula',\n 'Vanessa',\n 'Vera',\n 'Willemina',\n 'Wilma',\n 'Yvonne',\n 'Zo\u00EB',\n 'Eva',\n 'Jenna',\n 'Gwen',\n 'Gwenneth',\n 'Gwynne',\n 'Jena',\n 'Kerra',\n 'Lowenna',\n 'Merryn',\n 'Pasca',\n 'Tamsin',\n 'Tressa',\n 'Ad\u00E9la\u00EFde',\n 'Adeline',\n 'Agn\u00E8s',\n 'Alberte',\n 'Albertine',\n 'Alex',\n 'Alexandra',\n 'Alexandrine',\n 'Alexis',\n 'Alice',\n 'Alix',\n 'Ana\u00EFs',\n 'Anastasie',\n 'Angeline',\n 'Ang\u00E9lique',\n 'Anna',\n 'Annabelle',\n 'Anne',\n 'Annette',\n 'Annie',\n 'Antoinette',\n 'Ariel',\n 'Astrid',\n 'Augustine',\n 'Aurore',\n 'Babette',\n 'Barbara',\n 'B\u00E9atrice',\n 'B\u00E9r\u00E9nice',\n 'Bernadette',\n 'Berthe',\n 'Blanche',\n 'Brigitte',\n 'Camille',\n 'Caroline',\n 'Cassandra',\n 'Catherine',\n 'C\u00E9cile',\n 'C\u00E9leste',\n 'Charlotte',\n 'Chlo\u00E9',\n 'Christine',\n 'Claire',\n 'Clarisse',\n 'Claudette',\n 'Cl\u00E9mentine',\n 'Colette',\n 'Constance',\n 'Danielle',\n 'Daphn\u00E9',\n 'Daphn\u00E9e',\n 'Denise',\n 'Diane',\n 'Dominique',\n '\u00C9dith',\n 'El\u00E9onore',\n '\u00C9lisabeth',\n '\u00C9lo\u00EFse',\n 'Emma',\n 'Emmanuelle',\n 'Ernestine',\n 'Estelle',\n 'Esther',\n '\u00C8ve',\n 'Eveline',\n 'Fanny',\n 'F\u00E9licit\u00E9',\n 'Fifi',\n 'Florence',\n 'Florentine',\n 'Francine',\n 'Francis',\n 'Gabrielle',\n 'Genevi\u00E8ve',\n 'Georgette',\n 'Georgine',\n 'Gigi',\n 'Gilberte',\n 'Gwendoline',\n 'Hannah',\n 'Henriette',\n 'Hortense',\n 'Ir\u00E8ne',\n 'Iris',\n 'Isabelle',\n 'Jacqueline',\n 'Jeanette',\n 'Jeanine',\n 'Jessica',\n 'Joanne',\n 'Jos\u00E9phine',\n 'Judith',\n 'Juliane',\n 'Julie',\n 'Juliette',\n 'Justine',\n 'Lili',\n 'Lilian',\n 'Linda',\n 'Louise',\n 'Lucille',\n 'Madeleine',\n 'Margot',\n 'Marianne',\n 'Marie',\n 'Marilou',\n 'Marthe',\n 'M\u00E9lissa',\n 'M\u00E9lody',\n 'Michelle',\n 'Modeste',\n 'Monique',\n 'Muriel',\n 'Nadine',\n 'Nathalie',\n 'Nicole',\n 'Nina',\n 'Pauline',\n 'P\u00E9n\u00E9lope',\n 'Rachel',\n 'R\u00E9becca',\n 'Ren\u00E9e',\n 'Rosalie',\n 'Rose',\n 'Rosette',\n 'Roxanne',\n 'Sandra',\n 'Sara',\n 'Sarah',\n 'Sophie',\n 'St\u00E9phanie',\n 'Suzanne',\n 'Suzette',\n 'Sylvie',\n 'Valentine',\n 'Violette',\n 'Virginie',\n 'Wanda',\n 'akemi',\n 'aki',\n 'akiko',\n 'akira',\n 'aya',\n 'chiyo',\n 'hana',\n 'hanako',\n 'haruka',\n 'hitomi',\n 'kasumi',\n 'keiko',\n 'mai',\n 'mariko',\n 'michiko',\n 'mitsuko',\n 'nana',\n 'naomi',\n 'natsumi',\n 'noriko',\n 'ren',\n 'rina',\n 'sakura',\n 'setsuko',\n 'yoko',\n 'Abiga\u00EDl',\n 'Adelaida',\n 'Adriana',\n 'Alexandra',\n 'Alexis',\n 'Alicia',\n 'Alma',\n 'Amada',\n 'Amanda',\n 'Am\u00E9rica',\n 'Ana',\n 'Anabel',\n 'Ana Mar\u00EDa',\n 'Ana Sof\u00EDa',\n 'Anastasia',\n 'Andrea',\n '\u00C1ngela',\n 'Ang\u00E9lica',\n 'Angelina',\n 'Anita',\n 'Ariel',\n 'Aurelia',\n 'Beatriz',\n 'Berta',\n 'Blanca',\n 'Camila',\n 'Carla',\n 'Carmen',\n 'Carolina',\n 'Clara',\n 'Clementina',\n 'Conchita',\n 'Consuela',\n 'Cristina',\n 'Dalia',\n 'Delia',\n 'Diana',\n 'Dolores',\n 'Dominga',\n 'Dora',\n 'Dulce',\n 'Elena',\n 'Elisa',\n 'Elodia',\n 'Elo\u00EDsa',\n 'Emilia',\n 'Emma',\n 'Encarnita',\n 'Esmeralda',\n 'Esperanza',\n 'Esther',\n 'Eulalia',\n 'Eva',\n 'Eva Mar\u00EDa',\n 'Evangelina',\n 'Evita',\n 'Fanny',\n 'F\u00E1tima',\n 'Felicia',\n 'Felipa',\n 'Flora',\n 'Florentina',\n 'Fran',\n 'Francisca',\n 'Gabriela',\n 'Georgina',\n 'Gertrudis',\n 'Gisela',\n 'Gloria',\n 'Guadalupe',\n 'Hayd\u00E9e',\n 'Hilda',\n 'In\u00E9s',\n 'Irene',\n 'Iris',\n 'Irma',\n 'Isabela',\n 'Isidora',\n 'Jenifer',\n 'Jennifer',\n 'Jenny',\n 'Jessica',\n 'Johana',\n 'Josefina',\n 'Juanita',\n 'Judith',\n 'Julia',\n 'Julieta',\n 'Justina',\n 'Laura',\n 'Leandra',\n 'Leticia',\n 'Liliana',\n 'Lola',\n 'Lolita',\n 'Luna',\n 'Lupe',\n 'Magdalena',\n 'Marcela',\n 'Marcia',\n 'Margarita',\n 'Mar\u00EDa',\n 'Mar\u00EDa Carmen',\n 'Mar\u00EDa Cristina',\n 'Mar\u00EDa Dolores',\n 'Mar\u00EDa Fernanda',\n 'Mar\u00EDa Guadalupe',\n 'Mar\u00EDa Jes\u00FAs',\n 'Mar\u00EDa Jos\u00E9',\n 'Mar\u00EDa Luisa',\n 'Mar\u00EDa Manuela',\n 'Mariana',\n 'Mar\u00EDa Teresa',\n 'Marisa',\n 'Maritza',\n 'Marta',\n 'Matilde',\n 'Mercedes',\n 'Miriam',\n 'Modesta',\n 'M\u00F3nica',\n 'Nadia',\n 'Natalia',\n 'Octavia',\n 'Ofelia',\n 'Olga',\n 'Olivia',\n 'Oriana',\n 'Paloma',\n 'Paola',\n 'Patricia',\n 'Paula',\n 'Paulina',\n 'Paz',\n 'Perla',\n 'Perlita',\n 'Pilar',\n 'Priscila',\n 'Ramona',\n 'Raquel',\n 'Regina',\n 'Remedios',\n 'Renata',\n 'Rita',\n 'Roberta',\n 'Rosa',\n 'Rosario',\n 'Ruth',\n 'Sandra',\n 'Sara',\n 'Selena',\n 'Silvia',\n 'Sof\u00EDa',\n 'Soledad',\n 'Susana',\n 'Tamara',\n 'Teresa',\n '\u00DArsula',\n 'Valentina',\n 'Valeria',\n 'Vera',\n 'Ver\u00F3nica',\n 'Victoria',\n 'Violeta',\n 'Virginia',\n 'Viviana',\n 'Yasmina',\n 'Yolanda'\n ],\n surname: [\n 'Ahearn',\n 'Bell',\n 'Berryman',\n 'Boden',\n 'Bray',\n 'Brock',\n 'Burrows',\n 'Connor',\n 'Craddick',\n 'Crocker',\n 'Deane',\n 'Drew',\n 'Evans',\n 'Fry',\n 'Gay',\n 'Godden',\n 'Goldsworthy',\n 'Hancock',\n 'Hart',\n 'Harvey',\n 'Hawke',\n 'Hoskins',\n 'Hutchens',\n 'James',\n 'Jewell',\n 'Johns',\n 'Kemp',\n 'Kent',\n 'Kinsey',\n 'Kirby',\n 'Lowry',\n 'Lean',\n 'Lyon',\n 'May',\n 'Moon',\n 'Nance',\n 'Nicholls',\n 'Oates',\n 'Pawley',\n 'Perrin',\n 'Phillips',\n 'Quick',\n 'Rickard',\n 'Roach',\n 'Roberts',\n 'Rodgers',\n 'Sanders',\n 'Symons',\n 'Stevens',\n 'Thorne',\n 'Warren',\n 'Franke',\n 'Peeters',\n 'Aaldenberg',\n 'Aalders',\n 'Abram',\n 'Abrams',\n 'Acker',\n 'Addens',\n 'Adema',\n 'Ahlers',\n 'Akkerman',\n 'Alberda',\n 'Alberdink',\n 'Albers',\n 'Alberts',\n 'Alders',\n 'Alting',\n 'Arntz',\n 'Baker',\n 'Banner',\n 'Beringer',\n 'Beulens',\n 'Boer',\n 'Boon',\n 'Bosch',\n 'Brams',\n 'Brinkerhoff',\n 'Carman',\n 'Clark',\n 'Cuyper',\n 'Dahl',\n 'Dahlman',\n 'De Witte',\n 'Dirks',\n 'Dreyer',\n 'Dykstra',\n 'Evers',\n 'Franke',\n 'Haas',\n 'Hansen',\n 'Hendrix',\n 'Herberts',\n 'Herman',\n 'Heyman',\n 'Holt',\n 'Hummel',\n 'Jacobs',\n 'Jacobson',\n 'Jansen',\n 'Jansing',\n 'Karl',\n 'King',\n 'Klein',\n 'Koning',\n 'Krantz',\n 'Lucas',\n 'Lyon',\n 'Michel',\n 'Miller',\n 'Moore',\n 'Nagel',\n 'Peeters',\n 'Peters',\n 'Philips',\n 'Richard',\n 'Robert',\n 'Roosevelt',\n 'Samson',\n 'Schneider',\n 'Schuyler',\n 'Schwarzenberg',\n 'Seeger',\n 'Smith',\n 'Snyder',\n 'Thomas',\n 'Van Aalsburg',\n 'Van Buren',\n 'Van Der Beek',\n 'Van Der Veen',\n 'Van Hassel',\n 'Van Horn',\n 'Van Houte',\n 'fujimoto',\n 'hayashi',\n 'kimura',\n 'kurosawa',\n 'matsumoto',\n 'minami',\n 'suzuki',\n 'yamaguchi',\n 'Babineaux',\n 'Barre',\n 'Beaufort',\n 'Beaumont',\n 'Bellamy',\n 'Belmont',\n 'Berger',\n 'Bernard',\n 'Blanchard',\n 'Bonhomme',\n 'Borde',\n 'Charpentier',\n 'Chevalier',\n 'Colbert',\n 'Coste',\n 'David',\n 'Deforest',\n 'Delacroix',\n 'Desroches',\n 'Dubois',\n 'Duchamps',\n 'Dupont',\n 'Fabian',\n 'Favreau',\n 'Fontaine',\n 'Forest',\n 'Forestier',\n 'Fran\u00E7ois',\n 'Garcon',\n 'Germain',\n 'Giles',\n 'Granger',\n 'Hardy',\n 'Harman',\n 'Herbert',\n 'Jordan',\n 'Labelle',\n 'Lachance',\n 'Lachapelle',\n 'Lane',\n 'Lapointe',\n 'Larue',\n 'Laurent',\n 'Lebeau',\n 'Leblanc',\n 'Leclair',\n 'Leroy',\n 'Lyon',\n 'Marchand',\n 'Martel',\n 'Martin',\n 'Montagne',\n 'Mullins',\n 'Olivier',\n 'Page',\n 'Pettigrew',\n 'Pierre',\n 'Renaud',\n 'Robert',\n 'Roche',\n 'Rose',\n 'Roy',\n 'Salmon',\n 'Samson',\n 'Sargent',\n 'Sauvage',\n 'Segal',\n 'S\u00E9verin',\n 'Simon',\n 'Thayer',\n 'Thomas',\n 'Tolbert',\n 'Travers',\n 'Tremblay',\n 'Vincent',\n 'Abel',\n 'Abraham',\n 'Acosta',\n 'Aguilar',\n 'Alfaro',\n 'Alonso',\n 'Alvarado',\n '\u00C1lvarez',\n 'Amador',\n 'Antonio',\n 'Ant\u00FAnez',\n 'Armando',\n 'Arriola',\n 'Asturias',\n 'Banderas',\n 'Bautista',\n 'Bello',\n 'Belmonte',\n 'Blanco',\n 'Bol\u00EDvar',\n 'Bustos',\n 'Caballero',\n 'Cabrera',\n 'Campo',\n 'Campos',\n 'Carrasco',\n 'Castellano',\n 'Castilla',\n 'Castillo',\n 'Castro',\n 'Cervantes',\n 'Col\u00F3n',\n 'Cortez',\n 'Cruz',\n 'De la Cruz',\n 'De Le\u00F3n',\n 'Delgado',\n 'Del R\u00EDo',\n 'D\u00EDaz',\n 'Dom\u00EDnguez',\n 'Escarr\u00E0',\n 'Espinosa',\n 'Espinoza',\n 'Esteban',\n 'Est\u00E9vez',\n 'Feliciano',\n 'Fern\u00E1ndez',\n 'Fierro',\n 'Figueroa',\n 'Flores',\n 'Fontana',\n 'Franco',\n 'Fuentes',\n 'Garc\u00EDa',\n 'Gaspar',\n 'Gim\u00E9nez',\n 'G\u00F3mez',\n 'Gonzales',\n 'Gonz\u00E1lez',\n 'Guti\u00E9rrez',\n 'Hern\u00E1ndez',\n 'Herrera',\n 'Hidalgo',\n 'Ibarra',\n 'Ju\u00E1rez',\n 'Le\u00F3n',\n 'Lopez',\n 'Lorenzo',\n 'Loyola',\n 'Lucas',\n 'Luna',\n 'Machado',\n 'Marino',\n 'M\u00E1rquez',\n 'Mart\u00EDn',\n 'Mart\u00EDnez',\n 'Martinez',\n 'M\u00E9ndez',\n 'Mendoza',\n 'Molina',\n 'Montero',\n 'Morales',\n 'Moralez',\n 'Mu\u00F1oz',\n 'Navarro',\n 'Olmos',\n 'Ortega',\n 'Padilla',\n 'Paz',\n 'P\u00E9rez',\n 'Perez',\n 'Quesada',\n 'Ram\u00EDrez',\n 'Ramos',\n 'Reyes',\n 'R\u00EDos',\n 'Rivera',\n 'Rodr\u00EDguez',\n 'Rodriquez',\n 'Romero',\n 'Rosales',\n 'Rosario',\n 'Rubio',\n 'Ruiz',\n 'Salamanca',\n 'Salinas',\n 'S\u00E1nchez',\n 'Sanchez',\n 'Santana',\n 'Santiago',\n 'Santos',\n 'Sierra',\n 'Silva',\n 'Torres',\n 'Valencia',\n 'Vega',\n 'Vel\u00E1squez',\n 'Vidal'\n ]\n }\n];\n", "/**\n * @prop {Object} events Store the events here. String => Array\n * @prop {Boolean} debug So you can more easily in dev see when events are triggered.\n */\nexport default class EventEmitter {\n constructor () {\n this.events = {};\n this.debug = false;\n }\n /**\n * Get index of listener in the event array.\n * -1 means it isn't there\n * @param {String} event Event to check.\n * @param {Function} listener Listener to check.\n * @return {Number}\n */\n _listenerIndex (event, listener) {\n return this.events[event].findIndex((item) => {\n return item.listener === listener;\n });\n }\n /**\n * Listen to an event\n * @param {String} event Name of the event to listen for.\n * @param {Function} listener Callback to trigger for event\n * @param {Object} boundObj Object to bind the callback to.\n * @return {Function} Function to remove the event listener.\n */\n on (event, listener, boundObj = null) {\n if (typeof listener !== 'function') {\n return;\n }\n this.events[event] = this.events[event] || [];\n if (this.events[event].length > 0) {\n const index = this._listenerIndex(event, listener);\n // Replace the listener if it already exists.\n if (index > -1) {\n this.events[event].splice(index, 1);\n }\n }\n this.events[event].push({ listener: listener, boundObj: boundObj });\n return this.off.bind(this, event, listener, boundObj);\n }\n /**\n * Stop listening to an event.\n * Remove event if it was the last listener.\n * @param {String} event Name of the event.\n * @param {Function} listener Callback to remove.\n * @return {undefined}\n */\n off (event, listener) {\n if (Array.isArray(this.events[event])) {\n const index = this._listenerIndex(event, listener);\n if (index === -1) {\n return;\n }\n this.events[event].splice(index, 1);\n if (this.events[event].length === 0) {\n delete this.events[event];\n }\n }\n }\n /**\n * Listen for an event but only trigger it once, then it is removed.\n * @param {String} event Name of the event to listen for.\n * @param {Function} listener Callback to trigger for event.\n * @param {Object} boundObj Object to bind the callback to.\n */\n once (event, listener, boundObj) {\n this.on(event, function wrap () {\n this.off(event, wrap);\n const binder = typeof boundObj === 'undefined' ? this : boundObj;\n listener.apply(binder, arguments);\n });\n }\n /**\n * Trigger an event. This will cause any listeners for that event to be called.\n * Any arguments after the event will be passed on to the callback(s).\n * @param {String} event Event to trigger.\n */\n trigger (event) {\n if (this.debug && console) {\n console.log(`EventEmitter triggered: ${event}`);\n }\n const args = [].slice.call(arguments, 1);\n\n if (Array.isArray(this.events[event])) {\n this.events[event].forEach((listenObj) => {\n const binder = listenObj.boundObj === null ? this : listenObj.boundObj;\n listenObj.listener.apply(binder, args);\n });\n }\n };\n};\n", "import TableRoller from '../../node_modules/rpg-table-randomizer/src/TableRoller.js';\nimport RandomTable from '../../node_modules/rpg-table-randomizer/src/RandomTable.js';\nimport RandomNameGenerator from '../../node_modules/rpg-table-randomizer/src/RandomNameGenerator.js';\nimport RandomNameType from '../../node_modules/rpg-table-randomizer/src/RandomNameType.js';\nimport tables from '../data/tables.js';\nimport names from '../data/names.js';\nimport { rollDie } from '../../node_modules/rpg-table-randomizer/src/dice_roller.js';\nimport EventEmitter from '../models/EventEmitter.js';\n\nconst tableEmitter = new EventEmitter();\nconst tableRoller = new TableRoller({});\nconst randomTables = {};\n\n// Format name data\nconst nameTypes = [];\nnames.forEach((data) => {\n nameTypes.push(new RandomNameType(data));\n});\n// Create a default name generator.\nconst nameGenerator = new RandomNameGenerator({ namedata: nameTypes });\n// Assign it to the name token of the table roller.\ntableRoller.registerTokenType('name', nameGenerator.nameTokenCallback.bind(nameGenerator));\n\ntables.forEach((data) => {\n const key = data.key;\n if (!key) {\n return;\n }\n randomTables[key] = new RandomTable(data);\n});\n/**\n * Get 1 table by it's key.\n * @param key {String} Table key.\n * @returns {RandomTable|null}\n */\nconst getTableByKey = function (key) {\n if (randomTables[key]) {\n return randomTables[key];\n }\n return null;\n};\ntableRoller.setTableKeyLookup(getTableByKey);\n\n/**\n * Get all tables.\n * @returns {RandomTable[]}\n */\nconst getAllTables = function () {\n const arr = [];\n Object.keys(randomTables).forEach((key) => {\n const table = randomTables[key];\n arr.push(table);\n });\n return arr;\n};\n\n/**\n * Get result for a table by its key.\n * @param key {String} table key.\n * @param {String} subtable\n * @returns {RandomTableResultSet|null}\n */\nconst getResultByTableKey = function (key, subtable = '') {\n return tableRoller.getTableResultSetByKey(key, subtable);\n};\n/**\n * Get results from a table using the whole table.\n * @param table {RandomTable}\n * @param {String} subtable\n * @returns {RandomTableResultSet|null}\n */\nconst getResultFromTable = function (table, subtable = '') {\n return tableRoller.getResultSetForTable(table, subtable);\n};\n\n/**\n * Return a name\n * @param, {String} [nameType] Name list to use.\n * @returns {String}\n */\nconst getNPCName = function (nameType) {\n return nameGenerator.selectName(nameType);\n};\n\n/**\n * Convert a token to a result string.\n * @param token RandomTable token string\n * @returns {RandomTableResultSet|RandomTableResultSet[]|DiceResult|String|Any}\n */\nconst convertToken = function (token) {\n return tableRoller.convertToken(token);\n};\n\nexport {\n getAllTables,\n getTableByKey,\n getResultByTableKey,\n getResultFromTable,\n rollDie,\n getNPCName,\n convertToken,\n tableEmitter,\n tableRoller\n};\n", "import { tableEmitter } from '../services/randomTableService.js';\n\nconst template = document.createElement('template');\ntemplate.innerHTML = `\n \n \n Hadleyville: Rules Light RPG \n \n \n \n \n Tables \n
\n \n`;\n\nclass Header extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n\n this.setAttribute('role', 'header');\n\n this.toggleButton = this.shadowRoot.querySelector('button');\n }\n\n connectedCallback () {\n tableEmitter.on('table:drawer', this._toggleOpenButton.bind(this));\n this.toggleButton.addEventListener('click', this._toggleDrawer.bind(this));\n this.shadowRoot.querySelectorAll('a').forEach((el) => {\n el.addEventListener('click', this._triggerRoute.bind(this));\n });\n }\n\n disconnectedCallback () {\n tableEmitter.off('table:drawer', this._toggleOpenButton.bind(this));\n this.toggleButton.removeEventListener('click', this._toggleDrawer.bind(this));\n this.shadowRoot.querySelectorAll('a').forEach((el) => {\n el.removeEventListener('click', this._triggerRoute.bind(this));\n });\n }\n /**\n * Trigger a route change.\n * @param {Event} ev\n */\n _triggerRoute (ev) {\n ev.preventDefault();\n const detail = {\n route: ev.target.href\n };\n // The body can't listen for clicks inside the shadowDom\n // so we have to send out a bubbling end from the component.\n // I guess theoretically we could re-send the click event, but this seems more clear.\n this.dispatchEvent(new CustomEvent('loadRoute', { bubbles: true, detail }));\n }\n /**\n * Click event on the toggle button.\n * Triggers event on emitter.\n */\n _toggleDrawer () {\n const open = !this.toggleButton.classList.contains('open');\n tableEmitter.trigger('table:drawer', { open });\n }\n /**\n * Handler for the table:drawer event.\n * @param {Boolean} open\n */\n _toggleOpenButton ({ open }) {\n if (open) {\n this.toggleButton.classList.add('open');\n return;\n }\n this.toggleButton.classList.remove('open');\n }\n};\n\nwindow.customElements.define('had-header', Header);\n\nexport default Header;\n", "const template = document.createElement('template');\ntemplate.innerHTML = `\n \n\nWritten in Mar-Apr 2021 by Derik A. Badman https://derikbadman.com Game info and updates at https://madinkbeard.itch.io/hadleyville
\n`;\n\nclass Footer extends HTMLElement {\n constructor () {\n super();\n this.attachShadow({ mode: 'open' });\n this.shadowRoot.appendChild(template.content.cloneNode(true));\n\n this.setAttribute('role', 'footer');\n }\n\n connectedCallback () {\n }\n\n disconnectedCallback () {\n\n }\n};\n\nwindow.customElements.define('had-footer', Footer);\n\nexport default Footer;\n", "var focusableSelectors = [\n 'a[href]:not([tabindex^=\"-\"])',\n 'area[href]:not([tabindex^=\"-\"])',\n 'input:not([type=\"hidden\"]):not([type=\"radio\"]):not([disabled]):not([tabindex^=\"-\"])',\n 'input[type=\"radio\"]:not([disabled]):not([tabindex^=\"-\"])',\n 'select:not([disabled]):not([tabindex^=\"-\"])',\n 'textarea:not([disabled]):not([tabindex^=\"-\"])',\n 'button:not([disabled]):not([tabindex^=\"-\"])',\n 'iframe:not([tabindex^=\"-\"])',\n 'audio[controls]:not([tabindex^=\"-\"])',\n 'video[controls]:not([tabindex^=\"-\"])',\n '[contenteditable]:not([tabindex^=\"-\"])',\n '[tabindex]:not([tabindex^=\"-\"])',\n];\n\nvar TAB_KEY = 9;\nvar ESCAPE_KEY = 27;\n\n/**\n * Define the constructor to instantiate a dialog\n *\n * @constructor\n * @param {Element} element\n */\nfunction A11yDialog(element) {\n // Prebind the functions that will be bound in addEventListener and\n // removeEventListener to avoid losing references\n this._show = this.show.bind(this);\n this._hide = this.hide.bind(this);\n this._maintainFocus = this._maintainFocus.bind(this);\n this._bindKeypress = this._bindKeypress.bind(this);\n\n this.$el = element;\n this.shown = false;\n this._id = this.$el.getAttribute('data-a11y-dialog') || this.$el.id;\n this._previouslyFocused = null;\n this._listeners = {};\n\n // Initialise everything needed for the dialog to work properly\n this.create();\n}\n\n/**\n * Set up everything necessary for the dialog to be functioning\n *\n * @param {(NodeList | Element | string)} targets\n * @return {this}\n */\nA11yDialog.prototype.create = function () {\n this.$el.setAttribute('aria-hidden', true);\n this.$el.setAttribute('aria-modal', true);\n this.$el.setAttribute('tabindex', -1);\n\n if (!this.$el.hasAttribute('role')) {\n this.$el.setAttribute('role', 'dialog');\n }\n\n // Keep a collection of dialog openers, each of which will be bound a click\n // event listener to open the dialog\n this._openers = $$('[data-a11y-dialog-show=\"' + this._id + '\"]');\n this._openers.forEach(\n function (opener) {\n opener.addEventListener('click', this._show);\n }.bind(this)\n );\n\n // Keep a collection of dialog closers, each of which will be bound a click\n // event listener to close the dialog\n this._closers = $$('[data-a11y-dialog-hide]', this.$el).concat(\n $$('[data-a11y-dialog-hide=\"' + this._id + '\"]')\n );\n this._closers.forEach(\n function (closer) {\n closer.addEventListener('click', this._hide);\n }.bind(this)\n );\n\n // Execute all callbacks registered for the `create` event\n this._fire('create');\n\n return this\n};\n\n/**\n * Show the dialog element, disable all the targets (siblings), trap the\n * current focus within it, listen for some specific key presses and fire all\n * registered callbacks for `show` event\n *\n * @param {Event} event\n * @return {this}\n */\nA11yDialog.prototype.show = function (event) {\n // If the dialog is already open, abort\n if (this.shown) {\n return this\n }\n\n // Keep a reference to the currently focused element to be able to restore\n // it later\n this._previouslyFocused = document.activeElement;\n this.$el.removeAttribute('aria-hidden');\n this.shown = true;\n\n // Set the focus to the dialog element\n moveFocusToDialog(this.$el);\n\n // Bind a focus event listener to the body element to make sure the focus\n // stays trapped inside the dialog while open, and start listening for some\n // specific key presses (TAB and ESC)\n document.body.addEventListener('focus', this._maintainFocus, true);\n document.addEventListener('keydown', this._bindKeypress);\n\n // Execute all callbacks registered for the `show` event\n this._fire('show', event);\n\n return this\n};\n\n/**\n * Hide the dialog element, enable all the targets (siblings), restore the\n * focus to the previously active element, stop listening for some specific\n * key presses and fire all registered callbacks for `hide` event\n *\n * @param {Event} event\n * @return {this}\n */\nA11yDialog.prototype.hide = function (event) {\n // If the dialog is already closed, abort\n if (!this.shown) {\n return this\n }\n\n this.shown = false;\n this.$el.setAttribute('aria-hidden', 'true');\n\n // If there was a focused element before the dialog was opened (and it has a\n // `focus` method), restore the focus back to it\n // See: https://github.com/KittyGiraudel/a11y-dialog/issues/108\n if (this._previouslyFocused && this._previouslyFocused.focus) {\n this._previouslyFocused.focus();\n }\n\n // Remove the focus event listener to the body element and stop listening\n // for specific key presses\n document.body.removeEventListener('focus', this._maintainFocus, true);\n document.removeEventListener('keydown', this._bindKeypress);\n\n // Execute all callbacks registered for the `hide` event\n this._fire('hide', event);\n\n return this\n};\n\n/**\n * Destroy the current instance (after making sure the dialog has been hidden)\n * and remove all associated listeners from dialog openers and closers\n *\n * @return {this}\n */\nA11yDialog.prototype.destroy = function () {\n // Hide the dialog to avoid destroying an open instance\n this.hide();\n\n // Remove the click event listener from all dialog openers\n this._openers.forEach(\n function (opener) {\n opener.removeEventListener('click', this._show);\n }.bind(this)\n );\n\n // Remove the click event listener from all dialog closers\n this._closers.forEach(\n function (closer) {\n closer.removeEventListener('click', this._hide);\n }.bind(this)\n );\n\n // Execute all callbacks registered for the `destroy` event\n this._fire('destroy');\n\n // Keep an object of listener types mapped to callback functions\n this._listeners = {};\n\n return this\n};\n\n/**\n * Register a new callback for the given event type\n *\n * @param {string} type\n * @param {Function} handler\n */\nA11yDialog.prototype.on = function (type, handler) {\n if (typeof this._listeners[type] === 'undefined') {\n this._listeners[type] = [];\n }\n\n this._listeners[type].push(handler);\n\n return this\n};\n\n/**\n * Unregister an existing callback for the given event type\n *\n * @param {string} type\n * @param {Function} handler\n */\nA11yDialog.prototype.off = function (type, handler) {\n var index = (this._listeners[type] || []).indexOf(handler);\n\n if (index > -1) {\n this._listeners[type].splice(index, 1);\n }\n\n return this\n};\n\n/**\n * Iterate over all registered handlers for given type and call them all with\n * the dialog element as first argument, event as second argument (if any). Also\n * dispatch a custom event on the DOM element itself to make it possible to\n * react to the lifecycle of auto-instantiated dialogs.\n *\n * @access private\n * @param {string} type\n * @param {Event} event\n */\nA11yDialog.prototype._fire = function (type, event) {\n var listeners = this._listeners[type] || [];\n var domEvent = new CustomEvent(type, { detail: event });\n\n this.$el.dispatchEvent(domEvent);\n\n listeners.forEach(\n function (listener) {\n listener(this.$el, event);\n }.bind(this)\n );\n};\n\n/**\n * Private event handler used when listening to some specific key presses\n * (namely ESCAPE and TAB)\n *\n * @access private\n * @param {Event} event\n */\nA11yDialog.prototype._bindKeypress = function (event) {\n // This is an escape hatch in case there are nested dialogs, so the keypresses\n // are only reacted to for the most recent one\n if (!this.$el.contains(document.activeElement)) return\n\n // If the dialog is shown and the ESCAPE key is being pressed, prevent any\n // further effects from the ESCAPE key and hide the dialog, unless its role\n // is 'alertdialog', which should be modal\n if (\n this.shown &&\n event.which === ESCAPE_KEY &&\n this.$el.getAttribute('role') !== 'alertdialog'\n ) {\n event.preventDefault();\n this.hide(event);\n }\n\n // If the dialog is shown and the TAB key is being pressed, make sure the\n // focus stays trapped within the dialog element\n if (this.shown && event.which === TAB_KEY) {\n trapTabKey(this.$el, event);\n }\n};\n\n/**\n * Private event handler used when making sure the focus stays within the\n * currently open dialog\n *\n * @access private\n * @param {Event} event\n */\nA11yDialog.prototype._maintainFocus = function (event) {\n // If the dialog is shown and the focus is not within a dialog element (either\n // this one or another one in case of nested dialogs) or within an element\n // with the `data-a11y-dialog-focus-trap-ignore` attribute, move it back to\n // its first focusable child.\n // See: https://github.com/KittyGiraudel/a11y-dialog/issues/177\n if (\n this.shown &&\n !event.target.closest('[aria-modal=\"true\"]') &&\n !event.target.closest('[data-a11y-dialog-ignore-focus-trap]')\n ) {\n moveFocusToDialog(this.$el);\n }\n};\n\n/**\n * Convert a NodeList into an array\n *\n * @param {NodeList} collection\n * @return {Array}\n */\nfunction toArray(collection) {\n return Array.prototype.slice.call(collection)\n}\n\n/**\n * Query the DOM for nodes matching the given selector, scoped to context (or\n * the whole document)\n *\n * @param {String} selector\n * @param {Element} [context = document]\n * @return {Array}\n */\nfunction $$(selector, context) {\n return toArray((context || document).querySelectorAll(selector))\n}\n\n/**\n * Set the focus to the first element with `autofocus` with the element or the\n * element itself\n *\n * @param {Element} node\n */\nfunction moveFocusToDialog(node) {\n var focused = node.querySelector('[autofocus]') || node;\n\n focused.focus();\n}\n\n/**\n * Get the focusable children of the given element\n *\n * @param {Element} node\n * @return {Array}\n */\nfunction getFocusableChildren(node) {\n return $$(focusableSelectors.join(','), node).filter(function (child) {\n return !!(\n child.offsetWidth ||\n child.offsetHeight ||\n child.getClientRects().length\n )\n })\n}\n\n/**\n * Trap the focus inside the given element\n *\n * @param {Element} node\n * @param {Event} event\n */\nfunction trapTabKey(node, event) {\n var focusableChildren = getFocusableChildren(node);\n var focusedItemIndex = focusableChildren.indexOf(document.activeElement);\n\n // If the SHIFT key is being pressed while tabbing (moving backwards) and\n // the currently focused item is the first one, move the focus to the last\n // focusable item from the dialog element\n if (event.shiftKey && focusedItemIndex === 0) {\n focusableChildren[focusableChildren.length - 1].focus();\n event.preventDefault();\n // If the SHIFT key is not being pressed (moving forwards) and the currently\n // focused item is the last one, move the focus to the first focusable item\n // from the dialog element\n } else if (\n !event.shiftKey &&\n focusedItemIndex === focusableChildren.length - 1\n ) {\n focusableChildren[0].focus();\n event.preventDefault();\n }\n}\n\nfunction instantiateDialogs() {\n $$('[data-a11y-dialog]').forEach(function (node) {\n new A11yDialog(node);\n });\n}\n\nif (typeof document !== 'undefined') {\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', instantiateDialogs);\n } else {\n if (window.requestAnimationFrame) {\n window.requestAnimationFrame(instantiateDialogs);\n } else {\n window.setTimeout(instantiateDialogs, 16);\n }\n }\n}\n\nexport { A11yDialog as default };\n", "import store from '../store/store.js';\nimport { createNote, updateNote, deleteNote, sortNotes, clearNotes, importNotes } from '../store/notes-reducer.js';\nimport Note from '../models/note.js';\nimport EventEmitter from '../models/EventEmitter.js';\nimport NoteDisplay from '../components/notedisplay.js';\n\n/**\n * @prop {EventEmitter}\n */\nconst emitter = new EventEmitter();\n\n/**\n * Get all notes.\n * @returns {Note[]}\n */\nconst getAll = function () {\n const notes = store.getState().notes;\n return notes.map((obj) => new Note(obj));\n};\n/**\n * Get single note.\n * @param {String} id\n * @returns {Note|null}\n */\nconst getById = function (id) {\n const notes = store.getState().notes;\n const data = notes.find((el) => el.uuid === id);\n if (data) {\n return new Note(data);\n }\n return null;\n};\n/**\n * Save a new note.\n * @param {String} mode view|edit\n * @param {Note} note\n * @returns {Note}\n */\nconst create = function (mode = 'view', note = null) {\n if (!(note instanceof Note)) {\n note = new Note({});\n }\n store.dispatch(createNote({ note: note.toJSON() }));\n emitter.trigger('note:add', {\n item: note,\n mode\n });\n return note;\n};\n\n/**\n * Update a note.\n * @param {Note} note\n */\nconst save = function (note) {\n store.dispatch(updateNote({ note: note.toJSON() }));\n emitter.trigger('note:edit', {\n item: note\n });\n};\n\nconst remove = function (uuid) {\n store.dispatch(deleteNote({ uuid }));\n emitter.trigger('note:delete', {\n id: uuid\n });\n};\n\nconst sort = function (sortUuids) {\n store.dispatch(sortNotes({ sortUuids }));\n};\n\n/**\n * Delete all the notes at once.\n */\nconst deleteAll = function () {\n store.dispatch(clearNotes());\n // probably should trigger an event here?\n};\n/**\n * Import notes.\n * @param {Note[]} notes\n */\nconst importAll = function (notes) {\n store.dispatch(importNotes({ notes }));\n notes.forEach((noteData) => {\n if (!noteData.uuid) {\n return;\n }\n const note = new Note(noteData);\n emitter.trigger('note:add', {\n item: note\n });\n });\n};\n\nconst getDisplay = function () {\n return new NoteDisplay();\n};\n\nexport {\n emitter,\n getAll,\n getById,\n create,\n save,\n sort,\n remove,\n deleteAll,\n importAll,\n getDisplay\n};\n", "const errors = {\n\t0: \"Illegal state\",\n\t1: \"Immer drafts cannot have computed properties\",\n\t2: \"This object has been frozen and should not be mutated\",\n\t3(data: any) {\n\t\treturn (\n\t\t\t\"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? \" +\n\t\t\tdata\n\t\t)\n\t},\n\t4: \"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.\",\n\t5: \"Immer forbids circular references\",\n\t6: \"The first or second argument to `produce` must be a function\",\n\t7: \"The third argument to `produce` must be a function or undefined\",\n\t8: \"First argument to `createDraft` must be a plain object, an array, or an immerable object\",\n\t9: \"First argument to `finishDraft` must be a draft returned by `createDraft`\",\n\t10: \"The given draft is already finalized\",\n\t11: \"Object.defineProperty() cannot be used on an Immer draft\",\n\t12: \"Object.setPrototypeOf() cannot be used on an Immer draft\",\n\t13: \"Immer only supports deleting array indices\",\n\t14: \"Immer only supports setting array indices and the 'length' property\",\n\t15(path: string) {\n\t\treturn \"Cannot apply patch, path doesn't resolve: \" + path\n\t},\n\t16: 'Sets cannot have \"replace\" patches.',\n\t17(op: string) {\n\t\treturn \"Unsupported patch operation: \" + op\n\t},\n\t18(plugin: string) {\n\t\treturn `The plugin for '${plugin}' has not been loaded into Immer. To enable the plugin, import and call \\`enable${plugin}()\\` when initializing your application.`\n\t},\n\t20: \"Cannot use proxies if Proxy, Proxy.revocable or Reflect are not available\",\n\t21(thing: string) {\n\t\treturn `produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${thing}'`\n\t},\n\t22(thing: string) {\n\t\treturn `'current' expects a draft, got: ${thing}`\n\t},\n\t23(thing: string) {\n\t\treturn `'original' expects a draft, got: ${thing}`\n\t},\n\t24: \"Patching reserved attributes like __proto__, prototype and constructor is not allowed\"\n} as const\n\nexport function die(error: keyof typeof errors, ...args: any[]): never {\n\tif (__DEV__) {\n\t\tconst e = errors[error]\n\t\tconst msg = !e\n\t\t\t? \"unknown error nr: \" + error\n\t\t\t: typeof e === \"function\"\n\t\t\t? e.apply(null, args as any)\n\t\t\t: e\n\t\tthrow new Error(`[Immer] ${msg}`)\n\t}\n\tthrow new Error(\n\t\t`[Immer] minified error nr: ${error}${\n\t\t\targs.length ? \" \" + args.map(s => `'${s}'`).join(\",\") : \"\"\n\t\t}. Find the full error at: https://bit.ly/3cXEKWf`\n\t)\n}\n", "import {\n\tDRAFT_STATE,\n\tDRAFTABLE,\n\thasSet,\n\tObjectish,\n\tDrafted,\n\tAnyObject,\n\tAnyMap,\n\tAnySet,\n\tImmerState,\n\thasMap,\n\tArchtype,\n\tdie\n} from \"../internal\"\n\n/** Returns true if the given value is an Immer draft */\n/*#__PURE__*/\nexport function isDraft(value: any): boolean {\n\treturn !!value && !!value[DRAFT_STATE]\n}\n\n/** Returns true if the given value can be drafted by Immer */\n/*#__PURE__*/\nexport function isDraftable(value: any): boolean {\n\tif (!value) return false\n\treturn (\n\t\tisPlainObject(value) ||\n\t\tArray.isArray(value) ||\n\t\t!!value[DRAFTABLE] ||\n\t\t!!value.constructor[DRAFTABLE] ||\n\t\tisMap(value) ||\n\t\tisSet(value)\n\t)\n}\n\nconst objectCtorString = Object.prototype.constructor.toString()\n/*#__PURE__*/\nexport function isPlainObject(value: any): boolean {\n\tif (!value || typeof value !== \"object\") return false\n\tconst proto = Object.getPrototypeOf(value)\n\tif (proto === null) {\n\t\treturn true\n\t}\n\tconst Ctor =\n\t\tObject.hasOwnProperty.call(proto, \"constructor\") && proto.constructor\n\n\tif (Ctor === Object) return true\n\n\treturn (\n\t\ttypeof Ctor == \"function\" &&\n\t\tFunction.toString.call(Ctor) === objectCtorString\n\t)\n}\n\n/** Get the underlying object that is represented by the given draft */\n/*#__PURE__*/\nexport function original(value: T): T | undefined\nexport function original(value: Drafted): any {\n\tif (!isDraft(value)) die(23, value)\n\treturn value[DRAFT_STATE].base_\n}\n\n/*#__PURE__*/\nexport const ownKeys: (target: AnyObject) => PropertyKey[] =\n\ttypeof Reflect !== \"undefined\" && Reflect.ownKeys\n\t\t? Reflect.ownKeys\n\t\t: typeof Object.getOwnPropertySymbols !== \"undefined\"\n\t\t? obj =>\n\t\t\t\tObject.getOwnPropertyNames(obj).concat(\n\t\t\t\t\tObject.getOwnPropertySymbols(obj) as any\n\t\t\t\t)\n\t\t: /* istanbul ignore next */ Object.getOwnPropertyNames\n\nexport const getOwnPropertyDescriptors =\n\tObject.getOwnPropertyDescriptors ||\n\tfunction getOwnPropertyDescriptors(target: any) {\n\t\t// Polyfill needed for Hermes and IE, see https://github.com/facebook/hermes/issues/274\n\t\tconst res: any = {}\n\t\townKeys(target).forEach(key => {\n\t\t\tres[key] = Object.getOwnPropertyDescriptor(target, key)\n\t\t})\n\t\treturn res\n\t}\n\nexport function each(\n\tobj: T,\n\titer: (key: string | number, value: any, source: T) => void,\n\tenumerableOnly?: boolean\n): void\nexport function each(obj: any, iter: any, enumerableOnly = false) {\n\tif (getArchtype(obj) === Archtype.Object) {\n\t\t;(enumerableOnly ? Object.keys : ownKeys)(obj).forEach(key => {\n\t\t\tif (!enumerableOnly || typeof key !== \"symbol\") iter(key, obj[key], obj)\n\t\t})\n\t} else {\n\t\tobj.forEach((entry: any, index: any) => iter(index, entry, obj))\n\t}\n}\n\n/*#__PURE__*/\nexport function getArchtype(thing: any): Archtype {\n\t/* istanbul ignore next */\n\tconst state: undefined | ImmerState = thing[DRAFT_STATE]\n\treturn state\n\t\t? state.type_ > 3\n\t\t\t? state.type_ - 4 // cause Object and Array map back from 4 and 5\n\t\t\t: (state.type_ as any) // others are the same\n\t\t: Array.isArray(thing)\n\t\t? Archtype.Array\n\t\t: isMap(thing)\n\t\t? Archtype.Map\n\t\t: isSet(thing)\n\t\t? Archtype.Set\n\t\t: Archtype.Object\n}\n\n/*#__PURE__*/\nexport function has(thing: any, prop: PropertyKey): boolean {\n\treturn getArchtype(thing) === Archtype.Map\n\t\t? thing.has(prop)\n\t\t: Object.prototype.hasOwnProperty.call(thing, prop)\n}\n\n/*#__PURE__*/\nexport function get(thing: AnyMap | AnyObject, prop: PropertyKey): any {\n\t// @ts-ignore\n\treturn getArchtype(thing) === Archtype.Map ? thing.get(prop) : thing[prop]\n}\n\n/*#__PURE__*/\nexport function set(thing: any, propOrOldValue: PropertyKey, value: any) {\n\tconst t = getArchtype(thing)\n\tif (t === Archtype.Map) thing.set(propOrOldValue, value)\n\telse if (t === Archtype.Set) {\n\t\tthing.delete(propOrOldValue)\n\t\tthing.add(value)\n\t} else thing[propOrOldValue] = value\n}\n\n/*#__PURE__*/\nexport function is(x: any, y: any): boolean {\n\t// From: https://github.com/facebook/fbjs/blob/c69904a511b900266935168223063dd8772dfc40/packages/fbjs/src/core/shallowEqual.js\n\tif (x === y) {\n\t\treturn x !== 0 || 1 / x === 1 / y\n\t} else {\n\t\treturn x !== x && y !== y\n\t}\n}\n\n/*#__PURE__*/\nexport function isMap(target: any): target is AnyMap {\n\treturn hasMap && target instanceof Map\n}\n\n/*#__PURE__*/\nexport function isSet(target: any): target is AnySet {\n\treturn hasSet && target instanceof Set\n}\n/*#__PURE__*/\nexport function latest(state: ImmerState): any {\n\treturn state.copy_ || state.base_\n}\n\n/*#__PURE__*/\nexport function shallowCopy(base: any) {\n\tif (Array.isArray(base)) return Array.prototype.slice.call(base)\n\tconst descriptors = getOwnPropertyDescriptors(base)\n\tdelete descriptors[DRAFT_STATE as any]\n\tlet keys = ownKeys(descriptors)\n\tfor (let i = 0; i < keys.length; i++) {\n\t\tconst key: any = keys[i]\n\t\tconst desc = descriptors[key]\n\t\tif (desc.writable === false) {\n\t\t\tdesc.writable = true\n\t\t\tdesc.configurable = true\n\t\t}\n\t\t// like object.assign, we will read any _own_, get/set accessors. This helps in dealing\n\t\t// with libraries that trap values, like mobx or vue\n\t\t// unlike object.assign, non-enumerables will be copied as well\n\t\tif (desc.get || desc.set)\n\t\t\tdescriptors[key] = {\n\t\t\t\tconfigurable: true,\n\t\t\t\twritable: true, // could live with !!desc.set as well here...\n\t\t\t\tenumerable: desc.enumerable,\n\t\t\t\tvalue: base[key]\n\t\t\t}\n\t}\n\treturn Object.create(Object.getPrototypeOf(base), descriptors)\n}\n\n/**\n * Freezes draftable objects. Returns the original object.\n * By default freezes shallowly, but if the second argument is `true` it will freeze recursively.\n *\n * @param obj\n * @param deep\n */\nexport function freeze(obj: T, deep?: boolean): T\nexport function freeze(obj: any, deep: boolean = false): T {\n\tif (isFrozen(obj) || isDraft(obj) || !isDraftable(obj)) return obj\n\tif (getArchtype(obj) > 1 /* Map or Set */) {\n\t\tobj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections as any\n\t}\n\tObject.freeze(obj)\n\tif (deep) each(obj, (key, value) => freeze(value, true), true)\n\treturn obj\n}\n\nfunction dontMutateFrozenCollections() {\n\tdie(2)\n}\n\nexport function isFrozen(obj: any): boolean {\n\tif (obj == null || typeof obj !== \"object\") return true\n\t// See #600, IE dies on non-objects in Object.isFrozen\n\treturn Object.isFrozen(obj)\n}\n", "import {\n\tImmerState,\n\tPatch,\n\tImmerScope,\n\tDrafted,\n\tAnyObject,\n\tImmerBaseState,\n\tAnyMap,\n\tAnySet,\n\tProxyType,\n\tdie\n} from \"../internal\"\n\n/** Plugin utilities */\nconst plugins: {\n\tPatches?: {\n\t\tgeneratePatches_(\n\t\t\tstate: ImmerState,\n\t\t\tbasePath: PatchPath,\n\t\t\tpatches: Patch[],\n\t\t\tinversePatches: Patch[]\n\t\t): void\n\t\tgenerateReplacementPatches_(\n\t\t\trootState: ImmerState,\n\t\t\treplacement: any,\n\t\t\tpatches: Patch[],\n\t\t\tinversePatches: Patch[]\n\t\t): void\n\t\tapplyPatches_(draft: T, patches: Patch[]): T\n\t}\n\tES5?: {\n\t\twillFinalizeES5_(scope: ImmerScope, result: any, isReplaced: boolean): void\n\t\tcreateES5Proxy_(\n\t\t\tbase: T,\n\t\t\tparent?: ImmerState\n\t\t): Drafted\n\t\thasChanges_(state: ES5ArrayState | ES5ObjectState): boolean\n\t}\n\tMapSet?: {\n\t\tproxyMap_(target: T, parent?: ImmerState): T\n\t\tproxySet_(target: T, parent?: ImmerState): T\n\t}\n} = {}\n\ntype Plugins = typeof plugins\n\nexport function getPlugin(\n\tpluginKey: K\n): Exclude {\n\tconst plugin = plugins[pluginKey]\n\tif (!plugin) {\n\t\tdie(18, pluginKey)\n\t}\n\t// @ts-ignore\n\treturn plugin\n}\n\nexport function loadPlugin(\n\tpluginKey: K,\n\timplementation: Plugins[K]\n): void {\n\tif (!plugins[pluginKey]) plugins[pluginKey] = implementation\n}\n\n/** ES5 Plugin */\n\ninterface ES5BaseState extends ImmerBaseState {\n\tassigned_: {[key: string]: any}\n\tparent_?: ImmerState\n\trevoked_: boolean\n}\n\nexport interface ES5ObjectState extends ES5BaseState {\n\ttype_: ProxyType.ES5Object\n\tdraft_: Drafted\n\tbase_: AnyObject\n\tcopy_: AnyObject | null\n}\n\nexport interface ES5ArrayState extends ES5BaseState {\n\ttype_: ProxyType.ES5Array\n\tdraft_: Drafted\n\tbase_: any\n\tcopy_: any\n}\n\n/** Map / Set plugin */\n\nexport interface MapState extends ImmerBaseState {\n\ttype_: ProxyType.Map\n\tcopy_: AnyMap | undefined\n\tassigned_: Map | undefined\n\tbase_: AnyMap\n\trevoked_: boolean\n\tdraft_: Drafted\n}\n\nexport interface SetState extends ImmerBaseState {\n\ttype_: ProxyType.Set\n\tcopy_: AnySet | undefined\n\tbase_: AnySet\n\tdrafts_: Map // maps the original value to the draft value in the new set\n\trevoked_: boolean\n\tdraft_: Drafted\n}\n\n/** Patches plugin */\n\nexport type PatchPath = (string | number)[]\n", "import {\n\tPatch,\n\tPatchListener,\n\tDrafted,\n\tImmer,\n\tDRAFT_STATE,\n\tImmerState,\n\tProxyType,\n\tgetPlugin\n} from \"../internal\"\nimport {die} from \"../utils/errors\"\n\n/** Each scope represents a `produce` call. */\n\nexport interface ImmerScope {\n\tpatches_?: Patch[]\n\tinversePatches_?: Patch[]\n\tcanAutoFreeze_: boolean\n\tdrafts_: any[]\n\tparent_?: ImmerScope\n\tpatchListener_?: PatchListener\n\timmer_: Immer\n\tunfinalizedDrafts_: number\n}\n\nlet currentScope: ImmerScope | undefined\n\nexport function getCurrentScope() {\n\tif (__DEV__ && !currentScope) die(0)\n\treturn currentScope!\n}\n\nfunction createScope(\n\tparent_: ImmerScope | undefined,\n\timmer_: Immer\n): ImmerScope {\n\treturn {\n\t\tdrafts_: [],\n\t\tparent_,\n\t\timmer_,\n\t\t// Whenever the modified draft contains a draft from another scope, we\n\t\t// need to prevent auto-freezing so the unowned draft can be finalized.\n\t\tcanAutoFreeze_: true,\n\t\tunfinalizedDrafts_: 0\n\t}\n}\n\nexport function usePatchesInScope(\n\tscope: ImmerScope,\n\tpatchListener?: PatchListener\n) {\n\tif (patchListener) {\n\t\tgetPlugin(\"Patches\") // assert we have the plugin\n\t\tscope.patches_ = []\n\t\tscope.inversePatches_ = []\n\t\tscope.patchListener_ = patchListener\n\t}\n}\n\nexport function revokeScope(scope: ImmerScope) {\n\tleaveScope(scope)\n\tscope.drafts_.forEach(revokeDraft)\n\t// @ts-ignore\n\tscope.drafts_ = null\n}\n\nexport function leaveScope(scope: ImmerScope) {\n\tif (scope === currentScope) {\n\t\tcurrentScope = scope.parent_\n\t}\n}\n\nexport function enterScope(immer: Immer) {\n\treturn (currentScope = createScope(currentScope, immer))\n}\n\nfunction revokeDraft(draft: Drafted) {\n\tconst state: ImmerState = draft[DRAFT_STATE]\n\tif (\n\t\tstate.type_ === ProxyType.ProxyObject ||\n\t\tstate.type_ === ProxyType.ProxyArray\n\t)\n\t\tstate.revoke_()\n\telse state.revoked_ = true\n}\n", "import {\n\tImmerScope,\n\tDRAFT_STATE,\n\tisDraftable,\n\tNOTHING,\n\tPatchPath,\n\teach,\n\thas,\n\tfreeze,\n\tImmerState,\n\tisDraft,\n\tSetState,\n\tset,\n\tProxyType,\n\tgetPlugin,\n\tdie,\n\trevokeScope,\n\tisFrozen,\n\tshallowCopy\n} from \"../internal\"\n\nexport function processResult(result: any, scope: ImmerScope) {\n\tscope.unfinalizedDrafts_ = scope.drafts_.length\n\tconst baseDraft = scope.drafts_![0]\n\tconst isReplaced = result !== undefined && result !== baseDraft\n\tif (!scope.immer_.useProxies_)\n\t\tgetPlugin(\"ES5\").willFinalizeES5_(scope, result, isReplaced)\n\tif (isReplaced) {\n\t\tif (baseDraft[DRAFT_STATE].modified_) {\n\t\t\trevokeScope(scope)\n\t\t\tdie(4)\n\t\t}\n\t\tif (isDraftable(result)) {\n\t\t\t// Finalize the result in case it contains (or is) a subset of the draft.\n\t\t\tresult = finalize(scope, result)\n\t\t\tif (!scope.parent_) maybeFreeze(scope, result)\n\t\t}\n\t\tif (scope.patches_) {\n\t\t\tgetPlugin(\"Patches\").generateReplacementPatches_(\n\t\t\t\tbaseDraft[DRAFT_STATE],\n\t\t\t\tresult,\n\t\t\t\tscope.patches_,\n\t\t\t\tscope.inversePatches_!\n\t\t\t)\n\t\t}\n\t} else {\n\t\t// Finalize the base draft.\n\t\tresult = finalize(scope, baseDraft, [])\n\t}\n\trevokeScope(scope)\n\tif (scope.patches_) {\n\t\tscope.patchListener_!(scope.patches_, scope.inversePatches_!)\n\t}\n\treturn result !== NOTHING ? result : undefined\n}\n\nfunction finalize(rootScope: ImmerScope, value: any, path?: PatchPath) {\n\t// Don't recurse in tho recursive data structures\n\tif (isFrozen(value)) return value\n\n\tconst state: ImmerState = value[DRAFT_STATE]\n\t// A plain object, might need freezing, might contain drafts\n\tif (!state) {\n\t\teach(\n\t\t\tvalue,\n\t\t\t(key, childValue) =>\n\t\t\t\tfinalizeProperty(rootScope, state, value, key, childValue, path),\n\t\t\ttrue // See #590, don't recurse into non-enumerable of non drafted objects\n\t\t)\n\t\treturn value\n\t}\n\t// Never finalize drafts owned by another scope.\n\tif (state.scope_ !== rootScope) return value\n\t// Unmodified draft, return the (frozen) original\n\tif (!state.modified_) {\n\t\tmaybeFreeze(rootScope, state.base_, true)\n\t\treturn state.base_\n\t}\n\t// Not finalized yet, let's do that now\n\tif (!state.finalized_) {\n\t\tstate.finalized_ = true\n\t\tstate.scope_.unfinalizedDrafts_--\n\t\tconst result =\n\t\t\t// For ES5, create a good copy from the draft first, with added keys and without deleted keys.\n\t\t\tstate.type_ === ProxyType.ES5Object || state.type_ === ProxyType.ES5Array\n\t\t\t\t? (state.copy_ = shallowCopy(state.draft_))\n\t\t\t\t: state.copy_\n\t\t// Finalize all children of the copy\n\t\t// For sets we clone before iterating, otherwise we can get in endless loop due to modifying during iteration, see #628\n\t\t// Although the original test case doesn't seem valid anyway, so if this in the way we can turn the next line\n\t\t// back to each(result, ....)\n\t\teach(\n\t\t\tstate.type_ === ProxyType.Set ? new Set(result) : result,\n\t\t\t(key, childValue) =>\n\t\t\t\tfinalizeProperty(rootScope, state, result, key, childValue, path)\n\t\t)\n\t\t// everything inside is frozen, we can freeze here\n\t\tmaybeFreeze(rootScope, result, false)\n\t\t// first time finalizing, let's create those patches\n\t\tif (path && rootScope.patches_) {\n\t\t\tgetPlugin(\"Patches\").generatePatches_(\n\t\t\t\tstate,\n\t\t\t\tpath,\n\t\t\t\trootScope.patches_,\n\t\t\t\trootScope.inversePatches_!\n\t\t\t)\n\t\t}\n\t}\n\treturn state.copy_\n}\n\nfunction finalizeProperty(\n\trootScope: ImmerScope,\n\tparentState: undefined | ImmerState,\n\ttargetObject: any,\n\tprop: string | number,\n\tchildValue: any,\n\trootPath?: PatchPath\n) {\n\tif (__DEV__ && childValue === targetObject) die(5)\n\tif (isDraft(childValue)) {\n\t\tconst path =\n\t\t\trootPath &&\n\t\t\tparentState &&\n\t\t\tparentState!.type_ !== ProxyType.Set && // Set objects are atomic since they have no keys.\n\t\t\t!has((parentState as Exclude).assigned_!, prop) // Skip deep patches for assigned keys.\n\t\t\t\t? rootPath!.concat(prop)\n\t\t\t\t: undefined\n\t\t// Drafts owned by `scope` are finalized here.\n\t\tconst res = finalize(rootScope, childValue, path)\n\t\tset(targetObject, prop, res)\n\t\t// Drafts from another scope must prevented to be frozen\n\t\t// if we got a draft back from finalize, we're in a nested produce and shouldn't freeze\n\t\tif (isDraft(res)) {\n\t\t\trootScope.canAutoFreeze_ = false\n\t\t} else return\n\t}\n\t// Search new objects for unfinalized drafts. Frozen objects should never contain drafts.\n\tif (isDraftable(childValue) && !isFrozen(childValue)) {\n\t\tif (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {\n\t\t\t// optimization: if an object is not a draft, and we don't have to\n\t\t\t// deepfreeze everything, and we are sure that no drafts are left in the remaining object\n\t\t\t// cause we saw and finalized all drafts already; we can stop visiting the rest of the tree.\n\t\t\t// This benefits especially adding large data tree's without further processing.\n\t\t\t// See add-data.js perf test\n\t\t\treturn\n\t\t}\n\t\tfinalize(rootScope, childValue)\n\t\t// immer deep freezes plain objects, so if there is no parent state, we freeze as well\n\t\tif (!parentState || !parentState.scope_.parent_)\n\t\t\tmaybeFreeze(rootScope, childValue)\n\t}\n}\n\nfunction maybeFreeze(scope: ImmerScope, value: any, deep = false) {\n\tif (scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {\n\t\tfreeze(value, deep)\n\t}\n}\n", "import {\n\teach,\n\thas,\n\tis,\n\tisDraftable,\n\tshallowCopy,\n\tlatest,\n\tImmerBaseState,\n\tImmerState,\n\tDrafted,\n\tAnyObject,\n\tAnyArray,\n\tObjectish,\n\tgetCurrentScope,\n\tDRAFT_STATE,\n\tdie,\n\tcreateProxy,\n\tProxyType\n} from \"../internal\"\n\ninterface ProxyBaseState extends ImmerBaseState {\n\tassigned_: {\n\t\t[property: string]: boolean\n\t}\n\tparent_?: ImmerState\n\trevoke_(): void\n}\n\nexport interface ProxyObjectState extends ProxyBaseState {\n\ttype_: ProxyType.ProxyObject\n\tbase_: any\n\tcopy_: any\n\tdraft_: Drafted\n}\n\nexport interface ProxyArrayState extends ProxyBaseState {\n\ttype_: ProxyType.ProxyArray\n\tbase_: AnyArray\n\tcopy_: AnyArray | null\n\tdraft_: Drafted\n}\n\ntype ProxyState = ProxyObjectState | ProxyArrayState\n\n/**\n * Returns a new draft of the `base` object.\n *\n * The second argument is the parent draft-state (used internally).\n */\nexport function createProxyProxy(\n\tbase: T,\n\tparent?: ImmerState\n): Drafted {\n\tconst isArray = Array.isArray(base)\n\tconst state: ProxyState = {\n\t\ttype_: isArray ? ProxyType.ProxyArray : (ProxyType.ProxyObject as any),\n\t\t// Track which produce call this is associated with.\n\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t// True for both shallow and deep changes.\n\t\tmodified_: false,\n\t\t// Used during finalization.\n\t\tfinalized_: false,\n\t\t// Track which properties have been assigned (true) or deleted (false).\n\t\tassigned_: {},\n\t\t// The parent draft state.\n\t\tparent_: parent,\n\t\t// The base state.\n\t\tbase_: base,\n\t\t// The base proxy.\n\t\tdraft_: null as any, // set below\n\t\t// The base copy with any updated values.\n\t\tcopy_: null,\n\t\t// Called by the `produce` function.\n\t\trevoke_: null as any,\n\t\tisManual_: false\n\t}\n\n\t// the traps must target something, a bit like the 'real' base.\n\t// but also, we need to be able to determine from the target what the relevant state is\n\t// (to avoid creating traps per instance to capture the state in closure,\n\t// and to avoid creating weird hidden properties as well)\n\t// So the trick is to use 'state' as the actual 'target'! (and make sure we intercept everything)\n\t// Note that in the case of an array, we put the state in an array to have better Reflect defaults ootb\n\tlet target: T = state as any\n\tlet traps: ProxyHandler> = objectTraps\n\tif (isArray) {\n\t\ttarget = [state] as any\n\t\ttraps = arrayTraps\n\t}\n\n\tconst {revoke, proxy} = Proxy.revocable(target, traps)\n\tstate.draft_ = proxy as any\n\tstate.revoke_ = revoke\n\treturn proxy as any\n}\n\n/**\n * Object drafts\n */\nexport const objectTraps: ProxyHandler = {\n\tget(state, prop) {\n\t\tif (prop === DRAFT_STATE) return state\n\n\t\tconst source = latest(state)\n\t\tif (!has(source, prop)) {\n\t\t\t// non-existing or non-own property...\n\t\t\treturn readPropFromProto(state, source, prop)\n\t\t}\n\t\tconst value = source[prop]\n\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\treturn value\n\t\t}\n\t\t// Check for existing draft in modified state.\n\t\t// Assigned values are never drafted. This catches any drafts we created, too.\n\t\tif (value === peek(state.base_, prop)) {\n\t\t\tprepareCopy(state)\n\t\t\treturn (state.copy_![prop as any] = createProxy(\n\t\t\t\tstate.scope_.immer_,\n\t\t\t\tvalue,\n\t\t\t\tstate\n\t\t\t))\n\t\t}\n\t\treturn value\n\t},\n\thas(state, prop) {\n\t\treturn prop in latest(state)\n\t},\n\townKeys(state) {\n\t\treturn Reflect.ownKeys(latest(state))\n\t},\n\tset(\n\t\tstate: ProxyObjectState,\n\t\tprop: string /* strictly not, but helps TS */,\n\t\tvalue\n\t) {\n\t\tconst desc = getDescriptorFromProto(latest(state), prop)\n\t\tif (desc?.set) {\n\t\t\t// special case: if this write is captured by a setter, we have\n\t\t\t// to trigger it with the correct context\n\t\t\tdesc.set.call(state.draft_, value)\n\t\t\treturn true\n\t\t}\n\t\tif (!state.modified_) {\n\t\t\t// the last check is because we need to be able to distinguish setting a non-existing to undefined (which is a change)\n\t\t\t// from setting an existing property with value undefined to undefined (which is not a change)\n\t\t\tconst current = peek(latest(state), prop)\n\t\t\t// special case, if we assigning the original value to a draft, we can ignore the assignment\n\t\t\tconst currentState: ProxyObjectState = current?.[DRAFT_STATE]\n\t\t\tif (currentState && currentState.base_ === value) {\n\t\t\t\tstate.copy_![prop] = value\n\t\t\t\tstate.assigned_[prop] = false\n\t\t\t\treturn true\n\t\t\t}\n\t\t\tif (is(value, current) && (value !== undefined || has(state.base_, prop)))\n\t\t\t\treturn true\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t}\n\n\t\tif (\n\t\t\tstate.copy_![prop] === value &&\n\t\t\t// special case: NaN\n\t\t\ttypeof value !== \"number\" &&\n\t\t\t// special case: handle new props with value 'undefined'\n\t\t\t(value !== undefined || prop in state.copy_)\n\t\t)\n\t\t\treturn true\n\n\t\t// @ts-ignore\n\t\tstate.copy_![prop] = value\n\t\tstate.assigned_[prop] = true\n\t\treturn true\n\t},\n\tdeleteProperty(state, prop: string) {\n\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\tif (peek(state.base_, prop) !== undefined || prop in state.base_) {\n\t\t\tstate.assigned_[prop] = false\n\t\t\tprepareCopy(state)\n\t\t\tmarkChanged(state)\n\t\t} else {\n\t\t\t// if an originally not assigned property was deleted\n\t\t\tdelete state.assigned_[prop]\n\t\t}\n\t\t// @ts-ignore\n\t\tif (state.copy_) delete state.copy_[prop]\n\t\treturn true\n\t},\n\t// Note: We never coerce `desc.value` into an Immer draft, because we can't make\n\t// the same guarantee in ES5 mode.\n\tgetOwnPropertyDescriptor(state, prop) {\n\t\tconst owner = latest(state)\n\t\tconst desc = Reflect.getOwnPropertyDescriptor(owner, prop)\n\t\tif (!desc) return desc\n\t\treturn {\n\t\t\twritable: true,\n\t\t\tconfigurable: state.type_ !== ProxyType.ProxyArray || prop !== \"length\",\n\t\t\tenumerable: desc.enumerable,\n\t\t\tvalue: owner[prop]\n\t\t}\n\t},\n\tdefineProperty() {\n\t\tdie(11)\n\t},\n\tgetPrototypeOf(state) {\n\t\treturn Object.getPrototypeOf(state.base_)\n\t},\n\tsetPrototypeOf() {\n\t\tdie(12)\n\t}\n}\n\n/**\n * Array drafts\n */\n\nconst arrayTraps: ProxyHandler<[ProxyArrayState]> = {}\neach(objectTraps, (key, fn) => {\n\t// @ts-ignore\n\tarrayTraps[key] = function() {\n\t\targuments[0] = arguments[0][0]\n\t\treturn fn.apply(this, arguments)\n\t}\n})\narrayTraps.deleteProperty = function(state, prop) {\n\tif (__DEV__ && isNaN(parseInt(prop as any))) die(13)\n\treturn objectTraps.deleteProperty!.call(this, state[0], prop)\n}\narrayTraps.set = function(state, prop, value) {\n\tif (__DEV__ && prop !== \"length\" && isNaN(parseInt(prop as any))) die(14)\n\treturn objectTraps.set!.call(this, state[0], prop, value, state[0])\n}\n\n// Access a property without creating an Immer draft.\nfunction peek(draft: Drafted, prop: PropertyKey) {\n\tconst state = draft[DRAFT_STATE]\n\tconst source = state ? latest(state) : draft\n\treturn source[prop]\n}\n\nfunction readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {\n\tconst desc = getDescriptorFromProto(source, prop)\n\treturn desc\n\t\t? `value` in desc\n\t\t\t? desc.value\n\t\t\t: // This is a very special case, if the prop is a getter defined by the\n\t\t\t // prototype, we should invoke it with the draft as context!\n\t\t\t desc.get?.call(state.draft_)\n\t\t: undefined\n}\n\nfunction getDescriptorFromProto(\n\tsource: any,\n\tprop: PropertyKey\n): PropertyDescriptor | undefined {\n\t// 'in' checks proto!\n\tif (!(prop in source)) return undefined\n\tlet proto = Object.getPrototypeOf(source)\n\twhile (proto) {\n\t\tconst desc = Object.getOwnPropertyDescriptor(proto, prop)\n\t\tif (desc) return desc\n\t\tproto = Object.getPrototypeOf(proto)\n\t}\n\treturn undefined\n}\n\nexport function markChanged(state: ImmerState) {\n\tif (!state.modified_) {\n\t\tstate.modified_ = true\n\t\tif (state.parent_) {\n\t\t\tmarkChanged(state.parent_)\n\t\t}\n\t}\n}\n\nexport function prepareCopy(state: {base_: any; copy_: any}) {\n\tif (!state.copy_) {\n\t\tstate.copy_ = shallowCopy(state.base_)\n\t}\n}\n", "import {\n\tIProduceWithPatches,\n\tIProduce,\n\tImmerState,\n\tDrafted,\n\tisDraftable,\n\tprocessResult,\n\tPatch,\n\tObjectish,\n\tDRAFT_STATE,\n\tDraft,\n\tPatchListener,\n\tisDraft,\n\tisMap,\n\tisSet,\n\tcreateProxyProxy,\n\tgetPlugin,\n\tdie,\n\thasProxies,\n\tenterScope,\n\trevokeScope,\n\tleaveScope,\n\tusePatchesInScope,\n\tgetCurrentScope,\n\tNOTHING,\n\tfreeze,\n\tcurrent\n} from \"../internal\"\n\ninterface ProducersFns {\n\tproduce: IProduce\n\tproduceWithPatches: IProduceWithPatches\n}\n\nexport class Immer implements ProducersFns {\n\tuseProxies_: boolean = hasProxies\n\n\tautoFreeze_: boolean = true\n\n\tconstructor(config?: {useProxies?: boolean; autoFreeze?: boolean}) {\n\t\tif (typeof config?.useProxies === \"boolean\")\n\t\t\tthis.setUseProxies(config!.useProxies)\n\t\tif (typeof config?.autoFreeze === \"boolean\")\n\t\t\tthis.setAutoFreeze(config!.autoFreeze)\n\t}\n\n\t/**\n\t * The `produce` function takes a value and a \"recipe function\" (whose\n\t * return value often depends on the base state). The recipe function is\n\t * free to mutate its first argument however it wants. All mutations are\n\t * only ever applied to a __copy__ of the base state.\n\t *\n\t * Pass only a function to create a \"curried producer\" which relieves you\n\t * from passing the recipe function every time.\n\t *\n\t * Only plain objects and arrays are made mutable. All other objects are\n\t * considered uncopyable.\n\t *\n\t * Note: This function is __bound__ to its `Immer` instance.\n\t *\n\t * @param {any} base - the initial state\n\t * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified\n\t * @param {Function} patchListener - optional function that will be called with all the patches produced here\n\t * @returns {any} a new state, or the initial state if nothing was modified\n\t */\n\tproduce: IProduce = (base: any, recipe?: any, patchListener?: any) => {\n\t\t// curried invocation\n\t\tif (typeof base === \"function\" && typeof recipe !== \"function\") {\n\t\t\tconst defaultBase = recipe\n\t\t\trecipe = base\n\n\t\t\tconst self = this\n\t\t\treturn function curriedProduce(\n\t\t\t\tthis: any,\n\t\t\t\tbase = defaultBase,\n\t\t\t\t...args: any[]\n\t\t\t) {\n\t\t\t\treturn self.produce(base, (draft: Drafted) => recipe.call(this, draft, ...args)) // prettier-ignore\n\t\t\t}\n\t\t}\n\n\t\tif (typeof recipe !== \"function\") die(6)\n\t\tif (patchListener !== undefined && typeof patchListener !== \"function\")\n\t\t\tdie(7)\n\n\t\tlet result\n\n\t\t// Only plain objects, arrays, and \"immerable classes\" are drafted.\n\t\tif (isDraftable(base)) {\n\t\t\tconst scope = enterScope(this)\n\t\t\tconst proxy = createProxy(this, base, undefined)\n\t\t\tlet hasError = true\n\t\t\ttry {\n\t\t\t\tresult = recipe(proxy)\n\t\t\t\thasError = false\n\t\t\t} finally {\n\t\t\t\t// finally instead of catch + rethrow better preserves original stack\n\t\t\t\tif (hasError) revokeScope(scope)\n\t\t\t\telse leaveScope(scope)\n\t\t\t}\n\t\t\tif (typeof Promise !== \"undefined\" && result instanceof Promise) {\n\t\t\t\treturn result.then(\n\t\t\t\t\tresult => {\n\t\t\t\t\t\tusePatchesInScope(scope, patchListener)\n\t\t\t\t\t\treturn processResult(result, scope)\n\t\t\t\t\t},\n\t\t\t\t\terror => {\n\t\t\t\t\t\trevokeScope(scope)\n\t\t\t\t\t\tthrow error\n\t\t\t\t\t}\n\t\t\t\t)\n\t\t\t}\n\t\t\tusePatchesInScope(scope, patchListener)\n\t\t\treturn processResult(result, scope)\n\t\t} else if (!base || typeof base !== \"object\") {\n\t\t\tresult = recipe(base)\n\t\t\tif (result === NOTHING) return undefined\n\t\t\tif (result === undefined) result = base\n\t\t\tif (this.autoFreeze_) freeze(result, true)\n\t\t\treturn result\n\t\t} else die(21, base)\n\t}\n\n\tproduceWithPatches: IProduceWithPatches = (\n\t\targ1: any,\n\t\targ2?: any,\n\t\targ3?: any\n\t): any => {\n\t\tif (typeof arg1 === \"function\") {\n\t\t\treturn (state: any, ...args: any[]) =>\n\t\t\t\tthis.produceWithPatches(state, (draft: any) => arg1(draft, ...args))\n\t\t}\n\n\t\tlet patches: Patch[], inversePatches: Patch[]\n\t\tconst nextState = this.produce(arg1, arg2, (p: Patch[], ip: Patch[]) => {\n\t\t\tpatches = p\n\t\t\tinversePatches = ip\n\t\t})\n\t\treturn [nextState, patches!, inversePatches!]\n\t}\n\n\tcreateDraft(base: T): Draft {\n\t\tif (!isDraftable(base)) die(8)\n\t\tif (isDraft(base)) base = current(base)\n\t\tconst scope = enterScope(this)\n\t\tconst proxy = createProxy(this, base, undefined)\n\t\tproxy[DRAFT_STATE].isManual_ = true\n\t\tleaveScope(scope)\n\t\treturn proxy as any\n\t}\n\n\tfinishDraft>(\n\t\tdraft: D,\n\t\tpatchListener?: PatchListener\n\t): D extends Draft ? T : never {\n\t\tconst state: ImmerState = draft && (draft as any)[DRAFT_STATE]\n\t\tif (__DEV__) {\n\t\t\tif (!state || !state.isManual_) die(9)\n\t\t\tif (state.finalized_) die(10)\n\t\t}\n\t\tconst {scope_: scope} = state\n\t\tusePatchesInScope(scope, patchListener)\n\t\treturn processResult(undefined, scope)\n\t}\n\n\t/**\n\t * Pass true to automatically freeze all copies created by Immer.\n\t *\n\t * By default, auto-freezing is enabled.\n\t */\n\tsetAutoFreeze(value: boolean) {\n\t\tthis.autoFreeze_ = value\n\t}\n\n\t/**\n\t * Pass true to use the ES2015 `Proxy` class when creating drafts, which is\n\t * always faster than using ES5 proxies.\n\t *\n\t * By default, feature detection is used, so calling this is rarely necessary.\n\t */\n\tsetUseProxies(value: boolean) {\n\t\tif (value && !hasProxies) {\n\t\t\tdie(20)\n\t\t}\n\t\tthis.useProxies_ = value\n\t}\n\n\tapplyPatches(base: T, patches: Patch[]): T {\n\t\t// If a patch replaces the entire state, take that replacement as base\n\t\t// before applying patches\n\t\tlet i: number\n\t\tfor (i = patches.length - 1; i >= 0; i--) {\n\t\t\tconst patch = patches[i]\n\t\t\tif (patch.path.length === 0 && patch.op === \"replace\") {\n\t\t\t\tbase = patch.value\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\t// If there was a patch that replaced the entire state, start from the\n\t\t// patch after that.\n\t\tif (i > -1) {\n\t\t\tpatches = patches.slice(i + 1)\n\t\t}\n\n\t\tconst applyPatchesImpl = getPlugin(\"Patches\").applyPatches_\n\t\tif (isDraft(base)) {\n\t\t\t// N.B: never hits if some patch a replacement, patches are never drafts\n\t\t\treturn applyPatchesImpl(base, patches)\n\t\t}\n\t\t// Otherwise, produce a copy of the base state.\n\t\treturn this.produce(base, (draft: Drafted) =>\n\t\t\tapplyPatchesImpl(draft, patches)\n\t\t)\n\t}\n}\n\nexport function createProxy(\n\timmer: Immer,\n\tvalue: T,\n\tparent?: ImmerState\n): Drafted {\n\t// precondition: createProxy should be guarded by isDraftable, so we know we can safely draft\n\tconst draft: Drafted = isMap(value)\n\t\t? getPlugin(\"MapSet\").proxyMap_(value, parent)\n\t\t: isSet(value)\n\t\t? getPlugin(\"MapSet\").proxySet_(value, parent)\n\t\t: immer.useProxies_\n\t\t? createProxyProxy(value, parent)\n\t\t: getPlugin(\"ES5\").createES5Proxy_(value, parent)\n\n\tconst scope = parent ? parent.scope_ : getCurrentScope()\n\tscope.drafts_.push(draft)\n\treturn draft\n}\n", "import {\n\tdie,\n\tisDraft,\n\tshallowCopy,\n\teach,\n\tDRAFT_STATE,\n\tget,\n\tset,\n\tImmerState,\n\tisDraftable,\n\tArchtype,\n\tgetArchtype,\n\tgetPlugin\n} from \"../internal\"\n\n/** Takes a snapshot of the current state of a draft and finalizes it (but without freezing). This is a great utility to print the current state during debugging (no Proxies in the way). The output of current can also be safely leaked outside the producer. */\nexport function current(value: T): T\nexport function current(value: any): any {\n\tif (!isDraft(value)) die(22, value)\n\treturn currentImpl(value)\n}\n\nfunction currentImpl(value: any): any {\n\tif (!isDraftable(value)) return value\n\tconst state: ImmerState | undefined = value[DRAFT_STATE]\n\tlet copy: any\n\tconst archType = getArchtype(value)\n\tif (state) {\n\t\tif (\n\t\t\t!state.modified_ &&\n\t\t\t(state.type_ < 4 || !getPlugin(\"ES5\").hasChanges_(state as any))\n\t\t)\n\t\t\treturn state.base_\n\t\t// Optimization: avoid generating new drafts during copying\n\t\tstate.finalized_ = true\n\t\tcopy = copyHelper(value, archType)\n\t\tstate.finalized_ = false\n\t} else {\n\t\tcopy = copyHelper(value, archType)\n\t}\n\n\teach(copy, (key, childValue) => {\n\t\tif (state && get(state.base_, key) === childValue) return // no need to copy or search in something that didn't change\n\t\tset(copy, key, currentImpl(childValue))\n\t})\n\t// In the future, we might consider freezing here, based on the current settings\n\treturn archType === Archtype.Set ? new Set(copy) : copy\n}\n\nfunction copyHelper(value: any, archType: number): any {\n\t// creates a shallow copy, even if it is a map or set\n\tswitch (archType) {\n\t\tcase Archtype.Map:\n\t\t\treturn new Map(value)\n\t\tcase Archtype.Set:\n\t\t\t// Set will be cloned as array temporarily, so that we can replace individual items\n\t\t\treturn Array.from(value)\n\t}\n\treturn shallowCopy(value)\n}\n", "import {\n\tImmerState,\n\tDrafted,\n\tES5ArrayState,\n\tES5ObjectState,\n\teach,\n\thas,\n\tisDraft,\n\tlatest,\n\tDRAFT_STATE,\n\tis,\n\tloadPlugin,\n\tImmerScope,\n\tProxyType,\n\tgetCurrentScope,\n\tdie,\n\tmarkChanged,\n\tobjectTraps,\n\townKeys,\n\tgetOwnPropertyDescriptors\n} from \"../internal\"\n\ntype ES5State = ES5ArrayState | ES5ObjectState\n\nexport function enableES5() {\n\tfunction willFinalizeES5_(\n\t\tscope: ImmerScope,\n\t\tresult: any,\n\t\tisReplaced: boolean\n\t) {\n\t\tif (!isReplaced) {\n\t\t\tif (scope.patches_) {\n\t\t\t\tmarkChangesRecursively(scope.drafts_![0])\n\t\t\t}\n\t\t\t// This is faster when we don't care about which attributes changed.\n\t\t\tmarkChangesSweep(scope.drafts_)\n\t\t}\n\t\t// When a child draft is returned, look for changes.\n\t\telse if (\n\t\t\tisDraft(result) &&\n\t\t\t(result[DRAFT_STATE] as ES5State).scope_ === scope\n\t\t) {\n\t\t\tmarkChangesSweep(scope.drafts_)\n\t\t}\n\t}\n\n\tfunction createES5Draft(isArray: boolean, base: any) {\n\t\tif (isArray) {\n\t\t\tconst draft = new Array(base.length)\n\t\t\tfor (let i = 0; i < base.length; i++)\n\t\t\t\tObject.defineProperty(draft, \"\" + i, proxyProperty(i, true))\n\t\t\treturn draft\n\t\t} else {\n\t\t\tconst descriptors = getOwnPropertyDescriptors(base)\n\t\t\tdelete descriptors[DRAFT_STATE as any]\n\t\t\tconst keys = ownKeys(descriptors)\n\t\t\tfor (let i = 0; i < keys.length; i++) {\n\t\t\t\tconst key: any = keys[i]\n\t\t\t\tdescriptors[key] = proxyProperty(\n\t\t\t\t\tkey,\n\t\t\t\t\tisArray || !!descriptors[key].enumerable\n\t\t\t\t)\n\t\t\t}\n\t\t\treturn Object.create(Object.getPrototypeOf(base), descriptors)\n\t\t}\n\t}\n\n\tfunction createES5Proxy_(\n\t\tbase: T,\n\t\tparent?: ImmerState\n\t): Drafted {\n\t\tconst isArray = Array.isArray(base)\n\t\tconst draft = createES5Draft(isArray, base)\n\n\t\tconst state: ES5ObjectState | ES5ArrayState = {\n\t\t\ttype_: isArray ? ProxyType.ES5Array : (ProxyType.ES5Object as any),\n\t\t\tscope_: parent ? parent.scope_ : getCurrentScope(),\n\t\t\tmodified_: false,\n\t\t\tfinalized_: false,\n\t\t\tassigned_: {},\n\t\t\tparent_: parent,\n\t\t\t// base is the object we are drafting\n\t\t\tbase_: base,\n\t\t\t// draft is the draft object itself, that traps all reads and reads from either the base (if unmodified) or copy (if modified)\n\t\t\tdraft_: draft,\n\t\t\tcopy_: null,\n\t\t\trevoked_: false,\n\t\t\tisManual_: false\n\t\t}\n\n\t\tObject.defineProperty(draft, DRAFT_STATE, {\n\t\t\tvalue: state,\n\t\t\t// enumerable: false <- the default\n\t\t\twritable: true\n\t\t})\n\t\treturn draft\n\t}\n\n\t// property descriptors are recycled to make sure we don't create a get and set closure per property,\n\t// but share them all instead\n\tconst descriptors: {[prop: string]: PropertyDescriptor} = {}\n\n\tfunction proxyProperty(\n\t\tprop: string | number,\n\t\tenumerable: boolean\n\t): PropertyDescriptor {\n\t\tlet desc = descriptors[prop]\n\t\tif (desc) {\n\t\t\tdesc.enumerable = enumerable\n\t\t} else {\n\t\t\tdescriptors[prop] = desc = {\n\t\t\t\tconfigurable: true,\n\t\t\t\tenumerable,\n\t\t\t\tget(this: any) {\n\t\t\t\t\tconst state = this[DRAFT_STATE]\n\t\t\t\t\tif (__DEV__) assertUnrevoked(state)\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\treturn objectTraps.get(state, prop)\n\t\t\t\t},\n\t\t\t\tset(this: any, value) {\n\t\t\t\t\tconst state = this[DRAFT_STATE]\n\t\t\t\t\tif (__DEV__) assertUnrevoked(state)\n\t\t\t\t\t// @ts-ignore\n\t\t\t\t\tobjectTraps.set(state, prop, value)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn desc\n\t}\n\n\t// This looks expensive, but only proxies are visited, and only objects without known changes are scanned.\n\tfunction markChangesSweep(drafts: Drafted[]) {\n\t\t// The natural order of drafts in the `scope` array is based on when they\n\t\t// were accessed. By processing drafts in reverse natural order, we have a\n\t\t// better chance of processing leaf nodes first. When a leaf node is known to\n\t\t// have changed, we can avoid any traversal of its ancestor nodes.\n\t\tfor (let i = drafts.length - 1; i >= 0; i--) {\n\t\t\tconst state: ES5State = drafts[i][DRAFT_STATE]\n\t\t\tif (!state.modified_) {\n\t\t\t\tswitch (state.type_) {\n\t\t\t\t\tcase ProxyType.ES5Array:\n\t\t\t\t\t\tif (hasArrayChanges(state)) markChanged(state)\n\t\t\t\t\t\tbreak\n\t\t\t\t\tcase ProxyType.ES5Object:\n\t\t\t\t\t\tif (hasObjectChanges(state)) markChanged(state)\n\t\t\t\t\t\tbreak\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction markChangesRecursively(object: any) {\n\t\tif (!object || typeof object !== \"object\") return\n\t\tconst state: ES5State | undefined = object[DRAFT_STATE]\n\t\tif (!state) return\n\t\tconst {base_, draft_, assigned_, type_} = state\n\t\tif (type_ === ProxyType.ES5Object) {\n\t\t\t// Look for added keys.\n\t\t\t// probably there is a faster way to detect changes, as sweep + recurse seems to do some\n\t\t\t// unnecessary work.\n\t\t\t// also: probably we can store the information we detect here, to speed up tree finalization!\n\t\t\teach(draft_, key => {\n\t\t\t\tif ((key as any) === DRAFT_STATE) return\n\t\t\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\t\t\tif ((base_ as any)[key] === undefined && !has(base_, key)) {\n\t\t\t\t\tassigned_[key] = true\n\t\t\t\t\tmarkChanged(state)\n\t\t\t\t} else if (!assigned_[key]) {\n\t\t\t\t\t// Only untouched properties trigger recursion.\n\t\t\t\t\tmarkChangesRecursively(draft_[key])\n\t\t\t\t}\n\t\t\t})\n\t\t\t// Look for removed keys.\n\t\t\teach(base_, key => {\n\t\t\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\t\t\tif (draft_[key] === undefined && !has(draft_, key)) {\n\t\t\t\t\tassigned_[key] = false\n\t\t\t\t\tmarkChanged(state)\n\t\t\t\t}\n\t\t\t})\n\t\t} else if (type_ === ProxyType.ES5Array) {\n\t\t\tif (hasArrayChanges(state as ES5ArrayState)) {\n\t\t\t\tmarkChanged(state)\n\t\t\t\tassigned_.length = true\n\t\t\t}\n\n\t\t\tif (draft_.length < base_.length) {\n\t\t\t\tfor (let i = draft_.length; i < base_.length; i++) assigned_[i] = false\n\t\t\t} else {\n\t\t\t\tfor (let i = base_.length; i < draft_.length; i++) assigned_[i] = true\n\t\t\t}\n\n\t\t\t// Minimum count is enough, the other parts has been processed.\n\t\t\tconst min = Math.min(draft_.length, base_.length)\n\n\t\t\tfor (let i = 0; i < min; i++) {\n\t\t\t\t// Only untouched indices trigger recursion.\n\t\t\t\tif (assigned_[i] === undefined) markChangesRecursively(draft_[i])\n\t\t\t}\n\t\t}\n\t}\n\n\tfunction hasObjectChanges(state: ES5ObjectState) {\n\t\tconst {base_, draft_} = state\n\n\t\t// Search for added keys and changed keys. Start at the back, because\n\t\t// non-numeric keys are ordered by time of definition on the object.\n\t\tconst keys = ownKeys(draft_)\n\t\tfor (let i = keys.length - 1; i >= 0; i--) {\n\t\t\tconst key: any = keys[i]\n\t\t\tif (key === DRAFT_STATE) continue\n\t\t\tconst baseValue = base_[key]\n\t\t\t// The `undefined` check is a fast path for pre-existing keys.\n\t\t\tif (baseValue === undefined && !has(base_, key)) {\n\t\t\t\treturn true\n\t\t\t}\n\t\t\t// Once a base key is deleted, future changes go undetected, because its\n\t\t\t// descriptor is erased. This branch detects any missed changes.\n\t\t\telse {\n\t\t\t\tconst value = draft_[key]\n\t\t\t\tconst state: ImmerState = value && value[DRAFT_STATE]\n\t\t\t\tif (state ? state.base_ !== baseValue : !is(value, baseValue)) {\n\t\t\t\t\treturn true\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// At this point, no keys were added or changed.\n\t\t// Compare key count to determine if keys were deleted.\n\t\tconst baseIsDraft = !!base_[DRAFT_STATE as any]\n\t\treturn keys.length !== ownKeys(base_).length + (baseIsDraft ? 0 : 1) // + 1 to correct for DRAFT_STATE\n\t}\n\n\tfunction hasArrayChanges(state: ES5ArrayState) {\n\t\tconst {draft_} = state\n\t\tif (draft_.length !== state.base_.length) return true\n\t\t// See #116\n\t\t// If we first shorten the length, our array interceptors will be removed.\n\t\t// If after that new items are added, result in the same original length,\n\t\t// those last items will have no intercepting property.\n\t\t// So if there is no own descriptor on the last position, we know that items were removed and added\n\t\t// N.B.: splice, unshift, etc only shift values around, but not prop descriptors, so we only have to check\n\t\t// the last one\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(\n\t\t\tdraft_,\n\t\t\tdraft_.length - 1\n\t\t)\n\t\t// descriptor can be null, but only for newly created sparse arrays, eg. new Array(10)\n\t\tif (descriptor && !descriptor.get) return true\n\t\t// For all other cases, we don't have to compare, as they would have been picked up by the index setters\n\t\treturn false\n\t}\n\n\tfunction hasChanges_(state: ES5State) {\n\t\treturn state.type_ === ProxyType.ES5Object\n\t\t\t? hasObjectChanges(state)\n\t\t\t: hasArrayChanges(state)\n\t}\n\n\tfunction assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {\n\t\tif (state.revoked_) die(3, JSON.stringify(latest(state)))\n\t}\n\n\tloadPlugin(\"ES5\", {\n\t\tcreateES5Proxy_,\n\t\twillFinalizeES5_,\n\t\thasChanges_\n\t})\n}\n", "import {immerable} from \"../immer\"\nimport {\n\tImmerState,\n\tPatch,\n\tSetState,\n\tES5ArrayState,\n\tProxyArrayState,\n\tMapState,\n\tES5ObjectState,\n\tProxyObjectState,\n\tPatchPath,\n\tget,\n\teach,\n\thas,\n\tgetArchtype,\n\tisSet,\n\tisMap,\n\tloadPlugin,\n\tProxyType,\n\tArchtype,\n\tdie,\n\tisDraft,\n\tisDraftable,\n\tNOTHING\n} from \"../internal\"\n\nexport function enablePatches() {\n\tconst REPLACE = \"replace\"\n\tconst ADD = \"add\"\n\tconst REMOVE = \"remove\"\n\n\tfunction generatePatches_(\n\t\tstate: ImmerState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t): void {\n\t\tswitch (state.type_) {\n\t\t\tcase ProxyType.ProxyObject:\n\t\t\tcase ProxyType.ES5Object:\n\t\t\tcase ProxyType.Map:\n\t\t\t\treturn generatePatchesFromAssigned(\n\t\t\t\t\tstate,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches,\n\t\t\t\t\tinversePatches\n\t\t\t\t)\n\t\t\tcase ProxyType.ES5Array:\n\t\t\tcase ProxyType.ProxyArray:\n\t\t\t\treturn generateArrayPatches(state, basePath, patches, inversePatches)\n\t\t\tcase ProxyType.Set:\n\t\t\t\treturn generateSetPatches(\n\t\t\t\t\t(state as any) as SetState,\n\t\t\t\t\tbasePath,\n\t\t\t\t\tpatches,\n\t\t\t\t\tinversePatches\n\t\t\t\t)\n\t\t}\n\t}\n\n\tfunction generateArrayPatches(\n\t\tstate: ES5ArrayState | ProxyArrayState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, assigned_} = state\n\t\tlet copy_ = state.copy_!\n\n\t\t// Reduce complexity by ensuring `base` is never longer.\n\t\tif (copy_.length < base_.length) {\n\t\t\t// @ts-ignore\n\t\t\t;[base_, copy_] = [copy_, base_]\n\t\t\t;[patches, inversePatches] = [inversePatches, patches]\n\t\t}\n\n\t\t// Process replaced indices.\n\t\tfor (let i = 0; i < base_.length; i++) {\n\t\t\tif (assigned_[i] && copy_[i] !== base_[i]) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(copy_[i])\n\t\t\t\t})\n\t\t\t\tinversePatches.push({\n\t\t\t\t\top: REPLACE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue: clonePatchValueIfNeeded(base_[i])\n\t\t\t\t})\n\t\t\t}\n\t\t}\n\n\t\t// Process added indices.\n\t\tfor (let i = base_.length; i < copy_.length; i++) {\n\t\t\tconst path = basePath.concat([i])\n\t\t\tpatches.push({\n\t\t\t\top: ADD,\n\t\t\t\tpath,\n\t\t\t\t// Need to maybe clone it, as it can in fact be the original value\n\t\t\t\t// due to the base/copy inversion at the start of this function\n\t\t\t\tvalue: clonePatchValueIfNeeded(copy_[i])\n\t\t\t})\n\t\t}\n\t\tif (base_.length < copy_.length) {\n\t\t\tinversePatches.push({\n\t\t\t\top: REPLACE,\n\t\t\t\tpath: basePath.concat([\"length\"]),\n\t\t\t\tvalue: base_.length\n\t\t\t})\n\t\t}\n\t}\n\n\t// This is used for both Map objects and normal objects.\n\tfunction generatePatchesFromAssigned(\n\t\tstate: MapState | ES5ObjectState | ProxyObjectState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tconst {base_, copy_} = state\n\t\teach(state.assigned_!, (key, assignedValue) => {\n\t\t\tconst origValue = get(base_, key)\n\t\t\tconst value = get(copy_!, key)\n\t\t\tconst op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD\n\t\t\tif (origValue === value && op === REPLACE) return\n\t\t\tconst path = basePath.concat(key as any)\n\t\t\tpatches.push(op === REMOVE ? {op, path} : {op, path, value})\n\t\t\tinversePatches.push(\n\t\t\t\top === ADD\n\t\t\t\t\t? {op: REMOVE, path}\n\t\t\t\t\t: op === REMOVE\n\t\t\t\t\t? {op: ADD, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t\t\t: {op: REPLACE, path, value: clonePatchValueIfNeeded(origValue)}\n\t\t\t)\n\t\t})\n\t}\n\n\tfunction generateSetPatches(\n\t\tstate: SetState,\n\t\tbasePath: PatchPath,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t) {\n\t\tlet {base_, copy_} = state\n\n\t\tlet i = 0\n\t\tbase_.forEach((value: any) => {\n\t\t\tif (!copy_!.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t\ti = 0\n\t\tcopy_!.forEach((value: any) => {\n\t\t\tif (!base_.has(value)) {\n\t\t\t\tconst path = basePath.concat([i])\n\t\t\t\tpatches.push({\n\t\t\t\t\top: ADD,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t\tinversePatches.unshift({\n\t\t\t\t\top: REMOVE,\n\t\t\t\t\tpath,\n\t\t\t\t\tvalue\n\t\t\t\t})\n\t\t\t}\n\t\t\ti++\n\t\t})\n\t}\n\n\tfunction generateReplacementPatches_(\n\t\trootState: ImmerState,\n\t\treplacement: any,\n\t\tpatches: Patch[],\n\t\tinversePatches: Patch[]\n\t): void {\n\t\tpatches.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: replacement === NOTHING ? undefined : replacement\n\t\t})\n\t\tinversePatches.push({\n\t\t\top: REPLACE,\n\t\t\tpath: [],\n\t\t\tvalue: rootState.base_\n\t\t})\n\t}\n\n\tfunction applyPatches_(draft: T, patches: Patch[]): T {\n\t\tpatches.forEach(patch => {\n\t\t\tconst {path, op} = patch\n\n\t\t\tlet base: any = draft\n\t\t\tfor (let i = 0; i < path.length - 1; i++) {\n\t\t\t\tconst parentType = getArchtype(base)\n\t\t\t\tconst p = \"\" + path[i]\n\t\t\t\t// See #738, avoid prototype pollution\n\t\t\t\tif (\n\t\t\t\t\t(parentType === Archtype.Object || parentType === Archtype.Array) &&\n\t\t\t\t\t(p === \"__proto__\" || p === \"constructor\")\n\t\t\t\t)\n\t\t\t\t\tdie(24)\n\t\t\t\tif (typeof base === \"function\" && p === \"prototype\") die(24)\n\t\t\t\tbase = get(base, p)\n\t\t\t\tif (typeof base !== \"object\") die(15, path.join(\"/\"))\n\t\t\t}\n\n\t\t\tconst type = getArchtype(base)\n\t\t\tconst value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411\n\t\t\tconst key = path[path.length - 1]\n\t\t\tswitch (op) {\n\t\t\t\tcase REPLACE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase Archtype.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\t\tcase Archtype.Set:\n\t\t\t\t\t\t\tdie(16)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t// if value is an object, then it's assigned by reference\n\t\t\t\t\t\t\t// in the following add or remove ops, the value field inside the patch will also be modifyed\n\t\t\t\t\t\t\t// so we use value from the cloned patch\n\t\t\t\t\t\t\t// @ts-ignore\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase ADD:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase Archtype.Array:\n\t\t\t\t\t\t\treturn key === \"-\"\n\t\t\t\t\t\t\t\t? base.push(value)\n\t\t\t\t\t\t\t\t: base.splice(key as any, 0, value)\n\t\t\t\t\t\tcase Archtype.Map:\n\t\t\t\t\t\t\treturn base.set(key, value)\n\t\t\t\t\t\tcase Archtype.Set:\n\t\t\t\t\t\t\treturn base.add(value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn (base[key] = value)\n\t\t\t\t\t}\n\t\t\t\tcase REMOVE:\n\t\t\t\t\tswitch (type) {\n\t\t\t\t\t\tcase Archtype.Array:\n\t\t\t\t\t\t\treturn base.splice(key as any, 1)\n\t\t\t\t\t\tcase Archtype.Map:\n\t\t\t\t\t\t\treturn base.delete(key)\n\t\t\t\t\t\tcase Archtype.Set:\n\t\t\t\t\t\t\treturn base.delete(patch.value)\n\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\treturn delete base[key]\n\t\t\t\t\t}\n\t\t\t\tdefault:\n\t\t\t\t\tdie(17, op)\n\t\t\t}\n\t\t})\n\n\t\treturn draft\n\t}\n\n\t// optimize: this is quite a performance hit, can we detect intelligently when it is needed?\n\t// E.g. auto-draft when new objects from outside are assigned and modified?\n\t// (See failing test when deepClone just returns obj)\n\tfunction deepClonePatchValue(obj: T): T\n\tfunction deepClonePatchValue(obj: any) {\n\t\tif (!isDraftable(obj)) return obj\n\t\tif (Array.isArray(obj)) return obj.map(deepClonePatchValue)\n\t\tif (isMap(obj))\n\t\t\treturn new Map(\n\t\t\t\tArray.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])\n\t\t\t)\n\t\tif (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))\n\t\tconst cloned = Object.create(Object.getPrototypeOf(obj))\n\t\tfor (const key in obj) cloned[key] = deepClonePatchValue(obj[key])\n\t\tif (has(obj, immerable)) cloned[immerable] = obj[immerable]\n\t\treturn cloned\n\t}\n\n\tfunction clonePatchValueIfNeeded(obj: T): T {\n\t\tif (isDraft(obj)) {\n\t\t\treturn deepClonePatchValue(obj)\n\t\t} else return obj\n\t}\n\n\tloadPlugin(\"Patches\", {\n\t\tapplyPatches_,\n\t\tgeneratePatches_,\n\t\tgenerateReplacementPatches_\n\t})\n}\n", "// types only!\nimport {\n\tImmerState,\n\tAnyMap,\n\tAnySet,\n\tMapState,\n\tSetState,\n\tDRAFT_STATE,\n\tgetCurrentScope,\n\tlatest,\n\titeratorSymbol,\n\tisDraftable,\n\tcreateProxy,\n\tloadPlugin,\n\tmarkChanged,\n\tProxyType,\n\tdie,\n\teach\n} from \"../internal\"\n\nexport function enableMapSet() {\n\t/* istanbul ignore next */\n\tvar extendStatics = function(d: any, b: any): any {\n\t\textendStatics =\n\t\t\tObject.setPrototypeOf ||\n\t\t\t({__proto__: []} instanceof Array &&\n\t\t\t\tfunction(d, b) {\n\t\t\t\t\td.__proto__ = b\n\t\t\t\t}) ||\n\t\t\tfunction(d, b) {\n\t\t\t\tfor (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]\n\t\t\t}\n\t\treturn extendStatics(d, b)\n\t}\n\n\t// Ugly hack to resolve #502 and inherit built in Map / Set\n\tfunction __extends(d: any, b: any): any {\n\t\textendStatics(d, b)\n\t\tfunction __(this: any): any {\n\t\t\tthis.constructor = d\n\t\t}\n\t\td.prototype =\n\t\t\t// @ts-ignore\n\t\t\t((__.prototype = b.prototype), new __())\n\t}\n\n\tconst DraftMap = (function(_super) {\n\t\t__extends(DraftMap, _super)\n\t\t// Create class manually, cause #502\n\t\tfunction DraftMap(this: any, target: AnyMap, parent?: ImmerState): any {\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ProxyType.Map,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tassigned_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this as any,\n\t\t\t\tisManual_: false,\n\t\t\t\trevoked_: false\n\t\t\t} as MapState\n\t\t\treturn this\n\t\t}\n\t\tconst p = DraftMap.prototype\n\n\t\tObject.defineProperty(p, \"size\", {\n\t\t\tget: function() {\n\t\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t\t}\n\t\t\t// enumerable: false,\n\t\t\t// configurable: true\n\t\t})\n\n\t\tp.has = function(key: any): boolean {\n\t\t\treturn latest(this[DRAFT_STATE]).has(key)\n\t\t}\n\n\t\tp.set = function(key: any, value: any) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!latest(state).has(key) || latest(state).get(key) !== value) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t\tstate.copy_!.set(key, value)\n\t\t\t\tstate.assigned_!.set(key, true)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tp.delete = function(key: any): boolean {\n\t\t\tif (!this.has(key)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareMapCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\tstate.assigned_!.set(key, false)\n\t\t\tstate.copy_!.delete(key)\n\t\t\treturn true\n\t\t}\n\n\t\tp.clear = function() {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareMapCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.assigned_ = new Map()\n\t\t\t\teach(state.base_, key => {\n\t\t\t\t\tstate.assigned_!.set(key, false)\n\t\t\t\t})\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tp.forEach = function(\n\t\t\tcb: (value: any, key: any, self: any) => void,\n\t\t\tthisArg?: any\n\t\t) {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tlatest(state).forEach((_value: any, key: any, _map: any) => {\n\t\t\t\tcb.call(thisArg, this.get(key), key, this)\n\t\t\t})\n\t\t}\n\n\t\tp.get = function(key: any): any {\n\t\t\tconst state: MapState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tconst value = latest(state).get(key)\n\t\t\tif (state.finalized_ || !isDraftable(value)) {\n\t\t\t\treturn value\n\t\t\t}\n\t\t\tif (value !== state.base_.get(key)) {\n\t\t\t\treturn value // either already drafted or reassigned\n\t\t\t}\n\t\t\t// despite what it looks, this creates a draft only once, see above condition\n\t\t\tconst draft = createProxy(state.scope_.immer_, value, state)\n\t\t\tprepareMapCopy(state)\n\t\t\tstate.copy_!.set(key, draft)\n\t\t\treturn draft\n\t\t}\n\n\t\tp.keys = function(): IterableIterator {\n\t\t\treturn latest(this[DRAFT_STATE]).keys()\n\t\t}\n\n\t\tp.values = function(): IterableIterator {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[iteratorSymbol]: () => this.values(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\tp.entries = function(): IterableIterator<[any, any]> {\n\t\t\tconst iterator = this.keys()\n\t\t\treturn {\n\t\t\t\t[iteratorSymbol]: () => this.entries(),\n\t\t\t\tnext: () => {\n\t\t\t\t\tconst r = iterator.next()\n\t\t\t\t\t/* istanbul ignore next */\n\t\t\t\t\tif (r.done) return r\n\t\t\t\t\tconst value = this.get(r.value)\n\t\t\t\t\treturn {\n\t\t\t\t\t\tdone: false,\n\t\t\t\t\t\tvalue: [r.value, value]\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t} as any\n\t\t}\n\n\t\tp[iteratorSymbol] = function() {\n\t\t\treturn this.entries()\n\t\t}\n\n\t\treturn DraftMap\n\t})(Map)\n\n\tfunction proxyMap_(target: T, parent?: ImmerState): T {\n\t\t// @ts-ignore\n\t\treturn new DraftMap(target, parent)\n\t}\n\n\tfunction prepareMapCopy(state: MapState) {\n\t\tif (!state.copy_) {\n\t\t\tstate.assigned_ = new Map()\n\t\t\tstate.copy_ = new Map(state.base_)\n\t\t}\n\t}\n\n\tconst DraftSet = (function(_super) {\n\t\t__extends(DraftSet, _super)\n\t\t// Create class manually, cause #502\n\t\tfunction DraftSet(this: any, target: AnySet, parent?: ImmerState) {\n\t\t\tthis[DRAFT_STATE] = {\n\t\t\t\ttype_: ProxyType.Set,\n\t\t\t\tparent_: parent,\n\t\t\t\tscope_: parent ? parent.scope_ : getCurrentScope()!,\n\t\t\t\tmodified_: false,\n\t\t\t\tfinalized_: false,\n\t\t\t\tcopy_: undefined,\n\t\t\t\tbase_: target,\n\t\t\t\tdraft_: this,\n\t\t\t\tdrafts_: new Map(),\n\t\t\t\trevoked_: false,\n\t\t\t\tisManual_: false\n\t\t\t} as SetState\n\t\t\treturn this\n\t\t}\n\t\tconst p = DraftSet.prototype\n\n\t\tObject.defineProperty(p, \"size\", {\n\t\t\tget: function() {\n\t\t\t\treturn latest(this[DRAFT_STATE]).size\n\t\t\t}\n\t\t\t// enumerable: true,\n\t\t})\n\n\t\tp.has = function(value: any): boolean {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\t// bit of trickery here, to be able to recognize both the value, and the draft of its value\n\t\t\tif (!state.copy_) {\n\t\t\t\treturn state.base_.has(value)\n\t\t\t}\n\t\t\tif (state.copy_.has(value)) return true\n\t\t\tif (state.drafts_.has(value) && state.copy_.has(state.drafts_.get(value)))\n\t\t\t\treturn true\n\t\t\treturn false\n\t\t}\n\n\t\tp.add = function(value: any): any {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (!this.has(value)) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.add(value)\n\t\t\t}\n\t\t\treturn this\n\t\t}\n\n\t\tp.delete = function(value: any): any {\n\t\t\tif (!this.has(value)) {\n\t\t\t\treturn false\n\t\t\t}\n\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\tmarkChanged(state)\n\t\t\treturn (\n\t\t\t\tstate.copy_!.delete(value) ||\n\t\t\t\t(state.drafts_.has(value)\n\t\t\t\t\t? state.copy_!.delete(state.drafts_.get(value))\n\t\t\t\t\t: /* istanbul ignore next */ false)\n\t\t\t)\n\t\t}\n\n\t\tp.clear = function() {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tif (latest(state).size) {\n\t\t\t\tprepareSetCopy(state)\n\t\t\t\tmarkChanged(state)\n\t\t\t\tstate.copy_!.clear()\n\t\t\t}\n\t\t}\n\n\t\tp.values = function(): IterableIterator {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.values()\n\t\t}\n\n\t\tp.entries = function entries(): IterableIterator<[any, any]> {\n\t\t\tconst state: SetState = this[DRAFT_STATE]\n\t\t\tassertUnrevoked(state)\n\t\t\tprepareSetCopy(state)\n\t\t\treturn state.copy_!.entries()\n\t\t}\n\n\t\tp.keys = function(): IterableIterator {\n\t\t\treturn this.values()\n\t\t}\n\n\t\tp[iteratorSymbol] = function() {\n\t\t\treturn this.values()\n\t\t}\n\n\t\tp.forEach = function forEach(cb: any, thisArg?: any) {\n\t\t\tconst iterator = this.values()\n\t\t\tlet result = iterator.next()\n\t\t\twhile (!result.done) {\n\t\t\t\tcb.call(thisArg, result.value, result.value, this)\n\t\t\t\tresult = iterator.next()\n\t\t\t}\n\t\t}\n\n\t\treturn DraftSet\n\t})(Set)\n\n\tfunction proxySet_(target: T, parent?: ImmerState): T {\n\t\t// @ts-ignore\n\t\treturn new DraftSet(target, parent)\n\t}\n\n\tfunction prepareSetCopy(state: SetState) {\n\t\tif (!state.copy_) {\n\t\t\t// create drafts for all entries to preserve insertion order\n\t\t\tstate.copy_ = new Set()\n\t\t\tstate.base_.forEach(value => {\n\t\t\t\tif (isDraftable(value)) {\n\t\t\t\t\tconst draft = createProxy(state.scope_.immer_, value, state)\n\t\t\t\t\tstate.drafts_.set(value, draft)\n\t\t\t\t\tstate.copy_!.add(draft)\n\t\t\t\t} else {\n\t\t\t\t\tstate.copy_!.add(value)\n\t\t\t\t}\n\t\t\t})\n\t\t}\n\t}\n\n\tfunction assertUnrevoked(state: any /*ES5State | MapState | SetState*/) {\n\t\tif (state.revoked_) die(3, JSON.stringify(latest(state)))\n\t}\n\n\tloadPlugin(\"MapSet\", {proxyMap_, proxySet_})\n}\n", "import {enableES5} from \"./es5\"\nimport {enableMapSet} from \"./mapset\"\nimport {enablePatches} from \"./patches\"\n\nexport function enableAllPlugins() {\n\tenableES5()\n\tenableMapSet()\n\tenablePatches()\n}\n", "import {\n\tIProduce,\n\tIProduceWithPatches,\n\tImmer,\n\tDraft,\n\tImmutable\n} from \"./internal\"\n\nexport {\n\tDraft,\n\tImmutable,\n\tPatch,\n\tPatchListener,\n\toriginal,\n\tcurrent,\n\tisDraft,\n\tisDraftable,\n\tNOTHING as nothing,\n\tDRAFTABLE as immerable,\n\tfreeze\n} from \"./internal\"\n\nconst immer = new Immer()\n\n/**\n * The `produce` function takes a value and a \"recipe function\" (whose\n * return value often depends on the base state). The recipe function is\n * free to mutate its first argument however it wants. All mutations are\n * only ever applied to a __copy__ of the base state.\n *\n * Pass only a function to create a \"curried producer\" which relieves you\n * from passing the recipe function every time.\n *\n * Only plain objects and arrays are made mutable. All other objects are\n * considered uncopyable.\n *\n * Note: This function is __bound__ to its `Immer` instance.\n *\n * @param {any} base - the initial state\n * @param {Function} producer - function that receives a proxy of the base state as first argument and which can be freely modified\n * @param {Function} patchListener - optional function that will be called with all the patches produced here\n * @returns {any} a new state, or the initial state if nothing was modified\n */\nexport const produce: IProduce = immer.produce\nexport default produce\n\n/**\n * Like `produce`, but `produceWithPatches` always returns a tuple\n * [nextState, patches, inversePatches] (instead of just the next state)\n */\nexport const produceWithPatches: IProduceWithPatches = immer.produceWithPatches.bind(\n\timmer\n)\n\n/**\n * Pass true to automatically freeze all copies created by Immer.\n *\n * Always freeze by default, even in production mode\n */\nexport const setAutoFreeze = immer.setAutoFreeze.bind(immer)\n\n/**\n * Pass true to use the ES2015 `Proxy` class when creating drafts, which is\n * always faster than using ES5 proxies.\n *\n * By default, feature detection is used, so calling this is rarely necessary.\n */\nexport const setUseProxies = immer.setUseProxies.bind(immer)\n\n/**\n * Apply an array of Immer patches to the first argument.\n *\n * This function is a producer, which means copy-on-write is in effect.\n */\nexport const applyPatches = immer.applyPatches.bind(immer)\n\n/**\n * Create an Immer draft from the given base state, which may be a draft itself.\n * The draft can be modified until you finalize it with the `finishDraft` function.\n */\nexport const createDraft = immer.createDraft.bind(immer)\n\n/**\n * Finalize an Immer draft from a `createDraft` call, returning the base state\n * (if no changes were made) or a modified copy. The draft must *not* be\n * mutated afterwards.\n *\n * Pass a function as the 2nd argument to generate Immer patches based on the\n * changes that were made.\n */\nexport const finishDraft = immer.finishDraft.bind(immer)\n\n/**\n * This function is actually a no-op, but can be used to cast an immutable type\n * to an draft type and make TypeScript happy\n *\n * @param value\n */\nexport function castDraft(value: T): Draft {\n\treturn value as any\n}\n\n/**\n * This function is actually a no-op, but can be used to cast a mutable type\n * to an immutable type and make TypeScript happy\n * @param value\n */\nexport function castImmutable(value: T): Immutable {\n\treturn value as any\n}\n\nexport {Immer}\n\nexport {enableES5} from \"./plugins/es5\"\nexport {enablePatches} from \"./plugins/patches\"\nexport {enableMapSet} from \"./plugins/mapset\"\nexport {enableAllPlugins} from \"./plugins/all\"\n", "// Should be no imports here!\n\n// Some things that should be evaluated before all else...\n\n// We only want to know if non-polyfilled symbols are available\nconst hasSymbol =\n\ttypeof Symbol !== \"undefined\" && typeof Symbol(\"x\") === \"symbol\"\nexport const hasMap = typeof Map !== \"undefined\"\nexport const hasSet = typeof Set !== \"undefined\"\nexport const hasProxies =\n\ttypeof Proxy !== \"undefined\" &&\n\ttypeof Proxy.revocable !== \"undefined\" &&\n\ttypeof Reflect !== \"undefined\"\n\n/**\n * The sentinel value returned by producers to replace the draft with undefined.\n */\nexport const NOTHING: Nothing = hasSymbol\n\t? Symbol.for(\"immer-nothing\")\n\t: ({[\"immer-nothing\"]: true} as any)\n\n/**\n * To let Immer treat your class instances as plain immutable objects\n * (albeit with a custom prototype), you must define either an instance property\n * or a static property on each of your custom classes.\n *\n * Otherwise, your class instance will never be drafted, which means it won't be\n * safe to mutate in a produce callback.\n */\nexport const DRAFTABLE: unique symbol = hasSymbol\n\t? Symbol.for(\"immer-draftable\")\n\t: (\"__$immer_draftable\" as any)\n\nexport const DRAFT_STATE: unique symbol = hasSymbol\n\t? Symbol.for(\"immer-state\")\n\t: (\"__$immer_state\" as any)\n\n// Even a polyfilled Symbol might provide Symbol.iterator\nexport const iteratorSymbol: typeof Symbol.iterator =\n\t(typeof Symbol != \"undefined\" && Symbol.iterator) || (\"@@iterator\" as any)\n\n/** Use a class type for `nothing` so its type is unique */\nexport class Nothing {\n\t// This lets us do `Exclude`\n\t// @ts-ignore\n\tprivate _!: unique symbol\n}\n", "export default function _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n\n return obj;\n}", "import defineProperty from \"./defineProperty.js\";\n\nfunction ownKeys(object, enumerableOnly) {\n var keys = Object.keys(object);\n\n if (Object.getOwnPropertySymbols) {\n var symbols = Object.getOwnPropertySymbols(object);\n enumerableOnly && (symbols = symbols.filter(function (sym) {\n return Object.getOwnPropertyDescriptor(object, sym).enumerable;\n })), keys.push.apply(keys, symbols);\n }\n\n return keys;\n}\n\nexport default function _objectSpread2(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = null != arguments[i] ? arguments[i] : {};\n i % 2 ? ownKeys(Object(source), !0).forEach(function (key) {\n defineProperty(target, key, source[key]);\n }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) {\n Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));\n });\n }\n\n return target;\n}", "import _objectSpread from '@babel/runtime/helpers/esm/objectSpread2';\n\n/**\n * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js\n *\n * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes\n * during build.\n * @param {number} code\n */\nfunction formatProdErrorMessage(code) {\n return \"Minified Redux error #\" + code + \"; visit https://redux.js.org/Errors?code=\" + code + \" for the full message or \" + 'use the non-minified dev environment for full errors. ';\n}\n\n// Inlined version of the `symbol-observable` polyfill\nvar $$observable = (function () {\n return typeof Symbol === 'function' && Symbol.observable || '@@observable';\n})();\n\n/**\n * These are private action types reserved by Redux.\n * For any unknown actions, you must return the current state.\n * If the current state is undefined, you must return the initial state.\n * Do not reference these action types directly in your code.\n */\nvar randomString = function randomString() {\n return Math.random().toString(36).substring(7).split('').join('.');\n};\n\nvar ActionTypes = {\n INIT: \"@@redux/INIT\" + randomString(),\n REPLACE: \"@@redux/REPLACE\" + randomString(),\n PROBE_UNKNOWN_ACTION: function PROBE_UNKNOWN_ACTION() {\n return \"@@redux/PROBE_UNKNOWN_ACTION\" + randomString();\n }\n};\n\n/**\n * @param {any} obj The object to inspect.\n * @returns {boolean} True if the argument appears to be a plain object.\n */\nfunction isPlainObject(obj) {\n if (typeof obj !== 'object' || obj === null) return false;\n var proto = obj;\n\n while (Object.getPrototypeOf(proto) !== null) {\n proto = Object.getPrototypeOf(proto);\n }\n\n return Object.getPrototypeOf(obj) === proto;\n}\n\n// Inlined / shortened version of `kindOf` from https://github.com/jonschlinkert/kind-of\nfunction miniKindOf(val) {\n if (val === void 0) return 'undefined';\n if (val === null) return 'null';\n var type = typeof val;\n\n switch (type) {\n case 'boolean':\n case 'string':\n case 'number':\n case 'symbol':\n case 'function':\n {\n return type;\n }\n }\n\n if (Array.isArray(val)) return 'array';\n if (isDate(val)) return 'date';\n if (isError(val)) return 'error';\n var constructorName = ctorName(val);\n\n switch (constructorName) {\n case 'Symbol':\n case 'Promise':\n case 'WeakMap':\n case 'WeakSet':\n case 'Map':\n case 'Set':\n return constructorName;\n } // other\n\n\n return type.slice(8, -1).toLowerCase().replace(/\\s/g, '');\n}\n\nfunction ctorName(val) {\n return typeof val.constructor === 'function' ? val.constructor.name : null;\n}\n\nfunction isError(val) {\n return val instanceof Error || typeof val.message === 'string' && val.constructor && typeof val.constructor.stackTraceLimit === 'number';\n}\n\nfunction isDate(val) {\n if (val instanceof Date) return true;\n return typeof val.toDateString === 'function' && typeof val.getDate === 'function' && typeof val.setDate === 'function';\n}\n\nfunction kindOf(val) {\n var typeOfVal = typeof val;\n\n if (process.env.NODE_ENV !== 'production') {\n typeOfVal = miniKindOf(val);\n }\n\n return typeOfVal;\n}\n\n/**\n * Creates a Redux store that holds the state tree.\n * The only way to change the data in the store is to call `dispatch()` on it.\n *\n * There should only be a single store in your app. To specify how different\n * parts of the state tree respond to actions, you may combine several reducers\n * into a single reducer function by using `combineReducers`.\n *\n * @param {Function} reducer A function that returns the next state tree, given\n * the current state tree and the action to handle.\n *\n * @param {any} [preloadedState] The initial state. You may optionally specify it\n * to hydrate the state from the server in universal apps, or to restore a\n * previously serialized user session.\n * If you use `combineReducers` to produce the root reducer function, this must be\n * an object with the same shape as `combineReducers` keys.\n *\n * @param {Function} [enhancer] The store enhancer. You may optionally specify it\n * to enhance the store with third-party capabilities such as middleware,\n * time travel, persistence, etc. The only store enhancer that ships with Redux\n * is `applyMiddleware()`.\n *\n * @returns {Store} A Redux store that lets you read the state, dispatch actions\n * and subscribe to changes.\n */\n\nfunction createStore(reducer, preloadedState, enhancer) {\n var _ref2;\n\n if (typeof preloadedState === 'function' && typeof enhancer === 'function' || typeof enhancer === 'function' && typeof arguments[3] === 'function') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(0) : 'It looks like you are passing several store enhancers to ' + 'createStore(). This is not supported. Instead, compose them ' + 'together to a single function. See https://redux.js.org/tutorials/fundamentals/part-4-store#creating-a-store-with-enhancers for an example.');\n }\n\n if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') {\n enhancer = preloadedState;\n preloadedState = undefined;\n }\n\n if (typeof enhancer !== 'undefined') {\n if (typeof enhancer !== 'function') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(1) : \"Expected the enhancer to be a function. Instead, received: '\" + kindOf(enhancer) + \"'\");\n }\n\n return enhancer(createStore)(reducer, preloadedState);\n }\n\n if (typeof reducer !== 'function') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(2) : \"Expected the root reducer to be a function. Instead, received: '\" + kindOf(reducer) + \"'\");\n }\n\n var currentReducer = reducer;\n var currentState = preloadedState;\n var currentListeners = [];\n var nextListeners = currentListeners;\n var isDispatching = false;\n /**\n * This makes a shallow copy of currentListeners so we can use\n * nextListeners as a temporary list while dispatching.\n *\n * This prevents any bugs around consumers calling\n * subscribe/unsubscribe in the middle of a dispatch.\n */\n\n function ensureCanMutateNextListeners() {\n if (nextListeners === currentListeners) {\n nextListeners = currentListeners.slice();\n }\n }\n /**\n * Reads the state tree managed by the store.\n *\n * @returns {any} The current state tree of your application.\n */\n\n\n function getState() {\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(3) : 'You may not call store.getState() while the reducer is executing. ' + 'The reducer has already received the state as an argument. ' + 'Pass it down from the top reducer instead of reading it from the store.');\n }\n\n return currentState;\n }\n /**\n * Adds a change listener. It will be called any time an action is dispatched,\n * and some part of the state tree may potentially have changed. You may then\n * call `getState()` to read the current state tree inside the callback.\n *\n * You may call `dispatch()` from a change listener, with the following\n * caveats:\n *\n * 1. The subscriptions are snapshotted just before every `dispatch()` call.\n * If you subscribe or unsubscribe while the listeners are being invoked, this\n * will not have any effect on the `dispatch()` that is currently in progress.\n * However, the next `dispatch()` call, whether nested or not, will use a more\n * recent snapshot of the subscription list.\n *\n * 2. The listener should not expect to see all state changes, as the state\n * might have been updated multiple times during a nested `dispatch()` before\n * the listener is called. It is, however, guaranteed that all subscribers\n * registered before the `dispatch()` started will be called with the latest\n * state by the time it exits.\n *\n * @param {Function} listener A callback to be invoked on every dispatch.\n * @returns {Function} A function to remove this change listener.\n */\n\n\n function subscribe(listener) {\n if (typeof listener !== 'function') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(4) : \"Expected the listener to be a function. Instead, received: '\" + kindOf(listener) + \"'\");\n }\n\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(5) : 'You may not call store.subscribe() while the reducer is executing. ' + 'If you would like to be notified after the store has been updated, subscribe from a ' + 'component and invoke store.getState() in the callback to access the latest state. ' + 'See https://redux.js.org/api/store#subscribelistener for more details.');\n }\n\n var isSubscribed = true;\n ensureCanMutateNextListeners();\n nextListeners.push(listener);\n return function unsubscribe() {\n if (!isSubscribed) {\n return;\n }\n\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(6) : 'You may not unsubscribe from a store listener while the reducer is executing. ' + 'See https://redux.js.org/api/store#subscribelistener for more details.');\n }\n\n isSubscribed = false;\n ensureCanMutateNextListeners();\n var index = nextListeners.indexOf(listener);\n nextListeners.splice(index, 1);\n currentListeners = null;\n };\n }\n /**\n * Dispatches an action. It is the only way to trigger a state change.\n *\n * The `reducer` function, used to create the store, will be called with the\n * current state tree and the given `action`. Its return value will\n * be considered the **next** state of the tree, and the change listeners\n * will be notified.\n *\n * The base implementation only supports plain object actions. If you want to\n * dispatch a Promise, an Observable, a thunk, or something else, you need to\n * wrap your store creating function into the corresponding middleware. For\n * example, see the documentation for the `redux-thunk` package. Even the\n * middleware will eventually dispatch plain object actions using this method.\n *\n * @param {Object} action A plain object representing \u201Cwhat changed\u201D. It is\n * a good idea to keep actions serializable so you can record and replay user\n * sessions, or use the time travelling `redux-devtools`. An action must have\n * a `type` property which may not be `undefined`. It is a good idea to use\n * string constants for action types.\n *\n * @returns {Object} For convenience, the same action object you dispatched.\n *\n * Note that, if you use a custom middleware, it may wrap `dispatch()` to\n * return something else (for example, a Promise you can await).\n */\n\n\n function dispatch(action) {\n if (!isPlainObject(action)) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(7) : \"Actions must be plain objects. Instead, the actual type was: '\" + kindOf(action) + \"'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.\");\n }\n\n if (typeof action.type === 'undefined') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(8) : 'Actions may not have an undefined \"type\" property. You may have misspelled an action type string constant.');\n }\n\n if (isDispatching) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(9) : 'Reducers may not dispatch actions.');\n }\n\n try {\n isDispatching = true;\n currentState = currentReducer(currentState, action);\n } finally {\n isDispatching = false;\n }\n\n var listeners = currentListeners = nextListeners;\n\n for (var i = 0; i < listeners.length; i++) {\n var listener = listeners[i];\n listener();\n }\n\n return action;\n }\n /**\n * Replaces the reducer currently used by the store to calculate the state.\n *\n * You might need this if your app implements code splitting and you want to\n * load some of the reducers dynamically. You might also need this if you\n * implement a hot reloading mechanism for Redux.\n *\n * @param {Function} nextReducer The reducer for the store to use instead.\n * @returns {void}\n */\n\n\n function replaceReducer(nextReducer) {\n if (typeof nextReducer !== 'function') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(10) : \"Expected the nextReducer to be a function. Instead, received: '\" + kindOf(nextReducer));\n }\n\n currentReducer = nextReducer; // This action has a similiar effect to ActionTypes.INIT.\n // Any reducers that existed in both the new and old rootReducer\n // will receive the previous state. This effectively populates\n // the new state tree with any relevant data from the old one.\n\n dispatch({\n type: ActionTypes.REPLACE\n });\n }\n /**\n * Interoperability point for observable/reactive libraries.\n * @returns {observable} A minimal observable of state changes.\n * For more information, see the observable proposal:\n * https://github.com/tc39/proposal-observable\n */\n\n\n function observable() {\n var _ref;\n\n var outerSubscribe = subscribe;\n return _ref = {\n /**\n * The minimal observable subscription method.\n * @param {Object} observer Any object that can be used as an observer.\n * The observer object should have a `next` method.\n * @returns {subscription} An object with an `unsubscribe` method that can\n * be used to unsubscribe the observable from the store, and prevent further\n * emission of values from the observable.\n */\n subscribe: function subscribe(observer) {\n if (typeof observer !== 'object' || observer === null) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(11) : \"Expected the observer to be an object. Instead, received: '\" + kindOf(observer) + \"'\");\n }\n\n function observeState() {\n if (observer.next) {\n observer.next(getState());\n }\n }\n\n observeState();\n var unsubscribe = outerSubscribe(observeState);\n return {\n unsubscribe: unsubscribe\n };\n }\n }, _ref[$$observable] = function () {\n return this;\n }, _ref;\n } // When a store is created, an \"INIT\" action is dispatched so that every\n // reducer returns their initial state. This effectively populates\n // the initial state tree.\n\n\n dispatch({\n type: ActionTypes.INIT\n });\n return _ref2 = {\n dispatch: dispatch,\n subscribe: subscribe,\n getState: getState,\n replaceReducer: replaceReducer\n }, _ref2[$$observable] = observable, _ref2;\n}\n\n/**\n * Prints a warning in the console if it exists.\n *\n * @param {String} message The warning message.\n * @returns {void}\n */\nfunction warning(message) {\n /* eslint-disable no-console */\n if (typeof console !== 'undefined' && typeof console.error === 'function') {\n console.error(message);\n }\n /* eslint-enable no-console */\n\n\n try {\n // This error was thrown as a convenience so that if you enable\n // \"break on all exceptions\" in your console,\n // it would pause the execution at this line.\n throw new Error(message);\n } catch (e) {} // eslint-disable-line no-empty\n\n}\n\nfunction getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) {\n var reducerKeys = Object.keys(reducers);\n var argumentName = action && action.type === ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer';\n\n if (reducerKeys.length === 0) {\n return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.';\n }\n\n if (!isPlainObject(inputState)) {\n return \"The \" + argumentName + \" has unexpected type of \\\"\" + kindOf(inputState) + \"\\\". Expected argument to be an object with the following \" + (\"keys: \\\"\" + reducerKeys.join('\", \"') + \"\\\"\");\n }\n\n var unexpectedKeys = Object.keys(inputState).filter(function (key) {\n return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key];\n });\n unexpectedKeys.forEach(function (key) {\n unexpectedKeyCache[key] = true;\n });\n if (action && action.type === ActionTypes.REPLACE) return;\n\n if (unexpectedKeys.length > 0) {\n return \"Unexpected \" + (unexpectedKeys.length > 1 ? 'keys' : 'key') + \" \" + (\"\\\"\" + unexpectedKeys.join('\", \"') + \"\\\" found in \" + argumentName + \". \") + \"Expected to find one of the known reducer keys instead: \" + (\"\\\"\" + reducerKeys.join('\", \"') + \"\\\". Unexpected keys will be ignored.\");\n }\n}\n\nfunction assertReducerShape(reducers) {\n Object.keys(reducers).forEach(function (key) {\n var reducer = reducers[key];\n var initialState = reducer(undefined, {\n type: ActionTypes.INIT\n });\n\n if (typeof initialState === 'undefined') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(12) : \"The slice reducer for key \\\"\" + key + \"\\\" returned undefined during initialization. \" + \"If the state passed to the reducer is undefined, you must \" + \"explicitly return the initial state. The initial state may \" + \"not be undefined. If you don't want to set a value for this reducer, \" + \"you can use null instead of undefined.\");\n }\n\n if (typeof reducer(undefined, {\n type: ActionTypes.PROBE_UNKNOWN_ACTION()\n }) === 'undefined') {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(13) : \"The slice reducer for key \\\"\" + key + \"\\\" returned undefined when probed with a random type. \" + (\"Don't try to handle '\" + ActionTypes.INIT + \"' or other actions in \\\"redux/*\\\" \") + \"namespace. They are considered private. Instead, you must return the \" + \"current state for any unknown actions, unless it is undefined, \" + \"in which case you must return the initial state, regardless of the \" + \"action type. The initial state may not be undefined, but can be null.\");\n }\n });\n}\n/**\n * Turns an object whose values are different reducer functions, into a single\n * reducer function. It will call every child reducer, and gather their results\n * into a single state object, whose keys correspond to the keys of the passed\n * reducer functions.\n *\n * @param {Object} reducers An object whose values correspond to different\n * reducer functions that need to be combined into one. One handy way to obtain\n * it is to use ES6 `import * as reducers` syntax. The reducers may never return\n * undefined for any action. Instead, they should return their initial state\n * if the state passed to them was undefined, and the current state for any\n * unrecognized action.\n *\n * @returns {Function} A reducer function that invokes every reducer inside the\n * passed object, and builds a state object with the same shape.\n */\n\n\nfunction combineReducers(reducers) {\n var reducerKeys = Object.keys(reducers);\n var finalReducers = {};\n\n for (var i = 0; i < reducerKeys.length; i++) {\n var key = reducerKeys[i];\n\n if (process.env.NODE_ENV !== 'production') {\n if (typeof reducers[key] === 'undefined') {\n warning(\"No reducer provided for key \\\"\" + key + \"\\\"\");\n }\n }\n\n if (typeof reducers[key] === 'function') {\n finalReducers[key] = reducers[key];\n }\n }\n\n var finalReducerKeys = Object.keys(finalReducers); // This is used to make sure we don't warn about the same\n // keys multiple times.\n\n var unexpectedKeyCache;\n\n if (process.env.NODE_ENV !== 'production') {\n unexpectedKeyCache = {};\n }\n\n var shapeAssertionError;\n\n try {\n assertReducerShape(finalReducers);\n } catch (e) {\n shapeAssertionError = e;\n }\n\n return function combination(state, action) {\n if (state === void 0) {\n state = {};\n }\n\n if (shapeAssertionError) {\n throw shapeAssertionError;\n }\n\n if (process.env.NODE_ENV !== 'production') {\n var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache);\n\n if (warningMessage) {\n warning(warningMessage);\n }\n }\n\n var hasChanged = false;\n var nextState = {};\n\n for (var _i = 0; _i < finalReducerKeys.length; _i++) {\n var _key = finalReducerKeys[_i];\n var reducer = finalReducers[_key];\n var previousStateForKey = state[_key];\n var nextStateForKey = reducer(previousStateForKey, action);\n\n if (typeof nextStateForKey === 'undefined') {\n var actionType = action && action.type;\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(14) : \"When called with an action of type \" + (actionType ? \"\\\"\" + String(actionType) + \"\\\"\" : '(unknown type)') + \", the slice reducer for key \\\"\" + _key + \"\\\" returned undefined. \" + \"To ignore an action, you must explicitly return the previous state. \" + \"If you want this reducer to hold no value, you can return null instead of undefined.\");\n }\n\n nextState[_key] = nextStateForKey;\n hasChanged = hasChanged || nextStateForKey !== previousStateForKey;\n }\n\n hasChanged = hasChanged || finalReducerKeys.length !== Object.keys(state).length;\n return hasChanged ? nextState : state;\n };\n}\n\nfunction bindActionCreator(actionCreator, dispatch) {\n return function () {\n return dispatch(actionCreator.apply(this, arguments));\n };\n}\n/**\n * Turns an object whose values are action creators, into an object with the\n * same keys, but with every function wrapped into a `dispatch` call so they\n * may be invoked directly. This is just a convenience method, as you can call\n * `store.dispatch(MyActionCreators.doSomething())` yourself just fine.\n *\n * For convenience, you can also pass an action creator as the first argument,\n * and get a dispatch wrapped function in return.\n *\n * @param {Function|Object} actionCreators An object whose values are action\n * creator functions. One handy way to obtain it is to use ES6 `import * as`\n * syntax. You may also pass a single function.\n *\n * @param {Function} dispatch The `dispatch` function available on your Redux\n * store.\n *\n * @returns {Function|Object} The object mimicking the original object, but with\n * every action creator wrapped into the `dispatch` call. If you passed a\n * function as `actionCreators`, the return value will also be a single\n * function.\n */\n\n\nfunction bindActionCreators(actionCreators, dispatch) {\n if (typeof actionCreators === 'function') {\n return bindActionCreator(actionCreators, dispatch);\n }\n\n if (typeof actionCreators !== 'object' || actionCreators === null) {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(16) : \"bindActionCreators expected an object or a function, but instead received: '\" + kindOf(actionCreators) + \"'. \" + \"Did you write \\\"import ActionCreators from\\\" instead of \\\"import * as ActionCreators from\\\"?\");\n }\n\n var boundActionCreators = {};\n\n for (var key in actionCreators) {\n var actionCreator = actionCreators[key];\n\n if (typeof actionCreator === 'function') {\n boundActionCreators[key] = bindActionCreator(actionCreator, dispatch);\n }\n }\n\n return boundActionCreators;\n}\n\n/**\n * Composes single-argument functions from right to left. The rightmost\n * function can take multiple arguments as it provides the signature for\n * the resulting composite function.\n *\n * @param {...Function} funcs The functions to compose.\n * @returns {Function} A function obtained by composing the argument functions\n * from right to left. For example, compose(f, g, h) is identical to doing\n * (...args) => f(g(h(...args))).\n */\nfunction compose() {\n for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {\n funcs[_key] = arguments[_key];\n }\n\n if (funcs.length === 0) {\n return function (arg) {\n return arg;\n };\n }\n\n if (funcs.length === 1) {\n return funcs[0];\n }\n\n return funcs.reduce(function (a, b) {\n return function () {\n return a(b.apply(void 0, arguments));\n };\n });\n}\n\n/**\n * Creates a store enhancer that applies middleware to the dispatch method\n * of the Redux store. This is handy for a variety of tasks, such as expressing\n * asynchronous actions in a concise manner, or logging every action payload.\n *\n * See `redux-thunk` package as an example of the Redux middleware.\n *\n * Because middleware is potentially asynchronous, this should be the first\n * store enhancer in the composition chain.\n *\n * Note that each middleware will be given the `dispatch` and `getState` functions\n * as named arguments.\n *\n * @param {...Function} middlewares The middleware chain to be applied.\n * @returns {Function} A store enhancer applying the middleware.\n */\n\nfunction applyMiddleware() {\n for (var _len = arguments.length, middlewares = new Array(_len), _key = 0; _key < _len; _key++) {\n middlewares[_key] = arguments[_key];\n }\n\n return function (createStore) {\n return function () {\n var store = createStore.apply(void 0, arguments);\n\n var _dispatch = function dispatch() {\n throw new Error(process.env.NODE_ENV === \"production\" ? formatProdErrorMessage(15) : 'Dispatching while constructing your middleware is not allowed. ' + 'Other middleware would not be applied to this dispatch.');\n };\n\n var middlewareAPI = {\n getState: store.getState,\n dispatch: function dispatch() {\n return _dispatch.apply(void 0, arguments);\n }\n };\n var chain = middlewares.map(function (middleware) {\n return middleware(middlewareAPI);\n });\n _dispatch = compose.apply(void 0, chain)(store.dispatch);\n return _objectSpread(_objectSpread({}, store), {}, {\n dispatch: _dispatch\n });\n };\n };\n}\n\n/*\n * This is a dummy function to check if the function name has been altered by minification.\n * If the function has been minified and NODE_ENV !== 'production', warn the user.\n */\n\nfunction isCrushed() {}\n\nif (process.env.NODE_ENV !== 'production' && typeof isCrushed.name === 'string' && isCrushed.name !== 'isCrushed') {\n warning('You are currently using minified code outside of NODE_ENV === \"production\". ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or setting mode to production in webpack (https://webpack.js.org/concepts/mode/) ' + 'to ensure you have the correct code for your production build.');\n}\n\nexport { ActionTypes as __DO_NOT_USE__ActionTypes, applyMiddleware, bindActionCreators, combineReducers, compose, createStore };\n", "/** A function that accepts a potential \"extra argument\" value to be injected later,\r\n * and returns an instance of the thunk middleware that uses that value\r\n */\nfunction createThunkMiddleware(extraArgument) {\n // Standard Redux middleware definition pattern:\n // See: https://redux.js.org/tutorials/fundamentals/part-4-store#writing-custom-middleware\n var middleware = function middleware(_ref) {\n var dispatch = _ref.dispatch,\n getState = _ref.getState;\n return function (next) {\n return function (action) {\n // The thunk middleware looks for any functions that were passed to `store.dispatch`.\n // If this \"action\" is really a function, call it and return the result.\n if (typeof action === 'function') {\n // Inject the store's `dispatch` and `getState` methods, as well as any \"extra arg\"\n return action(dispatch, getState, extraArgument);\n } // Otherwise, pass the action down the middleware chain as usual\n\n\n return next(action);\n };\n };\n };\n\n return middleware;\n}\n\nvar thunk = createThunkMiddleware(); // Attach the factory function so users can create a customized version\n// with whatever \"extra arg\" they want to inject into their thunks\n\nthunk.withExtraArgument = createThunkMiddleware;\nexport default thunk;", "import { enableES5 } from 'immer'\r\nexport * from 'redux'\r\nexport {\r\n default as createNextState,\r\n current,\r\n freeze,\r\n original,\r\n isDraft,\r\n} from 'immer'\r\nexport type { Draft } from 'immer'\r\nexport { createSelector } from 'reselect'\r\nexport type {\r\n Selector,\r\n OutputParametricSelector,\r\n OutputSelector,\r\n ParametricSelector,\r\n} from 'reselect'\r\nexport { createDraftSafeSelector } from './createDraftSafeSelector'\r\nexport type { ThunkAction, ThunkDispatch } from 'redux-thunk'\r\n\r\n// We deliberately enable Immer's ES5 support, on the grounds that\r\n// we assume RTK will be used with React Native and other Proxy-less\r\n// environments. In addition, that's how Immer 4 behaved, and since\r\n// we want to ship this in an RTK minor, we should keep the same behavior.\r\nenableES5()\r\n\r\nexport {\r\n // js\r\n configureStore,\r\n} from './configureStore'\r\nexport type {\r\n // types\r\n ConfigureEnhancersCallback,\r\n ConfigureStoreOptions,\r\n EnhancedStore,\r\n} from './configureStore'\r\nexport {\r\n // js\r\n createAction,\r\n getType,\r\n} from './createAction'\r\nexport type {\r\n // types\r\n PayloadAction,\r\n PayloadActionCreator,\r\n ActionCreatorWithNonInferrablePayload,\r\n ActionCreatorWithOptionalPayload,\r\n ActionCreatorWithPayload,\r\n ActionCreatorWithoutPayload,\r\n ActionCreatorWithPreparedPayload,\r\n PrepareAction,\r\n} from './createAction'\r\nexport {\r\n // js\r\n createReducer,\r\n} from './createReducer'\r\nexport type {\r\n // types\r\n Actions,\r\n CaseReducer,\r\n CaseReducers,\r\n} from './createReducer'\r\nexport {\r\n // js\r\n createSlice,\r\n} from './createSlice'\r\n\r\nexport type {\r\n // types\r\n CreateSliceOptions,\r\n Slice,\r\n CaseReducerActions,\r\n SliceCaseReducers,\r\n ValidateSliceCaseReducers,\r\n CaseReducerWithPrepare,\r\n SliceActionCreator,\r\n} from './createSlice'\r\nexport {\r\n // js\r\n createImmutableStateInvariantMiddleware,\r\n isImmutableDefault,\r\n} from './immutableStateInvariantMiddleware'\r\nexport type {\r\n // types\r\n ImmutableStateInvariantMiddlewareOptions,\r\n} from './immutableStateInvariantMiddleware'\r\nexport {\r\n // js\r\n createSerializableStateInvariantMiddleware,\r\n findNonSerializableValue,\r\n isPlain,\r\n} from './serializableStateInvariantMiddleware'\r\nexport type {\r\n // types\r\n SerializableStateInvariantMiddlewareOptions,\r\n} from './serializableStateInvariantMiddleware'\r\nexport {\r\n // js\r\n getDefaultMiddleware,\r\n} from './getDefaultMiddleware'\r\nexport type {\r\n // types\r\n ActionReducerMapBuilder,\r\n} from './mapBuilders'\r\nexport { MiddlewareArray } from './utils'\r\n\r\nexport { createEntityAdapter } from './entities/create_adapter'\r\nexport type {\r\n Dictionary,\r\n EntityState,\r\n EntityAdapter,\r\n EntitySelectors,\r\n EntityStateAdapter,\r\n EntityId,\r\n Update,\r\n IdSelector,\r\n Comparer,\r\n} from './entities/models'\r\n\r\nexport {\r\n createAsyncThunk,\r\n unwrapResult,\r\n miniSerializeError,\r\n} from './createAsyncThunk'\r\nexport type {\r\n AsyncThunk,\r\n AsyncThunkOptions,\r\n AsyncThunkAction,\r\n AsyncThunkPayloadCreatorReturnValue,\r\n AsyncThunkPayloadCreator,\r\n SerializedError,\r\n} from './createAsyncThunk'\r\n\r\nexport {\r\n // js\r\n isAllOf,\r\n isAnyOf,\r\n isPending,\r\n isRejected,\r\n isFulfilled,\r\n isAsyncThunkAction,\r\n isRejectedWithValue,\r\n} from './matchers'\r\nexport type {\r\n // types\r\n ActionMatchingAllOf,\r\n ActionMatchingAnyOf,\r\n} from './matchers'\r\n\r\nexport { nanoid } from './nanoid'\r\n\r\nexport { default as isPlainObject } from './isPlainObject'\r\n", "import { current, isDraft } from 'immer'\r\nimport { createSelector } from 'reselect'\r\n\r\n/**\r\n * \"Draft-Safe\" version of `reselect`'s `createSelector`:\r\n * If an `immer`-drafted object is passed into the resulting selector's first argument,\r\n * the selector will act on the current draft value, instead of returning a cached value\r\n * that might be possibly outdated if the draft has been modified since.\r\n * @public\r\n */\r\nexport const createDraftSafeSelector: typeof createSelector = (\r\n ...args: unknown[]\r\n) => {\r\n const selector = (createSelector as any)(...args)\r\n const wrappedSelector = (value: unknown, ...rest: unknown[]) =>\r\n selector(isDraft(value) ? current(value) : value, ...rest)\r\n return wrappedSelector as any\r\n}\r\n", "import type {\r\n Reducer,\r\n ReducersMapObject,\r\n Middleware,\r\n Action,\r\n AnyAction,\r\n StoreEnhancer,\r\n Store,\r\n Dispatch,\r\n PreloadedState,\r\n CombinedState,\r\n} from 'redux'\r\nimport { createStore, compose, applyMiddleware, combineReducers } from 'redux'\r\nimport type { EnhancerOptions as DevToolsOptions } from './devtoolsExtension'\r\nimport { composeWithDevTools } from './devtoolsExtension'\r\n\r\nimport isPlainObject from './isPlainObject'\r\nimport type {\r\n ThunkMiddlewareFor,\r\n CurriedGetDefaultMiddleware,\r\n} from './getDefaultMiddleware'\r\nimport { curryGetDefaultMiddleware } from './getDefaultMiddleware'\r\nimport type { DispatchForMiddlewares, NoInfer } from './tsHelpers'\r\n\r\nconst IS_PRODUCTION = process.env.NODE_ENV === 'production'\r\n\r\n/**\r\n * Callback function type, to be used in `ConfigureStoreOptions.enhancers`\r\n *\r\n * @public\r\n */\r\nexport type ConfigureEnhancersCallback = (\r\n defaultEnhancers: readonly StoreEnhancer[]\r\n) => StoreEnhancer[]\r\n\r\n/**\r\n * Options for `configureStore()`.\r\n *\r\n * @public\r\n */\r\nexport interface ConfigureStoreOptions<\r\n S = any,\r\n A extends Action = AnyAction,\r\n M extends Middlewares = Middlewares\r\n> {\r\n /**\r\n * A single reducer function that will be used as the root reducer, or an\r\n * object of slice reducers that will be passed to `combineReducers()`.\r\n */\r\n reducer: Reducer | ReducersMapObject\r\n\r\n /**\r\n * An array of Redux middleware to install. If not supplied, defaults to\r\n * the set of middleware returned by `getDefaultMiddleware()`.\r\n */\r\n middleware?: ((getDefaultMiddleware: CurriedGetDefaultMiddleware) => M) | M\r\n\r\n /**\r\n * Whether to enable Redux DevTools integration. Defaults to `true`.\r\n *\r\n * Additional configuration can be done by passing Redux DevTools options\r\n */\r\n devTools?: boolean | DevToolsOptions\r\n\r\n /**\r\n * The initial state, same as Redux's createStore.\r\n * You may optionally specify it to hydrate the state\r\n * from the server in universal apps, or to restore a previously serialized\r\n * user session. If you use `combineReducers()` to produce the root reducer\r\n * function (either directly or indirectly by passing an object as `reducer`),\r\n * this must be an object with the same shape as the reducer map keys.\r\n */\r\n /* \r\n Not 100% correct but the best approximation we can get:\r\n - if S is a `CombinedState` applying a second `CombinedState` on it does not change anything.\r\n - if it is not, there could be two cases:\r\n - `ReducersMapObject` is being passed in. In this case, we will call `combineReducers` on it and `CombinedState` is correct\r\n - `Reducer` is being passed in. In this case, actually `CombinedState` is wrong and `S` would be correct.\r\n As we cannot distinguish between those two cases without adding another generic paramter, \r\n we just make the pragmatic assumption that the latter almost never happens.\r\n */\r\n preloadedState?: PreloadedState>>\r\n\r\n /**\r\n * The store enhancers to apply. See Redux's `createStore()`.\r\n * All enhancers will be included before the DevTools Extension enhancer.\r\n * If you need to customize the order of enhancers, supply a callback\r\n * function that will receive the original array (ie, `[applyMiddleware]`),\r\n * and should return a new array (such as `[applyMiddleware, offline]`).\r\n * If you only need to add middleware, you can use the `middleware` parameter instead.\r\n */\r\n enhancers?: StoreEnhancer[] | ConfigureEnhancersCallback\r\n}\r\n\r\ntype Middlewares = ReadonlyArray>\r\n\r\n/**\r\n * A Redux store returned by `configureStore()`. Supports dispatching\r\n * side-effectful _thunks_ in addition to plain actions.\r\n *\r\n * @public\r\n */\r\nexport interface EnhancedStore<\r\n S = any,\r\n A extends Action = AnyAction,\r\n M extends Middlewares = Middlewares\r\n> extends Store {\r\n /**\r\n * The `dispatch` method of your store, enhanced by all its middlewares.\r\n *\r\n * @inheritdoc\r\n */\r\n dispatch: Dispatch & DispatchForMiddlewares\r\n}\r\n\r\n/**\r\n * A friendly abstraction over the standard Redux `createStore()` function.\r\n *\r\n * @param config The store configuration.\r\n * @returns A configured Redux store.\r\n *\r\n * @public\r\n */\r\nexport function configureStore<\r\n S = any,\r\n A extends Action = AnyAction,\r\n M extends Middlewares = [ThunkMiddlewareFor]\r\n>(options: ConfigureStoreOptions): EnhancedStore {\r\n const curriedGetDefaultMiddleware = curryGetDefaultMiddleware()\r\n\r\n const {\r\n reducer = undefined,\r\n middleware = curriedGetDefaultMiddleware(),\r\n devTools = true,\r\n preloadedState = undefined,\r\n enhancers = undefined,\r\n } = options || {}\r\n\r\n let rootReducer: Reducer\r\n\r\n if (typeof reducer === 'function') {\r\n rootReducer = reducer\r\n } else if (isPlainObject(reducer)) {\r\n rootReducer = combineReducers(reducer)\r\n } else {\r\n throw new Error(\r\n '\"reducer\" is a required argument, and must be a function or an object of functions that can be passed to combineReducers'\r\n )\r\n }\r\n\r\n let finalMiddleware = middleware\r\n if (typeof finalMiddleware === 'function') {\r\n finalMiddleware = finalMiddleware(curriedGetDefaultMiddleware)\r\n\r\n if (!IS_PRODUCTION && !Array.isArray(finalMiddleware)) {\r\n throw new Error(\r\n 'when using a middleware builder function, an array of middleware must be returned'\r\n )\r\n }\r\n }\r\n if (\r\n !IS_PRODUCTION &&\r\n finalMiddleware.some((item) => typeof item !== 'function')\r\n ) {\r\n throw new Error(\r\n 'each middleware provided to configureStore must be a function'\r\n )\r\n }\r\n\r\n const middlewareEnhancer = applyMiddleware(...finalMiddleware)\r\n\r\n let finalCompose = compose\r\n\r\n if (devTools) {\r\n finalCompose = composeWithDevTools({\r\n // Enable capture of stack traces for dispatched Redux actions\r\n trace: !IS_PRODUCTION,\r\n ...(typeof devTools === 'object' && devTools),\r\n })\r\n }\r\n\r\n let storeEnhancers: StoreEnhancer[] = [middlewareEnhancer]\r\n\r\n if (Array.isArray(enhancers)) {\r\n storeEnhancers = [middlewareEnhancer, ...enhancers]\r\n } else if (typeof enhancers === 'function') {\r\n storeEnhancers = enhancers(storeEnhancers)\r\n }\r\n\r\n const composedEnhancer = finalCompose(...storeEnhancers) as any\r\n\r\n return createStore(rootReducer, preloadedState, composedEnhancer)\r\n}\r\n", "import type { Action, ActionCreator, StoreEnhancer } from 'redux'\r\nimport { compose } from 'redux'\r\n\r\n/**\r\n * @public\r\n */\r\nexport interface EnhancerOptions {\r\n /**\r\n * the instance name to be showed on the monitor page. Default value is `document.title`.\r\n * If not specified and there's no document title, it will consist of `tabId` and `instanceId`.\r\n */\r\n name?: string\r\n /**\r\n * action creators functions to be available in the Dispatcher.\r\n */\r\n actionCreators?: ActionCreator[] | { [key: string]: ActionCreator }\r\n /**\r\n * if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.\r\n * It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.\r\n * Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).\r\n *\r\n * @default 500 ms.\r\n */\r\n latency?: number\r\n /**\r\n * (> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.\r\n *\r\n * @default 50\r\n */\r\n maxAge?: number\r\n /**\r\n * See detailed documentation at http://extension.remotedev.io/docs/API/Arguments.html#serialize\r\n */\r\n serialize?:\r\n | boolean\r\n | {\r\n options?:\r\n | boolean\r\n | {\r\n date?: boolean\r\n regex?: boolean\r\n undefined?: boolean\r\n error?: boolean\r\n symbol?: boolean\r\n map?: boolean\r\n set?: boolean\r\n function?: boolean | Function\r\n }\r\n replacer?: (key: string, value: unknown) => unknown\r\n reviver?: (key: string, value: unknown) => unknown\r\n immutable?: unknown\r\n refs?: unknown[]\r\n }\r\n /**\r\n * function which takes `action` object and id number as arguments, and should return `action` object back.\r\n */\r\n actionSanitizer?: (action: A, id: number) => A\r\n /**\r\n * function which takes `state` object and index as arguments, and should return `state` object back.\r\n */\r\n stateSanitizer?: (state: S, index: number) => S\r\n /**\r\n * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\r\n * If `actionsWhitelist` specified, `actionsBlacklist` is ignored.\r\n */\r\n actionsBlacklist?: string | string[]\r\n /**\r\n * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\r\n * If `actionsWhitelist` specified, `actionsBlacklist` is ignored.\r\n */\r\n actionsWhitelist?: string | string[]\r\n /**\r\n * called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor.\r\n * Use it as a more advanced version of `actionsBlacklist`/`actionsWhitelist` parameters.\r\n */\r\n predicate?: (state: S, action: A) => boolean\r\n /**\r\n * if specified as `false`, it will not record the changes till clicking on `Start recording` button.\r\n * Available only for Redux enhancer, for others use `autoPause`.\r\n *\r\n * @default true\r\n */\r\n shouldRecordChanges?: boolean\r\n /**\r\n * if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.\r\n * If not specified, will commit when paused. Available only for Redux enhancer.\r\n *\r\n * @default \"@@PAUSED\"\"\r\n */\r\n pauseActionType?: string\r\n /**\r\n * auto pauses when the extension\u2019s window is not opened, and so has zero impact on your app when not in use.\r\n * Not available for Redux enhancer (as it already does it but storing the data to be sent).\r\n *\r\n * @default false\r\n */\r\n autoPause?: boolean\r\n /**\r\n * if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.\r\n * Available only for Redux enhancer.\r\n *\r\n * @default false\r\n */\r\n shouldStartLocked?: boolean\r\n /**\r\n * if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.\r\n *\r\n * @default true\r\n */\r\n shouldHotReload?: boolean\r\n /**\r\n * if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.\r\n *\r\n * @default false\r\n */\r\n shouldCatchErrors?: boolean\r\n /**\r\n * If you want to restrict the extension, specify the features you allow.\r\n * If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.\r\n * Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side.\r\n * Otherwise, you'll get/set the data right from the monitor part.\r\n */\r\n features?: {\r\n /**\r\n * start/pause recording of dispatched actions\r\n */\r\n pause?: boolean\r\n /**\r\n * lock/unlock dispatching actions and side effects\r\n */\r\n lock?: boolean\r\n /**\r\n * persist states on page reloading\r\n */\r\n persist?: boolean\r\n /**\r\n * export history of actions in a file\r\n */\r\n export?: boolean | 'custom'\r\n /**\r\n * import history of actions from a file\r\n */\r\n import?: boolean | 'custom'\r\n /**\r\n * jump back and forth (time travelling)\r\n */\r\n jump?: boolean\r\n /**\r\n * skip (cancel) actions\r\n */\r\n skip?: boolean\r\n /**\r\n * drag and drop actions in the history list\r\n */\r\n reorder?: boolean\r\n /**\r\n * dispatch custom actions or action creators\r\n */\r\n dispatch?: boolean\r\n /**\r\n * generate tests for the selected actions\r\n */\r\n test?: boolean\r\n }\r\n /**\r\n * Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.\r\n * Defaults to false.\r\n */\r\n trace?: boolean | ((action: A) => string)\r\n /**\r\n * The maximum number of stack trace entries to record per action. Defaults to 10.\r\n */\r\n traceLimit?: number\r\n}\r\n\r\n/**\r\n * @public\r\n */\r\nexport const composeWithDevTools: {\r\n (options: EnhancerOptions): typeof compose\r\n (...funcs: Array>): StoreEnhancer\r\n} =\r\n typeof window !== 'undefined' &&\r\n (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__\r\n ? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__\r\n : function () {\r\n if (arguments.length === 0) return undefined\r\n if (typeof arguments[0] === 'object') return compose\r\n return compose.apply(null, arguments as any as Function[])\r\n }\r\n\r\n/**\r\n * @public\r\n */\r\nexport const devToolsEnhancer: {\r\n (options: EnhancerOptions): StoreEnhancer\r\n} =\r\n typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION__\r\n ? (window as any).__REDUX_DEVTOOLS_EXTENSION__\r\n : function () {\r\n return function (noop) {\r\n return noop\r\n }\r\n }\r\n", "/**\r\n * Returns true if the passed value is \"plain\" object, i.e. an object whose\r\n * prototype is the root `Object.prototype`. This includes objects created\r\n * using object literals, but not for instance for class instances.\r\n *\r\n * @param {any} value The value to inspect.\r\n * @returns {boolean} True if the argument appears to be a plain object.\r\n *\r\n * @public\r\n */\r\nexport default function isPlainObject(value: unknown): value is object {\r\n if (typeof value !== 'object' || value === null) return false\r\n\r\n let proto = Object.getPrototypeOf(value)\r\n if (proto === null) return true\r\n\r\n let baseProto = proto\r\n while (Object.getPrototypeOf(baseProto) !== null) {\r\n baseProto = Object.getPrototypeOf(baseProto)\r\n }\r\n\r\n return proto === baseProto\r\n}\r\n", "import type { Middleware, AnyAction } from 'redux'\r\nimport type { ThunkMiddleware } from 'redux-thunk'\r\nimport thunkMiddleware from 'redux-thunk'\r\nimport type { ImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware'\r\n/* PROD_START_REMOVE_UMD */\r\nimport { createImmutableStateInvariantMiddleware } from './immutableStateInvariantMiddleware'\r\n/* PROD_STOP_REMOVE_UMD */\r\n\r\nimport type { SerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware'\r\nimport { createSerializableStateInvariantMiddleware } from './serializableStateInvariantMiddleware'\r\nimport { MiddlewareArray } from './utils'\r\n\r\nfunction isBoolean(x: any): x is boolean {\r\n return typeof x === 'boolean'\r\n}\r\n\r\ninterface ThunkOptions {\r\n extraArgument: E\r\n}\r\n\r\ninterface GetDefaultMiddlewareOptions {\r\n thunk?: boolean | ThunkOptions\r\n immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions\r\n serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions\r\n}\r\n\r\nexport type ThunkMiddlewareFor<\r\n S,\r\n O extends GetDefaultMiddlewareOptions = {}\r\n> = O extends {\r\n thunk: false\r\n}\r\n ? never\r\n : O extends { thunk: { extraArgument: infer E } }\r\n ? ThunkMiddleware\r\n :\r\n | ThunkMiddleware //The ThunkMiddleware with a `null` ExtraArgument is here to provide backwards-compatibility.\r\n | ThunkMiddleware\r\n\r\nexport type CurriedGetDefaultMiddleware = <\r\n O extends Partial = {\r\n thunk: true\r\n immutableCheck: true\r\n serializableCheck: true\r\n }\r\n>(\r\n options?: O\r\n) => MiddlewareArray | ThunkMiddlewareFor>\r\n\r\nexport function curryGetDefaultMiddleware<\r\n S = any\r\n>(): CurriedGetDefaultMiddleware {\r\n return function curriedGetDefaultMiddleware(options) {\r\n return getDefaultMiddleware(options)\r\n }\r\n}\r\n\r\n/**\r\n * Returns any array containing the default middleware installed by\r\n * `configureStore()`. Useful if you want to configure your store with a custom\r\n * `middleware` array but still keep the default set.\r\n *\r\n * @return The default middleware used by `configureStore()`.\r\n *\r\n * @public\r\n *\r\n * @deprecated Prefer to use the callback notation for the `middleware` option in `configureStore`\r\n * to access a pre-typed `getDefaultMiddleware` instead.\r\n */\r\nexport function getDefaultMiddleware<\r\n S = any,\r\n O extends Partial = {\r\n thunk: true\r\n immutableCheck: true\r\n serializableCheck: true\r\n }\r\n>(\r\n options: O = {} as O\r\n): MiddlewareArray | ThunkMiddlewareFor> {\r\n const {\r\n thunk = true,\r\n immutableCheck = true,\r\n serializableCheck = true,\r\n } = options\r\n\r\n let middlewareArray: Middleware<{}, S>[] = new MiddlewareArray()\r\n\r\n if (thunk) {\r\n if (isBoolean(thunk)) {\r\n middlewareArray.push(thunkMiddleware)\r\n } else {\r\n middlewareArray.push(\r\n thunkMiddleware.withExtraArgument(thunk.extraArgument)\r\n )\r\n }\r\n }\r\n\r\n if (process.env.NODE_ENV !== 'production') {\r\n if (immutableCheck) {\r\n /* PROD_START_REMOVE_UMD */\r\n let immutableOptions: ImmutableStateInvariantMiddlewareOptions = {}\r\n\r\n if (!isBoolean(immutableCheck)) {\r\n immutableOptions = immutableCheck\r\n }\r\n\r\n middlewareArray.unshift(\r\n createImmutableStateInvariantMiddleware(immutableOptions)\r\n )\r\n /* PROD_STOP_REMOVE_UMD */\r\n }\r\n\r\n if (serializableCheck) {\r\n let serializableOptions: SerializableStateInvariantMiddlewareOptions = {}\r\n\r\n if (!isBoolean(serializableCheck)) {\r\n serializableOptions = serializableCheck\r\n }\r\n\r\n middlewareArray.push(\r\n createSerializableStateInvariantMiddleware(serializableOptions)\r\n )\r\n }\r\n }\r\n\r\n return middlewareArray as any\r\n}\r\n", "import type { Middleware } from 'redux'\r\n\r\nexport function getTimeMeasureUtils(maxDelay: number, fnName: string) {\r\n let elapsed = 0\r\n return {\r\n measureTime(fn: () => T): T {\r\n const started = Date.now()\r\n try {\r\n return fn()\r\n } finally {\r\n const finished = Date.now()\r\n elapsed += finished - started\r\n }\r\n },\r\n warnIfExceeded() {\r\n if (elapsed > maxDelay) {\r\n console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms. \r\nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\r\nIt is disabled in production builds, so you don't need to worry about that.`)\r\n }\r\n },\r\n }\r\n}\r\n\r\n/**\r\n * @public\r\n */\r\nexport class MiddlewareArray<\r\n Middlewares extends Middleware\r\n> extends Array {\r\n constructor(arrayLength?: number)\r\n constructor(...items: Middlewares[])\r\n constructor(...args: any[]) {\r\n super(...args)\r\n Object.setPrototypeOf(this, MiddlewareArray.prototype)\r\n }\r\n\r\n static get [Symbol.species]() {\r\n return MiddlewareArray as any\r\n }\r\n\r\n concat>>(\r\n items: AdditionalMiddlewares\r\n ): MiddlewareArray\r\n\r\n concat>>(\r\n ...items: AdditionalMiddlewares\r\n ): MiddlewareArray\r\n concat(...arr: any[]) {\r\n return super.concat.apply(this, arr)\r\n }\r\n\r\n prepend>>(\r\n items: AdditionalMiddlewares\r\n ): MiddlewareArray\r\n\r\n prepend>>(\r\n ...items: AdditionalMiddlewares\r\n ): MiddlewareArray\r\n\r\n prepend(...arr: any[]) {\r\n if (arr.length === 1 && Array.isArray(arr[0])) {\r\n return new MiddlewareArray(...arr[0].concat(this))\r\n }\r\n return new MiddlewareArray(...arr.concat(this))\r\n }\r\n}\r\n", "import type { Middleware } from 'redux'\r\nimport { getTimeMeasureUtils } from './utils'\r\n\r\ntype EntryProcessor = (key: string, value: any) => any\r\n\r\nconst isProduction: boolean = process.env.NODE_ENV === 'production'\r\nconst prefix: string = 'Invariant failed'\r\n\r\n// Throw an error if the condition fails\r\n// Strip out error messages for production\r\n// > Not providing an inline default argument for message as the result is smaller\r\nfunction invariant(condition: any, message?: string) {\r\n if (condition) {\r\n return\r\n }\r\n // Condition not passed\r\n\r\n // In production we strip the message but still throw\r\n if (isProduction) {\r\n throw new Error(prefix)\r\n }\r\n\r\n // When not in production we allow the message to pass through\r\n // *This block will be removed in production builds*\r\n throw new Error(`${prefix}: ${message || ''}`)\r\n}\r\n\r\nfunction stringify(\r\n obj: any,\r\n serializer?: EntryProcessor,\r\n indent?: string | number,\r\n decycler?: EntryProcessor\r\n): string {\r\n return JSON.stringify(obj, getSerialize(serializer, decycler), indent)\r\n}\r\n\r\nfunction getSerialize(\r\n serializer?: EntryProcessor,\r\n decycler?: EntryProcessor\r\n): EntryProcessor {\r\n let stack: any[] = [],\r\n keys: any[] = []\r\n\r\n if (!decycler)\r\n decycler = function (_: string, value: any) {\r\n if (stack[0] === value) return '[Circular ~]'\r\n return (\r\n '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']'\r\n )\r\n }\r\n\r\n return function (this: any, key: string, value: any) {\r\n if (stack.length > 0) {\r\n var thisPos = stack.indexOf(this)\r\n ~thisPos ? stack.splice(thisPos + 1) : stack.push(this)\r\n ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)\r\n if (~stack.indexOf(value)) value = decycler!.call(this, key, value)\r\n } else stack.push(value)\r\n\r\n return serializer == null ? value : serializer.call(this, key, value)\r\n }\r\n}\r\n\r\n/**\r\n * The default `isImmutable` function.\r\n *\r\n * @public\r\n */\r\nexport function isImmutableDefault(value: unknown): boolean {\r\n return (\r\n typeof value !== 'object' ||\r\n value === null ||\r\n typeof value === 'undefined' ||\r\n Object.isFrozen(value)\r\n )\r\n}\r\n\r\nexport function trackForMutations(\r\n isImmutable: IsImmutableFunc,\r\n ignorePaths: string[] | undefined,\r\n obj: any\r\n) {\r\n const trackedProperties = trackProperties(isImmutable, ignorePaths, obj)\r\n return {\r\n detectMutations() {\r\n return detectMutations(isImmutable, ignorePaths, trackedProperties, obj)\r\n },\r\n }\r\n}\r\n\r\ninterface TrackedProperty {\r\n value: any\r\n children: Record\r\n}\r\n\r\nfunction trackProperties(\r\n isImmutable: IsImmutableFunc,\r\n ignorePaths: IgnorePaths = [],\r\n obj: Record,\r\n path: string = ''\r\n) {\r\n const tracked: Partial = { value: obj }\r\n\r\n if (!isImmutable(obj)) {\r\n tracked.children = {}\r\n\r\n for (const key in obj) {\r\n const childPath = path ? path + '.' + key : key\r\n if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {\r\n continue\r\n }\r\n\r\n tracked.children[key] = trackProperties(\r\n isImmutable,\r\n ignorePaths,\r\n obj[key],\r\n childPath\r\n )\r\n }\r\n }\r\n return tracked as TrackedProperty\r\n}\r\n\r\ntype IgnorePaths = readonly string[]\r\n\r\nfunction detectMutations(\r\n isImmutable: IsImmutableFunc,\r\n ignorePaths: IgnorePaths = [],\r\n trackedProperty: TrackedProperty,\r\n obj: any,\r\n sameParentRef: boolean = false,\r\n path: string = ''\r\n): { wasMutated: boolean; path?: string } {\r\n const prevObj = trackedProperty ? trackedProperty.value : undefined\r\n\r\n const sameRef = prevObj === obj\r\n\r\n if (sameParentRef && !sameRef && !Number.isNaN(obj)) {\r\n return { wasMutated: true, path }\r\n }\r\n\r\n if (isImmutable(prevObj) || isImmutable(obj)) {\r\n return { wasMutated: false }\r\n }\r\n\r\n // Gather all keys from prev (tracked) and after objs\r\n const keysToDetect: Record = {}\r\n for (let key in trackedProperty.children) {\r\n keysToDetect[key] = true\r\n }\r\n for (let key in obj) {\r\n keysToDetect[key] = true\r\n }\r\n\r\n for (let key in keysToDetect) {\r\n const childPath = path ? path + '.' + key : key\r\n if (ignorePaths.length && ignorePaths.indexOf(childPath) !== -1) {\r\n continue\r\n }\r\n\r\n const result = detectMutations(\r\n isImmutable,\r\n ignorePaths,\r\n trackedProperty.children[key],\r\n obj[key],\r\n sameRef,\r\n childPath\r\n )\r\n\r\n if (result.wasMutated) {\r\n return result\r\n }\r\n }\r\n return { wasMutated: false }\r\n}\r\n\r\ntype IsImmutableFunc = (value: any) => boolean\r\n\r\n/**\r\n * Options for `createImmutableStateInvariantMiddleware()`.\r\n *\r\n * @public\r\n */\r\nexport interface ImmutableStateInvariantMiddlewareOptions {\r\n /**\r\n Callback function to check if a value is considered to be immutable.\r\n This function is applied recursively to every value contained in the state.\r\n The default implementation will return true for primitive types \r\n (like numbers, strings, booleans, null and undefined).\r\n */\r\n isImmutable?: IsImmutableFunc\r\n /** \r\n An array of dot-separated path strings that match named nodes from \r\n the root state to ignore when checking for immutability.\r\n Defaults to undefined\r\n */\r\n ignoredPaths?: string[]\r\n /** Print a warning if checks take longer than N ms. Default: 32ms */\r\n warnAfter?: number\r\n // @deprecated. Use ignoredPaths\r\n ignore?: string[]\r\n}\r\n\r\n/**\r\n * Creates a middleware that checks whether any state was mutated in between\r\n * dispatches or during a dispatch. If any mutations are detected, an error is\r\n * thrown.\r\n *\r\n * @param options Middleware options.\r\n *\r\n * @public\r\n */\r\nexport function createImmutableStateInvariantMiddleware(\r\n options: ImmutableStateInvariantMiddlewareOptions = {}\r\n): Middleware {\r\n if (process.env.NODE_ENV === 'production') {\r\n return () => (next) => (action) => next(action)\r\n }\r\n\r\n let {\r\n isImmutable = isImmutableDefault,\r\n ignoredPaths,\r\n warnAfter = 32,\r\n ignore,\r\n } = options\r\n\r\n // Alias ignore->ignoredPaths, but prefer ignoredPaths if present\r\n ignoredPaths = ignoredPaths || ignore\r\n\r\n const track = trackForMutations.bind(null, isImmutable, ignoredPaths)\r\n\r\n return ({ getState }) => {\r\n let state = getState()\r\n let tracker = track(state)\r\n\r\n let result\r\n return (next) => (action) => {\r\n const measureUtils = getTimeMeasureUtils(\r\n warnAfter,\r\n 'ImmutableStateInvariantMiddleware'\r\n )\r\n\r\n measureUtils.measureTime(() => {\r\n state = getState()\r\n\r\n result = tracker.detectMutations()\r\n // Track before potentially not meeting the invariant\r\n tracker = track(state)\r\n\r\n invariant(\r\n !result.wasMutated,\r\n `A state mutation was detected between dispatches, in the path '${\r\n result.path || ''\r\n }'. This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`\r\n )\r\n })\r\n\r\n const dispatchedAction = next(action)\r\n\r\n measureUtils.measureTime(() => {\r\n state = getState()\r\n\r\n result = tracker.detectMutations()\r\n // Track before potentially not meeting the invariant\r\n tracker = track(state)\r\n\r\n result.wasMutated &&\r\n invariant(\r\n !result.wasMutated,\r\n `A state mutation was detected inside a dispatch, in the path: ${\r\n result.path || ''\r\n }. Take a look at the reducer(s) handling the action ${stringify(\r\n action\r\n )}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`\r\n )\r\n })\r\n\r\n measureUtils.warnIfExceeded()\r\n\r\n return dispatchedAction\r\n }\r\n }\r\n}\r\n", "import isPlainObject from './isPlainObject'\r\nimport type { Middleware } from 'redux'\r\nimport { getTimeMeasureUtils } from './utils'\r\n\r\n/**\r\n * Returns true if the passed value is \"plain\", i.e. a value that is either\r\n * directly JSON-serializable (boolean, number, string, array, plain object)\r\n * or `undefined`.\r\n *\r\n * @param val The value to check.\r\n *\r\n * @public\r\n */\r\nexport function isPlain(val: any) {\r\n const type = typeof val\r\n return (\r\n type === 'undefined' ||\r\n val === null ||\r\n type === 'string' ||\r\n type === 'boolean' ||\r\n type === 'number' ||\r\n Array.isArray(val) ||\r\n isPlainObject(val)\r\n )\r\n}\r\n\r\ninterface NonSerializableValue {\r\n keyPath: string\r\n value: unknown\r\n}\r\n\r\n/**\r\n * @public\r\n */\r\nexport function findNonSerializableValue(\r\n value: unknown,\r\n path: string = '',\r\n isSerializable: (value: unknown) => boolean = isPlain,\r\n getEntries?: (value: unknown) => [string, any][],\r\n ignoredPaths: readonly string[] = []\r\n): NonSerializableValue | false {\r\n let foundNestedSerializable: NonSerializableValue | false\r\n\r\n if (!isSerializable(value)) {\r\n return {\r\n keyPath: path || '',\r\n value: value,\r\n }\r\n }\r\n\r\n if (typeof value !== 'object' || value === null) {\r\n return false\r\n }\r\n\r\n const entries = getEntries != null ? getEntries(value) : Object.entries(value)\r\n\r\n const hasIgnoredPaths = ignoredPaths.length > 0\r\n\r\n for (const [key, nestedValue] of entries) {\r\n const nestedPath = path ? path + '.' + key : key\r\n\r\n if (hasIgnoredPaths && ignoredPaths.indexOf(nestedPath) >= 0) {\r\n continue\r\n }\r\n\r\n if (!isSerializable(nestedValue)) {\r\n return {\r\n keyPath: nestedPath,\r\n value: nestedValue,\r\n }\r\n }\r\n\r\n if (typeof nestedValue === 'object') {\r\n foundNestedSerializable = findNonSerializableValue(\r\n nestedValue,\r\n nestedPath,\r\n isSerializable,\r\n getEntries,\r\n ignoredPaths\r\n )\r\n\r\n if (foundNestedSerializable) {\r\n return foundNestedSerializable\r\n }\r\n }\r\n }\r\n\r\n return false\r\n}\r\n\r\n/**\r\n * Options for `createSerializableStateInvariantMiddleware()`.\r\n *\r\n * @public\r\n */\r\nexport interface SerializableStateInvariantMiddlewareOptions {\r\n /**\r\n * The function to check if a value is considered serializable. This\r\n * function is applied recursively to every value contained in the\r\n * state. Defaults to `isPlain()`.\r\n */\r\n isSerializable?: (value: any) => boolean\r\n /**\r\n * The function that will be used to retrieve entries from each\r\n * value. If unspecified, `Object.entries` will be used. Defaults\r\n * to `undefined`.\r\n */\r\n getEntries?: (value: any) => [string, any][]\r\n\r\n /**\r\n * An array of action types to ignore when checking for serializability.\r\n * Defaults to []\r\n */\r\n ignoredActions?: string[]\r\n\r\n /**\r\n * An array of dot-separated path strings to ignore when checking\r\n * for serializability, Defaults to ['meta.arg', 'meta.baseQueryMeta']\r\n */\r\n ignoredActionPaths?: string[]\r\n\r\n /**\r\n * An array of dot-separated path strings to ignore when checking\r\n * for serializability, Defaults to []\r\n */\r\n ignoredPaths?: string[]\r\n /**\r\n * Execution time warning threshold. If the middleware takes longer\r\n * than `warnAfter` ms, a warning will be displayed in the console.\r\n * Defaults to 32ms.\r\n */\r\n warnAfter?: number\r\n\r\n /**\r\n * Opt out of checking state, but continue checking actions\r\n */\r\n ignoreState?: boolean\r\n}\r\n\r\n/**\r\n * Creates a middleware that, after every state change, checks if the new\r\n * state is serializable. If a non-serializable value is found within the\r\n * state, an error is printed to the console.\r\n *\r\n * @param options Middleware options.\r\n *\r\n * @public\r\n */\r\nexport function createSerializableStateInvariantMiddleware(\r\n options: SerializableStateInvariantMiddlewareOptions = {}\r\n): Middleware {\r\n if (process.env.NODE_ENV === 'production') {\r\n return () => (next) => (action) => next(action)\r\n }\r\n const {\r\n isSerializable = isPlain,\r\n getEntries,\r\n ignoredActions = [],\r\n ignoredActionPaths = ['meta.arg', 'meta.baseQueryMeta'],\r\n ignoredPaths = [],\r\n warnAfter = 32,\r\n ignoreState = false,\r\n } = options\r\n\r\n return (storeAPI) => (next) => (action) => {\r\n if (ignoredActions.length && ignoredActions.indexOf(action.type) !== -1) {\r\n return next(action)\r\n }\r\n\r\n const measureUtils = getTimeMeasureUtils(\r\n warnAfter,\r\n 'SerializableStateInvariantMiddleware'\r\n )\r\n measureUtils.measureTime(() => {\r\n const foundActionNonSerializableValue = findNonSerializableValue(\r\n action,\r\n '',\r\n isSerializable,\r\n getEntries,\r\n ignoredActionPaths\r\n )\r\n\r\n if (foundActionNonSerializableValue) {\r\n const { keyPath, value } = foundActionNonSerializableValue\r\n\r\n console.error(\r\n `A non-serializable value was detected in an action, in the path: \\`${keyPath}\\`. Value:`,\r\n value,\r\n '\\nTake a look at the logic that dispatched this action: ',\r\n action,\r\n '\\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)',\r\n '\\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)'\r\n )\r\n }\r\n })\r\n\r\n const result = next(action)\r\n\r\n if (!ignoreState) {\r\n measureUtils.measureTime(() => {\r\n const state = storeAPI.getState()\r\n\r\n const foundStateNonSerializableValue = findNonSerializableValue(\r\n state,\r\n '',\r\n isSerializable,\r\n getEntries,\r\n ignoredPaths\r\n )\r\n\r\n if (foundStateNonSerializableValue) {\r\n const { keyPath, value } = foundStateNonSerializableValue\r\n\r\n console.error(\r\n `A non-serializable value was detected in the state, in the path: \\`${keyPath}\\`. Value:`,\r\n value,\r\n `\r\nTake a look at the reducer(s) handling this action type: ${action.type}.\r\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`\r\n )\r\n }\r\n })\r\n\r\n measureUtils.warnIfExceeded()\r\n }\r\n\r\n return result\r\n }\r\n}\r\n", "import type { Action } from 'redux'\r\nimport type {\r\n IsUnknownOrNonInferrable,\r\n IfMaybeUndefined,\r\n IfVoid,\r\n IsAny,\r\n} from './tsHelpers'\r\nimport isPlainObject from './isPlainObject'\r\n\r\n/**\r\n * An action with a string type and an associated payload. This is the\r\n * type of action returned by `createAction()` action creators.\r\n *\r\n * @template P The type of the action's payload.\r\n * @template T the type used for the action type.\r\n * @template M The type of the action's meta (optional)\r\n * @template E The type of the action's error (optional)\r\n *\r\n * @public\r\n */\r\nexport type PayloadAction<\r\n P = void,\r\n T extends string = string,\r\n M = never,\r\n E = never\r\n> = {\r\n payload: P\r\n type: T\r\n} & ([M] extends [never]\r\n ? {}\r\n : {\r\n meta: M\r\n }) &\r\n ([E] extends [never]\r\n ? {}\r\n : {\r\n error: E\r\n })\r\n\r\n/**\r\n * A \"prepare\" method to be used as the second parameter of `createAction`.\r\n * Takes any number of arguments and returns a Flux Standard Action without\r\n * type (will be added later) that *must* contain a payload (might be undefined).\r\n *\r\n * @public\r\n */\r\nexport type PrepareAction =\r\n | ((...args: any[]) => { payload: P })\r\n | ((...args: any[]) => { payload: P; meta: any })\r\n | ((...args: any[]) => { payload: P; error: any })\r\n | ((...args: any[]) => { payload: P; meta: any; error: any })\r\n\r\n/**\r\n * Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.\r\n *\r\n * @internal\r\n */\r\nexport type _ActionCreatorWithPreparedPayload<\r\n PA extends PrepareAction | void,\r\n T extends string = string\r\n> = PA extends PrepareAction\r\n ? ActionCreatorWithPreparedPayload<\r\n Parameters,\r\n P,\r\n T,\r\n ReturnType extends {\r\n error: infer E\r\n }\r\n ? E\r\n : never,\r\n ReturnType extends {\r\n meta: infer M\r\n }\r\n ? M\r\n : never\r\n >\r\n : void\r\n\r\n/**\r\n * Basic type for all action creators.\r\n *\r\n * @inheritdoc {redux#ActionCreator}\r\n */\r\ninterface BaseActionCreator {\r\n type: T\r\n match: (action: Action) => action is PayloadAction\r\n}\r\n\r\n/**\r\n * An action creator that takes multiple arguments that are passed\r\n * to a `PrepareAction` method to create the final Action.\r\n * @typeParam Args arguments for the action creator function\r\n * @typeParam P `payload` type\r\n * @typeParam T `type` name\r\n * @typeParam E optional `error` type\r\n * @typeParam M optional `meta` type\r\n *\r\n * @inheritdoc {redux#ActionCreator}\r\n *\r\n * @public\r\n */\r\nexport interface ActionCreatorWithPreparedPayload<\r\n Args extends unknown[],\r\n P,\r\n T extends string = string,\r\n E = never,\r\n M = never\r\n> extends BaseActionCreator
{\r\n /**\r\n * Calling this {@link redux#ActionCreator} with `Args` will return\r\n * an Action with a payload of type `P` and (depending on the `PrepareAction`\r\n * method used) a `meta`- and `error` property of types `M` and `E` respectively.\r\n */\r\n (...args: Args): PayloadAction
\r\n}\r\n\r\n/**\r\n * An action creator of type `T` that takes an optional payload of type `P`.\r\n *\r\n * @inheritdoc {redux#ActionCreator}\r\n *\r\n * @public\r\n */\r\nexport interface ActionCreatorWithOptionalPayload
\r\n extends BaseActionCreator
{\r\n /**\r\n * Calling this {@link redux#ActionCreator} with an argument will\r\n * return a {@link PayloadAction} of type `T` with a payload of `P`.\r\n * Calling it without an argument will return a PayloadAction with a payload of `undefined`.\r\n */\r\n (payload?: P): PayloadAction
\r\n}\r\n\r\n/**\r\n * An action creator of type `T` that takes no payload.\r\n *\r\n * @inheritdoc {redux#ActionCreator}\r\n *\r\n * @public\r\n */\r\nexport interface ActionCreatorWithoutPayload\r\n extends BaseActionCreator {\r\n /**\r\n * Calling this {@link redux#ActionCreator} will\r\n * return a {@link PayloadAction} of type `T` with a payload of `undefined`\r\n */\r\n (): PayloadAction\r\n}\r\n\r\n/**\r\n * An action creator of type `T` that requires a payload of type P.\r\n *\r\n * @inheritdoc {redux#ActionCreator}\r\n *\r\n * @public\r\n */\r\nexport interface ActionCreatorWithPayload\r\n extends BaseActionCreator
{\r\n /**\r\n * Calling this {@link redux#ActionCreator} with an argument will\r\n * return a {@link PayloadAction} of type `T` with a payload of `P`\r\n */\r\n (payload: P): PayloadAction
\r\n}\r\n\r\n/**\r\n * An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.\r\n *\r\n * @inheritdoc {redux#ActionCreator}\r\n *\r\n * @public\r\n */\r\nexport interface ActionCreatorWithNonInferrablePayload<\r\n T extends string = string\r\n> extends BaseActionCreator {\r\n /**\r\n * Calling this {@link redux#ActionCreator} with an argument will\r\n * return a {@link PayloadAction} of type `T` with a payload\r\n * of exactly the type of the argument.\r\n */\r\n (payload: PT): PayloadAction\r\n}\r\n\r\n/**\r\n * An action creator that produces actions with a `payload` attribute.\r\n *\r\n * @typeParam P the `payload` type\r\n * @typeParam T the `type` of the resulting action\r\n * @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.\r\n *\r\n * @public\r\n */\r\nexport type PayloadActionCreator<\r\n P = void,\r\n T extends string = string,\r\n PA extends PrepareAction | void = void\r\n> = IfPrepareActionMethodProvided<\r\n PA,\r\n _ActionCreatorWithPreparedPayload,\r\n // else\r\n IsAny<\r\n P,\r\n ActionCreatorWithPayload,\r\n IsUnknownOrNonInferrable<\r\n P,\r\n ActionCreatorWithNonInferrablePayload,\r\n // else\r\n IfVoid<\r\n P,\r\n ActionCreatorWithoutPayload,\r\n // else\r\n IfMaybeUndefined<\r\n P,\r\n ActionCreatorWithOptionalPayload,\r\n // else\r\n ActionCreatorWithPayload
\r\n >\r\n >\r\n >\r\n >\r\n>\r\n\r\n/**\r\n * A utility function to create an action creator for the given action type\r\n * string. The action creator accepts a single argument, which will be included\r\n * in the action object as a field called payload. The action creator function\r\n * will also have its toString() overriden so that it returns the action type,\r\n * allowing it to be used in reducer logic that is looking for that action type.\r\n *\r\n * @param type The action type to use for created actions.\r\n * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.\r\n * If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.\r\n *\r\n * @public\r\n */\r\nexport function createAction
(\r\n type: T\r\n): PayloadActionCreator
\r\n\r\n/**\r\n * A utility function to create an action creator for the given action type\r\n * string. The action creator accepts a single argument, which will be included\r\n * in the action object as a field called payload. The action creator function\r\n * will also have its toString() overriden so that it returns the action type,\r\n * allowing it to be used in reducer logic that is looking for that action type.\r\n *\r\n * @param type The action type to use for created actions.\r\n * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.\r\n * If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.\r\n *\r\n * @public\r\n */\r\nexport function createAction<\r\n PA extends PrepareAction,\r\n T extends string = string\r\n>(\r\n type: T,\r\n prepareAction: PA\r\n): PayloadActionCreator['payload'], T, PA>\r\n\r\nexport function createAction(type: string, prepareAction?: Function): any {\r\n function actionCreator(...args: any[]) {\r\n if (prepareAction) {\r\n let prepared = prepareAction(...args)\r\n if (!prepared) {\r\n throw new Error('prepareAction did not return an object')\r\n }\r\n\r\n return {\r\n type,\r\n payload: prepared.payload,\r\n ...('meta' in prepared && { meta: prepared.meta }),\r\n ...('error' in prepared && { error: prepared.error }),\r\n }\r\n }\r\n return { type, payload: args[0] }\r\n }\r\n\r\n actionCreator.toString = () => `${type}`\r\n\r\n actionCreator.type = type\r\n\r\n actionCreator.match = (action: Action): action is PayloadAction =>\r\n action.type === type\r\n\r\n return actionCreator\r\n}\r\n\r\nexport function isFSA(action: unknown): action is {\r\n type: string\r\n payload?: unknown\r\n error?: unknown\r\n meta?: unknown\r\n} {\r\n return (\r\n isPlainObject(action) &&\r\n typeof (action as any).type === 'string' &&\r\n Object.keys(action).every(isValidKey)\r\n )\r\n}\r\n\r\nfunction isValidKey(key: string) {\r\n return ['type', 'payload', 'error', 'meta'].indexOf(key) > -1\r\n}\r\n\r\n/**\r\n * Returns the action type of the actions created by the passed\r\n * `createAction()`-generated action creator (arbitrary action creators\r\n * are not supported).\r\n *\r\n * @param action The action creator whose action type to get.\r\n * @returns The action type used by the action creator.\r\n *\r\n * @public\r\n */\r\nexport function getType(\r\n actionCreator: PayloadActionCreator\r\n): T {\r\n return `${actionCreator}` as T\r\n}\r\n\r\n// helper types for more readable typings\r\n\r\ntype IfPrepareActionMethodProvided<\r\n PA extends PrepareAction | void,\r\n True,\r\n False\r\n> = PA extends (...args: any[]) => any ? True : False\r\n", "import type { Draft } from 'immer'\r\nimport createNextState, { isDraft, isDraftable } from 'immer'\r\nimport type { AnyAction, Action, Reducer } from 'redux'\r\nimport type { ActionReducerMapBuilder } from './mapBuilders'\r\nimport { executeReducerBuilderCallback } from './mapBuilders'\r\nimport type { NoInfer } from './tsHelpers'\r\n\r\n/**\r\n * Defines a mapping from action types to corresponding action object shapes.\r\n *\r\n * @deprecated This should not be used manually - it is only used for internal\r\n * inference purposes and should not have any further value.\r\n * It might be removed in the future.\r\n * @public\r\n */\r\nexport type Actions = Record\r\n\r\nexport interface ActionMatcher {\r\n (action: AnyAction): action is A\r\n}\r\n\r\nexport type ActionMatcherDescription = {\r\n matcher: ActionMatcher\r\n reducer: CaseReducer>\r\n}\r\n\r\nexport type ReadonlyActionMatcherDescriptionCollection = ReadonlyArray<\r\n ActionMatcherDescription\r\n>\r\n\r\nexport type ActionMatcherDescriptionCollection = Array<\r\n ActionMatcherDescription\r\n>\r\n\r\n/**\r\n * An *case reducer* is a reducer function for a specific action type. Case\r\n * reducers can be composed to full reducers using `createReducer()`.\r\n *\r\n * Unlike a normal Redux reducer, a case reducer is never called with an\r\n * `undefined` state to determine the initial state. Instead, the initial\r\n * state is explicitly specified as an argument to `createReducer()`.\r\n *\r\n * In addition, a case reducer can choose to mutate the passed-in `state`\r\n * value directly instead of returning a new state. This does not actually\r\n * cause the store state to be mutated directly; instead, thanks to\r\n * [immer](https://github.com/mweststrate/immer), the mutations are\r\n * translated to copy operations that result in a new state.\r\n *\r\n * @public\r\n */\r\nexport type CaseReducer = (\r\n state: Draft,\r\n action: A\r\n) => S | void | Draft\r\n\r\n/**\r\n * A mapping from action types to case reducers for `createReducer()`.\r\n *\r\n * @deprecated This should not be used manually - it is only used\r\n * for internal inference purposes and using it manually\r\n * would lead to type erasure.\r\n * It might be removed in the future.\r\n * @public\r\n */\r\nexport type CaseReducers = {\r\n [T in keyof AS]: AS[T] extends Action ? CaseReducer : void\r\n}\r\n\r\nexport type NotFunction = T extends Function ? never : T\r\n\r\nfunction isStateFunction(x: unknown): x is () => S {\r\n return typeof x === 'function'\r\n}\r\n\r\nexport type ReducerWithInitialState> = Reducer & {\r\n getInitialState: () => S\r\n}\r\n\r\n/**\r\n * A utility function that allows defining a reducer as a mapping from action\r\n * type to *case reducer* functions that handle these action types. The\r\n * reducer's initial state is passed as the first argument.\r\n *\r\n * @remarks\r\n * The body of every case reducer is implicitly wrapped with a call to\r\n * `produce()` from the [immer](https://github.com/mweststrate/immer) library.\r\n * This means that rather than returning a new state object, you can also\r\n * mutate the passed-in state object directly; these mutations will then be\r\n * automatically and efficiently translated into copies, giving you both\r\n * convenience and immutability.\r\n *\r\n * @overloadSummary\r\n * This overload accepts a callback function that receives a `builder` object as its argument.\r\n * That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be\r\n * called to define what actions this reducer will handle.\r\n *\r\n * @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\r\n * @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define\r\n * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.\r\n * @example\r\n```ts\r\nimport {\r\n createAction,\r\n createReducer,\r\n AnyAction,\r\n PayloadAction,\r\n} from \"@reduxjs/toolkit\";\r\n\r\nconst increment = createAction(\"increment\");\r\nconst decrement = createAction(\"decrement\");\r\n\r\nfunction isActionWithNumberPayload(\r\n action: AnyAction\r\n): action is PayloadAction {\r\n return typeof action.payload === \"number\";\r\n}\r\n\r\nconst reducer = createReducer(\r\n {\r\n counter: 0,\r\n sumOfNumberPayloads: 0,\r\n unhandledActions: 0,\r\n },\r\n (builder) => {\r\n builder\r\n .addCase(increment, (state, action) => {\r\n // action is inferred correctly here\r\n state.counter += action.payload;\r\n })\r\n // You can chain calls, or have separate `builder.addCase()` lines each time\r\n .addCase(decrement, (state, action) => {\r\n state.counter -= action.payload;\r\n })\r\n // You can apply a \"matcher function\" to incoming actions\r\n .addMatcher(isActionWithNumberPayload, (state, action) => {})\r\n // and provide a default case if no other handlers matched\r\n .addDefaultCase((state, action) => {});\r\n }\r\n);\r\n```\r\n * @public\r\n */\r\nexport function createReducer>(\r\n initialState: S | (() => S),\r\n builderCallback: (builder: ActionReducerMapBuilder) => void\r\n): ReducerWithInitialState\r\n\r\n/**\r\n * A utility function that allows defining a reducer as a mapping from action\r\n * type to *case reducer* functions that handle these action types. The\r\n * reducer's initial state is passed as the first argument.\r\n *\r\n * The body of every case reducer is implicitly wrapped with a call to\r\n * `produce()` from the [immer](https://github.com/mweststrate/immer) library.\r\n * This means that rather than returning a new state object, you can also\r\n * mutate the passed-in state object directly; these mutations will then be\r\n * automatically and efficiently translated into copies, giving you both\r\n * convenience and immutability.\r\n * \r\n * @overloadSummary\r\n * This overload accepts an object where the keys are string action types, and the values\r\n * are case reducer functions to handle those action types.\r\n *\r\n * @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\r\n * @param actionsMap - An object mapping from action types to _case reducers_, each of which handles one specific action type.\r\n * @param actionMatchers - An array of matcher definitions in the form `{matcher, reducer}`.\r\n * All matching reducers will be executed in order, independently if a case reducer matched or not.\r\n * @param defaultCaseReducer - A \"default case\" reducer that is executed if no case reducer and no matcher\r\n * reducer was executed for this action.\r\n *\r\n * @example\r\n```js\r\nconst counterReducer = createReducer(0, {\r\n increment: (state, action) => state + action.payload,\r\n decrement: (state, action) => state - action.payload\r\n})\r\n\r\n// Alternately, use a \"lazy initializer\" to provide the initial state\r\n// (works with either form of createReducer)\r\nconst initialState = () => 0\r\nconst counterReducer = createReducer(initialState, {\r\n increment: (state, action) => state + action.payload,\r\n decrement: (state, action) => state - action.payload\r\n})\r\n```\r\n \r\n * Action creators that were generated using [`createAction`](./createAction) may be used directly as the keys here, using computed property syntax:\r\n\r\n```js\r\nconst increment = createAction('increment')\r\nconst decrement = createAction('decrement')\r\n\r\nconst counterReducer = createReducer(0, {\r\n [increment]: (state, action) => state + action.payload,\r\n [decrement.type]: (state, action) => state - action.payload\r\n})\r\n```\r\n * @public\r\n */\r\nexport function createReducer<\r\n S extends NotFunction,\r\n CR extends CaseReducers = CaseReducers\r\n>(\r\n initialState: S | (() => S),\r\n actionsMap: CR,\r\n actionMatchers?: ActionMatcherDescriptionCollection,\r\n defaultCaseReducer?: CaseReducer\r\n): ReducerWithInitialState\r\n\r\nexport function createReducer>(\r\n initialState: S | (() => S),\r\n mapOrBuilderCallback:\r\n | CaseReducers\r\n | ((builder: ActionReducerMapBuilder) => void),\r\n actionMatchers: ReadonlyActionMatcherDescriptionCollection = [],\r\n defaultCaseReducer?: CaseReducer\r\n): ReducerWithInitialState {\r\n let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] =\r\n typeof mapOrBuilderCallback === 'function'\r\n ? executeReducerBuilderCallback(mapOrBuilderCallback)\r\n : [mapOrBuilderCallback, actionMatchers, defaultCaseReducer]\r\n\r\n // Ensure the initial state gets frozen either way\r\n let getInitialState: () => S\r\n if (isStateFunction(initialState)) {\r\n getInitialState = () => createNextState(initialState(), () => {})\r\n } else {\r\n const frozenInitialState = createNextState(initialState, () => {})\r\n getInitialState = () => frozenInitialState\r\n }\r\n\r\n function reducer(state = getInitialState(), action: any): S {\r\n let caseReducers = [\r\n actionsMap[action.type],\r\n ...finalActionMatchers\r\n .filter(({ matcher }) => matcher(action))\r\n .map(({ reducer }) => reducer),\r\n ]\r\n if (caseReducers.filter((cr) => !!cr).length === 0) {\r\n caseReducers = [finalDefaultCaseReducer]\r\n }\r\n\r\n return caseReducers.reduce((previousState, caseReducer): S => {\r\n if (caseReducer) {\r\n if (isDraft(previousState)) {\r\n // If it's already a draft, we must already be inside a `createNextState` call,\r\n // likely because this is being wrapped in `createReducer`, `createSlice`, or nested\r\n // inside an existing draft. It's safe to just pass the draft to the mutator.\r\n const draft = previousState as Draft // We can assume this is already a draft\r\n const result = caseReducer(draft, action)\r\n\r\n if (typeof result === 'undefined') {\r\n return previousState\r\n }\r\n\r\n return result as S\r\n } else if (!isDraftable(previousState)) {\r\n // If state is not draftable (ex: a primitive, such as 0), we want to directly\r\n // return the caseReducer func and not wrap it with produce.\r\n const result = caseReducer(previousState as any, action)\r\n\r\n if (typeof result === 'undefined') {\r\n if (previousState === null) {\r\n return previousState\r\n }\r\n throw Error(\r\n 'A case reducer on a non-draftable value must not return undefined'\r\n )\r\n }\r\n\r\n return result as S\r\n } else {\r\n // @ts-ignore createNextState() produces an Immutable> rather\r\n // than an Immutable, and TypeScript cannot find out how to reconcile\r\n // these two types.\r\n return createNextState(previousState, (draft: Draft) => {\r\n return caseReducer(draft, action)\r\n })\r\n }\r\n }\r\n\r\n return previousState\r\n }, state)\r\n }\r\n\r\n reducer.getInitialState = getInitialState\r\n\r\n return reducer as ReducerWithInitialState\r\n}\r\n", "import type { Action, AnyAction } from 'redux'\r\nimport type {\r\n CaseReducer,\r\n CaseReducers,\r\n ActionMatcher,\r\n ActionMatcherDescriptionCollection,\r\n} from './createReducer'\r\n\r\nexport interface TypedActionCreator {\r\n (...args: any[]): Action\r\n type: Type\r\n}\r\n\r\n/**\r\n * A builder for an action <-> reducer map.\r\n *\r\n * @public\r\n */\r\nexport interface ActionReducerMapBuilder {\r\n /**\r\n * Adds a case reducer to handle a single exact action type.\r\n * @remarks\r\n * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.\r\n * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\r\n * @param reducer - The actual case reducer function.\r\n */\r\n addCase>(\r\n actionCreator: ActionCreator,\r\n reducer: CaseReducer>\r\n ): ActionReducerMapBuilder\r\n /**\r\n * Adds a case reducer to handle a single exact action type.\r\n * @remarks\r\n * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.\r\n * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\r\n * @param reducer - The actual case reducer function.\r\n */\r\n addCase>(\r\n type: Type,\r\n reducer: CaseReducer\r\n ): ActionReducerMapBuilder\r\n\r\n /**\r\n * Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.\r\n * @remarks\r\n * If multiple matcher reducers match, all of them will be executed in the order\r\n * they were defined in - even if a case reducer already matched.\r\n * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and before any calls to `builder.addDefaultCase`.\r\n * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/advanced-types.html#using-type-predicates)\r\n * function\r\n * @param reducer - The actual case reducer function.\r\n *\r\n * @example\r\n```ts\r\nimport {\r\n createAction,\r\n createReducer,\r\n AsyncThunk,\r\n AnyAction,\r\n} from \"@reduxjs/toolkit\";\r\n\r\ntype GenericAsyncThunk = AsyncThunk;\r\n\r\ntype PendingAction = ReturnType;\r\ntype RejectedAction = ReturnType;\r\ntype FulfilledAction = ReturnType;\r\n\r\nconst initialState: Record = {};\r\nconst resetAction = createAction(\"reset-tracked-loading-state\");\r\n\r\nfunction isPendingAction(action: AnyAction): action is PendingAction {\r\n return action.type.endsWith(\"/pending\");\r\n}\r\n\r\nconst reducer = createReducer(initialState, (builder) => {\r\n builder\r\n .addCase(resetAction, () => initialState)\r\n // matcher can be defined outside as a type predicate function\r\n .addMatcher(isPendingAction, (state, action) => {\r\n state[action.meta.requestId] = \"pending\";\r\n })\r\n .addMatcher(\r\n // matcher can be defined inline as a type predicate function\r\n (action): action is RejectedAction => action.type.endsWith(\"/rejected\"),\r\n (state, action) => {\r\n state[action.meta.requestId] = \"rejected\";\r\n }\r\n )\r\n // matcher can just return boolean and the matcher can receive a generic argument\r\n .addMatcher(\r\n (action) => action.type.endsWith(\"/fulfilled\"),\r\n (state, action) => {\r\n state[action.meta.requestId] = \"fulfilled\";\r\n }\r\n );\r\n});\r\n```\r\n */\r\n addMatcher(\r\n matcher: ActionMatcher | ((action: AnyAction) => boolean),\r\n reducer: CaseReducer\r\n ): Omit, 'addCase'>\r\n\r\n /**\r\n * Adds a \"default case\" reducer that is executed if no case reducer and no matcher\r\n * reducer was executed for this action.\r\n * @param reducer - The fallback \"default case\" reducer function.\r\n *\r\n * @example\r\n```ts\r\nimport { createReducer } from '@reduxjs/toolkit'\r\nconst initialState = { otherActions: 0 }\r\nconst reducer = createReducer(initialState, builder => {\r\n builder\r\n // .addCase(...)\r\n // .addMatcher(...)\r\n .addDefaultCase((state, action) => {\r\n state.otherActions++\r\n })\r\n})\r\n```\r\n */\r\n addDefaultCase(reducer: CaseReducer): {}\r\n}\r\n\r\nexport function executeReducerBuilderCallback(\r\n builderCallback: (builder: ActionReducerMapBuilder) => void\r\n): [\r\n CaseReducers,\r\n ActionMatcherDescriptionCollection,\r\n CaseReducer | undefined\r\n] {\r\n const actionsMap: CaseReducers = {}\r\n const actionMatchers: ActionMatcherDescriptionCollection = []\r\n let defaultCaseReducer: CaseReducer | undefined\r\n const builder = {\r\n addCase(\r\n typeOrActionCreator: string | TypedActionCreator,\r\n reducer: CaseReducer\r\n ) {\r\n if (process.env.NODE_ENV !== 'production') {\r\n /*\r\n to keep the definition by the user in line with actual behavior, \r\n we enforce `addCase` to always be called before calling `addMatcher`\r\n as matching cases take precedence over matchers\r\n */\r\n if (actionMatchers.length > 0) {\r\n throw new Error(\r\n '`builder.addCase` should only be called before calling `builder.addMatcher`'\r\n )\r\n }\r\n if (defaultCaseReducer) {\r\n throw new Error(\r\n '`builder.addCase` should only be called before calling `builder.addDefaultCase`'\r\n )\r\n }\r\n }\r\n const type =\r\n typeof typeOrActionCreator === 'string'\r\n ? typeOrActionCreator\r\n : typeOrActionCreator.type\r\n if (type in actionsMap) {\r\n throw new Error(\r\n 'addCase cannot be called with two reducers for the same action type'\r\n )\r\n }\r\n actionsMap[type] = reducer\r\n return builder\r\n },\r\n addMatcher(\r\n matcher: ActionMatcher ,\r\n reducer: CaseReducer\r\n ) {\r\n if (process.env.NODE_ENV !== 'production') {\r\n if (defaultCaseReducer) {\r\n throw new Error(\r\n '`builder.addMatcher` should only be called before calling `builder.addDefaultCase`'\r\n )\r\n }\r\n }\r\n actionMatchers.push({ matcher, reducer })\r\n return builder\r\n },\r\n addDefaultCase(reducer: CaseReducer) {\r\n if (process.env.NODE_ENV !== 'production') {\r\n if (defaultCaseReducer) {\r\n throw new Error('`builder.addDefaultCase` can only be called once')\r\n }\r\n }\r\n defaultCaseReducer = reducer\r\n return builder\r\n },\r\n }\r\n builderCallback(builder)\r\n return [actionsMap, actionMatchers, defaultCaseReducer]\r\n}\r\n", "import type { AnyAction, Reducer } from 'redux'\r\nimport { createNextState } from '.'\r\nimport type {\r\n ActionCreatorWithoutPayload,\r\n PayloadAction,\r\n PayloadActionCreator,\r\n PrepareAction,\r\n _ActionCreatorWithPreparedPayload,\r\n} from './createAction'\r\nimport { createAction } from './createAction'\r\nimport type {\r\n CaseReducer,\r\n CaseReducers,\r\n ReducerWithInitialState,\r\n} from './createReducer'\r\nimport { createReducer, NotFunction } from './createReducer'\r\nimport type { ActionReducerMapBuilder } from './mapBuilders'\r\nimport { executeReducerBuilderCallback } from './mapBuilders'\r\nimport type { NoInfer } from './tsHelpers'\r\n\r\n/**\r\n * An action creator attached to a slice.\r\n *\r\n * @deprecated please use PayloadActionCreator directly\r\n *\r\n * @public\r\n */\r\nexport type SliceActionCreator = PayloadActionCreator
\r\n\r\n/**\r\n * The return value of `createSlice`\r\n *\r\n * @public\r\n */\r\nexport interface Slice<\r\n State = any,\r\n CaseReducers extends SliceCaseReducers = SliceCaseReducers,\r\n Name extends string = string\r\n> {\r\n /**\r\n * The slice name.\r\n */\r\n name: Name\r\n\r\n /**\r\n * The slice's reducer.\r\n */\r\n reducer: Reducer\r\n\r\n /**\r\n * Action creators for the types of actions that are handled by the slice\r\n * reducer.\r\n */\r\n actions: CaseReducerActions\r\n\r\n /**\r\n * The individual case reducer functions that were passed in the `reducers` parameter.\r\n * This enables reuse and testing if they were defined inline when calling `createSlice`.\r\n */\r\n caseReducers: SliceDefinedCaseReducers\r\n\r\n /**\r\n * Provides access to the initial state value given to the slice.\r\n * If a lazy state initializer was provided, it will be called and a fresh value returned.\r\n */\r\n getInitialState: () => State\r\n}\r\n\r\n/**\r\n * Options for `createSlice()`.\r\n *\r\n * @public\r\n */\r\nexport interface CreateSliceOptions<\r\n State = any,\r\n CR extends SliceCaseReducers = SliceCaseReducers,\r\n Name extends string = string\r\n> {\r\n /**\r\n * The slice's name. Used to namespace the generated action types.\r\n */\r\n name: Name\r\n\r\n /**\r\n * The initial state that should be used when the reducer is called the first time. This may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\r\n */\r\n initialState: State | (() => State)\r\n\r\n /**\r\n * A mapping from action types to action-type-specific *case reducer*\r\n * functions. For every action type, a matching action creator will be\r\n * generated using `createAction()`.\r\n */\r\n reducers: ValidateSliceCaseReducers\r\n\r\n /**\r\n * A callback that receives a *builder* object to define\r\n * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.\r\n * \r\n * Alternatively, a mapping from action types to action-type-specific *case reducer*\r\n * functions. These reducers should have existing action types used\r\n * as the keys, and action creators will _not_ be generated.\r\n * \r\n * @example\r\n```ts\r\nimport { createAction, createSlice, Action, AnyAction } from '@reduxjs/toolkit'\r\nconst incrementBy = createAction('incrementBy')\r\nconst decrement = createAction('decrement')\r\n\r\ninterface RejectedAction extends Action {\r\n error: Error\r\n}\r\n\r\nfunction isRejectedAction(action: AnyAction): action is RejectedAction {\r\n return action.type.endsWith('rejected')\r\n}\r\n\r\ncreateSlice({\r\n name: 'counter',\r\n initialState: 0,\r\n reducers: {},\r\n extraReducers: builder => {\r\n builder\r\n .addCase(incrementBy, (state, action) => {\r\n // action is inferred correctly here if using TS\r\n })\r\n // You can chain calls, or have separate `builder.addCase()` lines each time\r\n .addCase(decrement, (state, action) => {})\r\n // You can match a range of action types\r\n .addMatcher(\r\n isRejectedAction,\r\n // `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard\r\n (state, action) => {}\r\n )\r\n // and provide a default case if no other handlers matched\r\n .addDefaultCase((state, action) => {})\r\n }\r\n})\r\n```\r\n */\r\n extraReducers?:\r\n | CaseReducers, any>\r\n | ((builder: ActionReducerMapBuilder>) => void)\r\n}\r\n\r\n/**\r\n * A CaseReducer with a `prepare` method.\r\n *\r\n * @public\r\n */\r\nexport type CaseReducerWithPrepare = {\r\n reducer: CaseReducer