@rest-hooks/normalizr
Advanced tools
Comparing version 8.2.5 to 8.2.6
@@ -6,2 +6,12 @@ # Change Log | ||
### [8.2.6](https://github.com/coinbase/rest-hooks/compare/@rest-hooks/normalizr@8.2.5...@rest-hooks/normalizr@8.2.6) (2022-05-30) | ||
### 📦 Package | ||
* Update all non-major dependencies ([#2023](https://github.com/coinbase/rest-hooks/issues/2023)) ([9e1d0f7](https://github.com/coinbase/rest-hooks/commit/9e1d0f7d0082ae4375ef044a4b6f356cbaca373a)) | ||
* Use @babel/runtime@^7.13.0 to use CJS/ESM exports support ([#2019](https://github.com/coinbase/rest-hooks/issues/2019)) ([78a22f2](https://github.com/coinbase/rest-hooks/commit/78a22f29f86527ac10eb2c9b031984e044226dce)) | ||
### [8.2.5](https://github.com/coinbase/rest-hooks/compare/@rest-hooks/normalizr@8.2.4...@rest-hooks/normalizr@8.2.5) (2022-04-30) | ||
@@ -8,0 +18,0 @@ |
define(['exports'], (function (exports) { 'use strict'; | ||
function _arrayLikeToArray(arr, len) { | ||
if (len == null || len > arr.length) len = arr.length; | ||
function unwrapExports (x) { | ||
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; | ||
} | ||
for (var i = 0, arr2 = new Array(len); i < len; i++) { | ||
arr2[i] = arr[i]; | ||
} | ||
function createCommonjsModule(fn, module) { | ||
return module = { exports: {} }, fn(module, module.exports), module.exports; | ||
} | ||
return arr2; | ||
} | ||
var arrayLikeToArray = createCommonjsModule(function (module) { | ||
function _arrayLikeToArray(arr, len) { | ||
if (len == null || len > arr.length) len = arr.length; | ||
function _unsupportedIterableToArray(o, minLen) { | ||
if (!o) return; | ||
if (typeof o === "string") return _arrayLikeToArray(o, minLen); | ||
var n = Object.prototype.toString.call(o).slice(8, -1); | ||
if (n === "Object" && o.constructor) n = o.constructor.name; | ||
if (n === "Map" || n === "Set") return Array.from(o); | ||
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); | ||
} | ||
for (var i = 0, arr2 = new Array(len); i < len; i++) { | ||
arr2[i] = arr[i]; | ||
} | ||
function _createForOfIteratorHelperLoose(o, allowArrayLike) { | ||
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; | ||
if (it) return (it = it.call(o)).next.bind(it); | ||
return arr2; | ||
} | ||
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { | ||
if (it) o = it; | ||
var i = 0; | ||
return function () { | ||
if (i >= o.length) return { | ||
done: true | ||
}; | ||
return { | ||
done: false, | ||
value: o[i++] | ||
}; | ||
}; | ||
} | ||
module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); | ||
} | ||
unwrapExports(arrayLikeToArray); | ||
function _defineProperties(target, props) { | ||
for (var i = 0; i < props.length; i++) { | ||
var descriptor = props[i]; | ||
descriptor.enumerable = descriptor.enumerable || false; | ||
descriptor.configurable = true; | ||
if ("value" in descriptor) descriptor.writable = true; | ||
Object.defineProperty(target, descriptor.key, descriptor); | ||
} | ||
} | ||
var unsupportedIterableToArray = createCommonjsModule(function (module) { | ||
function _unsupportedIterableToArray(o, minLen) { | ||
if (!o) return; | ||
if (typeof o === "string") return arrayLikeToArray(o, minLen); | ||
var n = Object.prototype.toString.call(o).slice(8, -1); | ||
if (n === "Object" && o.constructor) n = o.constructor.name; | ||
if (n === "Map" || n === "Set") return Array.from(o); | ||
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); | ||
} | ||
function _createClass(Constructor, protoProps, staticProps) { | ||
if (protoProps) _defineProperties(Constructor.prototype, protoProps); | ||
if (staticProps) _defineProperties(Constructor, staticProps); | ||
Object.defineProperty(Constructor, "prototype", { | ||
writable: false | ||
}); | ||
return Constructor; | ||
} | ||
module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
/** | ||
* Helpers to enable Immutable compatibility *without* bringing in | ||
* the 'immutable' package as a dependency. | ||
*/ | ||
unwrapExports(unsupportedIterableToArray); | ||
/** | ||
* Check if an object is immutable by checking if it has a key specific | ||
* to the immutable library. | ||
* | ||
* @param {any} object | ||
* @return {bool} | ||
*/ | ||
// eslint-disable-next-line @typescript-eslint/ban-types | ||
function isImmutable(object) { | ||
return !!(typeof object.hasOwnProperty === 'function' && (Object.hasOwnProperty.call(object, '__ownerID') || // Immutable.Map | ||
object._map && Object.hasOwnProperty.call(object._map, '__ownerID'))); // Immutable.Record | ||
} | ||
/** | ||
* Denormalize an immutable entity. | ||
* | ||
* @param {Schema} schema | ||
* @param {Immutable.Map|Immutable.Record} input | ||
* @param {function} unvisit | ||
* @param {function} getDenormalizedEntity | ||
* @return {Immutable.Map|Immutable.Record} | ||
*/ | ||
var createForOfIteratorHelperLoose = createCommonjsModule(function (module) { | ||
function _createForOfIteratorHelperLoose(o, allowArrayLike) { | ||
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; | ||
if (it) return (it = it.call(o)).next.bind(it); | ||
function denormalizeImmutable(schema, input, unvisit) { | ||
var found = true; | ||
var deleted = false; | ||
return [Object.keys(schema).reduce(function (object, key) { | ||
// Immutable maps cast keys to strings on write so we need to ensure | ||
// we're accessing them using string keys. | ||
var stringKey = "" + key; | ||
if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { | ||
if (it) o = it; | ||
var i = 0; | ||
return function () { | ||
if (i >= o.length) return { | ||
done: true | ||
}; | ||
return { | ||
done: false, | ||
value: o[i++] | ||
}; | ||
}; | ||
} | ||
var _unvisit = unvisit(object.get(stringKey), schema[stringKey]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1], | ||
deletedItem = _unvisit[2]; | ||
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); | ||
} | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
module.exports = _createForOfIteratorHelperLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
if (deletedItem) { | ||
deleted = true; | ||
} | ||
var _createForOfIteratorHelperLoose = unwrapExports(createForOfIteratorHelperLoose); | ||
if (object.has(stringKey)) { | ||
return object.set(stringKey, item); | ||
} else { | ||
return object; | ||
} | ||
}, input), found, deleted]; | ||
} | ||
var createClass = createCommonjsModule(function (module) { | ||
function _defineProperties(target, props) { | ||
for (var i = 0; i < props.length; i++) { | ||
var descriptor = props[i]; | ||
descriptor.enumerable = descriptor.enumerable || false; | ||
descriptor.configurable = true; | ||
if ("value" in descriptor) descriptor.writable = true; | ||
Object.defineProperty(target, descriptor.key, descriptor); | ||
} | ||
} | ||
/** | ||
* Represents data that should be deduped by specifying a primary key. | ||
* @see https://resthooks.io/docs/api/Entity | ||
*/ | ||
function _createClass(Constructor, protoProps, staticProps) { | ||
if (protoProps) _defineProperties(Constructor.prototype, protoProps); | ||
if (staticProps) _defineProperties(Constructor, staticProps); | ||
Object.defineProperty(Constructor, "prototype", { | ||
writable: false | ||
}); | ||
return Constructor; | ||
} | ||
var Entity = /*#__PURE__*/function () { | ||
function Entity() {} | ||
module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
Entity.toJSON = function toJSON() { | ||
return { | ||
name: this.name, | ||
schema: this.schema, | ||
key: this.key | ||
}; | ||
} | ||
/** Defines nested entities */ | ||
var _createClass = unwrapExports(createClass); | ||
/** Returns the globally unique identifier for the static Entity */ | ||
; | ||
/** | ||
* Helpers to enable Immutable compatibility *without* bringing in | ||
* the 'immutable' package as a dependency. | ||
*/ | ||
/** Defines indexes to enable lookup by */ | ||
/** | ||
* Check if an object is immutable by checking if it has a key specific | ||
* to the immutable library. | ||
* | ||
* @param {any} object | ||
* @return {bool} | ||
*/ | ||
// eslint-disable-next-line @typescript-eslint/ban-types | ||
function isImmutable(object) { | ||
return !!(typeof object.hasOwnProperty === 'function' && (Object.hasOwnProperty.call(object, '__ownerID') || // Immutable.Map | ||
object._map && Object.hasOwnProperty.call(object._map, '__ownerID'))); // Immutable.Record | ||
} | ||
/** | ||
* Denormalize an immutable entity. | ||
* | ||
* @param {Schema} schema | ||
* @param {Immutable.Map|Immutable.Record} input | ||
* @param {function} unvisit | ||
* @param {function} getDenormalizedEntity | ||
* @return {Immutable.Map|Immutable.Record} | ||
*/ | ||
/** | ||
* A unique identifier for each Entity | ||
* | ||
* @param [value] POJO of the entity or subset used | ||
* @param [parent] When normalizing, the object which included the entity | ||
* @param [key] When normalizing, the key where this entity was found | ||
*/ | ||
Entity.pk = function pk(value, parent, key) { | ||
return this.prototype.pk.call(value, parent, key); | ||
} | ||
/** Return true to merge incoming data; false keeps existing entity */ | ||
; | ||
function denormalizeImmutable(schema, input, unvisit) { | ||
var found = true; | ||
var deleted = false; | ||
return [Object.keys(schema).reduce(function (object, key) { | ||
// Immutable maps cast keys to strings on write so we need to ensure | ||
// we're accessing them using string keys. | ||
var stringKey = "" + key; | ||
Entity.useIncoming = function useIncoming(existingMeta, incomingMeta, existing, incoming) { | ||
return existingMeta.fetchedAt <= incomingMeta.fetchedAt; | ||
} | ||
/** Creates new instance copying over defined values of arguments */ | ||
; | ||
var _unvisit = unvisit(object.get(stringKey), schema[stringKey]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1], | ||
deletedItem = _unvisit[2]; | ||
Entity.merge = function merge(existing, incoming) { | ||
return Object.assign({}, existing, incoming); | ||
} | ||
/** Factory method to convert from Plain JS Objects. | ||
* | ||
* @param [props] Plain Object of properties to assign. | ||
* @param [parent] When normalizing, the object which included the record | ||
* @param [key] When normalizing, the key where this record was found | ||
*/ | ||
; | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
Entity.fromJS = function fromJS( // TODO: this should only accept members that are not functions | ||
props) { | ||
if (props === void 0) { | ||
props = {}; | ||
} | ||
if (deletedItem) { | ||
deleted = true; | ||
} | ||
// we type guarded abstract case above, so ok to force typescript to allow constructor call | ||
var instance = new this(props); // we can't rely on constructors and override the defaults provided as property assignments | ||
// all occur after the constructor | ||
if (object.has(stringKey)) { | ||
return object.set(stringKey, item); | ||
} else { | ||
return object; | ||
} | ||
}, input), found, deleted]; | ||
} | ||
Object.assign(instance, props); | ||
return instance; | ||
} | ||
/** Do any transformations when first receiving input */ | ||
; | ||
/** | ||
* Represents data that should be deduped by specifying a primary key. | ||
* @see https://resthooks.io/docs/api/Entity | ||
*/ | ||
Entity.process = function (_process) { | ||
function process(_x, _x2, _x3) { | ||
return _process.apply(this, arguments); | ||
} | ||
var Entity = /*#__PURE__*/function () { | ||
function Entity() {} | ||
process.toString = function () { | ||
return _process.toString(); | ||
}; | ||
Entity.toJSON = function toJSON() { | ||
return { | ||
name: this.name, | ||
schema: this.schema, | ||
key: this.key | ||
}; | ||
} | ||
/** Defines nested entities */ | ||
return process; | ||
}(function (input, parent, key) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production' && this.automaticValidation !== 'silent') { | ||
if (Array.isArray(input)) { | ||
var errorMessage = "Attempted to initialize " + this.name + " with an array, but named members were expected\n\nThis is likely due to a malformed response.\nTry inspecting the network response or fetch() return value.\nOr use debugging tools: https://resthooks.io/docs/guides/debugging\nLearn more about schemas: https://resthooks.io/docs/api/schema\nIf this is a mistake, you can disable this check by setting static automaticValidation = 'silent'\n\nFirst three members: " + JSON.stringify(input.slice(0, 3), null, 2); | ||
/** Returns the globally unique identifier for the static Entity */ | ||
; | ||
if (this.automaticValidation !== 'warn') { | ||
var error = new Error(errorMessage); | ||
error.status = 400; | ||
throw error; | ||
} | ||
/** Defines indexes to enable lookup by */ | ||
console.warn(errorMessage); | ||
} | ||
} | ||
/** | ||
* A unique identifier for each Entity | ||
* | ||
* @param [value] POJO of the entity or subset used | ||
* @param [parent] When normalizing, the object which included the entity | ||
* @param [key] When normalizing, the key where this entity was found | ||
*/ | ||
Entity.pk = function pk(value, parent, key) { | ||
return this.prototype.pk.call(value, parent, key); | ||
} | ||
/** Return true to merge incoming data; false keeps existing entity */ | ||
; | ||
return Object.assign({}, input); | ||
}); | ||
Entity.useIncoming = function useIncoming(existingMeta, incomingMeta, existing, incoming) { | ||
return existingMeta.fetchedAt <= incomingMeta.fetchedAt; | ||
} | ||
/** Creates new instance copying over defined values of arguments */ | ||
; | ||
Entity.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
Entity.merge = function merge(existing, incoming) { | ||
return Object.assign({}, existing, incoming); | ||
} | ||
/** Factory method to convert from Plain JS Objects. | ||
* | ||
* @param [props] Plain Object of properties to assign. | ||
* @param [parent] When normalizing, the object which included the record | ||
* @param [key] When normalizing, the key where this record was found | ||
*/ | ||
; | ||
var processedEntity = this.process(input, parent, key); | ||
var id = this.pk(processedEntity, parent, key); | ||
Entity.fromJS = function fromJS( // TODO: this should only accept members that are not functions | ||
props) { | ||
if (props === void 0) { | ||
props = {}; | ||
} | ||
if (id === undefined || id === '') { | ||
if (process.env.NODE_ENV !== 'production') { | ||
var error = new Error("Missing usable primary key when normalizing response.\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n\n Entity: " + this.name + "\n Value (processed): " + (processedEntity && JSON.stringify(processedEntity, null, 2)) + "\n "); | ||
error.status = 400; | ||
throw error; | ||
} else { | ||
// these make the keys get deleted | ||
return undefined; | ||
} | ||
} | ||
// we type guarded abstract case above, so ok to force typescript to allow constructor call | ||
var instance = new this(props); // we can't rely on constructors and override the defaults provided as property assignments | ||
// all occur after the constructor | ||
var entityType = this.key; | ||
Object.assign(instance, props); | ||
return instance; | ||
} | ||
/** Do any transformations when first receiving input */ | ||
; | ||
if (!(entityType in visitedEntities)) { | ||
visitedEntities[entityType] = {}; | ||
} | ||
Entity.process = function (_process) { | ||
function process(_x, _x2, _x3) { | ||
return _process.apply(this, arguments); | ||
} | ||
if (!(id in visitedEntities[entityType])) { | ||
visitedEntities[entityType][id] = []; | ||
} | ||
process.toString = function () { | ||
return _process.toString(); | ||
}; | ||
if (visitedEntities[entityType][id].some(function (entity) { | ||
return entity === input; | ||
})) { | ||
return id; | ||
} | ||
return process; | ||
}(function (input, parent, key) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production' && this.automaticValidation !== 'silent') { | ||
if (Array.isArray(input)) { | ||
var errorMessage = "Attempted to initialize " + this.name + " with an array, but named members were expected\n\nThis is likely due to a malformed response.\nTry inspecting the network response or fetch() return value.\nOr use debugging tools: https://resthooks.io/docs/guides/debugging\nLearn more about schemas: https://resthooks.io/docs/api/schema\nIf this is a mistake, you can disable this check by setting static automaticValidation = 'silent'\n\nFirst three members: " + JSON.stringify(input.slice(0, 3), null, 2); | ||
var errorMessage = this.validate(processedEntity); | ||
if (this.automaticValidation !== 'warn') { | ||
var error = new Error(errorMessage); | ||
error.status = 400; | ||
throw error; | ||
} | ||
if (errorMessage) { | ||
var _error = new Error(errorMessage); | ||
console.warn(errorMessage); | ||
} | ||
} | ||
_error.status = 400; | ||
throw _error; | ||
} | ||
return Object.assign({}, input); | ||
}); | ||
visitedEntities[entityType][id].push(input); | ||
Object.keys(this.schema).forEach(function (key) { | ||
if (Object.prototype.hasOwnProperty.call(processedEntity, key)) { | ||
var schema = _this.schema[key]; | ||
processedEntity[key] = visit(processedEntity[key], processedEntity, key, schema, addEntity, visitedEntities); | ||
} | ||
}); | ||
addEntity(this, processedEntity, id); | ||
return id; | ||
}; | ||
Entity.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
Entity.validate = function validate(processedEntity) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production' && this.automaticValidation !== 'silent') { | ||
var keysOfRecord = new Set(Object.keys(this.defaults)); | ||
var keysOfProps = Object.keys(processedEntity); | ||
var found = [], | ||
missing = [], | ||
unexpected = []; | ||
var processedEntity = this.process(input, parent, key); | ||
var id = this.pk(processedEntity, parent, key); | ||
for (var _i = 0, _keysOfProps = keysOfProps; _i < _keysOfProps.length; _i++) { | ||
var keyOfProps = _keysOfProps[_i]; | ||
if (id === undefined || id === '') { | ||
if (process.env.NODE_ENV !== 'production') { | ||
var error = new Error("Missing usable primary key when normalizing response.\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n\n Entity: " + this.name + "\n Value (processed): " + (processedEntity && JSON.stringify(processedEntity, null, 2)) + "\n "); | ||
error.status = 400; | ||
throw error; | ||
} else { | ||
// these make the keys get deleted | ||
return undefined; | ||
} | ||
} | ||
if (keysOfRecord.has(keyOfProps)) { | ||
found.push(keyOfProps); | ||
} else { | ||
unexpected.push(keyOfProps); | ||
} | ||
} | ||
var entityType = this.key; | ||
for (var _iterator = _createForOfIteratorHelperLoose(keysOfRecord), _step; !(_step = _iterator()).done;) { | ||
var keyOfRecord = _step.value; | ||
if (!(entityType in visitedEntities)) { | ||
visitedEntities[entityType] = {}; | ||
} | ||
if (!found.includes(keyOfRecord)) { | ||
missing.push(keyOfRecord); | ||
} | ||
} // only bother with this if they used *any* defaults | ||
if (!(id in visitedEntities[entityType])) { | ||
visitedEntities[entityType][id] = []; | ||
} | ||
if (visitedEntities[entityType][id].some(function (entity) { | ||
return entity === input; | ||
})) { | ||
return id; | ||
} | ||
if (keysOfRecord.size) { | ||
var tooManyUnexpected = // unexpected compared to members in response | ||
Math.max(keysOfProps.length / 2, 1) <= unexpected.length && // unexpected compared to what we specified | ||
keysOfRecord.size > Math.max(unexpected.length, 2) && // as we find more and more be more easily assured it is correct | ||
Math.pow(found.length, 1.5) / 2 <= unexpected.length; | ||
var foundNothing = found.length < Math.min(1, keysOfRecord.size / 2); // if we find nothing (we expect at least one member for a pk) | ||
// or we find too many unexpected members | ||
var errorMessage = this.validate(processedEntity); | ||
if (tooManyUnexpected || foundNothing) { | ||
var extra = ''; | ||
var reason = 'substantially different than expected keys'; | ||
if (errorMessage) { | ||
var _error = new Error(errorMessage); | ||
if (foundNothing) { | ||
extra += "\n Missing: " + missing; | ||
reason = 'no matching keys found'; | ||
} | ||
_error.status = 400; | ||
throw _error; | ||
} | ||
if (tooManyUnexpected) { | ||
extra += "\n Unexpected keys: " + unexpected; | ||
reason = 'a large number of unexpected keys found'; | ||
} | ||
visitedEntities[entityType][id].push(input); | ||
Object.keys(this.schema).forEach(function (key) { | ||
if (Object.prototype.hasOwnProperty.call(processedEntity, key)) { | ||
var schema = _this.schema[key]; | ||
processedEntity[key] = visit(processedEntity[key], processedEntity, key, schema, addEntity, visitedEntities); | ||
} | ||
}); | ||
addEntity(this, processedEntity, id); | ||
return id; | ||
}; | ||
var errorMessage = "Attempted to initialize " + this.name + " with " + reason + "\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n If this is a mistake, you can disable this check by setting static automaticValidation = 'silent'\n\n Expected keys:\n Found: " + found + extra + "\n Value (processed): " + JSON.stringify(processedEntity, null, 2); | ||
Entity.validate = function validate(processedEntity) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production' && this.automaticValidation !== 'silent') { | ||
var keysOfRecord = new Set(Object.keys(this.defaults)); | ||
var keysOfProps = Object.keys(processedEntity); | ||
var found = [], | ||
missing = [], | ||
unexpected = []; | ||
if (found.length >= 4 && tooManyUnexpected || this.automaticValidation === 'warn') { | ||
console.warn(errorMessage); | ||
} else { | ||
return errorMessage; | ||
} | ||
} | ||
} | ||
} | ||
for (var _i = 0, _keysOfProps = keysOfProps; _i < _keysOfProps.length; _i++) { | ||
var keyOfProps = _keysOfProps[_i]; | ||
if (process.env.NODE_ENV !== 'production') { | ||
for (var _i2 = 0, _Object$keys = Object.keys(this.schema); _i2 < _Object$keys.length; _i2++) { | ||
var key = _Object$keys[_i2]; | ||
if (keysOfRecord.has(keyOfProps)) { | ||
found.push(keyOfProps); | ||
} else { | ||
unexpected.push(keyOfProps); | ||
} | ||
} | ||
if (!Object.prototype.hasOwnProperty.call(processedEntity, key)) { | ||
if (!Object.prototype.hasOwnProperty.call(this.defaults, key)) { | ||
return "Schema key is missing in Entity\n\n Be sure all schema members are also part of the entity\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about nesting schemas: https://resthooks.io/docs/guides/nested-response\n\n Entity keys: " + Object.keys(this.defaults) + "\n Schema key(missing): " + key + "\n "; | ||
} | ||
} | ||
} | ||
} | ||
}; | ||
for (var _iterator = _createForOfIteratorHelperLoose(keysOfRecord), _step; !(_step = _iterator()).done;) { | ||
var keyOfRecord = _step.value; | ||
Entity.infer = function infer(args, indexes, recurse) { | ||
if (!args[0]) return undefined; | ||
var id = this.pk(args[0], undefined, ''); // Was able to infer the entity's primary key from params | ||
if (!found.includes(keyOfRecord)) { | ||
missing.push(keyOfRecord); | ||
} | ||
} // only bother with this if they used *any* defaults | ||
if (id !== undefined && id !== '') return id; // now attempt lookup in indexes | ||
var indexName = indexFromParams(args[0], this.indexes); | ||
if (keysOfRecord.size) { | ||
var tooManyUnexpected = // unexpected compared to members in response | ||
Math.max(keysOfProps.length / 2, 1) <= unexpected.length && // unexpected compared to what we specified | ||
keysOfRecord.size > Math.max(unexpected.length, 2) && // as we find more and more be more easily assured it is correct | ||
Math.pow(found.length, 1.5) / 2 <= unexpected.length; | ||
var foundNothing = found.length < Math.min(1, keysOfRecord.size / 2); // if we find nothing (we expect at least one member for a pk) | ||
// or we find too many unexpected members | ||
if (indexName && indexes[this.key]) { | ||
// 'as Record<string, any>': indexName can only be found if params is a string key'd object | ||
var _id = indexes[this.key][indexName][args[0][indexName]]; | ||
return _id; | ||
} | ||
if (tooManyUnexpected || foundNothing) { | ||
var extra = ''; | ||
var reason = 'substantially different than expected keys'; | ||
return undefined; | ||
}; | ||
if (foundNothing) { | ||
extra += "\n Missing: " + missing; | ||
reason = 'no matching keys found'; | ||
} | ||
Entity.expiresAt = function expiresAt(meta, input) { | ||
return meta.expiresAt; | ||
}; | ||
if (tooManyUnexpected) { | ||
extra += "\n Unexpected keys: " + unexpected; | ||
reason = 'a large number of unexpected keys found'; | ||
} | ||
Entity.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
var errorMessage = "Attempted to initialize " + this.name + " with " + reason + "\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n If this is a mistake, you can disable this check by setting static automaticValidation = 'silent'\n\n Expected keys:\n Found: " + found + extra + "\n Value (processed): " + JSON.stringify(processedEntity, null, 2); | ||
if (isImmutable(input)) { | ||
if (this.validate(input.toJS())) return [undefined, false, true]; // Need to set this first so that if it is referenced further within the | ||
// denormalization the reference will already exist. | ||
if (found.length >= 4 && tooManyUnexpected || this.automaticValidation === 'warn') { | ||
console.warn(errorMessage); | ||
} else { | ||
return errorMessage; | ||
} | ||
} | ||
} | ||
} | ||
unvisit.setLocal == null ? void 0 : unvisit.setLocal(input); | ||
if (process.env.NODE_ENV !== 'production') { | ||
for (var _i2 = 0, _Object$keys = Object.keys(this.schema); _i2 < _Object$keys.length; _i2++) { | ||
var key = _Object$keys[_i2]; | ||
var _denormalizeImmutable = denormalizeImmutable(this.schema, input, unvisit), | ||
denormEntity = _denormalizeImmutable[0], | ||
found = _denormalizeImmutable[1], | ||
_deleted = _denormalizeImmutable[2]; | ||
if (!Object.prototype.hasOwnProperty.call(processedEntity, key)) { | ||
if (!Object.prototype.hasOwnProperty.call(this.defaults, key)) { | ||
return "Schema key is missing in Entity\n\n Be sure all schema members are also part of the entity\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about nesting schemas: https://resthooks.io/docs/guides/nested-response\n\n Entity keys: " + Object.keys(this.defaults) + "\n Schema key(missing): " + key + "\n "; | ||
} | ||
} | ||
} | ||
} | ||
}; | ||
return [this.fromJS(denormEntity.toObject()), found, _deleted]; | ||
} | ||
Entity.infer = function infer(args, indexes, recurse) { | ||
if (!args[0]) return undefined; | ||
var id = this.pk(args[0], undefined, ''); // Was able to infer the entity's primary key from params | ||
if (this.validate(input)) { | ||
return [undefined, false, true]; | ||
} | ||
if (id !== undefined && id !== '') return id; // now attempt lookup in indexes | ||
var entityCopy = this.fromJS(input); // Need to set this first so that if it is referenced further within the | ||
// denormalization the reference will already exist. | ||
var indexName = indexFromParams(args[0], this.indexes); | ||
unvisit.setLocal == null ? void 0 : unvisit.setLocal(entityCopy); | ||
var deleted = false; // note: iteration order must be stable | ||
if (indexName && indexes[this.key]) { | ||
// 'as Record<string, any>': indexName can only be found if params is a string key'd object | ||
var _id = indexes[this.key][indexName][args[0][indexName]]; | ||
return _id; | ||
} | ||
Object.keys(this.schema).forEach(function (key) { | ||
var schema = _this2.schema[key]; | ||
var nextInput = Object.prototype.hasOwnProperty.call(input, key) ? input[key] : undefined; | ||
return undefined; | ||
}; | ||
var _unvisit = unvisit(nextInput, schema), | ||
value = _unvisit[0], | ||
deletedItem = _unvisit[2]; | ||
Entity.expiresAt = function expiresAt(meta, input) { | ||
return meta.expiresAt; | ||
}; | ||
if (deletedItem && !(Object.prototype.hasOwnProperty.call(input, key) && !_this2.defaults[key])) { | ||
deleted = true; | ||
} | ||
Entity.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
if (Object.prototype.hasOwnProperty.call(input, key) && input[key] !== value) { | ||
_this2.set(entityCopy, key, value); | ||
} | ||
}); | ||
return [entityCopy, true, deleted]; | ||
} | ||
/** All instance defaults set */ | ||
; | ||
if (isImmutable(input)) { | ||
if (this.validate(input.toJS())) return [undefined, false, true]; // Need to set this first so that if it is referenced further within the | ||
// denormalization the reference will already exist. | ||
/** Used by denormalize to set nested members */ | ||
Entity.set = function set(entity, key, value) { | ||
entity[key] = value; | ||
}; | ||
unvisit.setLocal == null ? void 0 : unvisit.setLocal(input); | ||
_createClass(Entity, null, [{ | ||
key: "key", | ||
get: function get() { | ||
/* istanbul ignore next */ | ||
if (process.env.NODE_ENV !== 'production' && (this.name === '' || this.name === 'Entity' || this.name === '_temp')) throw new Error('Entity classes without a name must define `static get key()`'); | ||
return this.name; | ||
} | ||
}, { | ||
key: "defaults", | ||
get: function get() { | ||
if (!Object.prototype.hasOwnProperty.call(this, '__defaults')) this.__defaults = new this(); | ||
return this.__defaults; | ||
} | ||
}]); | ||
var _denormalizeImmutable = denormalizeImmutable(this.schema, input, unvisit), | ||
denormEntity = _denormalizeImmutable[0], | ||
found = _denormalizeImmutable[1], | ||
_deleted = _denormalizeImmutable[2]; | ||
return Entity; | ||
}(); | ||
Entity.schema = {}; | ||
return [this.fromJS(denormEntity.toObject()), found, _deleted]; | ||
} | ||
if (process.env.NODE_ENV !== 'production') { | ||
var superFrom = Entity.fromJS; // for those not using TypeScript this is a good catch to ensure they are defining | ||
// the abstract members | ||
if (this.validate(input)) { | ||
return [undefined, false, true]; | ||
} | ||
Entity.fromJS = function fromJS(props) { | ||
if (this.prototype.pk === undefined) throw new Error('cannot construct on abstract types'); | ||
return superFrom.call(this, props); | ||
}; | ||
} | ||
var entityCopy = this.fromJS(input); // Need to set this first so that if it is referenced further within the | ||
// denormalization the reference will already exist. | ||
function isEntity(schema) { | ||
return schema !== null && schema.pk !== undefined; | ||
} | ||
unvisit.setLocal == null ? void 0 : unvisit.setLocal(entityCopy); | ||
var deleted = false; // note: iteration order must be stable | ||
function indexFromParams(params, indexes) { | ||
if (!indexes) return undefined; | ||
return indexes.find(function (index) { | ||
return Object.prototype.hasOwnProperty.call(params, index); | ||
}); | ||
} | ||
Object.keys(this.schema).forEach(function (key) { | ||
var schema = _this2.schema[key]; | ||
var nextInput = Object.prototype.hasOwnProperty.call(input, key) ? input[key] : undefined; | ||
var DELETED = Symbol('ENTITY WAS DELETED'); | ||
var _unvisit = unvisit(nextInput, schema), | ||
value = _unvisit[0], | ||
deletedItem = _unvisit[2]; | ||
function _setPrototypeOf(o, p) { | ||
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}; | ||
if (deletedItem && !(Object.prototype.hasOwnProperty.call(input, key) && !_this2.defaults[key])) { | ||
deleted = true; | ||
} | ||
return _setPrototypeOf(o, p); | ||
} | ||
if (Object.prototype.hasOwnProperty.call(input, key) && input[key] !== value) { | ||
_this2.set(entityCopy, key, value); | ||
} | ||
}); | ||
return [entityCopy, true, deleted]; | ||
} | ||
/** All instance defaults set */ | ||
; | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
_setPrototypeOf(subClass, superClass); | ||
} | ||
/** Used by denormalize to set nested members */ | ||
Entity.set = function set(entity, key, value) { | ||
entity[key] = value; | ||
}; | ||
function _getPrototypeOf(o) { | ||
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { | ||
return o.__proto__ || Object.getPrototypeOf(o); | ||
}; | ||
return _getPrototypeOf(o); | ||
} | ||
_createClass(Entity, null, [{ | ||
key: "key", | ||
get: function get() { | ||
/* istanbul ignore next */ | ||
if (process.env.NODE_ENV !== 'production' && (this.name === '' || this.name === 'Entity' || this.name === '_temp')) throw new Error('Entity classes without a name must define `static get key()`'); | ||
return this.name; | ||
} | ||
}, { | ||
key: "defaults", | ||
get: function get() { | ||
if (!Object.prototype.hasOwnProperty.call(this, '__defaults')) this.__defaults = new this(); | ||
return this.__defaults; | ||
} | ||
}]); | ||
function _isNativeFunction(fn) { | ||
return Function.toString.call(fn).indexOf("[native code]") !== -1; | ||
} | ||
return Entity; | ||
}(); | ||
Entity.schema = {}; | ||
function _isNativeReflectConstruct() { | ||
if (typeof Reflect === "undefined" || !Reflect.construct) return false; | ||
if (Reflect.construct.sham) return false; | ||
if (typeof Proxy === "function") return true; | ||
if (process.env.NODE_ENV !== 'production') { | ||
var superFrom = Entity.fromJS; // for those not using TypeScript this is a good catch to ensure they are defining | ||
// the abstract members | ||
try { | ||
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
} | ||
Entity.fromJS = function fromJS(props) { | ||
if (this.prototype.pk === undefined) throw new Error('cannot construct on abstract types'); | ||
return superFrom.call(this, props); | ||
}; | ||
} | ||
function _construct(Parent, args, Class) { | ||
if (_isNativeReflectConstruct()) { | ||
_construct = Reflect.construct; | ||
} else { | ||
_construct = function _construct(Parent, args, Class) { | ||
var a = [null]; | ||
a.push.apply(a, args); | ||
var Constructor = Function.bind.apply(Parent, a); | ||
var instance = new Constructor(); | ||
if (Class) _setPrototypeOf(instance, Class.prototype); | ||
return instance; | ||
}; | ||
} | ||
function isEntity(schema) { | ||
return schema !== null && schema.pk !== undefined; | ||
} | ||
return _construct.apply(null, arguments); | ||
} | ||
function indexFromParams(params, indexes) { | ||
if (!indexes) return undefined; | ||
return indexes.find(function (index) { | ||
return Object.prototype.hasOwnProperty.call(params, index); | ||
}); | ||
} | ||
function _wrapNativeSuper(Class) { | ||
var _cache = typeof Map === "function" ? new Map() : undefined; | ||
var DELETED = Symbol('ENTITY WAS DELETED'); | ||
_wrapNativeSuper = function _wrapNativeSuper(Class) { | ||
if (Class === null || !_isNativeFunction(Class)) return Class; | ||
var setPrototypeOf = createCommonjsModule(function (module) { | ||
function _setPrototypeOf(o, p) { | ||
module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
return _setPrototypeOf(o, p); | ||
} | ||
if (typeof Class !== "function") { | ||
throw new TypeError("Super expression must either be null or a function"); | ||
} | ||
module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
if (typeof _cache !== "undefined") { | ||
if (_cache.has(Class)) return _cache.get(Class); | ||
unwrapExports(setPrototypeOf); | ||
_cache.set(Class, Wrapper); | ||
} | ||
var inheritsLoose = createCommonjsModule(function (module) { | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
setPrototypeOf(subClass, superClass); | ||
} | ||
function Wrapper() { | ||
return _construct(Class, arguments, _getPrototypeOf(this).constructor); | ||
} | ||
module.exports = _inheritsLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
Wrapper.prototype = Object.create(Class.prototype, { | ||
constructor: { | ||
value: Wrapper, | ||
enumerable: false, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
return _setPrototypeOf(Wrapper, Class); | ||
}; | ||
var _inheritsLoose = unwrapExports(inheritsLoose); | ||
return _wrapNativeSuper(Class); | ||
} | ||
var getPrototypeOf = createCommonjsModule(function (module) { | ||
function _getPrototypeOf(o) { | ||
module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { | ||
return o.__proto__ || Object.getPrototypeOf(o); | ||
}, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
return _getPrototypeOf(o); | ||
} | ||
/** Link in a chain */ | ||
var Link = function Link() { | ||
this.children = new WeakMap(); | ||
}; | ||
module.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
var KeySize = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(KeySize, _Error); | ||
unwrapExports(getPrototypeOf); | ||
function KeySize() { | ||
var _this; | ||
var isNativeFunction = createCommonjsModule(function (module) { | ||
function _isNativeFunction(fn) { | ||
return Function.toString.call(fn).indexOf("[native code]") !== -1; | ||
} | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
module.exports = _isNativeFunction, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
_this = _Error.call.apply(_Error, [this].concat(args)) || this; | ||
_this.message = 'Keys must include at least one member'; | ||
return _this; | ||
} | ||
unwrapExports(isNativeFunction); | ||
return KeySize; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
/** Maps from a list of objects (referentially) to any value | ||
* | ||
* If *any* members of the list get claned up, so does that key/value pair get removed. | ||
*/ | ||
var isNativeReflectConstruct = createCommonjsModule(function (module) { | ||
function _isNativeReflectConstruct() { | ||
if (typeof Reflect === "undefined" || !Reflect.construct) return false; | ||
if (Reflect.construct.sham) return false; | ||
if (typeof Proxy === "function") return true; | ||
try { | ||
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
} | ||
var WeakListMap = /*#__PURE__*/function () { | ||
function WeakListMap() { | ||
this.first = new WeakMap(); | ||
} | ||
module.exports = _isNativeReflectConstruct, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
var _proto = WeakListMap.prototype; | ||
unwrapExports(isNativeReflectConstruct); | ||
_proto.delete = function _delete(key) { | ||
var link = this.traverse(key); | ||
link == null ? true : delete link.value; | ||
return !!link; | ||
}; | ||
var construct = createCommonjsModule(function (module) { | ||
function _construct(Parent, args, Class) { | ||
if (isNativeReflectConstruct()) { | ||
module.exports = _construct = Reflect.construct, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
} else { | ||
module.exports = _construct = function _construct(Parent, args, Class) { | ||
var a = [null]; | ||
a.push.apply(a, args); | ||
var Constructor = Function.bind.apply(Parent, a); | ||
var instance = new Constructor(); | ||
if (Class) setPrototypeOf(instance, Class.prototype); | ||
return instance; | ||
}, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
} | ||
_proto.get = function get(key) { | ||
var link = this.traverse(key); | ||
return link == null ? void 0 : link.value; | ||
}; | ||
return _construct.apply(null, arguments); | ||
} | ||
_proto.has = function has(key) { | ||
var link = this.traverse(key); | ||
if (!link) return false; | ||
return Object.prototype.hasOwnProperty.call(link, 'value'); | ||
}; | ||
module.exports = _construct, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
_proto.set = function set(key, value) { | ||
if (key.length < 1) throw new KeySize(); | ||
var cur = this.first; | ||
var link; | ||
unwrapExports(construct); | ||
for (var i = 0; i < key.length; i++) { | ||
if (!cur.has(key[i])) { | ||
link = new Link(); | ||
cur.set(key[i], link); | ||
} else { | ||
link = cur.get(key[i]); | ||
} | ||
var wrapNativeSuper = createCommonjsModule(function (module) { | ||
function _wrapNativeSuper(Class) { | ||
var _cache = typeof Map === "function" ? new Map() : undefined; | ||
cur = link.children; // do on later iteration of loop. this makes typescript happy rather than putting after loop | ||
module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) { | ||
if (Class === null || !isNativeFunction(Class)) return Class; | ||
if (i === key.length - 1) { | ||
link.value = value; | ||
} | ||
} | ||
if (typeof Class !== "function") { | ||
throw new TypeError("Super expression must either be null or a function"); | ||
} | ||
return this; | ||
}; | ||
if (typeof _cache !== "undefined") { | ||
if (_cache.has(Class)) return _cache.get(Class); | ||
_proto.traverse = function traverse(key) { | ||
var cur = this.first; | ||
var link; | ||
_cache.set(Class, Wrapper); | ||
} | ||
for (var i = 0; i < key.length; i++) { | ||
link = cur.get(key[i]); | ||
if (!link) return; | ||
cur = link.children; | ||
} | ||
function Wrapper() { | ||
return construct(Class, arguments, getPrototypeOf(this).constructor); | ||
} | ||
return link; | ||
}; | ||
Wrapper.prototype = Object.create(Class.prototype, { | ||
constructor: { | ||
value: Wrapper, | ||
enumerable: false, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
return setPrototypeOf(Wrapper, Class); | ||
}, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
return _wrapNativeSuper(Class); | ||
} | ||
return WeakListMap; | ||
}(); | ||
module.exports = _wrapNativeSuper, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
var PolymorphicSchema = /*#__PURE__*/function () { | ||
function PolymorphicSchema(definition, schemaAttribute) { | ||
this.schema = void 0; | ||
var _wrapNativeSuper = unwrapExports(wrapNativeSuper); | ||
if (schemaAttribute) { | ||
this._schemaAttribute = typeof schemaAttribute === 'string' ? function (input) { | ||
return input[schemaAttribute]; | ||
} : schemaAttribute; | ||
} | ||
/** Link in a chain */ | ||
var Link = function Link() { | ||
this.children = new WeakMap(); | ||
}; | ||
this.define(definition); | ||
} | ||
var KeySize = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(KeySize, _Error); | ||
var _proto = PolymorphicSchema.prototype; | ||
function KeySize() { | ||
var _this; | ||
_proto.define = function define(definition) { | ||
this.schema = definition; | ||
}; | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
_proto.getSchemaAttribute = function getSchemaAttribute(input, parent, key) { | ||
return !this.isSingleSchema && this._schemaAttribute(input, parent, key); | ||
}; | ||
_this = _Error.call.apply(_Error, [this].concat(args)) || this; | ||
_this.message = 'Keys must include at least one member'; | ||
return _this; | ||
} | ||
_proto.inferSchema = function inferSchema(input, parent, key) { | ||
if (this.isSingleSchema) { | ||
return this.schema; | ||
} | ||
return KeySize; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
/** Maps from a list of objects (referentially) to any value | ||
* | ||
* If *any* members of the list get claned up, so does that key/value pair get removed. | ||
*/ | ||
var attr = this.getSchemaAttribute(input, parent, key); | ||
return this.schema[attr]; | ||
}; | ||
_proto.normalizeValue = function normalizeValue(value, parent, key, visit, addEntity, visitedEntities) { | ||
var schema = this.inferSchema(value, parent, key); | ||
var WeakListMap = /*#__PURE__*/function () { | ||
function WeakListMap() { | ||
this.first = new WeakMap(); | ||
} | ||
if (!schema) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production') { | ||
var attr = this.getSchemaAttribute(value, parent, key); | ||
console.warn("Schema attribute " + JSON.stringify(attr, undefined, 2) + " is not expected.\nExpected one of: " + Object.keys(this.schema).map(function (k) { | ||
return "\"" + k + "\""; | ||
}).join(', ') + "\n\nValue: " + JSON.stringify(value, undefined, 2)); | ||
} | ||
var _proto = WeakListMap.prototype; | ||
return value; | ||
} | ||
_proto.delete = function _delete(key) { | ||
var link = this.traverse(key); | ||
link == null ? true : delete link.value; | ||
return !!link; | ||
}; | ||
var normalizedValue = visit(value, parent, key, schema, addEntity, visitedEntities); | ||
return this.isSingleSchema || normalizedValue === undefined || normalizedValue === null ? normalizedValue : { | ||
id: normalizedValue, | ||
schema: this.getSchemaAttribute(value, parent, key) | ||
}; | ||
} // value is guaranteed by caller to not be null | ||
; | ||
_proto.get = function get(key) { | ||
var link = this.traverse(key); | ||
return link == null ? void 0 : link.value; | ||
}; | ||
_proto.denormalizeValue = function denormalizeValue(value, unvisit) { | ||
var schemaKey = isImmutable(value) ? value.get('schema') : value.schema; | ||
_proto.has = function has(key) { | ||
var link = this.traverse(key); | ||
if (!link) return false; | ||
return Object.prototype.hasOwnProperty.call(link, 'value'); | ||
}; | ||
if (!this.isSingleSchema && !schemaKey) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production') { | ||
console.warn("TypeError: Unable to infer schema for " + this.constructor.name + "\nValue: " + JSON.stringify(value, undefined, 2) + "."); | ||
} | ||
_proto.set = function set(key, value) { | ||
if (key.length < 1) throw new KeySize(); | ||
var cur = this.first; | ||
var link; | ||
return [value, true, false]; | ||
} | ||
for (var i = 0; i < key.length; i++) { | ||
if (!cur.has(key[i])) { | ||
link = new Link(); | ||
cur.set(key[i], link); | ||
} else { | ||
link = cur.get(key[i]); | ||
} | ||
var id = this.isSingleSchema ? undefined : isImmutable(value) ? value.get('id') : value.id; | ||
var schema = this.isSingleSchema ? this.schema : this.schema[schemaKey]; | ||
return unvisit(id || value, schema); | ||
}; | ||
cur = link.children; // do on later iteration of loop. this makes typescript happy rather than putting after loop | ||
_createClass(PolymorphicSchema, [{ | ||
key: "isSingleSchema", | ||
get: function get() { | ||
return !this._schemaAttribute; | ||
} | ||
}]); | ||
if (i === key.length - 1) { | ||
link.value = value; | ||
} | ||
} | ||
return PolymorphicSchema; | ||
}(); | ||
return this; | ||
}; | ||
var validateSchema = function validateSchema(definition) { | ||
var isArray = Array.isArray(definition); | ||
_proto.traverse = function traverse(key) { | ||
var cur = this.first; | ||
var link; | ||
if (isArray && definition.length > 1) { | ||
throw new Error("Expected schema definition to be a single schema, but found " + definition.length + "."); | ||
} | ||
for (var i = 0; i < key.length; i++) { | ||
link = cur.get(key[i]); | ||
if (!link) return; | ||
cur = link.children; | ||
} | ||
return definition[0]; | ||
}; | ||
return link; | ||
}; | ||
var getValues = function getValues(input) { | ||
return Array.isArray(input) ? input : Object.keys(input).map(function (key) { | ||
return input[key]; | ||
}); | ||
}; | ||
return WeakListMap; | ||
}(); | ||
var filterEmpty = function filterEmpty(_ref) { | ||
var item = _ref[0], | ||
deletedItem = _ref[2]; | ||
return item !== undefined && !deletedItem; | ||
}; | ||
var PolymorphicSchema = /*#__PURE__*/function () { | ||
function PolymorphicSchema(definition, schemaAttribute) { | ||
this.schema = void 0; | ||
var normalize$1 = function normalize(schema, input, parent, key, visit, addEntity, visitedEntities) { | ||
schema = validateSchema(schema); | ||
var values = getValues(input); // Special case: Arrays pass *their* parent on to their children, since there | ||
// is not any special information that can be gathered from themselves directly | ||
if (schemaAttribute) { | ||
this._schemaAttribute = typeof schemaAttribute === 'string' ? function (input) { | ||
return input[schemaAttribute]; | ||
} : schemaAttribute; | ||
} | ||
return values.map(function (value, index) { | ||
return visit(value, parent, key, schema, addEntity, visitedEntities); | ||
}); | ||
}; | ||
var denormalize$1 = function denormalize(schema, input, unvisit) { | ||
schema = validateSchema(schema); | ||
return [input.map ? input.map(function (entityOrId) { | ||
return unvisit(entityOrId, schema); | ||
}).filter(filterEmpty).map(function (_ref2) { | ||
var value = _ref2[0]; | ||
return value; | ||
}) : input, true, false]; | ||
}; | ||
this.define(definition); | ||
} | ||
function _infer$1(schema, args, indexes, recurse) { | ||
return undefined; | ||
} | ||
var _proto = PolymorphicSchema.prototype; | ||
var ArraySchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ArraySchema, _PolymorphicSchema); | ||
_proto.define = function define(definition) { | ||
this.schema = definition; | ||
}; | ||
function ArraySchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
} | ||
_proto.getSchemaAttribute = function getSchemaAttribute(input, parent, key) { | ||
return !this.isSingleSchema && this._schemaAttribute(input, parent, key); | ||
}; | ||
var _proto = ArraySchema.prototype; | ||
_proto.inferSchema = function inferSchema(input, parent, key) { | ||
if (this.isSingleSchema) { | ||
return this.schema; | ||
} | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
var attr = this.getSchemaAttribute(input, parent, key); | ||
return this.schema[attr]; | ||
}; | ||
var values = getValues(input); | ||
return values.map(function (value, index) { | ||
return _this.normalizeValue(value, parent, key, visit, addEntity, visitedEntities); | ||
}).filter(function (value) { | ||
return value !== undefined && value !== null; | ||
}); | ||
}; | ||
_proto.normalizeValue = function normalizeValue(value, parent, key, visit, addEntity, visitedEntities) { | ||
var schema = this.inferSchema(value, parent, key); | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
if (!schema) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production') { | ||
var attr = this.getSchemaAttribute(value, parent, key); | ||
console.warn("Schema attribute " + JSON.stringify(attr, undefined, 2) + " is not expected.\nExpected one of: " + Object.keys(this.schema).map(function (k) { | ||
return "\"" + k + "\""; | ||
}).join(', ') + "\n\nValue: " + JSON.stringify(value, undefined, 2)); | ||
} | ||
return [input.map ? input.map(function (entityOrId) { | ||
return _this2.denormalizeValue(entityOrId, unvisit); | ||
}).filter(filterEmpty).map(function (_ref3) { | ||
var value = _ref3[0]; | ||
return value; | ||
}) : input, true, false]; | ||
}; | ||
return value; | ||
} | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return _infer$1(this.schema); | ||
}; | ||
var normalizedValue = visit(value, parent, key, schema, addEntity, visitedEntities); | ||
return this.isSingleSchema || normalizedValue === undefined || normalizedValue === null ? normalizedValue : { | ||
id: normalizedValue, | ||
schema: this.getSchemaAttribute(value, parent, key) | ||
}; | ||
} // value is guaranteed by caller to not be null | ||
; | ||
return ArraySchema; | ||
}(PolymorphicSchema); | ||
_proto.denormalizeValue = function denormalizeValue(value, unvisit) { | ||
var schemaKey = isImmutable(value) ? value.get('schema') : value.schema; | ||
var _normalize = function normalize(schema, input, parent, key, visit, addEntity, visitedEntities) { | ||
var object = Object.assign({}, input); | ||
Object.keys(schema).forEach(function (key) { | ||
var localSchema = schema[key]; | ||
var value = visit(input[key], input, key, localSchema, addEntity, visitedEntities); | ||
if (!this.isSingleSchema && !schemaKey) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production') { | ||
console.warn("TypeError: Unable to infer schema for " + this.constructor.name + "\nValue: " + JSON.stringify(value, undefined, 2) + "."); | ||
} | ||
if (value === undefined || value === null) { | ||
delete object[key]; | ||
} else { | ||
object[key] = value; | ||
} | ||
}); | ||
return object; | ||
}; | ||
return [value, true, false]; | ||
} | ||
var _denormalize = function denormalize(schema, input, unvisit) { | ||
if (isImmutable(input)) { | ||
return denormalizeImmutable(schema, input, unvisit); | ||
} | ||
var id = this.isSingleSchema ? undefined : isImmutable(value) ? value.get('id') : value.id; | ||
var schema = this.isSingleSchema ? this.schema : this.schema[schemaKey]; | ||
return unvisit(id || value, schema); | ||
}; | ||
var object = Object.assign({}, input); | ||
var found = true; | ||
var deleted = false; | ||
Object.keys(schema).forEach(function (key) { | ||
var _unvisit = unvisit(object[key], schema[key]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1], | ||
deletedItem = _unvisit[2]; | ||
_createClass(PolymorphicSchema, [{ | ||
key: "isSingleSchema", | ||
get: function get() { | ||
return !this._schemaAttribute; | ||
} | ||
}]); | ||
if (object[key] !== undefined) { | ||
object[key] = item; | ||
} | ||
return PolymorphicSchema; | ||
}(); | ||
if (deletedItem) { | ||
deleted = true; | ||
} | ||
var validateSchema = function validateSchema(definition) { | ||
var isArray = Array.isArray(definition); | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
}); | ||
return [object, found, deleted]; | ||
}; | ||
if (isArray && definition.length > 1) { | ||
throw new Error("Expected schema definition to be a single schema, but found " + definition.length + "."); | ||
} | ||
function _infer(schema, args, indexes, recurse) { | ||
var resultObject = {}; | ||
return definition[0]; | ||
}; | ||
for (var _i = 0, _Object$keys = Object.keys(schema); _i < _Object$keys.length; _i++) { | ||
var k = _Object$keys[_i]; | ||
resultObject[k] = recurse(schema[k], args, indexes); | ||
} | ||
var getValues = function getValues(input) { | ||
return Array.isArray(input) ? input : Object.keys(input).map(function (key) { | ||
return input[key]; | ||
}); | ||
}; | ||
return resultObject; | ||
} | ||
var filterEmpty = function filterEmpty(_ref) { | ||
var item = _ref[0], | ||
deletedItem = _ref[2]; | ||
return item !== undefined && !deletedItem; | ||
}; | ||
var ObjectSchema = /*#__PURE__*/function () { | ||
function ObjectSchema(definition) { | ||
this.schema = void 0; | ||
this.define(definition); | ||
} | ||
var normalize$1 = function normalize(schema, input, parent, key, visit, addEntity, visitedEntities) { | ||
schema = validateSchema(schema); | ||
var values = getValues(input); // Special case: Arrays pass *their* parent on to their children, since there | ||
// is not any special information that can be gathered from themselves directly | ||
var _proto = ObjectSchema.prototype; | ||
return values.map(function (value, index) { | ||
return visit(value, parent, key, schema, addEntity, visitedEntities); | ||
}); | ||
}; | ||
var denormalize$1 = function denormalize(schema, input, unvisit) { | ||
schema = validateSchema(schema); | ||
return [input.map ? input.map(function (entityOrId) { | ||
return unvisit(entityOrId, schema); | ||
}).filter(filterEmpty).map(function (_ref2) { | ||
var value = _ref2[0]; | ||
return value; | ||
}) : input, true, false]; | ||
}; | ||
_proto.define = function define(definition) { | ||
this.schema = Object.keys(definition).reduce(function (entitySchema, key) { | ||
var _Object$assign; | ||
function _infer$1(schema, args, indexes, recurse) { | ||
return undefined; | ||
} | ||
var schema = definition[key]; | ||
return Object.assign({}, entitySchema, (_Object$assign = {}, _Object$assign[key] = schema, _Object$assign)); | ||
}, this.schema || {}); | ||
}; | ||
var ArraySchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ArraySchema, _PolymorphicSchema); | ||
_proto.normalize = function normalize() { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
function ArraySchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
} | ||
return _normalize.apply(void 0, [this.schema].concat(args)); | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
; | ||
var _proto = ArraySchema.prototype; | ||
_proto.denormalize = function denormalize() { | ||
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
args[_key2] = arguments[_key2]; | ||
} | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
return _denormalize.apply(void 0, [this.schema].concat(args)); | ||
}; | ||
var values = getValues(input); | ||
return values.map(function (value, index) { | ||
return _this.normalizeValue(value, parent, key, visit, addEntity, visitedEntities); | ||
}).filter(function (value) { | ||
return value !== undefined && value !== null; | ||
}); | ||
}; | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return _infer(this.schema, args, indexes, recurse); | ||
}; | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
return ObjectSchema; | ||
}(); | ||
return [input.map ? input.map(function (entityOrId) { | ||
return _this2.denormalizeValue(entityOrId, unvisit); | ||
}).filter(filterEmpty).map(function (_ref3) { | ||
var value = _ref3[0]; | ||
return value; | ||
}) : input, true, false]; | ||
}; | ||
var DRAFT = Symbol('draft'); | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return _infer$1(this.schema, args, indexes, recurse); | ||
}; | ||
var unvisitEntity = function unvisitEntity(entityOrId, schema, unvisit, getEntity, localCache, entityCache, dependencies, cycleIndex) { | ||
var entity = getEntity(entityOrId, schema); | ||
return ArraySchema; | ||
}(PolymorphicSchema); | ||
if (entity === DELETED) { | ||
return [undefined, true, true]; | ||
} | ||
var _normalize = function normalize(schema, input, parent, key, visit, addEntity, visitedEntities) { | ||
var object = Object.assign({}, input); | ||
Object.keys(schema).forEach(function (key) { | ||
var localSchema = schema[key]; | ||
var value = visit(input[key], input, key, localSchema, addEntity, visitedEntities); | ||
if (process.env.NODE_ENV !== 'production' && typeof entity === 'symbol' && entity.toString().includes('DELETED')) { | ||
throw new Error("Unrecognized symbol detected.\nMake sure you do not have multiple versions of @rest-hooks/normalizr installed."); | ||
} | ||
if (value === undefined || value === null) { | ||
delete object[key]; | ||
} else { | ||
object[key] = value; | ||
} | ||
}); | ||
return object; | ||
}; | ||
if (typeof entity !== 'object' || entity === null) { | ||
return [entity, false, false]; | ||
} | ||
var _denormalize = function denormalize(schema, input, unvisit) { | ||
if (isImmutable(input)) { | ||
return denormalizeImmutable(schema, input, unvisit); | ||
} | ||
var pk = typeof entityOrId === 'string' ? entityOrId : schema.pk(isImmutable(entity) ? entity.toJS() : entity); | ||
var object = Object.assign({}, input); | ||
var found = true; | ||
var deleted = false; | ||
Object.keys(schema).forEach(function (key) { | ||
var _unvisit = unvisit(object[key], schema[key]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1], | ||
deletedItem = _unvisit[2]; | ||
if (pk === undefined || pk === '') { | ||
return [entity, false, false]; | ||
} | ||
if (object[key] !== undefined) { | ||
object[key] = item; | ||
} | ||
if (localCache[schema.key] === undefined) { | ||
localCache[schema.key] = Object.create(null); | ||
} | ||
if (deletedItem) { | ||
deleted = true; | ||
} | ||
var found = true; | ||
var deleted = false; | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
}); | ||
return [object, found, deleted]; | ||
}; | ||
if (!localCache[schema.key][pk]) { | ||
var trackingIndex = dependencies.length; | ||
dependencies.push(entity); | ||
var wrappedUnvisit = withTrackedEntities(unvisit); // { [DRAFT] } means we are still processing - which if found indicates a cycle | ||
function _infer(schema, args, indexes, recurse) { | ||
var resultObject = {}; | ||
wrappedUnvisit.setLocal = function (entityCopy) { | ||
var _localCache$schema$ke; | ||
for (var _i = 0, _Object$keys = Object.keys(schema); _i < _Object$keys.length; _i++) { | ||
var k = _Object$keys[_i]; | ||
resultObject[k] = recurse(schema[k], args, indexes); | ||
} | ||
return localCache[schema.key][pk] = (_localCache$schema$ke = {}, _localCache$schema$ke[DRAFT] = entityCopy, _localCache$schema$ke.i = trackingIndex, _localCache$schema$ke); | ||
}; | ||
return resultObject; | ||
} | ||
var globalCacheEntry = getGlobalCacheEntry(entityCache, schema, pk); | ||
var ObjectSchema = /*#__PURE__*/function () { | ||
function ObjectSchema(definition) { | ||
this.schema = void 0; | ||
this.define(definition); | ||
} | ||
var _schema$denormalize = schema.denormalize(entity, wrappedUnvisit); | ||
var _proto = ObjectSchema.prototype; | ||
localCache[schema.key][pk] = _schema$denormalize[0]; | ||
found = _schema$denormalize[1]; | ||
deleted = _schema$denormalize[2]; | ||
// if in cycle, use the start of the cycle to track all deps | ||
// otherwise, we use our own trackingIndex | ||
var localKey = dependencies.slice(cycleIndex.i === -1 ? trackingIndex : cycleIndex.i); | ||
_proto.define = function define(definition) { | ||
this.schema = Object.keys(definition).reduce(function (entitySchema, key) { | ||
var _Object$assign; | ||
if (!globalCacheEntry.has(localKey)) { | ||
globalCacheEntry.set(localKey, localCache[schema.key][pk]); | ||
} else { | ||
localCache[schema.key][pk] = globalCacheEntry.get(localKey); | ||
} // start of cycle - reset cycle detection | ||
var schema = definition[key]; | ||
return Object.assign({}, entitySchema, (_Object$assign = {}, _Object$assign[key] = schema, _Object$assign)); | ||
}, this.schema || {}); | ||
}; | ||
_proto.normalize = function normalize() { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
if (cycleIndex.i === trackingIndex) { | ||
cycleIndex.i = -1; | ||
} | ||
} else { | ||
// cycle detected | ||
if (Object.prototype.hasOwnProperty.call(localCache[schema.key][pk], DRAFT)) { | ||
cycleIndex.i = localCache[schema.key][pk].i; | ||
return [localCache[schema.key][pk][DRAFT], found, deleted]; | ||
} else { | ||
// with no cycle, globalCacheEntry will have already been set | ||
dependencies.push(entity); | ||
} | ||
} | ||
return _normalize.apply(void 0, [this.schema].concat(args)); | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
; | ||
return [localCache[schema.key][pk], found, deleted]; | ||
}; | ||
_proto.denormalize = function denormalize() { | ||
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
args[_key2] = arguments[_key2]; | ||
} | ||
var getUnvisit = function getUnvisit(entities, entityCache, resultCache, localCache) { | ||
var getEntity = getEntities(entities); | ||
var dependencies = []; | ||
var cycleIndex = { | ||
i: -1 | ||
}; | ||
return _denormalize.apply(void 0, [this.schema].concat(args)); | ||
}; | ||
function unvisit(input, schema) { | ||
if (!schema) return [input, true, false]; // null is considered intentional, thus always 'found' as true | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return _infer(this.schema, args, indexes, recurse); | ||
}; | ||
if (input === null) { | ||
return [input, true, false]; | ||
} | ||
return ObjectSchema; | ||
}(); | ||
var hasDenormalize = typeof schema.denormalize === 'function'; | ||
var DRAFT = Symbol('draft'); | ||
if (!hasDenormalize && typeof schema === 'function') { | ||
if (input instanceof schema) return [input, true, false]; // field deserialization should never count against 'found' (whether to used inferred results) | ||
var unvisitEntity = function unvisitEntity(entityOrId, schema, unvisit, getEntity, localCache, entityCache, dependencies, cycleIndex) { | ||
var entity = getEntity(entityOrId, schema); | ||
if (input === undefined) return [input, true, false]; | ||
return [new schema(input), true, false]; | ||
} | ||
if (entity === DELETED) { | ||
return [undefined, true, true]; | ||
} | ||
if (input === undefined) { | ||
return [input, false, false]; | ||
} | ||
if (process.env.NODE_ENV !== 'production' && typeof entity === 'symbol' && entity.toString().includes('DELETED')) { | ||
throw new Error("Unrecognized symbol detected.\nMake sure you do not have multiple versions of @rest-hooks/normalizr installed."); | ||
} | ||
if (!hasDenormalize && typeof schema === 'object') { | ||
var method = Array.isArray(schema) ? denormalize$1 : _denormalize; | ||
return method(schema, input, unvisit); | ||
} | ||
if (typeof entity !== 'object' || entity === null) { | ||
return [entity, false, false]; | ||
} | ||
if (isEntity(schema)) { | ||
return unvisitEntity(input, schema, unvisit, getEntity, localCache, entityCache, dependencies, cycleIndex); | ||
} | ||
var pk = typeof entityOrId === 'string' ? entityOrId : schema.pk(isImmutable(entity) ? entity.toJS() : entity); | ||
if (hasDenormalize) { | ||
return schema.denormalize(input, unvisit); | ||
} | ||
if (pk === undefined || pk === '') { | ||
return [entity, false, false]; | ||
} | ||
return [input, true, false]; | ||
} //const wrappedUnvisit = withTrackedEntities(unvisit, globalKey); | ||
if (localCache[schema.key] === undefined) { | ||
localCache[schema.key] = Object.create(null); | ||
} | ||
var found = true; | ||
var deleted = false; | ||
return function (input, schema) { | ||
var ret = unvisit(input, schema); // in the case where WeakMap cannot be used | ||
// this test ensures null is properly excluded from WeakMap | ||
if (!localCache[schema.key][pk]) { | ||
var trackingIndex = dependencies.length; | ||
dependencies.push(entity); | ||
var wrappedUnvisit = withTrackedEntities(unvisit); // { [DRAFT] } means we are still processing - which if found indicates a cycle | ||
if (Object(input) !== input) return ret; | ||
dependencies.push(input); | ||
wrappedUnvisit.setLocal = function (entityCopy) { | ||
var _localCache$schema$ke; | ||
if (!resultCache.has(dependencies)) { | ||
resultCache.set(dependencies, ret[0]); | ||
return ret; | ||
} else { | ||
return [resultCache.get(dependencies), ret[1], ret[2]]; | ||
} | ||
}; | ||
}; | ||
return localCache[schema.key][pk] = (_localCache$schema$ke = {}, _localCache$schema$ke[DRAFT] = entityCopy, _localCache$schema$ke.i = trackingIndex, _localCache$schema$ke); | ||
}; | ||
var getEntities = function getEntities(entities) { | ||
var entityIsImmutable = isImmutable(entities); | ||
return function (entityOrId, schema) { | ||
var _entities$schemaKey; | ||
var globalCacheEntry = getGlobalCacheEntry(entityCache, schema, pk); | ||
var schemaKey = schema.key; | ||
var _schema$denormalize = schema.denormalize(entity, wrappedUnvisit); | ||
if (typeof entityOrId === 'object') { | ||
return entityOrId; | ||
} | ||
localCache[schema.key][pk] = _schema$denormalize[0]; | ||
found = _schema$denormalize[1]; | ||
deleted = _schema$denormalize[2]; | ||
// if in cycle, use the start of the cycle to track all deps | ||
// otherwise, we use our own trackingIndex | ||
var localKey = dependencies.slice(cycleIndex.i === -1 ? trackingIndex : cycleIndex.i); | ||
if (entityIsImmutable) { | ||
return entities.getIn([schemaKey, entityOrId]); | ||
} | ||
if (!globalCacheEntry.has(localKey)) { | ||
globalCacheEntry.set(localKey, localCache[schema.key][pk]); | ||
} else { | ||
localCache[schema.key][pk] = globalCacheEntry.get(localKey); | ||
} // start of cycle - reset cycle detection | ||
return (_entities$schemaKey = entities[schemaKey]) == null ? void 0 : _entities$schemaKey[entityOrId]; | ||
}; | ||
}; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types | ||
if (cycleIndex.i === trackingIndex) { | ||
cycleIndex.i = -1; | ||
} | ||
} else { | ||
// cycle detected | ||
if (Object.prototype.hasOwnProperty.call(localCache[schema.key][pk], DRAFT)) { | ||
cycleIndex.i = localCache[schema.key][pk].i; | ||
return [localCache[schema.key][pk][DRAFT], found, deleted]; | ||
} else { | ||
// with no cycle, globalCacheEntry will have already been set | ||
dependencies.push(entity); | ||
} | ||
} | ||
var denormalize = function denormalize(input, schema, entities, entityCache, resultCache) { | ||
if (entityCache === void 0) { | ||
entityCache = {}; | ||
} | ||
return [localCache[schema.key][pk], found, deleted]; | ||
}; | ||
if (resultCache === void 0) { | ||
resultCache = new WeakListMap(); | ||
} | ||
var getUnvisit = function getUnvisit(entities, entityCache, resultCache, localCache) { | ||
var getEntity = getEntities(entities); | ||
var dependencies = []; | ||
var cycleIndex = { | ||
i: -1 | ||
}; | ||
// undefined mean don't do anything | ||
if (schema === undefined) { | ||
return [input, true, false, {}]; | ||
} | ||
function unvisit(input, schema) { | ||
if (!schema) return [input, true, false]; // null is considered intentional, thus always 'found' as true | ||
if (input === undefined) { | ||
return [undefined, false, false, {}]; | ||
} | ||
if (input === null) { | ||
return [input, true, false]; | ||
} | ||
var resolvedEntities = {}; | ||
var unvisit = getUnvisit(entities, entityCache, resultCache, resolvedEntities); | ||
return [].concat(unvisit(input, schema), [resolvedEntities]); | ||
}; | ||
var hasDenormalize = typeof schema.denormalize === 'function'; | ||
function getGlobalCacheEntry(entityCache, schema, id) { | ||
if (!entityCache[schema.key]) entityCache[schema.key] = {}; | ||
if (!entityCache[schema.key][id]) entityCache[schema.key][id] = new WeakListMap(); | ||
return entityCache[schema.key][id]; | ||
} | ||
if (!hasDenormalize && typeof schema === 'function') { | ||
if (input instanceof schema) return [input, true, false]; // field deserialization should never count against 'found' (whether to used inferred results) | ||
function withTrackedEntities(unvisit) { | ||
// every time we nest, we want to unwrap back to the top. | ||
// this is due to only needed the next level of nested entities for lookup | ||
var originalUnvisit = unvisit.og || unvisit; | ||
if (input === undefined) return [input, true, false]; | ||
return [new schema(input), true, false]; | ||
} | ||
var wrappedUnvisit = function wrappedUnvisit(input, schema) { | ||
return originalUnvisit(input, schema); | ||
}; | ||
if (input === undefined) { | ||
return [input, false, false]; | ||
} | ||
wrappedUnvisit.og = unvisit; | ||
return wrappedUnvisit; | ||
} | ||
if (!hasDenormalize && typeof schema === 'object') { | ||
var method = Array.isArray(schema) ? denormalize$1 : _denormalize; | ||
return method(schema, input, unvisit); | ||
} | ||
var visit = function visit(value, parent, key, schema, addEntity, visitedEntities) { | ||
if (!value || !schema) { | ||
return value; | ||
} | ||
if (isEntity(schema)) { | ||
return unvisitEntity(input, schema, unvisit, getEntity, localCache, entityCache, dependencies, cycleIndex); | ||
} | ||
if (schema.normalize && typeof schema.normalize === 'function') { | ||
if (typeof value !== 'object') return value; | ||
return schema.normalize(value, parent, key, visit, addEntity, visitedEntities); | ||
} // serializable | ||
if (hasDenormalize) { | ||
return schema.denormalize(input, unvisit); | ||
} | ||
return [input, true, false]; | ||
} //const wrappedUnvisit = withTrackedEntities(unvisit, globalKey); | ||
if (typeof schema === 'function') { | ||
return new schema(value); | ||
} | ||
if (typeof value !== 'object' || typeof schema !== 'object') return value; | ||
var method = Array.isArray(schema) ? normalize$1 : _normalize; | ||
return method(schema, value, parent, key, visit, addEntity, visitedEntities); | ||
}; | ||
return function (input, schema) { | ||
var ret = unvisit(input, schema); // in the case where WeakMap cannot be used | ||
// this test ensures null is properly excluded from WeakMap | ||
var addEntities = function addEntities(entities, indexes, existingEntities, existingIndexes, entityMeta, meta) { | ||
var _s = $RefreshSig$(); | ||
if (Object(input) !== input) return ret; | ||
dependencies.push(input); | ||
return _s(function (schema, processedEntity, id) { | ||
_s(); | ||
if (!resultCache.has(dependencies)) { | ||
resultCache.set(dependencies, ret[0]); | ||
return ret; | ||
} else { | ||
return [resultCache.get(dependencies), ret[1], ret[2]]; | ||
} | ||
}; | ||
}; | ||
var schemaKey = schema.key; | ||
var getEntities = function getEntities(entities) { | ||
var entityIsImmutable = isImmutable(entities); | ||
return function (entityOrId, schema) { | ||
var _entities$schemaKey; | ||
if (!(schemaKey in entities)) { | ||
entities[schemaKey] = {}; | ||
existingEntities[schemaKey] = Object.assign({}, existingEntities[schemaKey]); | ||
entityMeta[schemaKey] = Object.assign({}, entityMeta[schemaKey]); | ||
} | ||
var schemaKey = schema.key; | ||
var existingEntity = entities[schemaKey][id]; | ||
if (typeof entityOrId === 'object') { | ||
return entityOrId; | ||
} | ||
if (existingEntity) { | ||
entities[schemaKey][id] = schema.merge(existingEntity, processedEntity); | ||
} else { | ||
// TODO: eventually assume this exists and don't check for conditional. probably early 2022 | ||
var entityExpiresAt = schema.expiresAt ? schema.expiresAt(meta, processedEntity) : meta.expiresAt; | ||
var inStoreEntity = existingEntities[schemaKey][id]; // this case we already have this entity in store | ||
if (entityIsImmutable) { | ||
return entities.getIn([schemaKey, entityOrId]); | ||
} | ||
if (inStoreEntity) { | ||
var _entityMeta$schemaKey, _entityMeta$schemaKey2, _entityMeta$schemaKey3, _meta$fetchedAt, _entityMeta$schemaKey4, _entityMeta$schemaKey5; | ||
return (_entities$schemaKey = entities[schemaKey]) == null ? void 0 : _entities$schemaKey[entityOrId]; | ||
}; | ||
}; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types | ||
var inStoreMeta = entityMeta[schemaKey][id]; | ||
var useIncoming = // we may have in store but not in meta; so this existance check is still important | ||
!inStoreMeta || ( // useIncoming should not be used with legacy optimistic | ||
schema.useIncoming && meta.fetchedAt ? schema.useIncoming(inStoreMeta, meta, inStoreEntity, processedEntity) : entityMeta[schemaKey][id].date <= meta.date); | ||
if (useIncoming) { | ||
if (typeof processedEntity !== typeof inStoreEntity) { | ||
entities[schemaKey][id] = processedEntity; | ||
} else { | ||
entities[schemaKey][id] = schema.merge(inStoreEntity, processedEntity); | ||
} | ||
} else { | ||
entities[schemaKey][id] = inStoreEntity; | ||
} | ||
var denormalize = function denormalize(input, schema, entities, entityCache, resultCache) { | ||
if (entityCache === void 0) { | ||
entityCache = {}; | ||
} | ||
entityMeta[schemaKey][id] = { | ||
expiresAt: Math.max(entityExpiresAt, (_entityMeta$schemaKey = entityMeta[schemaKey][id]) == null ? void 0 : _entityMeta$schemaKey.expiresAt), | ||
date: Math.max(meta.date, (_entityMeta$schemaKey2 = (_entityMeta$schemaKey3 = entityMeta[schemaKey][id]) == null ? void 0 : _entityMeta$schemaKey3.date) != null ? _entityMeta$schemaKey2 : 0), | ||
fetchedAt: Math.max((_meta$fetchedAt = meta.fetchedAt) != null ? _meta$fetchedAt : 0, (_entityMeta$schemaKey4 = (_entityMeta$schemaKey5 = entityMeta[schemaKey][id]) == null ? void 0 : _entityMeta$schemaKey5.fetchedAt) != null ? _entityMeta$schemaKey4 : 0) | ||
}; | ||
} else { | ||
var _meta$fetchedAt2; | ||
if (resultCache === void 0) { | ||
resultCache = new WeakListMap(); | ||
} | ||
entities[schemaKey][id] = processedEntity; | ||
entityMeta[schemaKey][id] = { | ||
expiresAt: entityExpiresAt, | ||
date: meta.date, | ||
fetchedAt: (_meta$fetchedAt2 = meta.fetchedAt) != null ? _meta$fetchedAt2 : meta.date | ||
}; | ||
} | ||
} // update index | ||
// undefined mean don't do anything | ||
if (schema === undefined) { | ||
return [input, true, false, {}]; | ||
} | ||
if (input === undefined) { | ||
return [undefined, false, false, {}]; | ||
} | ||
if (Array.isArray(schema.indexes)) { | ||
var entity = entities[schemaKey][id]; | ||
var resolvedEntities = {}; | ||
var unvisit = getUnvisit(entities, entityCache, resultCache, resolvedEntities); | ||
return [].concat(unvisit(input, schema), [resolvedEntities]); | ||
}; | ||
if (!(schemaKey in indexes)) { | ||
indexes[schemaKey] = {}; | ||
existingIndexes[schemaKey] = Object.assign({}, existingIndexes[schemaKey]); | ||
} | ||
function getGlobalCacheEntry(entityCache, schema, id) { | ||
if (!entityCache[schema.key]) entityCache[schema.key] = {}; | ||
if (!entityCache[schema.key][id]) entityCache[schema.key][id] = new WeakListMap(); | ||
return entityCache[schema.key][id]; | ||
} | ||
for (var _iterator = _createForOfIteratorHelperLoose(schema.indexes), _step; !(_step = _iterator()).done;) { | ||
var index = _step.value; | ||
function withTrackedEntities(unvisit) { | ||
// every time we nest, we want to unwrap back to the top. | ||
// this is due to only needed the next level of nested entities for lookup | ||
var originalUnvisit = unvisit.og || unvisit; | ||
if (!(index in indexes[schemaKey])) { | ||
existingIndexes[schemaKey][index] = indexes[schemaKey][index] = {}; | ||
} | ||
var wrappedUnvisit = function wrappedUnvisit(input, schema) { | ||
return originalUnvisit(input, schema); | ||
}; | ||
var indexMap = indexes[schemaKey][index]; | ||
wrappedUnvisit.og = unvisit; | ||
return wrappedUnvisit; | ||
} | ||
if (existingEntity) { | ||
delete indexMap[existingEntity[index]]; | ||
} // entity already in cache but the index changed | ||
var visit = function visit(value, parent, key, schema, addEntity, visitedEntities) { | ||
if (!value || !schema) { | ||
return value; | ||
} | ||
if (schema.normalize && typeof schema.normalize === 'function') { | ||
if (typeof value !== 'object') return value; | ||
return schema.normalize(value, parent, key, visit, addEntity, visitedEntities); | ||
} // serializable | ||
if (existingEntities[schemaKey] && existingEntities[schemaKey][id] && existingEntities[schemaKey][id][index] !== entity[index]) { | ||
indexMap[existingEntities[schemaKey][id][index]] = DELETED; | ||
} | ||
if (index in entity) { | ||
indexMap[entity[index]] = id; | ||
} | ||
/* istanbul ignore next */ | ||
else if ( // eslint-disable-next-line no-undef | ||
process.env.NODE_ENV !== 'production') { | ||
console.warn("Index not found in entity. Indexes must be top-level members of your entity.\nIndex: " + index + "\nEntity: " + JSON.stringify(entity, undefined, 2)); | ||
} | ||
} | ||
} // set this after index updates so we know what indexes to remove from | ||
if (typeof schema === 'function') { | ||
return new schema(value); | ||
} | ||
if (typeof value !== 'object' || typeof schema !== 'object') return value; | ||
var method = Array.isArray(schema) ? normalize$1 : _normalize; | ||
return method(schema, value, parent, key, visit, addEntity, visitedEntities); | ||
}; | ||
existingEntities[schemaKey][id] = entities[schemaKey][id]; | ||
}, "RSHyr3aBwsmLX8s7SwDQGEQTEhQ=", false, function () { | ||
return [schema.useIncoming]; | ||
}); | ||
}; | ||
var addEntities = function addEntities(entities, indexes, existingEntities, existingIndexes, entityMeta, meta) { | ||
var _s = $RefreshSig$(); | ||
function expectedSchemaType(schema) { | ||
return ['object', 'function'].includes(typeof schema) ? 'object' : typeof schema; | ||
} // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types | ||
return _s(function (schema, processedEntity, id) { | ||
_s(); | ||
var schemaKey = schema.key; | ||
var normalize = function normalize(input, schema, existingEntities, existingIndexes, existingEntityMeta, meta) { | ||
if (existingEntities === void 0) { | ||
existingEntities = {}; | ||
} | ||
if (!(schemaKey in entities)) { | ||
entities[schemaKey] = {}; | ||
existingEntities[schemaKey] = Object.assign({}, existingEntities[schemaKey]); | ||
entityMeta[schemaKey] = Object.assign({}, entityMeta[schemaKey]); | ||
} | ||
if (existingIndexes === void 0) { | ||
existingIndexes = {}; | ||
} | ||
var existingEntity = entities[schemaKey][id]; | ||
if (existingEntityMeta === void 0) { | ||
existingEntityMeta = {}; | ||
} | ||
if (existingEntity) { | ||
entities[schemaKey][id] = schema.merge(existingEntity, processedEntity); | ||
} else { | ||
// TODO: eventually assume this exists and don't check for conditional. probably early 2022 | ||
var entityExpiresAt = schema.expiresAt ? schema.expiresAt(meta, processedEntity) : meta.expiresAt; | ||
var inStoreEntity = existingEntities[schemaKey][id]; // this case we already have this entity in store | ||
if (meta === void 0) { | ||
meta = { | ||
date: Date.now(), | ||
expiresAt: Infinity, | ||
fetchedAt: 0 | ||
}; | ||
} | ||
if (inStoreEntity) { | ||
var _entityMeta$schemaKey, _entityMeta$schemaKey2, _entityMeta$schemaKey3, _meta$fetchedAt, _entityMeta$schemaKey4, _entityMeta$schemaKey5; | ||
// no schema means we don't process at all | ||
if (schema === undefined) return { | ||
entities: existingEntities, | ||
indexes: existingIndexes, | ||
result: input, | ||
entityMeta: existingEntityMeta | ||
}; | ||
var schemaType = expectedSchemaType(schema); | ||
var inStoreMeta = entityMeta[schemaKey][id]; | ||
var useIncoming = // we may have in store but not in meta; so this existance check is still important | ||
!inStoreMeta || ( // useIncoming should not be used with legacy optimistic | ||
schema.useIncoming && meta.fetchedAt ? schema.useIncoming(inStoreMeta, meta, inStoreEntity, processedEntity) : entityMeta[schemaKey][id].date <= meta.date); | ||
if (input === null || typeof input !== schemaType && !(schema.key !== undefined && typeof input === 'string')) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production') { | ||
var parseWorks = function parseWorks(input) { | ||
try { | ||
return typeof JSON.parse(input) !== 'string'; | ||
} catch (e) { | ||
return false; | ||
} | ||
}; | ||
if (useIncoming) { | ||
if (typeof processedEntity !== typeof inStoreEntity) { | ||
entities[schemaKey][id] = processedEntity; | ||
} else { | ||
entities[schemaKey][id] = schema.merge(inStoreEntity, processedEntity); | ||
} | ||
} else { | ||
entities[schemaKey][id] = inStoreEntity; | ||
} | ||
if (typeof input === 'string' && parseWorks(input)) { | ||
throw new Error("Normalizing a string, but this does match schema.\n\nParsing this input string as JSON worked. This likely indicates fetch function did not parse\nthe JSON. By default, this only happens if \"content-type\" header includes \"json\".\nSee https://resthooks.io/docs/guides/custom-networking for more information\n\n Schema: " + JSON.stringify(schema, undefined, 2) + "\n Input: \"" + input + "\""); | ||
} else { | ||
throw new Error("Unexpected input given to normalize. Expected type to be \"" + schemaType + "\", found \"" + (input === null ? 'null' : typeof input) + "\".\n\n Schema: " + JSON.stringify(schema, undefined, 2) + "\n Input: \"" + input + "\""); | ||
} | ||
} else { | ||
throw new Error("Unexpected input given to normalize. Expected type to be \"" + schemaType + "\", found \"" + (input === null ? 'null' : typeof input) + "\"."); | ||
} | ||
} | ||
entityMeta[schemaKey][id] = { | ||
expiresAt: Math.max(entityExpiresAt, (_entityMeta$schemaKey = entityMeta[schemaKey][id]) == null ? void 0 : _entityMeta$schemaKey.expiresAt), | ||
date: Math.max(meta.date, (_entityMeta$schemaKey2 = (_entityMeta$schemaKey3 = entityMeta[schemaKey][id]) == null ? void 0 : _entityMeta$schemaKey3.date) != null ? _entityMeta$schemaKey2 : 0), | ||
fetchedAt: Math.max((_meta$fetchedAt = meta.fetchedAt) != null ? _meta$fetchedAt : 0, (_entityMeta$schemaKey4 = (_entityMeta$schemaKey5 = entityMeta[schemaKey][id]) == null ? void 0 : _entityMeta$schemaKey5.fetchedAt) != null ? _entityMeta$schemaKey4 : 0) | ||
}; | ||
} else { | ||
var _meta$fetchedAt2; | ||
var newEntities = {}; | ||
var newIndexes = {}; | ||
var entities = Object.assign({}, existingEntities); | ||
var indexes = Object.assign({}, existingIndexes); | ||
var entityMeta = Object.assign({}, existingEntityMeta); | ||
var addEntity = addEntities(newEntities, newIndexes, entities, indexes, entityMeta, meta); | ||
var visitedEntities = {}; | ||
var result = visit(input, input, undefined, schema, addEntity, visitedEntities); | ||
return { | ||
entities: entities, | ||
indexes: indexes, | ||
result: result, | ||
entityMeta: entityMeta | ||
}; | ||
}; | ||
entities[schemaKey][id] = processedEntity; | ||
entityMeta[schemaKey][id] = { | ||
expiresAt: entityExpiresAt, | ||
date: meta.date, | ||
fetchedAt: (_meta$fetchedAt2 = meta.fetchedAt) != null ? _meta$fetchedAt2 : meta.date | ||
}; | ||
} | ||
} // update index | ||
/** | ||
* Represents polymorphic values. | ||
* @see https://resthooks.io/docs/api/Union | ||
*/ | ||
var UnionSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(UnionSchema, _PolymorphicSchema); | ||
if (Array.isArray(schema.indexes)) { | ||
var entity = entities[schemaKey][id]; | ||
function UnionSchema(definition, schemaAttribute) { | ||
if (!schemaAttribute) { | ||
throw new Error('Expected option "schemaAttribute" not found on UnionSchema.'); | ||
} | ||
if (!(schemaKey in indexes)) { | ||
indexes[schemaKey] = {}; | ||
existingIndexes[schemaKey] = Object.assign({}, existingIndexes[schemaKey]); | ||
} | ||
return _PolymorphicSchema.call(this, definition, schemaAttribute) || this; | ||
} | ||
for (var _iterator = _createForOfIteratorHelperLoose(schema.indexes), _step; !(_step = _iterator()).done;) { | ||
var index = _step.value; | ||
var _proto = UnionSchema.prototype; | ||
if (!(index in indexes[schemaKey])) { | ||
existingIndexes[schemaKey][index] = indexes[schemaKey][index] = {}; | ||
} | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
return this.normalizeValue(input, parent, key, visit, addEntity, visitedEntities); | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
; | ||
var indexMap = indexes[schemaKey][index]; | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
return this.denormalizeValue(input, unvisit); | ||
}; | ||
if (existingEntity) { | ||
delete indexMap[existingEntity[index]]; | ||
} // entity already in cache but the index changed | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
if (!args[0]) return undefined; | ||
var attr = this.getSchemaAttribute(args[0], undefined, ''); | ||
var discriminatedSchema = this.schema[attr]; // Was unable to infer the entity's schema from params | ||
if (discriminatedSchema === undefined) return undefined; | ||
return { | ||
id: recurse(discriminatedSchema, args, indexes), | ||
schema: attr | ||
}; | ||
}; | ||
if (existingEntities[schemaKey] && existingEntities[schemaKey][id] && existingEntities[schemaKey][id][index] !== entity[index]) { | ||
indexMap[existingEntities[schemaKey][id][index]] = DELETED; | ||
} | ||
return UnionSchema; | ||
}(PolymorphicSchema); | ||
if (index in entity) { | ||
indexMap[entity[index]] = id; | ||
} | ||
/* istanbul ignore next */ | ||
else if ( // eslint-disable-next-line no-undef | ||
process.env.NODE_ENV !== 'production') { | ||
console.warn("Index not found in entity. Indexes must be top-level members of your entity.\nIndex: " + index + "\nEntity: " + JSON.stringify(entity, undefined, 2)); | ||
} | ||
} | ||
} // set this after index updates so we know what indexes to remove from | ||
/** | ||
* Represents variably sized objects | ||
* @see https://resthooks.io/docs/api/Values | ||
*/ | ||
var ValuesSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ValuesSchema, _PolymorphicSchema); | ||
existingEntities[schemaKey][id] = entities[schemaKey][id]; | ||
}, "RSHyr3aBwsmLX8s7SwDQGEQTEhQ=", false, function () { | ||
return [schema.useIncoming]; | ||
}); | ||
}; | ||
function ValuesSchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
} | ||
function expectedSchemaType(schema) { | ||
return ['object', 'function'].includes(typeof schema) ? 'object' : typeof schema; | ||
} // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types | ||
var _proto = ValuesSchema.prototype; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
var normalize = function normalize(input, schema, existingEntities, existingIndexes, existingEntityMeta, meta) { | ||
if (existingEntities === void 0) { | ||
existingEntities = {}; | ||
} | ||
return Object.keys(input).reduce(function (output, key, index) { | ||
var _Object$assign; | ||
if (existingIndexes === void 0) { | ||
existingIndexes = {}; | ||
} | ||
var value = input[key]; | ||
return value !== undefined && value !== null ? Object.assign({}, output, (_Object$assign = {}, _Object$assign[key] = _this.normalizeValue(value, input, key, visit, addEntity, visitedEntities), _Object$assign)) : output; | ||
}, {}); | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
; | ||
if (existingEntityMeta === void 0) { | ||
existingEntityMeta = {}; | ||
} | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
if (meta === void 0) { | ||
meta = { | ||
date: Date.now(), | ||
expiresAt: Infinity, | ||
fetchedAt: 0 | ||
}; | ||
} | ||
var found = true; | ||
var deleted = false; | ||
return [Object.keys(input).reduce(function (output, key) { | ||
var _Object$assign2; | ||
// no schema means we don't process at all | ||
if (schema === undefined) return { | ||
entities: existingEntities, | ||
indexes: existingIndexes, | ||
result: input, | ||
entityMeta: existingEntityMeta | ||
}; | ||
var schemaType = expectedSchemaType(schema); | ||
var entityOrId = input[key]; | ||
if (input === null || typeof input !== schemaType && !(schema.key !== undefined && typeof input === 'string')) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production') { | ||
var parseWorks = function parseWorks(input) { | ||
try { | ||
return typeof JSON.parse(input) !== 'string'; | ||
} catch (e) { | ||
return false; | ||
} | ||
}; | ||
var _this2$denormalizeVal = _this2.denormalizeValue(entityOrId, unvisit), | ||
value = _this2$denormalizeVal[0], | ||
foundItem = _this2$denormalizeVal[1], | ||
deletedItem = _this2$denormalizeVal[2]; | ||
if (typeof input === 'string' && parseWorks(input)) { | ||
throw new Error("Normalizing a string, but this does match schema.\n\nParsing this input string as JSON worked. This likely indicates fetch function did not parse\nthe JSON. By default, this only happens if \"content-type\" header includes \"json\".\nSee https://resthooks.io/docs/guides/custom-networking for more information\n\n Schema: " + JSON.stringify(schema, undefined, 2) + "\n Input: \"" + input + "\""); | ||
} else { | ||
throw new Error("Unexpected input given to normalize. Expected type to be \"" + schemaType + "\", found \"" + (input === null ? 'null' : typeof input) + "\".\n\n Schema: " + JSON.stringify(schema, undefined, 2) + "\n Input: \"" + input + "\""); | ||
} | ||
} else { | ||
throw new Error("Unexpected input given to normalize. Expected type to be \"" + schemaType + "\", found \"" + (input === null ? 'null' : typeof input) + "\"."); | ||
} | ||
} | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
var newEntities = {}; | ||
var newIndexes = {}; | ||
var entities = Object.assign({}, existingEntities); | ||
var indexes = Object.assign({}, existingIndexes); | ||
var entityMeta = Object.assign({}, existingEntityMeta); | ||
var addEntity = addEntities(newEntities, newIndexes, entities, indexes, entityMeta, meta); | ||
var visitedEntities = {}; | ||
var result = visit(input, input, undefined, schema, addEntity, visitedEntities); | ||
return { | ||
entities: entities, | ||
indexes: indexes, | ||
result: result, | ||
entityMeta: entityMeta | ||
}; | ||
}; | ||
if (deletedItem) { | ||
deleted = true; | ||
} | ||
/** | ||
* Represents polymorphic values. | ||
* @see https://resthooks.io/docs/api/Union | ||
*/ | ||
if (!foundItem || deletedItem) return output; | ||
return Object.assign({}, output, (_Object$assign2 = {}, _Object$assign2[key] = value, _Object$assign2)); | ||
}, {}), found, deleted]; | ||
}; | ||
var UnionSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(UnionSchema, _PolymorphicSchema); | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return undefined; | ||
}; | ||
function UnionSchema(definition, schemaAttribute) { | ||
if (!schemaAttribute) { | ||
throw new Error('Expected option "schemaAttribute" not found on UnionSchema.'); | ||
} | ||
return ValuesSchema; | ||
}(PolymorphicSchema); | ||
return _PolymorphicSchema.call(this, definition, schemaAttribute) || this; | ||
} | ||
/** | ||
* Marks entity as deleted. | ||
* @see https://resthooks.io/docs/api/Delete | ||
*/ | ||
var _proto = UnionSchema.prototype; | ||
var Delete = /*#__PURE__*/function () { | ||
function Delete(entity) { | ||
if (process.env.NODE_ENV !== 'production' && !entity) { | ||
throw new Error('Expected option "entity" not found on DeleteSchema.'); | ||
} | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
return this.normalizeValue(input, parent, key, visit, addEntity, visitedEntities); | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
; | ||
this._entity = entity; | ||
} | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
return this.denormalizeValue(input, unvisit); | ||
}; | ||
var _proto = Delete.prototype; | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
if (!args[0]) return undefined; | ||
var attr = this.getSchemaAttribute(args[0], undefined, ''); | ||
var discriminatedSchema = this.schema[attr]; // Was unable to infer the entity's schema from params | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
// TODO: what's store needs to be a differing type from fromJS | ||
var processedEntity = this._entity.process(input, parent, key); | ||
if (discriminatedSchema === undefined) return undefined; | ||
return { | ||
id: recurse(discriminatedSchema, args, indexes), | ||
schema: attr | ||
}; | ||
}; | ||
var id = this._entity.pk(processedEntity, parent, key); | ||
return UnionSchema; | ||
}(PolymorphicSchema); | ||
if (process.env.NODE_ENV !== 'production' && (id === undefined || id === '')) { | ||
var _name; | ||
/** | ||
* Represents variably sized objects | ||
* @see https://resthooks.io/docs/api/Values | ||
*/ | ||
var error = new Error("Missing usable primary key when normalizing response.\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n\n Delete(Entity): Delete(" + ((_name = this._entity.name) != null ? _name : this._entity) + ")\n Value: " + (input && JSON.stringify(input, null, 2)) + "\n "); | ||
error.status = 400; | ||
throw error; | ||
} | ||
var ValuesSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ValuesSchema, _PolymorphicSchema); | ||
addEntity(this, DELETED, id); | ||
return id; | ||
}; | ||
function ValuesSchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
} | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return undefined; | ||
}; | ||
var _proto = ValuesSchema.prototype; | ||
_proto.denormalize = function denormalize(id, unvisit) { | ||
return unvisit(id, this._entity); | ||
} | ||
/* istanbul ignore next */ | ||
; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
_proto._denormalizeNullable = function _denormalizeNullable() { | ||
return []; | ||
} | ||
/* istanbul ignore next */ | ||
; | ||
return Object.keys(input).reduce(function (output, key, index) { | ||
var _Object$assign; | ||
_proto._normalizeNullable = function _normalizeNullable() { | ||
return []; | ||
} | ||
/* istanbul ignore next */ | ||
; | ||
var value = input[key]; | ||
return value !== undefined && value !== null ? Object.assign({}, output, (_Object$assign = {}, _Object$assign[key] = _this.normalizeValue(value, input, key, visit, addEntity, visitedEntities), _Object$assign)) : output; | ||
}, {}); | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
; | ||
_proto.merge = function merge(existing, incoming) { | ||
return incoming; | ||
}; | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
_proto.useIncoming = function useIncoming(existingMeta, incomingMeta, existing, incoming) { | ||
return existingMeta.date <= incomingMeta.date; | ||
}; | ||
var found = true; | ||
var deleted = false; | ||
return [Object.keys(input).reduce(function (output, key) { | ||
var _Object$assign2; | ||
_createClass(Delete, [{ | ||
key: "key", | ||
get: function get() { | ||
return this._entity.key; | ||
} | ||
}]); | ||
var entityOrId = input[key]; | ||
return Delete; | ||
}(); | ||
var _this2$denormalizeVal = _this2.denormalizeValue(entityOrId, unvisit), | ||
value = _this2$denormalizeVal[0], | ||
foundItem = _this2$denormalizeVal[1], | ||
deletedItem = _this2$denormalizeVal[2]; | ||
/* istanbul ignore file */ | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
var schema$1 = /*#__PURE__*/Object.freeze({ | ||
__proto__: null, | ||
Union: UnionSchema, | ||
Values: ValuesSchema, | ||
Array: ArraySchema, | ||
Object: ObjectSchema, | ||
Delete: Delete | ||
}); | ||
if (deletedItem) { | ||
deleted = true; | ||
} | ||
/** | ||
* Build the result parameter to denormalize from schema alone. | ||
* Tries to compute the entity ids from params. | ||
*/ | ||
if (!foundItem || deletedItem) return output; | ||
return Object.assign({}, output, (_Object$assign2 = {}, _Object$assign2[key] = value, _Object$assign2)); | ||
}, {}), found, deleted]; | ||
}; | ||
function inferResults(schema, args, indexes) { | ||
// schema classes | ||
if (canInfer(schema)) { | ||
return schema.infer(args, indexes, inferResults); | ||
} // plain case | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return undefined; | ||
}; | ||
return ValuesSchema; | ||
}(PolymorphicSchema); | ||
if (typeof schema === 'object' && schema) { | ||
var method = Array.isArray(schema) ? _infer$1 : _infer; | ||
return method(schema, args, indexes, inferResults); | ||
} // fallback for things like null or undefined | ||
/** | ||
* Marks entity as deleted. | ||
* @see https://resthooks.io/docs/api/Delete | ||
*/ | ||
var Delete = /*#__PURE__*/function () { | ||
function Delete(entity) { | ||
if (process.env.NODE_ENV !== 'production' && !entity) { | ||
throw new Error('Expected option "entity" not found on DeleteSchema.'); | ||
} | ||
return schema; | ||
} | ||
this._entity = entity; | ||
} | ||
function canInfer(schema) { | ||
return !!schema && typeof schema.infer === 'function'; | ||
} | ||
var _proto = Delete.prototype; | ||
exports.DELETED = DELETED; | ||
exports.Entity = Entity; | ||
exports.WeakListMap = WeakListMap; | ||
exports.denormalize = denormalize; | ||
exports.inferResults = inferResults; | ||
exports.isEntity = isEntity; | ||
exports.normalize = normalize; | ||
exports.schema = schema$1; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
// TODO: what's store needs to be a differing type from fromJS | ||
var processedEntity = this._entity.process(input, parent, key); | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
var id = this._entity.pk(processedEntity, parent, key); | ||
if (process.env.NODE_ENV !== 'production' && (id === undefined || id === '')) { | ||
var _name; | ||
var error = new Error("Missing usable primary key when normalizing response.\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n\n Delete(Entity): Delete(" + ((_name = this._entity.name) != null ? _name : this._entity) + ")\n Value: " + (input && JSON.stringify(input, null, 2)) + "\n "); | ||
error.status = 400; | ||
throw error; | ||
} | ||
addEntity(this, DELETED, id); | ||
return id; | ||
}; | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return undefined; | ||
}; | ||
_proto.denormalize = function denormalize(id, unvisit) { | ||
return unvisit(id, this._entity); | ||
} | ||
/* istanbul ignore next */ | ||
; | ||
_proto._denormalizeNullable = function _denormalizeNullable() { | ||
return []; | ||
} | ||
/* istanbul ignore next */ | ||
; | ||
_proto._normalizeNullable = function _normalizeNullable() { | ||
return []; | ||
} | ||
/* istanbul ignore next */ | ||
; | ||
_proto.merge = function merge(existing, incoming) { | ||
return incoming; | ||
}; | ||
_proto.useIncoming = function useIncoming(existingMeta, incomingMeta, existing, incoming) { | ||
return existingMeta.date <= incomingMeta.date; | ||
}; | ||
_createClass(Delete, [{ | ||
key: "key", | ||
get: function get() { | ||
return this._entity.key; | ||
} | ||
}]); | ||
return Delete; | ||
}(); | ||
/* istanbul ignore file */ | ||
var schema$1 = /*#__PURE__*/Object.freeze({ | ||
__proto__: null, | ||
Union: UnionSchema, | ||
Values: ValuesSchema, | ||
Array: ArraySchema, | ||
Object: ObjectSchema, | ||
Delete: Delete | ||
}); | ||
/** | ||
* Build the result parameter to denormalize from schema alone. | ||
* Tries to compute the entity ids from params. | ||
*/ | ||
function inferResults(schema, args, indexes) { | ||
// schema classes | ||
if (canInfer(schema)) { | ||
return schema.infer(args, indexes, inferResults); | ||
} // plain case | ||
if (typeof schema === 'object' && schema) { | ||
var method = Array.isArray(schema) ? _infer$1 : _infer; | ||
return method(schema, args, indexes, inferResults); | ||
} // fallback for things like null or undefined | ||
return schema; | ||
} | ||
function canInfer(schema) { | ||
return !!schema && typeof schema.infer === 'function'; | ||
} | ||
exports.DELETED = DELETED; | ||
exports.Entity = Entity; | ||
exports.WeakListMap = WeakListMap; | ||
exports.denormalize = denormalize; | ||
exports.inferResults = inferResults; | ||
exports.isEntity = isEntity; | ||
exports.normalize = normalize; | ||
exports.schema = schema$1; | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
})); |
var rest_hooks_normalizr = (function (exports) { | ||
'use strict'; | ||
'use strict'; | ||
function _arrayLikeToArray(arr, len) { | ||
if (len == null || len > arr.length) len = arr.length; | ||
function unwrapExports (x) { | ||
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; | ||
} | ||
for (var i = 0, arr2 = new Array(len); i < len; i++) { | ||
arr2[i] = arr[i]; | ||
} | ||
function createCommonjsModule(fn, module) { | ||
return module = { exports: {} }, fn(module, module.exports), module.exports; | ||
} | ||
return arr2; | ||
} | ||
var arrayLikeToArray = createCommonjsModule(function (module) { | ||
function _arrayLikeToArray(arr, len) { | ||
if (len == null || len > arr.length) len = arr.length; | ||
function _unsupportedIterableToArray(o, minLen) { | ||
if (!o) return; | ||
if (typeof o === "string") return _arrayLikeToArray(o, minLen); | ||
var n = Object.prototype.toString.call(o).slice(8, -1); | ||
if (n === "Object" && o.constructor) n = o.constructor.name; | ||
if (n === "Map" || n === "Set") return Array.from(o); | ||
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); | ||
} | ||
for (var i = 0, arr2 = new Array(len); i < len; i++) { | ||
arr2[i] = arr[i]; | ||
} | ||
function _createForOfIteratorHelperLoose(o, allowArrayLike) { | ||
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; | ||
if (it) return (it = it.call(o)).next.bind(it); | ||
return arr2; | ||
} | ||
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { | ||
if (it) o = it; | ||
var i = 0; | ||
return function () { | ||
if (i >= o.length) return { | ||
done: true | ||
}; | ||
return { | ||
done: false, | ||
value: o[i++] | ||
}; | ||
}; | ||
} | ||
module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); | ||
} | ||
unwrapExports(arrayLikeToArray); | ||
function _defineProperties(target, props) { | ||
for (var i = 0; i < props.length; i++) { | ||
var descriptor = props[i]; | ||
descriptor.enumerable = descriptor.enumerable || false; | ||
descriptor.configurable = true; | ||
if ("value" in descriptor) descriptor.writable = true; | ||
Object.defineProperty(target, descriptor.key, descriptor); | ||
} | ||
} | ||
var unsupportedIterableToArray = createCommonjsModule(function (module) { | ||
function _unsupportedIterableToArray(o, minLen) { | ||
if (!o) return; | ||
if (typeof o === "string") return arrayLikeToArray(o, minLen); | ||
var n = Object.prototype.toString.call(o).slice(8, -1); | ||
if (n === "Object" && o.constructor) n = o.constructor.name; | ||
if (n === "Map" || n === "Set") return Array.from(o); | ||
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); | ||
} | ||
function _createClass(Constructor, protoProps, staticProps) { | ||
if (protoProps) _defineProperties(Constructor.prototype, protoProps); | ||
if (staticProps) _defineProperties(Constructor, staticProps); | ||
Object.defineProperty(Constructor, "prototype", { | ||
writable: false | ||
}); | ||
return Constructor; | ||
} | ||
module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
/** | ||
* Helpers to enable Immutable compatibility *without* bringing in | ||
* the 'immutable' package as a dependency. | ||
*/ | ||
unwrapExports(unsupportedIterableToArray); | ||
/** | ||
* Check if an object is immutable by checking if it has a key specific | ||
* to the immutable library. | ||
* | ||
* @param {any} object | ||
* @return {bool} | ||
*/ | ||
// eslint-disable-next-line @typescript-eslint/ban-types | ||
function isImmutable(object) { | ||
return !!(typeof object.hasOwnProperty === 'function' && (Object.hasOwnProperty.call(object, '__ownerID') || // Immutable.Map | ||
object._map && Object.hasOwnProperty.call(object._map, '__ownerID'))); // Immutable.Record | ||
} | ||
/** | ||
* Denormalize an immutable entity. | ||
* | ||
* @param {Schema} schema | ||
* @param {Immutable.Map|Immutable.Record} input | ||
* @param {function} unvisit | ||
* @param {function} getDenormalizedEntity | ||
* @return {Immutable.Map|Immutable.Record} | ||
*/ | ||
var createForOfIteratorHelperLoose = createCommonjsModule(function (module) { | ||
function _createForOfIteratorHelperLoose(o, allowArrayLike) { | ||
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; | ||
if (it) return (it = it.call(o)).next.bind(it); | ||
function denormalizeImmutable(schema, input, unvisit) { | ||
var found = true; | ||
var deleted = false; | ||
return [Object.keys(schema).reduce(function (object, key) { | ||
// Immutable maps cast keys to strings on write so we need to ensure | ||
// we're accessing them using string keys. | ||
var stringKey = "" + key; | ||
if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { | ||
if (it) o = it; | ||
var i = 0; | ||
return function () { | ||
if (i >= o.length) return { | ||
done: true | ||
}; | ||
return { | ||
done: false, | ||
value: o[i++] | ||
}; | ||
}; | ||
} | ||
var _unvisit = unvisit(object.get(stringKey), schema[stringKey]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1], | ||
deletedItem = _unvisit[2]; | ||
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); | ||
} | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
module.exports = _createForOfIteratorHelperLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
if (deletedItem) { | ||
deleted = true; | ||
} | ||
var _createForOfIteratorHelperLoose = unwrapExports(createForOfIteratorHelperLoose); | ||
if (object.has(stringKey)) { | ||
return object.set(stringKey, item); | ||
} else { | ||
return object; | ||
} | ||
}, input), found, deleted]; | ||
} | ||
var createClass = createCommonjsModule(function (module) { | ||
function _defineProperties(target, props) { | ||
for (var i = 0; i < props.length; i++) { | ||
var descriptor = props[i]; | ||
descriptor.enumerable = descriptor.enumerable || false; | ||
descriptor.configurable = true; | ||
if ("value" in descriptor) descriptor.writable = true; | ||
Object.defineProperty(target, descriptor.key, descriptor); | ||
} | ||
} | ||
/** | ||
* Represents data that should be deduped by specifying a primary key. | ||
* @see https://resthooks.io/docs/api/Entity | ||
*/ | ||
function _createClass(Constructor, protoProps, staticProps) { | ||
if (protoProps) _defineProperties(Constructor.prototype, protoProps); | ||
if (staticProps) _defineProperties(Constructor, staticProps); | ||
Object.defineProperty(Constructor, "prototype", { | ||
writable: false | ||
}); | ||
return Constructor; | ||
} | ||
var Entity = /*#__PURE__*/function () { | ||
function Entity() {} | ||
module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
Entity.toJSON = function toJSON() { | ||
return { | ||
name: this.name, | ||
schema: this.schema, | ||
key: this.key | ||
}; | ||
} | ||
/** Defines nested entities */ | ||
var _createClass = unwrapExports(createClass); | ||
/** Returns the globally unique identifier for the static Entity */ | ||
; | ||
/** | ||
* Helpers to enable Immutable compatibility *without* bringing in | ||
* the 'immutable' package as a dependency. | ||
*/ | ||
/** Defines indexes to enable lookup by */ | ||
/** | ||
* Check if an object is immutable by checking if it has a key specific | ||
* to the immutable library. | ||
* | ||
* @param {any} object | ||
* @return {bool} | ||
*/ | ||
// eslint-disable-next-line @typescript-eslint/ban-types | ||
function isImmutable(object) { | ||
return !!(typeof object.hasOwnProperty === 'function' && (Object.hasOwnProperty.call(object, '__ownerID') || // Immutable.Map | ||
object._map && Object.hasOwnProperty.call(object._map, '__ownerID'))); // Immutable.Record | ||
} | ||
/** | ||
* Denormalize an immutable entity. | ||
* | ||
* @param {Schema} schema | ||
* @param {Immutable.Map|Immutable.Record} input | ||
* @param {function} unvisit | ||
* @param {function} getDenormalizedEntity | ||
* @return {Immutable.Map|Immutable.Record} | ||
*/ | ||
/** | ||
* A unique identifier for each Entity | ||
* | ||
* @param [value] POJO of the entity or subset used | ||
* @param [parent] When normalizing, the object which included the entity | ||
* @param [key] When normalizing, the key where this entity was found | ||
*/ | ||
Entity.pk = function pk(value, parent, key) { | ||
return this.prototype.pk.call(value, parent, key); | ||
} | ||
/** Return true to merge incoming data; false keeps existing entity */ | ||
; | ||
function denormalizeImmutable(schema, input, unvisit) { | ||
var found = true; | ||
var deleted = false; | ||
return [Object.keys(schema).reduce(function (object, key) { | ||
// Immutable maps cast keys to strings on write so we need to ensure | ||
// we're accessing them using string keys. | ||
var stringKey = "" + key; | ||
Entity.useIncoming = function useIncoming(existingMeta, incomingMeta, existing, incoming) { | ||
return existingMeta.fetchedAt <= incomingMeta.fetchedAt; | ||
} | ||
/** Creates new instance copying over defined values of arguments */ | ||
; | ||
var _unvisit = unvisit(object.get(stringKey), schema[stringKey]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1], | ||
deletedItem = _unvisit[2]; | ||
Entity.merge = function merge(existing, incoming) { | ||
return Object.assign({}, existing, incoming); | ||
} | ||
/** Factory method to convert from Plain JS Objects. | ||
* | ||
* @param [props] Plain Object of properties to assign. | ||
* @param [parent] When normalizing, the object which included the record | ||
* @param [key] When normalizing, the key where this record was found | ||
*/ | ||
; | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
Entity.fromJS = function fromJS( // TODO: this should only accept members that are not functions | ||
props) { | ||
if (props === void 0) { | ||
props = {}; | ||
} | ||
if (deletedItem) { | ||
deleted = true; | ||
} | ||
// we type guarded abstract case above, so ok to force typescript to allow constructor call | ||
var instance = new this(props); // we can't rely on constructors and override the defaults provided as property assignments | ||
// all occur after the constructor | ||
if (object.has(stringKey)) { | ||
return object.set(stringKey, item); | ||
} else { | ||
return object; | ||
} | ||
}, input), found, deleted]; | ||
} | ||
Object.assign(instance, props); | ||
return instance; | ||
} | ||
/** Do any transformations when first receiving input */ | ||
; | ||
/** | ||
* Represents data that should be deduped by specifying a primary key. | ||
* @see https://resthooks.io/docs/api/Entity | ||
*/ | ||
Entity.process = function (_process) { | ||
function process(_x, _x2, _x3) { | ||
return _process.apply(this, arguments); | ||
} | ||
var Entity = /*#__PURE__*/function () { | ||
function Entity() {} | ||
process.toString = function () { | ||
return _process.toString(); | ||
}; | ||
Entity.toJSON = function toJSON() { | ||
return { | ||
name: this.name, | ||
schema: this.schema, | ||
key: this.key | ||
}; | ||
} | ||
/** Defines nested entities */ | ||
return process; | ||
}(function (input, parent, key) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production' && this.automaticValidation !== 'silent') { | ||
if (Array.isArray(input)) { | ||
var errorMessage = "Attempted to initialize " + this.name + " with an array, but named members were expected\n\nThis is likely due to a malformed response.\nTry inspecting the network response or fetch() return value.\nOr use debugging tools: https://resthooks.io/docs/guides/debugging\nLearn more about schemas: https://resthooks.io/docs/api/schema\nIf this is a mistake, you can disable this check by setting static automaticValidation = 'silent'\n\nFirst three members: " + JSON.stringify(input.slice(0, 3), null, 2); | ||
/** Returns the globally unique identifier for the static Entity */ | ||
; | ||
if (this.automaticValidation !== 'warn') { | ||
var error = new Error(errorMessage); | ||
error.status = 400; | ||
throw error; | ||
} | ||
/** Defines indexes to enable lookup by */ | ||
console.warn(errorMessage); | ||
} | ||
} | ||
/** | ||
* A unique identifier for each Entity | ||
* | ||
* @param [value] POJO of the entity or subset used | ||
* @param [parent] When normalizing, the object which included the entity | ||
* @param [key] When normalizing, the key where this entity was found | ||
*/ | ||
Entity.pk = function pk(value, parent, key) { | ||
return this.prototype.pk.call(value, parent, key); | ||
} | ||
/** Return true to merge incoming data; false keeps existing entity */ | ||
; | ||
return Object.assign({}, input); | ||
}); | ||
Entity.useIncoming = function useIncoming(existingMeta, incomingMeta, existing, incoming) { | ||
return existingMeta.fetchedAt <= incomingMeta.fetchedAt; | ||
} | ||
/** Creates new instance copying over defined values of arguments */ | ||
; | ||
Entity.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
Entity.merge = function merge(existing, incoming) { | ||
return Object.assign({}, existing, incoming); | ||
} | ||
/** Factory method to convert from Plain JS Objects. | ||
* | ||
* @param [props] Plain Object of properties to assign. | ||
* @param [parent] When normalizing, the object which included the record | ||
* @param [key] When normalizing, the key where this record was found | ||
*/ | ||
; | ||
var processedEntity = this.process(input, parent, key); | ||
var id = this.pk(processedEntity, parent, key); | ||
Entity.fromJS = function fromJS( // TODO: this should only accept members that are not functions | ||
props) { | ||
if (props === void 0) { | ||
props = {}; | ||
} | ||
if (id === undefined || id === '') { | ||
if (process.env.NODE_ENV !== 'production') { | ||
var error = new Error("Missing usable primary key when normalizing response.\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n\n Entity: " + this.name + "\n Value (processed): " + (processedEntity && JSON.stringify(processedEntity, null, 2)) + "\n "); | ||
error.status = 400; | ||
throw error; | ||
} else { | ||
// these make the keys get deleted | ||
return undefined; | ||
} | ||
} | ||
// we type guarded abstract case above, so ok to force typescript to allow constructor call | ||
var instance = new this(props); // we can't rely on constructors and override the defaults provided as property assignments | ||
// all occur after the constructor | ||
var entityType = this.key; | ||
Object.assign(instance, props); | ||
return instance; | ||
} | ||
/** Do any transformations when first receiving input */ | ||
; | ||
if (!(entityType in visitedEntities)) { | ||
visitedEntities[entityType] = {}; | ||
} | ||
Entity.process = function (_process) { | ||
function process(_x, _x2, _x3) { | ||
return _process.apply(this, arguments); | ||
} | ||
if (!(id in visitedEntities[entityType])) { | ||
visitedEntities[entityType][id] = []; | ||
} | ||
process.toString = function () { | ||
return _process.toString(); | ||
}; | ||
if (visitedEntities[entityType][id].some(function (entity) { | ||
return entity === input; | ||
})) { | ||
return id; | ||
} | ||
return process; | ||
}(function (input, parent, key) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production' && this.automaticValidation !== 'silent') { | ||
if (Array.isArray(input)) { | ||
var errorMessage = "Attempted to initialize " + this.name + " with an array, but named members were expected\n\nThis is likely due to a malformed response.\nTry inspecting the network response or fetch() return value.\nOr use debugging tools: https://resthooks.io/docs/guides/debugging\nLearn more about schemas: https://resthooks.io/docs/api/schema\nIf this is a mistake, you can disable this check by setting static automaticValidation = 'silent'\n\nFirst three members: " + JSON.stringify(input.slice(0, 3), null, 2); | ||
var errorMessage = this.validate(processedEntity); | ||
if (this.automaticValidation !== 'warn') { | ||
var error = new Error(errorMessage); | ||
error.status = 400; | ||
throw error; | ||
} | ||
if (errorMessage) { | ||
var _error = new Error(errorMessage); | ||
console.warn(errorMessage); | ||
} | ||
} | ||
_error.status = 400; | ||
throw _error; | ||
} | ||
return Object.assign({}, input); | ||
}); | ||
visitedEntities[entityType][id].push(input); | ||
Object.keys(this.schema).forEach(function (key) { | ||
if (Object.prototype.hasOwnProperty.call(processedEntity, key)) { | ||
var schema = _this.schema[key]; | ||
processedEntity[key] = visit(processedEntity[key], processedEntity, key, schema, addEntity, visitedEntities); | ||
} | ||
}); | ||
addEntity(this, processedEntity, id); | ||
return id; | ||
}; | ||
Entity.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
Entity.validate = function validate(processedEntity) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production' && this.automaticValidation !== 'silent') { | ||
var keysOfRecord = new Set(Object.keys(this.defaults)); | ||
var keysOfProps = Object.keys(processedEntity); | ||
var found = [], | ||
missing = [], | ||
unexpected = []; | ||
var processedEntity = this.process(input, parent, key); | ||
var id = this.pk(processedEntity, parent, key); | ||
for (var _i = 0, _keysOfProps = keysOfProps; _i < _keysOfProps.length; _i++) { | ||
var keyOfProps = _keysOfProps[_i]; | ||
if (id === undefined || id === '') { | ||
if (process.env.NODE_ENV !== 'production') { | ||
var error = new Error("Missing usable primary key when normalizing response.\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n\n Entity: " + this.name + "\n Value (processed): " + (processedEntity && JSON.stringify(processedEntity, null, 2)) + "\n "); | ||
error.status = 400; | ||
throw error; | ||
} else { | ||
// these make the keys get deleted | ||
return undefined; | ||
} | ||
} | ||
if (keysOfRecord.has(keyOfProps)) { | ||
found.push(keyOfProps); | ||
} else { | ||
unexpected.push(keyOfProps); | ||
} | ||
} | ||
var entityType = this.key; | ||
for (var _iterator = _createForOfIteratorHelperLoose(keysOfRecord), _step; !(_step = _iterator()).done;) { | ||
var keyOfRecord = _step.value; | ||
if (!(entityType in visitedEntities)) { | ||
visitedEntities[entityType] = {}; | ||
} | ||
if (!found.includes(keyOfRecord)) { | ||
missing.push(keyOfRecord); | ||
} | ||
} // only bother with this if they used *any* defaults | ||
if (!(id in visitedEntities[entityType])) { | ||
visitedEntities[entityType][id] = []; | ||
} | ||
if (visitedEntities[entityType][id].some(function (entity) { | ||
return entity === input; | ||
})) { | ||
return id; | ||
} | ||
if (keysOfRecord.size) { | ||
var tooManyUnexpected = // unexpected compared to members in response | ||
Math.max(keysOfProps.length / 2, 1) <= unexpected.length && // unexpected compared to what we specified | ||
keysOfRecord.size > Math.max(unexpected.length, 2) && // as we find more and more be more easily assured it is correct | ||
Math.pow(found.length, 1.5) / 2 <= unexpected.length; | ||
var foundNothing = found.length < Math.min(1, keysOfRecord.size / 2); // if we find nothing (we expect at least one member for a pk) | ||
// or we find too many unexpected members | ||
var errorMessage = this.validate(processedEntity); | ||
if (tooManyUnexpected || foundNothing) { | ||
var extra = ''; | ||
var reason = 'substantially different than expected keys'; | ||
if (errorMessage) { | ||
var _error = new Error(errorMessage); | ||
if (foundNothing) { | ||
extra += "\n Missing: " + missing; | ||
reason = 'no matching keys found'; | ||
} | ||
_error.status = 400; | ||
throw _error; | ||
} | ||
if (tooManyUnexpected) { | ||
extra += "\n Unexpected keys: " + unexpected; | ||
reason = 'a large number of unexpected keys found'; | ||
} | ||
visitedEntities[entityType][id].push(input); | ||
Object.keys(this.schema).forEach(function (key) { | ||
if (Object.prototype.hasOwnProperty.call(processedEntity, key)) { | ||
var schema = _this.schema[key]; | ||
processedEntity[key] = visit(processedEntity[key], processedEntity, key, schema, addEntity, visitedEntities); | ||
} | ||
}); | ||
addEntity(this, processedEntity, id); | ||
return id; | ||
}; | ||
var errorMessage = "Attempted to initialize " + this.name + " with " + reason + "\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n If this is a mistake, you can disable this check by setting static automaticValidation = 'silent'\n\n Expected keys:\n Found: " + found + extra + "\n Value (processed): " + JSON.stringify(processedEntity, null, 2); | ||
Entity.validate = function validate(processedEntity) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production' && this.automaticValidation !== 'silent') { | ||
var keysOfRecord = new Set(Object.keys(this.defaults)); | ||
var keysOfProps = Object.keys(processedEntity); | ||
var found = [], | ||
missing = [], | ||
unexpected = []; | ||
if (found.length >= 4 && tooManyUnexpected || this.automaticValidation === 'warn') { | ||
console.warn(errorMessage); | ||
} else { | ||
return errorMessage; | ||
} | ||
} | ||
} | ||
} | ||
for (var _i = 0, _keysOfProps = keysOfProps; _i < _keysOfProps.length; _i++) { | ||
var keyOfProps = _keysOfProps[_i]; | ||
if (process.env.NODE_ENV !== 'production') { | ||
for (var _i2 = 0, _Object$keys = Object.keys(this.schema); _i2 < _Object$keys.length; _i2++) { | ||
var key = _Object$keys[_i2]; | ||
if (keysOfRecord.has(keyOfProps)) { | ||
found.push(keyOfProps); | ||
} else { | ||
unexpected.push(keyOfProps); | ||
} | ||
} | ||
if (!Object.prototype.hasOwnProperty.call(processedEntity, key)) { | ||
if (!Object.prototype.hasOwnProperty.call(this.defaults, key)) { | ||
return "Schema key is missing in Entity\n\n Be sure all schema members are also part of the entity\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about nesting schemas: https://resthooks.io/docs/guides/nested-response\n\n Entity keys: " + Object.keys(this.defaults) + "\n Schema key(missing): " + key + "\n "; | ||
} | ||
} | ||
} | ||
} | ||
}; | ||
for (var _iterator = _createForOfIteratorHelperLoose(keysOfRecord), _step; !(_step = _iterator()).done;) { | ||
var keyOfRecord = _step.value; | ||
Entity.infer = function infer(args, indexes, recurse) { | ||
if (!args[0]) return undefined; | ||
var id = this.pk(args[0], undefined, ''); // Was able to infer the entity's primary key from params | ||
if (!found.includes(keyOfRecord)) { | ||
missing.push(keyOfRecord); | ||
} | ||
} // only bother with this if they used *any* defaults | ||
if (id !== undefined && id !== '') return id; // now attempt lookup in indexes | ||
var indexName = indexFromParams(args[0], this.indexes); | ||
if (keysOfRecord.size) { | ||
var tooManyUnexpected = // unexpected compared to members in response | ||
Math.max(keysOfProps.length / 2, 1) <= unexpected.length && // unexpected compared to what we specified | ||
keysOfRecord.size > Math.max(unexpected.length, 2) && // as we find more and more be more easily assured it is correct | ||
Math.pow(found.length, 1.5) / 2 <= unexpected.length; | ||
var foundNothing = found.length < Math.min(1, keysOfRecord.size / 2); // if we find nothing (we expect at least one member for a pk) | ||
// or we find too many unexpected members | ||
if (indexName && indexes[this.key]) { | ||
// 'as Record<string, any>': indexName can only be found if params is a string key'd object | ||
var _id = indexes[this.key][indexName][args[0][indexName]]; | ||
return _id; | ||
} | ||
if (tooManyUnexpected || foundNothing) { | ||
var extra = ''; | ||
var reason = 'substantially different than expected keys'; | ||
return undefined; | ||
}; | ||
if (foundNothing) { | ||
extra += "\n Missing: " + missing; | ||
reason = 'no matching keys found'; | ||
} | ||
Entity.expiresAt = function expiresAt(meta, input) { | ||
return meta.expiresAt; | ||
}; | ||
if (tooManyUnexpected) { | ||
extra += "\n Unexpected keys: " + unexpected; | ||
reason = 'a large number of unexpected keys found'; | ||
} | ||
Entity.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
var errorMessage = "Attempted to initialize " + this.name + " with " + reason + "\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n If this is a mistake, you can disable this check by setting static automaticValidation = 'silent'\n\n Expected keys:\n Found: " + found + extra + "\n Value (processed): " + JSON.stringify(processedEntity, null, 2); | ||
if (isImmutable(input)) { | ||
if (this.validate(input.toJS())) return [undefined, false, true]; // Need to set this first so that if it is referenced further within the | ||
// denormalization the reference will already exist. | ||
if (found.length >= 4 && tooManyUnexpected || this.automaticValidation === 'warn') { | ||
console.warn(errorMessage); | ||
} else { | ||
return errorMessage; | ||
} | ||
} | ||
} | ||
} | ||
unvisit.setLocal == null ? void 0 : unvisit.setLocal(input); | ||
if (process.env.NODE_ENV !== 'production') { | ||
for (var _i2 = 0, _Object$keys = Object.keys(this.schema); _i2 < _Object$keys.length; _i2++) { | ||
var key = _Object$keys[_i2]; | ||
var _denormalizeImmutable = denormalizeImmutable(this.schema, input, unvisit), | ||
denormEntity = _denormalizeImmutable[0], | ||
found = _denormalizeImmutable[1], | ||
_deleted = _denormalizeImmutable[2]; | ||
if (!Object.prototype.hasOwnProperty.call(processedEntity, key)) { | ||
if (!Object.prototype.hasOwnProperty.call(this.defaults, key)) { | ||
return "Schema key is missing in Entity\n\n Be sure all schema members are also part of the entity\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about nesting schemas: https://resthooks.io/docs/guides/nested-response\n\n Entity keys: " + Object.keys(this.defaults) + "\n Schema key(missing): " + key + "\n "; | ||
} | ||
} | ||
} | ||
} | ||
}; | ||
return [this.fromJS(denormEntity.toObject()), found, _deleted]; | ||
} | ||
Entity.infer = function infer(args, indexes, recurse) { | ||
if (!args[0]) return undefined; | ||
var id = this.pk(args[0], undefined, ''); // Was able to infer the entity's primary key from params | ||
if (this.validate(input)) { | ||
return [undefined, false, true]; | ||
} | ||
if (id !== undefined && id !== '') return id; // now attempt lookup in indexes | ||
var entityCopy = this.fromJS(input); // Need to set this first so that if it is referenced further within the | ||
// denormalization the reference will already exist. | ||
var indexName = indexFromParams(args[0], this.indexes); | ||
unvisit.setLocal == null ? void 0 : unvisit.setLocal(entityCopy); | ||
var deleted = false; // note: iteration order must be stable | ||
if (indexName && indexes[this.key]) { | ||
// 'as Record<string, any>': indexName can only be found if params is a string key'd object | ||
var _id = indexes[this.key][indexName][args[0][indexName]]; | ||
return _id; | ||
} | ||
Object.keys(this.schema).forEach(function (key) { | ||
var schema = _this2.schema[key]; | ||
var nextInput = Object.prototype.hasOwnProperty.call(input, key) ? input[key] : undefined; | ||
return undefined; | ||
}; | ||
var _unvisit = unvisit(nextInput, schema), | ||
value = _unvisit[0], | ||
deletedItem = _unvisit[2]; | ||
Entity.expiresAt = function expiresAt(meta, input) { | ||
return meta.expiresAt; | ||
}; | ||
if (deletedItem && !(Object.prototype.hasOwnProperty.call(input, key) && !_this2.defaults[key])) { | ||
deleted = true; | ||
} | ||
Entity.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
if (Object.prototype.hasOwnProperty.call(input, key) && input[key] !== value) { | ||
_this2.set(entityCopy, key, value); | ||
} | ||
}); | ||
return [entityCopy, true, deleted]; | ||
} | ||
/** All instance defaults set */ | ||
; | ||
if (isImmutable(input)) { | ||
if (this.validate(input.toJS())) return [undefined, false, true]; // Need to set this first so that if it is referenced further within the | ||
// denormalization the reference will already exist. | ||
/** Used by denormalize to set nested members */ | ||
Entity.set = function set(entity, key, value) { | ||
entity[key] = value; | ||
}; | ||
unvisit.setLocal == null ? void 0 : unvisit.setLocal(input); | ||
_createClass(Entity, null, [{ | ||
key: "key", | ||
get: function get() { | ||
/* istanbul ignore next */ | ||
if (process.env.NODE_ENV !== 'production' && (this.name === '' || this.name === 'Entity' || this.name === '_temp')) throw new Error('Entity classes without a name must define `static get key()`'); | ||
return this.name; | ||
} | ||
}, { | ||
key: "defaults", | ||
get: function get() { | ||
if (!Object.prototype.hasOwnProperty.call(this, '__defaults')) this.__defaults = new this(); | ||
return this.__defaults; | ||
} | ||
}]); | ||
var _denormalizeImmutable = denormalizeImmutable(this.schema, input, unvisit), | ||
denormEntity = _denormalizeImmutable[0], | ||
found = _denormalizeImmutable[1], | ||
_deleted = _denormalizeImmutable[2]; | ||
return Entity; | ||
}(); | ||
Entity.schema = {}; | ||
return [this.fromJS(denormEntity.toObject()), found, _deleted]; | ||
} | ||
if (process.env.NODE_ENV !== 'production') { | ||
var superFrom = Entity.fromJS; // for those not using TypeScript this is a good catch to ensure they are defining | ||
// the abstract members | ||
if (this.validate(input)) { | ||
return [undefined, false, true]; | ||
} | ||
Entity.fromJS = function fromJS(props) { | ||
if (this.prototype.pk === undefined) throw new Error('cannot construct on abstract types'); | ||
return superFrom.call(this, props); | ||
}; | ||
} | ||
var entityCopy = this.fromJS(input); // Need to set this first so that if it is referenced further within the | ||
// denormalization the reference will already exist. | ||
function isEntity(schema) { | ||
return schema !== null && schema.pk !== undefined; | ||
} | ||
unvisit.setLocal == null ? void 0 : unvisit.setLocal(entityCopy); | ||
var deleted = false; // note: iteration order must be stable | ||
function indexFromParams(params, indexes) { | ||
if (!indexes) return undefined; | ||
return indexes.find(function (index) { | ||
return Object.prototype.hasOwnProperty.call(params, index); | ||
}); | ||
} | ||
Object.keys(this.schema).forEach(function (key) { | ||
var schema = _this2.schema[key]; | ||
var nextInput = Object.prototype.hasOwnProperty.call(input, key) ? input[key] : undefined; | ||
var DELETED = Symbol('ENTITY WAS DELETED'); | ||
var _unvisit = unvisit(nextInput, schema), | ||
value = _unvisit[0], | ||
deletedItem = _unvisit[2]; | ||
function _setPrototypeOf(o, p) { | ||
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}; | ||
if (deletedItem && !(Object.prototype.hasOwnProperty.call(input, key) && !_this2.defaults[key])) { | ||
deleted = true; | ||
} | ||
return _setPrototypeOf(o, p); | ||
} | ||
if (Object.prototype.hasOwnProperty.call(input, key) && input[key] !== value) { | ||
_this2.set(entityCopy, key, value); | ||
} | ||
}); | ||
return [entityCopy, true, deleted]; | ||
} | ||
/** All instance defaults set */ | ||
; | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
_setPrototypeOf(subClass, superClass); | ||
} | ||
/** Used by denormalize to set nested members */ | ||
Entity.set = function set(entity, key, value) { | ||
entity[key] = value; | ||
}; | ||
function _getPrototypeOf(o) { | ||
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { | ||
return o.__proto__ || Object.getPrototypeOf(o); | ||
}; | ||
return _getPrototypeOf(o); | ||
} | ||
_createClass(Entity, null, [{ | ||
key: "key", | ||
get: function get() { | ||
/* istanbul ignore next */ | ||
if (process.env.NODE_ENV !== 'production' && (this.name === '' || this.name === 'Entity' || this.name === '_temp')) throw new Error('Entity classes without a name must define `static get key()`'); | ||
return this.name; | ||
} | ||
}, { | ||
key: "defaults", | ||
get: function get() { | ||
if (!Object.prototype.hasOwnProperty.call(this, '__defaults')) this.__defaults = new this(); | ||
return this.__defaults; | ||
} | ||
}]); | ||
function _isNativeFunction(fn) { | ||
return Function.toString.call(fn).indexOf("[native code]") !== -1; | ||
} | ||
return Entity; | ||
}(); | ||
Entity.schema = {}; | ||
function _isNativeReflectConstruct() { | ||
if (typeof Reflect === "undefined" || !Reflect.construct) return false; | ||
if (Reflect.construct.sham) return false; | ||
if (typeof Proxy === "function") return true; | ||
if (process.env.NODE_ENV !== 'production') { | ||
var superFrom = Entity.fromJS; // for those not using TypeScript this is a good catch to ensure they are defining | ||
// the abstract members | ||
try { | ||
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
} | ||
Entity.fromJS = function fromJS(props) { | ||
if (this.prototype.pk === undefined) throw new Error('cannot construct on abstract types'); | ||
return superFrom.call(this, props); | ||
}; | ||
} | ||
function _construct(Parent, args, Class) { | ||
if (_isNativeReflectConstruct()) { | ||
_construct = Reflect.construct; | ||
} else { | ||
_construct = function _construct(Parent, args, Class) { | ||
var a = [null]; | ||
a.push.apply(a, args); | ||
var Constructor = Function.bind.apply(Parent, a); | ||
var instance = new Constructor(); | ||
if (Class) _setPrototypeOf(instance, Class.prototype); | ||
return instance; | ||
}; | ||
} | ||
function isEntity(schema) { | ||
return schema !== null && schema.pk !== undefined; | ||
} | ||
return _construct.apply(null, arguments); | ||
} | ||
function indexFromParams(params, indexes) { | ||
if (!indexes) return undefined; | ||
return indexes.find(function (index) { | ||
return Object.prototype.hasOwnProperty.call(params, index); | ||
}); | ||
} | ||
function _wrapNativeSuper(Class) { | ||
var _cache = typeof Map === "function" ? new Map() : undefined; | ||
var DELETED = Symbol('ENTITY WAS DELETED'); | ||
_wrapNativeSuper = function _wrapNativeSuper(Class) { | ||
if (Class === null || !_isNativeFunction(Class)) return Class; | ||
var setPrototypeOf = createCommonjsModule(function (module) { | ||
function _setPrototypeOf(o, p) { | ||
module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
return _setPrototypeOf(o, p); | ||
} | ||
if (typeof Class !== "function") { | ||
throw new TypeError("Super expression must either be null or a function"); | ||
} | ||
module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
if (typeof _cache !== "undefined") { | ||
if (_cache.has(Class)) return _cache.get(Class); | ||
unwrapExports(setPrototypeOf); | ||
_cache.set(Class, Wrapper); | ||
} | ||
var inheritsLoose = createCommonjsModule(function (module) { | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
setPrototypeOf(subClass, superClass); | ||
} | ||
function Wrapper() { | ||
return _construct(Class, arguments, _getPrototypeOf(this).constructor); | ||
} | ||
module.exports = _inheritsLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
Wrapper.prototype = Object.create(Class.prototype, { | ||
constructor: { | ||
value: Wrapper, | ||
enumerable: false, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
return _setPrototypeOf(Wrapper, Class); | ||
}; | ||
var _inheritsLoose = unwrapExports(inheritsLoose); | ||
return _wrapNativeSuper(Class); | ||
} | ||
var getPrototypeOf = createCommonjsModule(function (module) { | ||
function _getPrototypeOf(o) { | ||
module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { | ||
return o.__proto__ || Object.getPrototypeOf(o); | ||
}, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
return _getPrototypeOf(o); | ||
} | ||
/** Link in a chain */ | ||
var Link = function Link() { | ||
this.children = new WeakMap(); | ||
}; | ||
module.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
var KeySize = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(KeySize, _Error); | ||
unwrapExports(getPrototypeOf); | ||
function KeySize() { | ||
var _this; | ||
var isNativeFunction = createCommonjsModule(function (module) { | ||
function _isNativeFunction(fn) { | ||
return Function.toString.call(fn).indexOf("[native code]") !== -1; | ||
} | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
module.exports = _isNativeFunction, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
_this = _Error.call.apply(_Error, [this].concat(args)) || this; | ||
_this.message = 'Keys must include at least one member'; | ||
return _this; | ||
} | ||
unwrapExports(isNativeFunction); | ||
return KeySize; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
/** Maps from a list of objects (referentially) to any value | ||
* | ||
* If *any* members of the list get claned up, so does that key/value pair get removed. | ||
*/ | ||
var isNativeReflectConstruct = createCommonjsModule(function (module) { | ||
function _isNativeReflectConstruct() { | ||
if (typeof Reflect === "undefined" || !Reflect.construct) return false; | ||
if (Reflect.construct.sham) return false; | ||
if (typeof Proxy === "function") return true; | ||
try { | ||
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
} | ||
var WeakListMap = /*#__PURE__*/function () { | ||
function WeakListMap() { | ||
this.first = new WeakMap(); | ||
} | ||
module.exports = _isNativeReflectConstruct, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
var _proto = WeakListMap.prototype; | ||
unwrapExports(isNativeReflectConstruct); | ||
_proto.delete = function _delete(key) { | ||
var link = this.traverse(key); | ||
link == null ? true : delete link.value; | ||
return !!link; | ||
}; | ||
var construct = createCommonjsModule(function (module) { | ||
function _construct(Parent, args, Class) { | ||
if (isNativeReflectConstruct()) { | ||
module.exports = _construct = Reflect.construct, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
} else { | ||
module.exports = _construct = function _construct(Parent, args, Class) { | ||
var a = [null]; | ||
a.push.apply(a, args); | ||
var Constructor = Function.bind.apply(Parent, a); | ||
var instance = new Constructor(); | ||
if (Class) setPrototypeOf(instance, Class.prototype); | ||
return instance; | ||
}, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
} | ||
_proto.get = function get(key) { | ||
var link = this.traverse(key); | ||
return link == null ? void 0 : link.value; | ||
}; | ||
return _construct.apply(null, arguments); | ||
} | ||
_proto.has = function has(key) { | ||
var link = this.traverse(key); | ||
if (!link) return false; | ||
return Object.prototype.hasOwnProperty.call(link, 'value'); | ||
}; | ||
module.exports = _construct, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
_proto.set = function set(key, value) { | ||
if (key.length < 1) throw new KeySize(); | ||
var cur = this.first; | ||
var link; | ||
unwrapExports(construct); | ||
for (var i = 0; i < key.length; i++) { | ||
if (!cur.has(key[i])) { | ||
link = new Link(); | ||
cur.set(key[i], link); | ||
} else { | ||
link = cur.get(key[i]); | ||
} | ||
var wrapNativeSuper = createCommonjsModule(function (module) { | ||
function _wrapNativeSuper(Class) { | ||
var _cache = typeof Map === "function" ? new Map() : undefined; | ||
cur = link.children; // do on later iteration of loop. this makes typescript happy rather than putting after loop | ||
module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) { | ||
if (Class === null || !isNativeFunction(Class)) return Class; | ||
if (i === key.length - 1) { | ||
link.value = value; | ||
} | ||
} | ||
if (typeof Class !== "function") { | ||
throw new TypeError("Super expression must either be null or a function"); | ||
} | ||
return this; | ||
}; | ||
if (typeof _cache !== "undefined") { | ||
if (_cache.has(Class)) return _cache.get(Class); | ||
_proto.traverse = function traverse(key) { | ||
var cur = this.first; | ||
var link; | ||
_cache.set(Class, Wrapper); | ||
} | ||
for (var i = 0; i < key.length; i++) { | ||
link = cur.get(key[i]); | ||
if (!link) return; | ||
cur = link.children; | ||
} | ||
function Wrapper() { | ||
return construct(Class, arguments, getPrototypeOf(this).constructor); | ||
} | ||
return link; | ||
}; | ||
Wrapper.prototype = Object.create(Class.prototype, { | ||
constructor: { | ||
value: Wrapper, | ||
enumerable: false, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
return setPrototypeOf(Wrapper, Class); | ||
}, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
return _wrapNativeSuper(Class); | ||
} | ||
return WeakListMap; | ||
}(); | ||
module.exports = _wrapNativeSuper, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
var PolymorphicSchema = /*#__PURE__*/function () { | ||
function PolymorphicSchema(definition, schemaAttribute) { | ||
this.schema = void 0; | ||
var _wrapNativeSuper = unwrapExports(wrapNativeSuper); | ||
if (schemaAttribute) { | ||
this._schemaAttribute = typeof schemaAttribute === 'string' ? function (input) { | ||
return input[schemaAttribute]; | ||
} : schemaAttribute; | ||
} | ||
/** Link in a chain */ | ||
var Link = function Link() { | ||
this.children = new WeakMap(); | ||
}; | ||
this.define(definition); | ||
} | ||
var KeySize = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(KeySize, _Error); | ||
var _proto = PolymorphicSchema.prototype; | ||
function KeySize() { | ||
var _this; | ||
_proto.define = function define(definition) { | ||
this.schema = definition; | ||
}; | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
_proto.getSchemaAttribute = function getSchemaAttribute(input, parent, key) { | ||
return !this.isSingleSchema && this._schemaAttribute(input, parent, key); | ||
}; | ||
_this = _Error.call.apply(_Error, [this].concat(args)) || this; | ||
_this.message = 'Keys must include at least one member'; | ||
return _this; | ||
} | ||
_proto.inferSchema = function inferSchema(input, parent, key) { | ||
if (this.isSingleSchema) { | ||
return this.schema; | ||
} | ||
return KeySize; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
/** Maps from a list of objects (referentially) to any value | ||
* | ||
* If *any* members of the list get claned up, so does that key/value pair get removed. | ||
*/ | ||
var attr = this.getSchemaAttribute(input, parent, key); | ||
return this.schema[attr]; | ||
}; | ||
_proto.normalizeValue = function normalizeValue(value, parent, key, visit, addEntity, visitedEntities) { | ||
var schema = this.inferSchema(value, parent, key); | ||
var WeakListMap = /*#__PURE__*/function () { | ||
function WeakListMap() { | ||
this.first = new WeakMap(); | ||
} | ||
if (!schema) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production') { | ||
var attr = this.getSchemaAttribute(value, parent, key); | ||
console.warn("Schema attribute " + JSON.stringify(attr, undefined, 2) + " is not expected.\nExpected one of: " + Object.keys(this.schema).map(function (k) { | ||
return "\"" + k + "\""; | ||
}).join(', ') + "\n\nValue: " + JSON.stringify(value, undefined, 2)); | ||
} | ||
var _proto = WeakListMap.prototype; | ||
return value; | ||
} | ||
_proto.delete = function _delete(key) { | ||
var link = this.traverse(key); | ||
link == null ? true : delete link.value; | ||
return !!link; | ||
}; | ||
var normalizedValue = visit(value, parent, key, schema, addEntity, visitedEntities); | ||
return this.isSingleSchema || normalizedValue === undefined || normalizedValue === null ? normalizedValue : { | ||
id: normalizedValue, | ||
schema: this.getSchemaAttribute(value, parent, key) | ||
}; | ||
} // value is guaranteed by caller to not be null | ||
; | ||
_proto.get = function get(key) { | ||
var link = this.traverse(key); | ||
return link == null ? void 0 : link.value; | ||
}; | ||
_proto.denormalizeValue = function denormalizeValue(value, unvisit) { | ||
var schemaKey = isImmutable(value) ? value.get('schema') : value.schema; | ||
_proto.has = function has(key) { | ||
var link = this.traverse(key); | ||
if (!link) return false; | ||
return Object.prototype.hasOwnProperty.call(link, 'value'); | ||
}; | ||
if (!this.isSingleSchema && !schemaKey) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production') { | ||
console.warn("TypeError: Unable to infer schema for " + this.constructor.name + "\nValue: " + JSON.stringify(value, undefined, 2) + "."); | ||
} | ||
_proto.set = function set(key, value) { | ||
if (key.length < 1) throw new KeySize(); | ||
var cur = this.first; | ||
var link; | ||
return [value, true, false]; | ||
} | ||
for (var i = 0; i < key.length; i++) { | ||
if (!cur.has(key[i])) { | ||
link = new Link(); | ||
cur.set(key[i], link); | ||
} else { | ||
link = cur.get(key[i]); | ||
} | ||
var id = this.isSingleSchema ? undefined : isImmutable(value) ? value.get('id') : value.id; | ||
var schema = this.isSingleSchema ? this.schema : this.schema[schemaKey]; | ||
return unvisit(id || value, schema); | ||
}; | ||
cur = link.children; // do on later iteration of loop. this makes typescript happy rather than putting after loop | ||
_createClass(PolymorphicSchema, [{ | ||
key: "isSingleSchema", | ||
get: function get() { | ||
return !this._schemaAttribute; | ||
} | ||
}]); | ||
if (i === key.length - 1) { | ||
link.value = value; | ||
} | ||
} | ||
return PolymorphicSchema; | ||
}(); | ||
return this; | ||
}; | ||
var validateSchema = function validateSchema(definition) { | ||
var isArray = Array.isArray(definition); | ||
_proto.traverse = function traverse(key) { | ||
var cur = this.first; | ||
var link; | ||
if (isArray && definition.length > 1) { | ||
throw new Error("Expected schema definition to be a single schema, but found " + definition.length + "."); | ||
} | ||
for (var i = 0; i < key.length; i++) { | ||
link = cur.get(key[i]); | ||
if (!link) return; | ||
cur = link.children; | ||
} | ||
return definition[0]; | ||
}; | ||
return link; | ||
}; | ||
var getValues = function getValues(input) { | ||
return Array.isArray(input) ? input : Object.keys(input).map(function (key) { | ||
return input[key]; | ||
}); | ||
}; | ||
return WeakListMap; | ||
}(); | ||
var filterEmpty = function filterEmpty(_ref) { | ||
var item = _ref[0], | ||
deletedItem = _ref[2]; | ||
return item !== undefined && !deletedItem; | ||
}; | ||
var PolymorphicSchema = /*#__PURE__*/function () { | ||
function PolymorphicSchema(definition, schemaAttribute) { | ||
this.schema = void 0; | ||
var normalize$1 = function normalize(schema, input, parent, key, visit, addEntity, visitedEntities) { | ||
schema = validateSchema(schema); | ||
var values = getValues(input); // Special case: Arrays pass *their* parent on to their children, since there | ||
// is not any special information that can be gathered from themselves directly | ||
if (schemaAttribute) { | ||
this._schemaAttribute = typeof schemaAttribute === 'string' ? function (input) { | ||
return input[schemaAttribute]; | ||
} : schemaAttribute; | ||
} | ||
return values.map(function (value, index) { | ||
return visit(value, parent, key, schema, addEntity, visitedEntities); | ||
}); | ||
}; | ||
var denormalize$1 = function denormalize(schema, input, unvisit) { | ||
schema = validateSchema(schema); | ||
return [input.map ? input.map(function (entityOrId) { | ||
return unvisit(entityOrId, schema); | ||
}).filter(filterEmpty).map(function (_ref2) { | ||
var value = _ref2[0]; | ||
return value; | ||
}) : input, true, false]; | ||
}; | ||
this.define(definition); | ||
} | ||
function _infer$1(schema, args, indexes, recurse) { | ||
return undefined; | ||
} | ||
var _proto = PolymorphicSchema.prototype; | ||
var ArraySchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ArraySchema, _PolymorphicSchema); | ||
_proto.define = function define(definition) { | ||
this.schema = definition; | ||
}; | ||
function ArraySchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
} | ||
_proto.getSchemaAttribute = function getSchemaAttribute(input, parent, key) { | ||
return !this.isSingleSchema && this._schemaAttribute(input, parent, key); | ||
}; | ||
var _proto = ArraySchema.prototype; | ||
_proto.inferSchema = function inferSchema(input, parent, key) { | ||
if (this.isSingleSchema) { | ||
return this.schema; | ||
} | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
var attr = this.getSchemaAttribute(input, parent, key); | ||
return this.schema[attr]; | ||
}; | ||
var values = getValues(input); | ||
return values.map(function (value, index) { | ||
return _this.normalizeValue(value, parent, key, visit, addEntity, visitedEntities); | ||
}).filter(function (value) { | ||
return value !== undefined && value !== null; | ||
}); | ||
}; | ||
_proto.normalizeValue = function normalizeValue(value, parent, key, visit, addEntity, visitedEntities) { | ||
var schema = this.inferSchema(value, parent, key); | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
if (!schema) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production') { | ||
var attr = this.getSchemaAttribute(value, parent, key); | ||
console.warn("Schema attribute " + JSON.stringify(attr, undefined, 2) + " is not expected.\nExpected one of: " + Object.keys(this.schema).map(function (k) { | ||
return "\"" + k + "\""; | ||
}).join(', ') + "\n\nValue: " + JSON.stringify(value, undefined, 2)); | ||
} | ||
return [input.map ? input.map(function (entityOrId) { | ||
return _this2.denormalizeValue(entityOrId, unvisit); | ||
}).filter(filterEmpty).map(function (_ref3) { | ||
var value = _ref3[0]; | ||
return value; | ||
}) : input, true, false]; | ||
}; | ||
return value; | ||
} | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return _infer$1(this.schema); | ||
}; | ||
var normalizedValue = visit(value, parent, key, schema, addEntity, visitedEntities); | ||
return this.isSingleSchema || normalizedValue === undefined || normalizedValue === null ? normalizedValue : { | ||
id: normalizedValue, | ||
schema: this.getSchemaAttribute(value, parent, key) | ||
}; | ||
} // value is guaranteed by caller to not be null | ||
; | ||
return ArraySchema; | ||
}(PolymorphicSchema); | ||
_proto.denormalizeValue = function denormalizeValue(value, unvisit) { | ||
var schemaKey = isImmutable(value) ? value.get('schema') : value.schema; | ||
var _normalize = function normalize(schema, input, parent, key, visit, addEntity, visitedEntities) { | ||
var object = Object.assign({}, input); | ||
Object.keys(schema).forEach(function (key) { | ||
var localSchema = schema[key]; | ||
var value = visit(input[key], input, key, localSchema, addEntity, visitedEntities); | ||
if (!this.isSingleSchema && !schemaKey) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production') { | ||
console.warn("TypeError: Unable to infer schema for " + this.constructor.name + "\nValue: " + JSON.stringify(value, undefined, 2) + "."); | ||
} | ||
if (value === undefined || value === null) { | ||
delete object[key]; | ||
} else { | ||
object[key] = value; | ||
} | ||
}); | ||
return object; | ||
}; | ||
return [value, true, false]; | ||
} | ||
var _denormalize = function denormalize(schema, input, unvisit) { | ||
if (isImmutable(input)) { | ||
return denormalizeImmutable(schema, input, unvisit); | ||
} | ||
var id = this.isSingleSchema ? undefined : isImmutable(value) ? value.get('id') : value.id; | ||
var schema = this.isSingleSchema ? this.schema : this.schema[schemaKey]; | ||
return unvisit(id || value, schema); | ||
}; | ||
var object = Object.assign({}, input); | ||
var found = true; | ||
var deleted = false; | ||
Object.keys(schema).forEach(function (key) { | ||
var _unvisit = unvisit(object[key], schema[key]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1], | ||
deletedItem = _unvisit[2]; | ||
_createClass(PolymorphicSchema, [{ | ||
key: "isSingleSchema", | ||
get: function get() { | ||
return !this._schemaAttribute; | ||
} | ||
}]); | ||
if (object[key] !== undefined) { | ||
object[key] = item; | ||
} | ||
return PolymorphicSchema; | ||
}(); | ||
if (deletedItem) { | ||
deleted = true; | ||
} | ||
var validateSchema = function validateSchema(definition) { | ||
var isArray = Array.isArray(definition); | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
}); | ||
return [object, found, deleted]; | ||
}; | ||
if (isArray && definition.length > 1) { | ||
throw new Error("Expected schema definition to be a single schema, but found " + definition.length + "."); | ||
} | ||
function _infer(schema, args, indexes, recurse) { | ||
var resultObject = {}; | ||
return definition[0]; | ||
}; | ||
for (var _i = 0, _Object$keys = Object.keys(schema); _i < _Object$keys.length; _i++) { | ||
var k = _Object$keys[_i]; | ||
resultObject[k] = recurse(schema[k], args, indexes); | ||
} | ||
var getValues = function getValues(input) { | ||
return Array.isArray(input) ? input : Object.keys(input).map(function (key) { | ||
return input[key]; | ||
}); | ||
}; | ||
return resultObject; | ||
} | ||
var filterEmpty = function filterEmpty(_ref) { | ||
var item = _ref[0], | ||
deletedItem = _ref[2]; | ||
return item !== undefined && !deletedItem; | ||
}; | ||
var ObjectSchema = /*#__PURE__*/function () { | ||
function ObjectSchema(definition) { | ||
this.schema = void 0; | ||
this.define(definition); | ||
} | ||
var normalize$1 = function normalize(schema, input, parent, key, visit, addEntity, visitedEntities) { | ||
schema = validateSchema(schema); | ||
var values = getValues(input); // Special case: Arrays pass *their* parent on to their children, since there | ||
// is not any special information that can be gathered from themselves directly | ||
var _proto = ObjectSchema.prototype; | ||
return values.map(function (value, index) { | ||
return visit(value, parent, key, schema, addEntity, visitedEntities); | ||
}); | ||
}; | ||
var denormalize$1 = function denormalize(schema, input, unvisit) { | ||
schema = validateSchema(schema); | ||
return [input.map ? input.map(function (entityOrId) { | ||
return unvisit(entityOrId, schema); | ||
}).filter(filterEmpty).map(function (_ref2) { | ||
var value = _ref2[0]; | ||
return value; | ||
}) : input, true, false]; | ||
}; | ||
_proto.define = function define(definition) { | ||
this.schema = Object.keys(definition).reduce(function (entitySchema, key) { | ||
var _Object$assign; | ||
function _infer$1(schema, args, indexes, recurse) { | ||
return undefined; | ||
} | ||
var schema = definition[key]; | ||
return Object.assign({}, entitySchema, (_Object$assign = {}, _Object$assign[key] = schema, _Object$assign)); | ||
}, this.schema || {}); | ||
}; | ||
var ArraySchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ArraySchema, _PolymorphicSchema); | ||
_proto.normalize = function normalize() { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
function ArraySchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
} | ||
return _normalize.apply(void 0, [this.schema].concat(args)); | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
; | ||
var _proto = ArraySchema.prototype; | ||
_proto.denormalize = function denormalize() { | ||
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
args[_key2] = arguments[_key2]; | ||
} | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
return _denormalize.apply(void 0, [this.schema].concat(args)); | ||
}; | ||
var values = getValues(input); | ||
return values.map(function (value, index) { | ||
return _this.normalizeValue(value, parent, key, visit, addEntity, visitedEntities); | ||
}).filter(function (value) { | ||
return value !== undefined && value !== null; | ||
}); | ||
}; | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return _infer(this.schema, args, indexes, recurse); | ||
}; | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
return ObjectSchema; | ||
}(); | ||
return [input.map ? input.map(function (entityOrId) { | ||
return _this2.denormalizeValue(entityOrId, unvisit); | ||
}).filter(filterEmpty).map(function (_ref3) { | ||
var value = _ref3[0]; | ||
return value; | ||
}) : input, true, false]; | ||
}; | ||
var DRAFT = Symbol('draft'); | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return _infer$1(this.schema, args, indexes, recurse); | ||
}; | ||
var unvisitEntity = function unvisitEntity(entityOrId, schema, unvisit, getEntity, localCache, entityCache, dependencies, cycleIndex) { | ||
var entity = getEntity(entityOrId, schema); | ||
return ArraySchema; | ||
}(PolymorphicSchema); | ||
if (entity === DELETED) { | ||
return [undefined, true, true]; | ||
} | ||
var _normalize = function normalize(schema, input, parent, key, visit, addEntity, visitedEntities) { | ||
var object = Object.assign({}, input); | ||
Object.keys(schema).forEach(function (key) { | ||
var localSchema = schema[key]; | ||
var value = visit(input[key], input, key, localSchema, addEntity, visitedEntities); | ||
if (process.env.NODE_ENV !== 'production' && typeof entity === 'symbol' && entity.toString().includes('DELETED')) { | ||
throw new Error("Unrecognized symbol detected.\nMake sure you do not have multiple versions of @rest-hooks/normalizr installed."); | ||
} | ||
if (value === undefined || value === null) { | ||
delete object[key]; | ||
} else { | ||
object[key] = value; | ||
} | ||
}); | ||
return object; | ||
}; | ||
if (typeof entity !== 'object' || entity === null) { | ||
return [entity, false, false]; | ||
} | ||
var _denormalize = function denormalize(schema, input, unvisit) { | ||
if (isImmutable(input)) { | ||
return denormalizeImmutable(schema, input, unvisit); | ||
} | ||
var pk = typeof entityOrId === 'string' ? entityOrId : schema.pk(isImmutable(entity) ? entity.toJS() : entity); | ||
var object = Object.assign({}, input); | ||
var found = true; | ||
var deleted = false; | ||
Object.keys(schema).forEach(function (key) { | ||
var _unvisit = unvisit(object[key], schema[key]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1], | ||
deletedItem = _unvisit[2]; | ||
if (pk === undefined || pk === '') { | ||
return [entity, false, false]; | ||
} | ||
if (object[key] !== undefined) { | ||
object[key] = item; | ||
} | ||
if (localCache[schema.key] === undefined) { | ||
localCache[schema.key] = Object.create(null); | ||
} | ||
if (deletedItem) { | ||
deleted = true; | ||
} | ||
var found = true; | ||
var deleted = false; | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
}); | ||
return [object, found, deleted]; | ||
}; | ||
if (!localCache[schema.key][pk]) { | ||
var trackingIndex = dependencies.length; | ||
dependencies.push(entity); | ||
var wrappedUnvisit = withTrackedEntities(unvisit); // { [DRAFT] } means we are still processing - which if found indicates a cycle | ||
function _infer(schema, args, indexes, recurse) { | ||
var resultObject = {}; | ||
wrappedUnvisit.setLocal = function (entityCopy) { | ||
var _localCache$schema$ke; | ||
for (var _i = 0, _Object$keys = Object.keys(schema); _i < _Object$keys.length; _i++) { | ||
var k = _Object$keys[_i]; | ||
resultObject[k] = recurse(schema[k], args, indexes); | ||
} | ||
return localCache[schema.key][pk] = (_localCache$schema$ke = {}, _localCache$schema$ke[DRAFT] = entityCopy, _localCache$schema$ke.i = trackingIndex, _localCache$schema$ke); | ||
}; | ||
return resultObject; | ||
} | ||
var globalCacheEntry = getGlobalCacheEntry(entityCache, schema, pk); | ||
var ObjectSchema = /*#__PURE__*/function () { | ||
function ObjectSchema(definition) { | ||
this.schema = void 0; | ||
this.define(definition); | ||
} | ||
var _schema$denormalize = schema.denormalize(entity, wrappedUnvisit); | ||
var _proto = ObjectSchema.prototype; | ||
localCache[schema.key][pk] = _schema$denormalize[0]; | ||
found = _schema$denormalize[1]; | ||
deleted = _schema$denormalize[2]; | ||
// if in cycle, use the start of the cycle to track all deps | ||
// otherwise, we use our own trackingIndex | ||
var localKey = dependencies.slice(cycleIndex.i === -1 ? trackingIndex : cycleIndex.i); | ||
_proto.define = function define(definition) { | ||
this.schema = Object.keys(definition).reduce(function (entitySchema, key) { | ||
var _Object$assign; | ||
if (!globalCacheEntry.has(localKey)) { | ||
globalCacheEntry.set(localKey, localCache[schema.key][pk]); | ||
} else { | ||
localCache[schema.key][pk] = globalCacheEntry.get(localKey); | ||
} // start of cycle - reset cycle detection | ||
var schema = definition[key]; | ||
return Object.assign({}, entitySchema, (_Object$assign = {}, _Object$assign[key] = schema, _Object$assign)); | ||
}, this.schema || {}); | ||
}; | ||
_proto.normalize = function normalize() { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
if (cycleIndex.i === trackingIndex) { | ||
cycleIndex.i = -1; | ||
} | ||
} else { | ||
// cycle detected | ||
if (Object.prototype.hasOwnProperty.call(localCache[schema.key][pk], DRAFT)) { | ||
cycleIndex.i = localCache[schema.key][pk].i; | ||
return [localCache[schema.key][pk][DRAFT], found, deleted]; | ||
} else { | ||
// with no cycle, globalCacheEntry will have already been set | ||
dependencies.push(entity); | ||
} | ||
} | ||
return _normalize.apply(void 0, [this.schema].concat(args)); | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
; | ||
return [localCache[schema.key][pk], found, deleted]; | ||
}; | ||
_proto.denormalize = function denormalize() { | ||
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
args[_key2] = arguments[_key2]; | ||
} | ||
var getUnvisit = function getUnvisit(entities, entityCache, resultCache, localCache) { | ||
var getEntity = getEntities(entities); | ||
var dependencies = []; | ||
var cycleIndex = { | ||
i: -1 | ||
}; | ||
return _denormalize.apply(void 0, [this.schema].concat(args)); | ||
}; | ||
function unvisit(input, schema) { | ||
if (!schema) return [input, true, false]; // null is considered intentional, thus always 'found' as true | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return _infer(this.schema, args, indexes, recurse); | ||
}; | ||
if (input === null) { | ||
return [input, true, false]; | ||
} | ||
return ObjectSchema; | ||
}(); | ||
var hasDenormalize = typeof schema.denormalize === 'function'; | ||
var DRAFT = Symbol('draft'); | ||
if (!hasDenormalize && typeof schema === 'function') { | ||
if (input instanceof schema) return [input, true, false]; // field deserialization should never count against 'found' (whether to used inferred results) | ||
var unvisitEntity = function unvisitEntity(entityOrId, schema, unvisit, getEntity, localCache, entityCache, dependencies, cycleIndex) { | ||
var entity = getEntity(entityOrId, schema); | ||
if (input === undefined) return [input, true, false]; | ||
return [new schema(input), true, false]; | ||
} | ||
if (entity === DELETED) { | ||
return [undefined, true, true]; | ||
} | ||
if (input === undefined) { | ||
return [input, false, false]; | ||
} | ||
if (process.env.NODE_ENV !== 'production' && typeof entity === 'symbol' && entity.toString().includes('DELETED')) { | ||
throw new Error("Unrecognized symbol detected.\nMake sure you do not have multiple versions of @rest-hooks/normalizr installed."); | ||
} | ||
if (!hasDenormalize && typeof schema === 'object') { | ||
var method = Array.isArray(schema) ? denormalize$1 : _denormalize; | ||
return method(schema, input, unvisit); | ||
} | ||
if (typeof entity !== 'object' || entity === null) { | ||
return [entity, false, false]; | ||
} | ||
if (isEntity(schema)) { | ||
return unvisitEntity(input, schema, unvisit, getEntity, localCache, entityCache, dependencies, cycleIndex); | ||
} | ||
var pk = typeof entityOrId === 'string' ? entityOrId : schema.pk(isImmutable(entity) ? entity.toJS() : entity); | ||
if (hasDenormalize) { | ||
return schema.denormalize(input, unvisit); | ||
} | ||
if (pk === undefined || pk === '') { | ||
return [entity, false, false]; | ||
} | ||
return [input, true, false]; | ||
} //const wrappedUnvisit = withTrackedEntities(unvisit, globalKey); | ||
if (localCache[schema.key] === undefined) { | ||
localCache[schema.key] = Object.create(null); | ||
} | ||
var found = true; | ||
var deleted = false; | ||
return function (input, schema) { | ||
var ret = unvisit(input, schema); // in the case where WeakMap cannot be used | ||
// this test ensures null is properly excluded from WeakMap | ||
if (!localCache[schema.key][pk]) { | ||
var trackingIndex = dependencies.length; | ||
dependencies.push(entity); | ||
var wrappedUnvisit = withTrackedEntities(unvisit); // { [DRAFT] } means we are still processing - which if found indicates a cycle | ||
if (Object(input) !== input) return ret; | ||
dependencies.push(input); | ||
wrappedUnvisit.setLocal = function (entityCopy) { | ||
var _localCache$schema$ke; | ||
if (!resultCache.has(dependencies)) { | ||
resultCache.set(dependencies, ret[0]); | ||
return ret; | ||
} else { | ||
return [resultCache.get(dependencies), ret[1], ret[2]]; | ||
} | ||
}; | ||
}; | ||
return localCache[schema.key][pk] = (_localCache$schema$ke = {}, _localCache$schema$ke[DRAFT] = entityCopy, _localCache$schema$ke.i = trackingIndex, _localCache$schema$ke); | ||
}; | ||
var getEntities = function getEntities(entities) { | ||
var entityIsImmutable = isImmutable(entities); | ||
return function (entityOrId, schema) { | ||
var _entities$schemaKey; | ||
var globalCacheEntry = getGlobalCacheEntry(entityCache, schema, pk); | ||
var schemaKey = schema.key; | ||
var _schema$denormalize = schema.denormalize(entity, wrappedUnvisit); | ||
if (typeof entityOrId === 'object') { | ||
return entityOrId; | ||
} | ||
localCache[schema.key][pk] = _schema$denormalize[0]; | ||
found = _schema$denormalize[1]; | ||
deleted = _schema$denormalize[2]; | ||
// if in cycle, use the start of the cycle to track all deps | ||
// otherwise, we use our own trackingIndex | ||
var localKey = dependencies.slice(cycleIndex.i === -1 ? trackingIndex : cycleIndex.i); | ||
if (entityIsImmutable) { | ||
return entities.getIn([schemaKey, entityOrId]); | ||
} | ||
if (!globalCacheEntry.has(localKey)) { | ||
globalCacheEntry.set(localKey, localCache[schema.key][pk]); | ||
} else { | ||
localCache[schema.key][pk] = globalCacheEntry.get(localKey); | ||
} // start of cycle - reset cycle detection | ||
return (_entities$schemaKey = entities[schemaKey]) == null ? void 0 : _entities$schemaKey[entityOrId]; | ||
}; | ||
}; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types | ||
if (cycleIndex.i === trackingIndex) { | ||
cycleIndex.i = -1; | ||
} | ||
} else { | ||
// cycle detected | ||
if (Object.prototype.hasOwnProperty.call(localCache[schema.key][pk], DRAFT)) { | ||
cycleIndex.i = localCache[schema.key][pk].i; | ||
return [localCache[schema.key][pk][DRAFT], found, deleted]; | ||
} else { | ||
// with no cycle, globalCacheEntry will have already been set | ||
dependencies.push(entity); | ||
} | ||
} | ||
var denormalize = function denormalize(input, schema, entities, entityCache, resultCache) { | ||
if (entityCache === void 0) { | ||
entityCache = {}; | ||
} | ||
return [localCache[schema.key][pk], found, deleted]; | ||
}; | ||
if (resultCache === void 0) { | ||
resultCache = new WeakListMap(); | ||
} | ||
var getUnvisit = function getUnvisit(entities, entityCache, resultCache, localCache) { | ||
var getEntity = getEntities(entities); | ||
var dependencies = []; | ||
var cycleIndex = { | ||
i: -1 | ||
}; | ||
// undefined mean don't do anything | ||
if (schema === undefined) { | ||
return [input, true, false, {}]; | ||
} | ||
function unvisit(input, schema) { | ||
if (!schema) return [input, true, false]; // null is considered intentional, thus always 'found' as true | ||
if (input === undefined) { | ||
return [undefined, false, false, {}]; | ||
} | ||
if (input === null) { | ||
return [input, true, false]; | ||
} | ||
var resolvedEntities = {}; | ||
var unvisit = getUnvisit(entities, entityCache, resultCache, resolvedEntities); | ||
return [].concat(unvisit(input, schema), [resolvedEntities]); | ||
}; | ||
var hasDenormalize = typeof schema.denormalize === 'function'; | ||
function getGlobalCacheEntry(entityCache, schema, id) { | ||
if (!entityCache[schema.key]) entityCache[schema.key] = {}; | ||
if (!entityCache[schema.key][id]) entityCache[schema.key][id] = new WeakListMap(); | ||
return entityCache[schema.key][id]; | ||
} | ||
if (!hasDenormalize && typeof schema === 'function') { | ||
if (input instanceof schema) return [input, true, false]; // field deserialization should never count against 'found' (whether to used inferred results) | ||
function withTrackedEntities(unvisit) { | ||
// every time we nest, we want to unwrap back to the top. | ||
// this is due to only needed the next level of nested entities for lookup | ||
var originalUnvisit = unvisit.og || unvisit; | ||
if (input === undefined) return [input, true, false]; | ||
return [new schema(input), true, false]; | ||
} | ||
var wrappedUnvisit = function wrappedUnvisit(input, schema) { | ||
return originalUnvisit(input, schema); | ||
}; | ||
if (input === undefined) { | ||
return [input, false, false]; | ||
} | ||
wrappedUnvisit.og = unvisit; | ||
return wrappedUnvisit; | ||
} | ||
if (!hasDenormalize && typeof schema === 'object') { | ||
var method = Array.isArray(schema) ? denormalize$1 : _denormalize; | ||
return method(schema, input, unvisit); | ||
} | ||
var visit = function visit(value, parent, key, schema, addEntity, visitedEntities) { | ||
if (!value || !schema) { | ||
return value; | ||
} | ||
if (isEntity(schema)) { | ||
return unvisitEntity(input, schema, unvisit, getEntity, localCache, entityCache, dependencies, cycleIndex); | ||
} | ||
if (schema.normalize && typeof schema.normalize === 'function') { | ||
if (typeof value !== 'object') return value; | ||
return schema.normalize(value, parent, key, visit, addEntity, visitedEntities); | ||
} // serializable | ||
if (hasDenormalize) { | ||
return schema.denormalize(input, unvisit); | ||
} | ||
return [input, true, false]; | ||
} //const wrappedUnvisit = withTrackedEntities(unvisit, globalKey); | ||
if (typeof schema === 'function') { | ||
return new schema(value); | ||
} | ||
if (typeof value !== 'object' || typeof schema !== 'object') return value; | ||
var method = Array.isArray(schema) ? normalize$1 : _normalize; | ||
return method(schema, value, parent, key, visit, addEntity, visitedEntities); | ||
}; | ||
return function (input, schema) { | ||
var ret = unvisit(input, schema); // in the case where WeakMap cannot be used | ||
// this test ensures null is properly excluded from WeakMap | ||
var addEntities = function addEntities(entities, indexes, existingEntities, existingIndexes, entityMeta, meta) { | ||
var _s = $RefreshSig$(); | ||
if (Object(input) !== input) return ret; | ||
dependencies.push(input); | ||
return _s(function (schema, processedEntity, id) { | ||
_s(); | ||
if (!resultCache.has(dependencies)) { | ||
resultCache.set(dependencies, ret[0]); | ||
return ret; | ||
} else { | ||
return [resultCache.get(dependencies), ret[1], ret[2]]; | ||
} | ||
}; | ||
}; | ||
var schemaKey = schema.key; | ||
var getEntities = function getEntities(entities) { | ||
var entityIsImmutable = isImmutable(entities); | ||
return function (entityOrId, schema) { | ||
var _entities$schemaKey; | ||
if (!(schemaKey in entities)) { | ||
entities[schemaKey] = {}; | ||
existingEntities[schemaKey] = Object.assign({}, existingEntities[schemaKey]); | ||
entityMeta[schemaKey] = Object.assign({}, entityMeta[schemaKey]); | ||
} | ||
var schemaKey = schema.key; | ||
var existingEntity = entities[schemaKey][id]; | ||
if (typeof entityOrId === 'object') { | ||
return entityOrId; | ||
} | ||
if (existingEntity) { | ||
entities[schemaKey][id] = schema.merge(existingEntity, processedEntity); | ||
} else { | ||
// TODO: eventually assume this exists and don't check for conditional. probably early 2022 | ||
var entityExpiresAt = schema.expiresAt ? schema.expiresAt(meta, processedEntity) : meta.expiresAt; | ||
var inStoreEntity = existingEntities[schemaKey][id]; // this case we already have this entity in store | ||
if (entityIsImmutable) { | ||
return entities.getIn([schemaKey, entityOrId]); | ||
} | ||
if (inStoreEntity) { | ||
var _entityMeta$schemaKey, _entityMeta$schemaKey2, _entityMeta$schemaKey3, _meta$fetchedAt, _entityMeta$schemaKey4, _entityMeta$schemaKey5; | ||
return (_entities$schemaKey = entities[schemaKey]) == null ? void 0 : _entities$schemaKey[entityOrId]; | ||
}; | ||
}; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types | ||
var inStoreMeta = entityMeta[schemaKey][id]; | ||
var useIncoming = // we may have in store but not in meta; so this existance check is still important | ||
!inStoreMeta || ( // useIncoming should not be used with legacy optimistic | ||
schema.useIncoming && meta.fetchedAt ? schema.useIncoming(inStoreMeta, meta, inStoreEntity, processedEntity) : entityMeta[schemaKey][id].date <= meta.date); | ||
if (useIncoming) { | ||
if (typeof processedEntity !== typeof inStoreEntity) { | ||
entities[schemaKey][id] = processedEntity; | ||
} else { | ||
entities[schemaKey][id] = schema.merge(inStoreEntity, processedEntity); | ||
} | ||
} else { | ||
entities[schemaKey][id] = inStoreEntity; | ||
} | ||
var denormalize = function denormalize(input, schema, entities, entityCache, resultCache) { | ||
if (entityCache === void 0) { | ||
entityCache = {}; | ||
} | ||
entityMeta[schemaKey][id] = { | ||
expiresAt: Math.max(entityExpiresAt, (_entityMeta$schemaKey = entityMeta[schemaKey][id]) == null ? void 0 : _entityMeta$schemaKey.expiresAt), | ||
date: Math.max(meta.date, (_entityMeta$schemaKey2 = (_entityMeta$schemaKey3 = entityMeta[schemaKey][id]) == null ? void 0 : _entityMeta$schemaKey3.date) != null ? _entityMeta$schemaKey2 : 0), | ||
fetchedAt: Math.max((_meta$fetchedAt = meta.fetchedAt) != null ? _meta$fetchedAt : 0, (_entityMeta$schemaKey4 = (_entityMeta$schemaKey5 = entityMeta[schemaKey][id]) == null ? void 0 : _entityMeta$schemaKey5.fetchedAt) != null ? _entityMeta$schemaKey4 : 0) | ||
}; | ||
} else { | ||
var _meta$fetchedAt2; | ||
if (resultCache === void 0) { | ||
resultCache = new WeakListMap(); | ||
} | ||
entities[schemaKey][id] = processedEntity; | ||
entityMeta[schemaKey][id] = { | ||
expiresAt: entityExpiresAt, | ||
date: meta.date, | ||
fetchedAt: (_meta$fetchedAt2 = meta.fetchedAt) != null ? _meta$fetchedAt2 : meta.date | ||
}; | ||
} | ||
} // update index | ||
// undefined mean don't do anything | ||
if (schema === undefined) { | ||
return [input, true, false, {}]; | ||
} | ||
if (input === undefined) { | ||
return [undefined, false, false, {}]; | ||
} | ||
if (Array.isArray(schema.indexes)) { | ||
var entity = entities[schemaKey][id]; | ||
var resolvedEntities = {}; | ||
var unvisit = getUnvisit(entities, entityCache, resultCache, resolvedEntities); | ||
return [].concat(unvisit(input, schema), [resolvedEntities]); | ||
}; | ||
if (!(schemaKey in indexes)) { | ||
indexes[schemaKey] = {}; | ||
existingIndexes[schemaKey] = Object.assign({}, existingIndexes[schemaKey]); | ||
} | ||
function getGlobalCacheEntry(entityCache, schema, id) { | ||
if (!entityCache[schema.key]) entityCache[schema.key] = {}; | ||
if (!entityCache[schema.key][id]) entityCache[schema.key][id] = new WeakListMap(); | ||
return entityCache[schema.key][id]; | ||
} | ||
for (var _iterator = _createForOfIteratorHelperLoose(schema.indexes), _step; !(_step = _iterator()).done;) { | ||
var index = _step.value; | ||
function withTrackedEntities(unvisit) { | ||
// every time we nest, we want to unwrap back to the top. | ||
// this is due to only needed the next level of nested entities for lookup | ||
var originalUnvisit = unvisit.og || unvisit; | ||
if (!(index in indexes[schemaKey])) { | ||
existingIndexes[schemaKey][index] = indexes[schemaKey][index] = {}; | ||
} | ||
var wrappedUnvisit = function wrappedUnvisit(input, schema) { | ||
return originalUnvisit(input, schema); | ||
}; | ||
var indexMap = indexes[schemaKey][index]; | ||
wrappedUnvisit.og = unvisit; | ||
return wrappedUnvisit; | ||
} | ||
if (existingEntity) { | ||
delete indexMap[existingEntity[index]]; | ||
} // entity already in cache but the index changed | ||
var visit = function visit(value, parent, key, schema, addEntity, visitedEntities) { | ||
if (!value || !schema) { | ||
return value; | ||
} | ||
if (schema.normalize && typeof schema.normalize === 'function') { | ||
if (typeof value !== 'object') return value; | ||
return schema.normalize(value, parent, key, visit, addEntity, visitedEntities); | ||
} // serializable | ||
if (existingEntities[schemaKey] && existingEntities[schemaKey][id] && existingEntities[schemaKey][id][index] !== entity[index]) { | ||
indexMap[existingEntities[schemaKey][id][index]] = DELETED; | ||
} | ||
if (index in entity) { | ||
indexMap[entity[index]] = id; | ||
} | ||
/* istanbul ignore next */ | ||
else if ( // eslint-disable-next-line no-undef | ||
process.env.NODE_ENV !== 'production') { | ||
console.warn("Index not found in entity. Indexes must be top-level members of your entity.\nIndex: " + index + "\nEntity: " + JSON.stringify(entity, undefined, 2)); | ||
} | ||
} | ||
} // set this after index updates so we know what indexes to remove from | ||
if (typeof schema === 'function') { | ||
return new schema(value); | ||
} | ||
if (typeof value !== 'object' || typeof schema !== 'object') return value; | ||
var method = Array.isArray(schema) ? normalize$1 : _normalize; | ||
return method(schema, value, parent, key, visit, addEntity, visitedEntities); | ||
}; | ||
existingEntities[schemaKey][id] = entities[schemaKey][id]; | ||
}, "RSHyr3aBwsmLX8s7SwDQGEQTEhQ=", false, function () { | ||
return [schema.useIncoming]; | ||
}); | ||
}; | ||
var addEntities = function addEntities(entities, indexes, existingEntities, existingIndexes, entityMeta, meta) { | ||
var _s = $RefreshSig$(); | ||
function expectedSchemaType(schema) { | ||
return ['object', 'function'].includes(typeof schema) ? 'object' : typeof schema; | ||
} // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types | ||
return _s(function (schema, processedEntity, id) { | ||
_s(); | ||
var schemaKey = schema.key; | ||
var normalize = function normalize(input, schema, existingEntities, existingIndexes, existingEntityMeta, meta) { | ||
if (existingEntities === void 0) { | ||
existingEntities = {}; | ||
} | ||
if (!(schemaKey in entities)) { | ||
entities[schemaKey] = {}; | ||
existingEntities[schemaKey] = Object.assign({}, existingEntities[schemaKey]); | ||
entityMeta[schemaKey] = Object.assign({}, entityMeta[schemaKey]); | ||
} | ||
if (existingIndexes === void 0) { | ||
existingIndexes = {}; | ||
} | ||
var existingEntity = entities[schemaKey][id]; | ||
if (existingEntityMeta === void 0) { | ||
existingEntityMeta = {}; | ||
} | ||
if (existingEntity) { | ||
entities[schemaKey][id] = schema.merge(existingEntity, processedEntity); | ||
} else { | ||
// TODO: eventually assume this exists and don't check for conditional. probably early 2022 | ||
var entityExpiresAt = schema.expiresAt ? schema.expiresAt(meta, processedEntity) : meta.expiresAt; | ||
var inStoreEntity = existingEntities[schemaKey][id]; // this case we already have this entity in store | ||
if (meta === void 0) { | ||
meta = { | ||
date: Date.now(), | ||
expiresAt: Infinity, | ||
fetchedAt: 0 | ||
}; | ||
} | ||
if (inStoreEntity) { | ||
var _entityMeta$schemaKey, _entityMeta$schemaKey2, _entityMeta$schemaKey3, _meta$fetchedAt, _entityMeta$schemaKey4, _entityMeta$schemaKey5; | ||
// no schema means we don't process at all | ||
if (schema === undefined) return { | ||
entities: existingEntities, | ||
indexes: existingIndexes, | ||
result: input, | ||
entityMeta: existingEntityMeta | ||
}; | ||
var schemaType = expectedSchemaType(schema); | ||
var inStoreMeta = entityMeta[schemaKey][id]; | ||
var useIncoming = // we may have in store but not in meta; so this existance check is still important | ||
!inStoreMeta || ( // useIncoming should not be used with legacy optimistic | ||
schema.useIncoming && meta.fetchedAt ? schema.useIncoming(inStoreMeta, meta, inStoreEntity, processedEntity) : entityMeta[schemaKey][id].date <= meta.date); | ||
if (input === null || typeof input !== schemaType && !(schema.key !== undefined && typeof input === 'string')) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production') { | ||
var parseWorks = function parseWorks(input) { | ||
try { | ||
return typeof JSON.parse(input) !== 'string'; | ||
} catch (e) { | ||
return false; | ||
} | ||
}; | ||
if (useIncoming) { | ||
if (typeof processedEntity !== typeof inStoreEntity) { | ||
entities[schemaKey][id] = processedEntity; | ||
} else { | ||
entities[schemaKey][id] = schema.merge(inStoreEntity, processedEntity); | ||
} | ||
} else { | ||
entities[schemaKey][id] = inStoreEntity; | ||
} | ||
if (typeof input === 'string' && parseWorks(input)) { | ||
throw new Error("Normalizing a string, but this does match schema.\n\nParsing this input string as JSON worked. This likely indicates fetch function did not parse\nthe JSON. By default, this only happens if \"content-type\" header includes \"json\".\nSee https://resthooks.io/docs/guides/custom-networking for more information\n\n Schema: " + JSON.stringify(schema, undefined, 2) + "\n Input: \"" + input + "\""); | ||
} else { | ||
throw new Error("Unexpected input given to normalize. Expected type to be \"" + schemaType + "\", found \"" + (input === null ? 'null' : typeof input) + "\".\n\n Schema: " + JSON.stringify(schema, undefined, 2) + "\n Input: \"" + input + "\""); | ||
} | ||
} else { | ||
throw new Error("Unexpected input given to normalize. Expected type to be \"" + schemaType + "\", found \"" + (input === null ? 'null' : typeof input) + "\"."); | ||
} | ||
} | ||
entityMeta[schemaKey][id] = { | ||
expiresAt: Math.max(entityExpiresAt, (_entityMeta$schemaKey = entityMeta[schemaKey][id]) == null ? void 0 : _entityMeta$schemaKey.expiresAt), | ||
date: Math.max(meta.date, (_entityMeta$schemaKey2 = (_entityMeta$schemaKey3 = entityMeta[schemaKey][id]) == null ? void 0 : _entityMeta$schemaKey3.date) != null ? _entityMeta$schemaKey2 : 0), | ||
fetchedAt: Math.max((_meta$fetchedAt = meta.fetchedAt) != null ? _meta$fetchedAt : 0, (_entityMeta$schemaKey4 = (_entityMeta$schemaKey5 = entityMeta[schemaKey][id]) == null ? void 0 : _entityMeta$schemaKey5.fetchedAt) != null ? _entityMeta$schemaKey4 : 0) | ||
}; | ||
} else { | ||
var _meta$fetchedAt2; | ||
var newEntities = {}; | ||
var newIndexes = {}; | ||
var entities = Object.assign({}, existingEntities); | ||
var indexes = Object.assign({}, existingIndexes); | ||
var entityMeta = Object.assign({}, existingEntityMeta); | ||
var addEntity = addEntities(newEntities, newIndexes, entities, indexes, entityMeta, meta); | ||
var visitedEntities = {}; | ||
var result = visit(input, input, undefined, schema, addEntity, visitedEntities); | ||
return { | ||
entities: entities, | ||
indexes: indexes, | ||
result: result, | ||
entityMeta: entityMeta | ||
}; | ||
}; | ||
entities[schemaKey][id] = processedEntity; | ||
entityMeta[schemaKey][id] = { | ||
expiresAt: entityExpiresAt, | ||
date: meta.date, | ||
fetchedAt: (_meta$fetchedAt2 = meta.fetchedAt) != null ? _meta$fetchedAt2 : meta.date | ||
}; | ||
} | ||
} // update index | ||
/** | ||
* Represents polymorphic values. | ||
* @see https://resthooks.io/docs/api/Union | ||
*/ | ||
var UnionSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(UnionSchema, _PolymorphicSchema); | ||
if (Array.isArray(schema.indexes)) { | ||
var entity = entities[schemaKey][id]; | ||
function UnionSchema(definition, schemaAttribute) { | ||
if (!schemaAttribute) { | ||
throw new Error('Expected option "schemaAttribute" not found on UnionSchema.'); | ||
} | ||
if (!(schemaKey in indexes)) { | ||
indexes[schemaKey] = {}; | ||
existingIndexes[schemaKey] = Object.assign({}, existingIndexes[schemaKey]); | ||
} | ||
return _PolymorphicSchema.call(this, definition, schemaAttribute) || this; | ||
} | ||
for (var _iterator = _createForOfIteratorHelperLoose(schema.indexes), _step; !(_step = _iterator()).done;) { | ||
var index = _step.value; | ||
var _proto = UnionSchema.prototype; | ||
if (!(index in indexes[schemaKey])) { | ||
existingIndexes[schemaKey][index] = indexes[schemaKey][index] = {}; | ||
} | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
return this.normalizeValue(input, parent, key, visit, addEntity, visitedEntities); | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
; | ||
var indexMap = indexes[schemaKey][index]; | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
return this.denormalizeValue(input, unvisit); | ||
}; | ||
if (existingEntity) { | ||
delete indexMap[existingEntity[index]]; | ||
} // entity already in cache but the index changed | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
if (!args[0]) return undefined; | ||
var attr = this.getSchemaAttribute(args[0], undefined, ''); | ||
var discriminatedSchema = this.schema[attr]; // Was unable to infer the entity's schema from params | ||
if (discriminatedSchema === undefined) return undefined; | ||
return { | ||
id: recurse(discriminatedSchema, args, indexes), | ||
schema: attr | ||
}; | ||
}; | ||
if (existingEntities[schemaKey] && existingEntities[schemaKey][id] && existingEntities[schemaKey][id][index] !== entity[index]) { | ||
indexMap[existingEntities[schemaKey][id][index]] = DELETED; | ||
} | ||
return UnionSchema; | ||
}(PolymorphicSchema); | ||
if (index in entity) { | ||
indexMap[entity[index]] = id; | ||
} | ||
/* istanbul ignore next */ | ||
else if ( // eslint-disable-next-line no-undef | ||
process.env.NODE_ENV !== 'production') { | ||
console.warn("Index not found in entity. Indexes must be top-level members of your entity.\nIndex: " + index + "\nEntity: " + JSON.stringify(entity, undefined, 2)); | ||
} | ||
} | ||
} // set this after index updates so we know what indexes to remove from | ||
/** | ||
* Represents variably sized objects | ||
* @see https://resthooks.io/docs/api/Values | ||
*/ | ||
var ValuesSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ValuesSchema, _PolymorphicSchema); | ||
existingEntities[schemaKey][id] = entities[schemaKey][id]; | ||
}, "RSHyr3aBwsmLX8s7SwDQGEQTEhQ=", false, function () { | ||
return [schema.useIncoming]; | ||
}); | ||
}; | ||
function ValuesSchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
} | ||
function expectedSchemaType(schema) { | ||
return ['object', 'function'].includes(typeof schema) ? 'object' : typeof schema; | ||
} // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types | ||
var _proto = ValuesSchema.prototype; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
var normalize = function normalize(input, schema, existingEntities, existingIndexes, existingEntityMeta, meta) { | ||
if (existingEntities === void 0) { | ||
existingEntities = {}; | ||
} | ||
return Object.keys(input).reduce(function (output, key, index) { | ||
var _Object$assign; | ||
if (existingIndexes === void 0) { | ||
existingIndexes = {}; | ||
} | ||
var value = input[key]; | ||
return value !== undefined && value !== null ? Object.assign({}, output, (_Object$assign = {}, _Object$assign[key] = _this.normalizeValue(value, input, key, visit, addEntity, visitedEntities), _Object$assign)) : output; | ||
}, {}); | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
; | ||
if (existingEntityMeta === void 0) { | ||
existingEntityMeta = {}; | ||
} | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
if (meta === void 0) { | ||
meta = { | ||
date: Date.now(), | ||
expiresAt: Infinity, | ||
fetchedAt: 0 | ||
}; | ||
} | ||
var found = true; | ||
var deleted = false; | ||
return [Object.keys(input).reduce(function (output, key) { | ||
var _Object$assign2; | ||
// no schema means we don't process at all | ||
if (schema === undefined) return { | ||
entities: existingEntities, | ||
indexes: existingIndexes, | ||
result: input, | ||
entityMeta: existingEntityMeta | ||
}; | ||
var schemaType = expectedSchemaType(schema); | ||
var entityOrId = input[key]; | ||
if (input === null || typeof input !== schemaType && !(schema.key !== undefined && typeof input === 'string')) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production') { | ||
var parseWorks = function parseWorks(input) { | ||
try { | ||
return typeof JSON.parse(input) !== 'string'; | ||
} catch (e) { | ||
return false; | ||
} | ||
}; | ||
var _this2$denormalizeVal = _this2.denormalizeValue(entityOrId, unvisit), | ||
value = _this2$denormalizeVal[0], | ||
foundItem = _this2$denormalizeVal[1], | ||
deletedItem = _this2$denormalizeVal[2]; | ||
if (typeof input === 'string' && parseWorks(input)) { | ||
throw new Error("Normalizing a string, but this does match schema.\n\nParsing this input string as JSON worked. This likely indicates fetch function did not parse\nthe JSON. By default, this only happens if \"content-type\" header includes \"json\".\nSee https://resthooks.io/docs/guides/custom-networking for more information\n\n Schema: " + JSON.stringify(schema, undefined, 2) + "\n Input: \"" + input + "\""); | ||
} else { | ||
throw new Error("Unexpected input given to normalize. Expected type to be \"" + schemaType + "\", found \"" + (input === null ? 'null' : typeof input) + "\".\n\n Schema: " + JSON.stringify(schema, undefined, 2) + "\n Input: \"" + input + "\""); | ||
} | ||
} else { | ||
throw new Error("Unexpected input given to normalize. Expected type to be \"" + schemaType + "\", found \"" + (input === null ? 'null' : typeof input) + "\"."); | ||
} | ||
} | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
var newEntities = {}; | ||
var newIndexes = {}; | ||
var entities = Object.assign({}, existingEntities); | ||
var indexes = Object.assign({}, existingIndexes); | ||
var entityMeta = Object.assign({}, existingEntityMeta); | ||
var addEntity = addEntities(newEntities, newIndexes, entities, indexes, entityMeta, meta); | ||
var visitedEntities = {}; | ||
var result = visit(input, input, undefined, schema, addEntity, visitedEntities); | ||
return { | ||
entities: entities, | ||
indexes: indexes, | ||
result: result, | ||
entityMeta: entityMeta | ||
}; | ||
}; | ||
if (deletedItem) { | ||
deleted = true; | ||
} | ||
/** | ||
* Represents polymorphic values. | ||
* @see https://resthooks.io/docs/api/Union | ||
*/ | ||
if (!foundItem || deletedItem) return output; | ||
return Object.assign({}, output, (_Object$assign2 = {}, _Object$assign2[key] = value, _Object$assign2)); | ||
}, {}), found, deleted]; | ||
}; | ||
var UnionSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(UnionSchema, _PolymorphicSchema); | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return undefined; | ||
}; | ||
function UnionSchema(definition, schemaAttribute) { | ||
if (!schemaAttribute) { | ||
throw new Error('Expected option "schemaAttribute" not found on UnionSchema.'); | ||
} | ||
return ValuesSchema; | ||
}(PolymorphicSchema); | ||
return _PolymorphicSchema.call(this, definition, schemaAttribute) || this; | ||
} | ||
/** | ||
* Marks entity as deleted. | ||
* @see https://resthooks.io/docs/api/Delete | ||
*/ | ||
var _proto = UnionSchema.prototype; | ||
var Delete = /*#__PURE__*/function () { | ||
function Delete(entity) { | ||
if (process.env.NODE_ENV !== 'production' && !entity) { | ||
throw new Error('Expected option "entity" not found on DeleteSchema.'); | ||
} | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
return this.normalizeValue(input, parent, key, visit, addEntity, visitedEntities); | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
; | ||
this._entity = entity; | ||
} | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
return this.denormalizeValue(input, unvisit); | ||
}; | ||
var _proto = Delete.prototype; | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
if (!args[0]) return undefined; | ||
var attr = this.getSchemaAttribute(args[0], undefined, ''); | ||
var discriminatedSchema = this.schema[attr]; // Was unable to infer the entity's schema from params | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
// TODO: what's store needs to be a differing type from fromJS | ||
var processedEntity = this._entity.process(input, parent, key); | ||
if (discriminatedSchema === undefined) return undefined; | ||
return { | ||
id: recurse(discriminatedSchema, args, indexes), | ||
schema: attr | ||
}; | ||
}; | ||
var id = this._entity.pk(processedEntity, parent, key); | ||
return UnionSchema; | ||
}(PolymorphicSchema); | ||
if (process.env.NODE_ENV !== 'production' && (id === undefined || id === '')) { | ||
var _name; | ||
/** | ||
* Represents variably sized objects | ||
* @see https://resthooks.io/docs/api/Values | ||
*/ | ||
var error = new Error("Missing usable primary key when normalizing response.\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n\n Delete(Entity): Delete(" + ((_name = this._entity.name) != null ? _name : this._entity) + ")\n Value: " + (input && JSON.stringify(input, null, 2)) + "\n "); | ||
error.status = 400; | ||
throw error; | ||
} | ||
var ValuesSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ValuesSchema, _PolymorphicSchema); | ||
addEntity(this, DELETED, id); | ||
return id; | ||
}; | ||
function ValuesSchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
} | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return undefined; | ||
}; | ||
var _proto = ValuesSchema.prototype; | ||
_proto.denormalize = function denormalize(id, unvisit) { | ||
return unvisit(id, this._entity); | ||
} | ||
/* istanbul ignore next */ | ||
; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
_proto._denormalizeNullable = function _denormalizeNullable() { | ||
return []; | ||
} | ||
/* istanbul ignore next */ | ||
; | ||
return Object.keys(input).reduce(function (output, key, index) { | ||
var _Object$assign; | ||
_proto._normalizeNullable = function _normalizeNullable() { | ||
return []; | ||
} | ||
/* istanbul ignore next */ | ||
; | ||
var value = input[key]; | ||
return value !== undefined && value !== null ? Object.assign({}, output, (_Object$assign = {}, _Object$assign[key] = _this.normalizeValue(value, input, key, visit, addEntity, visitedEntities), _Object$assign)) : output; | ||
}, {}); | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
; | ||
_proto.merge = function merge(existing, incoming) { | ||
return incoming; | ||
}; | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
_proto.useIncoming = function useIncoming(existingMeta, incomingMeta, existing, incoming) { | ||
return existingMeta.date <= incomingMeta.date; | ||
}; | ||
var found = true; | ||
var deleted = false; | ||
return [Object.keys(input).reduce(function (output, key) { | ||
var _Object$assign2; | ||
_createClass(Delete, [{ | ||
key: "key", | ||
get: function get() { | ||
return this._entity.key; | ||
} | ||
}]); | ||
var entityOrId = input[key]; | ||
return Delete; | ||
}(); | ||
var _this2$denormalizeVal = _this2.denormalizeValue(entityOrId, unvisit), | ||
value = _this2$denormalizeVal[0], | ||
foundItem = _this2$denormalizeVal[1], | ||
deletedItem = _this2$denormalizeVal[2]; | ||
/* istanbul ignore file */ | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
var schema$1 = /*#__PURE__*/Object.freeze({ | ||
__proto__: null, | ||
Union: UnionSchema, | ||
Values: ValuesSchema, | ||
Array: ArraySchema, | ||
Object: ObjectSchema, | ||
Delete: Delete | ||
}); | ||
if (deletedItem) { | ||
deleted = true; | ||
} | ||
/** | ||
* Build the result parameter to denormalize from schema alone. | ||
* Tries to compute the entity ids from params. | ||
*/ | ||
if (!foundItem || deletedItem) return output; | ||
return Object.assign({}, output, (_Object$assign2 = {}, _Object$assign2[key] = value, _Object$assign2)); | ||
}, {}), found, deleted]; | ||
}; | ||
function inferResults(schema, args, indexes) { | ||
// schema classes | ||
if (canInfer(schema)) { | ||
return schema.infer(args, indexes, inferResults); | ||
} // plain case | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return undefined; | ||
}; | ||
return ValuesSchema; | ||
}(PolymorphicSchema); | ||
if (typeof schema === 'object' && schema) { | ||
var method = Array.isArray(schema) ? _infer$1 : _infer; | ||
return method(schema, args, indexes, inferResults); | ||
} // fallback for things like null or undefined | ||
/** | ||
* Marks entity as deleted. | ||
* @see https://resthooks.io/docs/api/Delete | ||
*/ | ||
var Delete = /*#__PURE__*/function () { | ||
function Delete(entity) { | ||
if (process.env.NODE_ENV !== 'production' && !entity) { | ||
throw new Error('Expected option "entity" not found on DeleteSchema.'); | ||
} | ||
return schema; | ||
} | ||
this._entity = entity; | ||
} | ||
function canInfer(schema) { | ||
return !!schema && typeof schema.infer === 'function'; | ||
} | ||
var _proto = Delete.prototype; | ||
exports.DELETED = DELETED; | ||
exports.Entity = Entity; | ||
exports.WeakListMap = WeakListMap; | ||
exports.denormalize = denormalize; | ||
exports.inferResults = inferResults; | ||
exports.isEntity = isEntity; | ||
exports.normalize = normalize; | ||
exports.schema = schema$1; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
// TODO: what's store needs to be a differing type from fromJS | ||
var processedEntity = this._entity.process(input, parent, key); | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
var id = this._entity.pk(processedEntity, parent, key); | ||
return exports; | ||
if (process.env.NODE_ENV !== 'production' && (id === undefined || id === '')) { | ||
var _name; | ||
var error = new Error("Missing usable primary key when normalizing response.\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n\n Delete(Entity): Delete(" + ((_name = this._entity.name) != null ? _name : this._entity) + ")\n Value: " + (input && JSON.stringify(input, null, 2)) + "\n "); | ||
error.status = 400; | ||
throw error; | ||
} | ||
addEntity(this, DELETED, id); | ||
return id; | ||
}; | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return undefined; | ||
}; | ||
_proto.denormalize = function denormalize(id, unvisit) { | ||
return unvisit(id, this._entity); | ||
} | ||
/* istanbul ignore next */ | ||
; | ||
_proto._denormalizeNullable = function _denormalizeNullable() { | ||
return []; | ||
} | ||
/* istanbul ignore next */ | ||
; | ||
_proto._normalizeNullable = function _normalizeNullable() { | ||
return []; | ||
} | ||
/* istanbul ignore next */ | ||
; | ||
_proto.merge = function merge(existing, incoming) { | ||
return incoming; | ||
}; | ||
_proto.useIncoming = function useIncoming(existingMeta, incomingMeta, existing, incoming) { | ||
return existingMeta.date <= incomingMeta.date; | ||
}; | ||
_createClass(Delete, [{ | ||
key: "key", | ||
get: function get() { | ||
return this._entity.key; | ||
} | ||
}]); | ||
return Delete; | ||
}(); | ||
/* istanbul ignore file */ | ||
var schema$1 = /*#__PURE__*/Object.freeze({ | ||
__proto__: null, | ||
Union: UnionSchema, | ||
Values: ValuesSchema, | ||
Array: ArraySchema, | ||
Object: ObjectSchema, | ||
Delete: Delete | ||
}); | ||
/** | ||
* Build the result parameter to denormalize from schema alone. | ||
* Tries to compute the entity ids from params. | ||
*/ | ||
function inferResults(schema, args, indexes) { | ||
// schema classes | ||
if (canInfer(schema)) { | ||
return schema.infer(args, indexes, inferResults); | ||
} // plain case | ||
if (typeof schema === 'object' && schema) { | ||
var method = Array.isArray(schema) ? _infer$1 : _infer; | ||
return method(schema, args, indexes, inferResults); | ||
} // fallback for things like null or undefined | ||
return schema; | ||
} | ||
function canInfer(schema) { | ||
return !!schema && typeof schema.infer === 'function'; | ||
} | ||
exports.DELETED = DELETED; | ||
exports.Entity = Entity; | ||
exports.WeakListMap = WeakListMap; | ||
exports.denormalize = denormalize; | ||
exports.inferResults = inferResults; | ||
exports.isEntity = isEntity; | ||
exports.normalize = normalize; | ||
exports.schema = schema$1; | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
return exports; | ||
})({}); |
@@ -1,1 +0,1 @@ | ||
function e(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function t(t,n){var r="undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(r)return(r=r.call(t)).next.bind(r);if(Array.isArray(t)||(r=function(t,n){if(t){if("string"==typeof t)return e(t,n);var r=Object.prototype.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?e(t,n):void 0}}(t))||n&&t&&"number"==typeof t.length){r&&(t=r);var i=0;return function(){return i>=t.length?{done:!0}:{done:!1,value:t[i++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function n(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function r(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function i(e){return!("function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}function o(e,t,n){var r=!0,i=!1;return[Object.keys(e).reduce((function(t,o){var s=""+o,a=n(t.get(s),e[s]),u=a[0],c=a[1],f=a[2];return c||(r=!1),f&&(i=!0),t.has(s)?t.set(s,u):t}),t),r,i]}var s=function(){function e(){}return e.toJSON=function(){return{name:this.name,schema:this.schema,key:this.key}},e.pk=function(e,t,n){return this.prototype.pk.call(e,t,n)},e.useIncoming=function(e,t,n,r){return e.fetchedAt<=t.fetchedAt},e.merge=function(e,t){return Object.assign({},e,t)},e.fromJS=function(e){void 0===e&&(e={});var t=new this(e);return Object.assign(t,e),t},e.process=function(e){function t(t,n,r){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e,t,n){if("production"!==process.env.NODE_ENV&&"silent"!==this.automaticValidation&&Array.isArray(e)){var r="Attempted to initialize "+this.name+" with an array, but named members were expected\n\nThis is likely due to a malformed response.\nTry inspecting the network response or fetch() return value.\nOr use debugging tools: https://resthooks.io/docs/guides/debugging\nLearn more about schemas: https://resthooks.io/docs/api/schema\nIf this is a mistake, you can disable this check by setting static automaticValidation = 'silent'\n\nFirst three members: "+JSON.stringify(e.slice(0,3),null,2);if("warn"!==this.automaticValidation){var i=new Error(r);throw i.status=400,i}console.warn(r)}return Object.assign({},e)})),e.normalize=function(e,t,n,r,i,o){var s=this,a=this.process(e,t,n),u=this.pk(a,t,n);if(void 0!==u&&""!==u){var c=this.key;if(c in o||(o[c]={}),u in o[c]||(o[c][u]=[]),o[c][u].some((function(t){return t===e})))return u;var f=this.validate(a);if(f){var l=new Error(f);throw l.status=400,l}return o[c][u].push(e),Object.keys(this.schema).forEach((function(e){if(Object.prototype.hasOwnProperty.call(a,e)){var t=s.schema[e];a[e]=r(a[e],a,e,t,i,o)}})),i(this,a,u),u}if("production"!==process.env.NODE_ENV){var h=new Error("Missing usable primary key when normalizing response.\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n\n Entity: "+this.name+"\n Value (processed): "+(a&&JSON.stringify(a,null,2))+"\n ");throw h.status=400,h}},e.validate=function(e){if("production"!==process.env.NODE_ENV&&"silent"!==this.automaticValidation){for(var n=new Set(Object.keys(this.defaults)),r=Object.keys(e),i=[],o=[],s=[],a=0,u=r;a<u.length;a++){var c=u[a];n.has(c)?i.push(c):s.push(c)}for(var f,l=t(n);!(f=l()).done;){var h=f.value;i.includes(h)||o.push(h)}if(n.size){var p=Math.max(r.length/2,1)<=s.length&&n.size>Math.max(s.length,2)&&Math.pow(i.length,1.5)/2<=s.length,d=i.length<Math.min(1,n.size/2);if(p||d){var y="",m="substantially different than expected keys";d&&(y+="\n Missing: "+o,m="no matching keys found"),p&&(y+="\n Unexpected keys: "+s,m="a large number of unexpected keys found");var v="Attempted to initialize "+this.name+" with "+m+"\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n If this is a mistake, you can disable this check by setting static automaticValidation = 'silent'\n\n Expected keys:\n Found: "+i+y+"\n Value (processed): "+JSON.stringify(e,null,2);if(!(i.length>=4&&p||"warn"===this.automaticValidation))return v;console.warn(v)}}}if("production"!==process.env.NODE_ENV)for(var g=0,b=Object.keys(this.schema);g<b.length;g++){var O=b[g];if(!Object.prototype.hasOwnProperty.call(e,O)&&!Object.prototype.hasOwnProperty.call(this.defaults,O))return"Schema key is missing in Entity\n\n Be sure all schema members are also part of the entity\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about nesting schemas: https://resthooks.io/docs/guides/nested-response\n\n Entity keys: "+Object.keys(this.defaults)+"\n Schema key(missing): "+O+"\n "}},e.infer=function(e,t,n){if(e[0]){var r=this.pk(e[0],void 0,"");if(void 0!==r&&""!==r)return r;var i=function(e,t){return t?t.find((function(t){return Object.prototype.hasOwnProperty.call(e,t)})):void 0}(e[0],this.indexes);if(i&&t[this.key])return t[this.key][i][e[0][i]]}},e.expiresAt=function(e,t){return e.expiresAt},e.denormalize=function(e,t){var n=this;if(i(e)){if(this.validate(e.toJS()))return[void 0,!1,!0];null==t.setLocal||t.setLocal(e);var r=o(this.schema,e,t),s=r[0],a=r[1],u=r[2];return[this.fromJS(s.toObject()),a,u]}if(this.validate(e))return[void 0,!1,!0];var c=this.fromJS(e);null==t.setLocal||t.setLocal(c);var f=!1;return Object.keys(this.schema).forEach((function(r){var i=n.schema[r],o=Object.prototype.hasOwnProperty.call(e,r)?e[r]:void 0,s=t(o,i),a=s[0];!s[2]||Object.prototype.hasOwnProperty.call(e,r)&&!n.defaults[r]||(f=!0),Object.prototype.hasOwnProperty.call(e,r)&&e[r]!==a&&n.set(c,r,a)})),[c,!0,f]},e.set=function(e,t,n){e[t]=n},r(e,null,[{key:"key",get:function(){if("production"!==process.env.NODE_ENV&&(""===this.name||"Entity"===this.name||"_temp"===this.name))throw new Error("Entity classes without a name must define `static get key()`");return this.name}},{key:"defaults",get:function(){return Object.prototype.hasOwnProperty.call(this,"__defaults")||(this.__defaults=new this),this.__defaults}}]),e}();if(s.schema={},"production"!==process.env.NODE_ENV){var a=s.fromJS;s.fromJS=function(e){if(void 0===this.prototype.pk)throw new Error("cannot construct on abstract types");return a.call(this,e)}}function u(e){return null!==e&&void 0!==e.pk}var c=Symbol("ENTITY WAS DELETED");function f(e,t){return(f=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}function l(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,f(e,t)}function h(e){return(h=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function p(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function d(e,t,n){return(d=p()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&f(i,n.prototype),i}).apply(null,arguments)}function y(e){var t="function"==typeof Map?new Map:void 0;return(y=function(e){if(null===e||(n=e,-1===Function.toString.call(n).indexOf("[native code]")))return e;var n;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return d(e,arguments,h(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),f(r,e)})(e)}var m=function(){this.children=new WeakMap},v=function(e){function t(){for(var t,n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];return(t=e.call.apply(e,[this].concat(r))||this).message="Keys must include at least one member",t}return l(t,e),t}(y(Error)),g=function(){function e(){this.first=new WeakMap}var t=e.prototype;return t.delete=function(e){var t=this.traverse(e);return null==t||delete t.value,!!t},t.get=function(e){var t=this.traverse(e);return null==t?void 0:t.value},t.has=function(e){var t=this.traverse(e);return!!t&&Object.prototype.hasOwnProperty.call(t,"value")},t.set=function(e,t){if(e.length<1)throw new v;for(var n,r=this.first,i=0;i<e.length;i++)r.has(e[i])?n=r.get(e[i]):(n=new m,r.set(e[i],n)),r=n.children,i===e.length-1&&(n.value=t);return this},t.traverse=function(e){for(var t,n=this.first,r=0;r<e.length;r++){if(!(t=n.get(e[r])))return;n=t.children}return t},e}(),b=function(){function e(e,t){this.schema=void 0,t&&(this._schemaAttribute="string"==typeof t?function(e){return e[t]}:t),this.define(e)}var t=e.prototype;return t.define=function(e){this.schema=e},t.getSchemaAttribute=function(e,t,n){return!this.isSingleSchema&&this._schemaAttribute(e,t,n)},t.inferSchema=function(e,t,n){if(this.isSingleSchema)return this.schema;var r=this.getSchemaAttribute(e,t,n);return this.schema[r]},t.normalizeValue=function(e,t,n,r,i,o){var s=this.inferSchema(e,t,n);if(!s){if("production"!==process.env.NODE_ENV){var a=this.getSchemaAttribute(e,t,n);console.warn("Schema attribute "+JSON.stringify(a,void 0,2)+" is not expected.\nExpected one of: "+Object.keys(this.schema).map((function(e){return'"'+e+'"'})).join(", ")+"\n\nValue: "+JSON.stringify(e,void 0,2))}return e}var u=r(e,t,n,s,i,o);return this.isSingleSchema||null==u?u:{id:u,schema:this.getSchemaAttribute(e,t,n)}},t.denormalizeValue=function(e,t){var n=i(e)?e.get("schema"):e.schema;return this.isSingleSchema||n?t((this.isSingleSchema?void 0:i(e)?e.get("id"):e.id)||e,this.isSingleSchema?this.schema:this.schema[n]):("production"!==process.env.NODE_ENV&&console.warn("TypeError: Unable to infer schema for "+this.constructor.name+"\nValue: "+JSON.stringify(e,void 0,2)+"."),[e,!0,!1])},r(e,[{key:"isSingleSchema",get:function(){return!this._schemaAttribute}}]),e}(),O=function(e){if(Array.isArray(e)&&e.length>1)throw new Error("Expected schema definition to be a single schema, but found "+e.length+".");return e[0]},k=function(e){return Array.isArray(e)?e:Object.keys(e).map((function(t){return e[t]}))},w=function(e){var t=e[0],n=e[2];return void 0!==t&&!n},j=function(e,t,n,r,i,o,s){return e=O(e),k(t).map((function(t,a){return i(t,n,r,e,o,s)}))},E=function(e,t,n){return e=O(e),[t.map?t.map((function(t){return n(t,e)})).filter(w).map((function(e){return e[0]})):t,!0,!1]};function S(e,t,n,r){}var A=function(e){function t(){return e.apply(this,arguments)||this}l(t,e);var n=t.prototype;return n.normalize=function(e,t,n,r,i,o){var s=this;return k(e).map((function(e,a){return s.normalizeValue(e,t,n,r,i,o)})).filter((function(e){return null!=e}))},n.denormalize=function(e,t){var n=this;return[e.map?e.map((function(e){return n.denormalizeValue(e,t)})).filter(w).map((function(e){return e[0]})):e,!0,!1]},n.infer=function(e,t,n){this.schema},t}(b),_=function(e,t,n,r,i,o,s){var a=Object.assign({},t);return Object.keys(e).forEach((function(n){var r=e[n],u=i(t[n],t,n,r,o,s);null==u?delete a[n]:a[n]=u})),a},N=function(e,t,n){if(i(t))return o(e,t,n);var r=Object.assign({},t),s=!0,a=!1;return Object.keys(e).forEach((function(t){var i=n(r[t],e[t]),o=i[0],u=i[1],c=i[2];void 0!==r[t]&&(r[t]=o),c&&(a=!0),u||(s=!1)})),[r,s,a]};function x(e,t,n,r){for(var i={},o=0,s=Object.keys(e);o<s.length;o++){var a=s[o];i[a]=r(e[a],t,n)}return i}var z=function(){function e(e){this.schema=void 0,this.define(e)}var t=e.prototype;return t.define=function(e){this.schema=Object.keys(e).reduce((function(t,n){var r,i=e[n];return Object.assign({},t,((r={})[n]=i,r))}),this.schema||{})},t.normalize=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return _.apply(void 0,[this.schema].concat(t))},t.denormalize=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return N.apply(void 0,[this.schema].concat(t))},t.infer=function(e,t,n){return x(this.schema,e,t,n)},e}(),V=Symbol("draft"),D=function(e,t,n,r,o,s,a,u){var f=r(e,t);if(f===c)return[void 0,!0,!0];if("production"!==process.env.NODE_ENV&&"symbol"==typeof f&&f.toString().includes("DELETED"))throw new Error("Unrecognized symbol detected.\nMake sure you do not have multiple versions of @rest-hooks/normalizr installed.");if("object"!=typeof f||null===f)return[f,!1,!1];var l="string"==typeof e?e:t.pk(i(f)?f.toJS():f);if(void 0===l||""===l)return[f,!1,!1];void 0===o[t.key]&&(o[t.key]=Object.create(null));var h=!0,p=!1;if(o[t.key][l]){if(Object.prototype.hasOwnProperty.call(o[t.key][l],V))return u.i=o[t.key][l].i,[o[t.key][l][V],h,p];a.push(f)}else{var d=a.length;a.push(f);var y=function(e){var t=e.og||e,n=function(e,n){return t(e,n)};return n.og=e,n}(n);y.setLocal=function(e){var n;return o[t.key][l]=((n={})[V]=e,n.i=d,n)};var m=function(e,t,n){e[t.key]||(e[t.key]={});e[t.key][n]||(e[t.key][n]=new g);return e[t.key][n]}(s,t,l),v=t.denormalize(f,y);o[t.key][l]=v[0],h=v[1],p=v[2];var b=a.slice(-1===u.i?d:u.i);m.has(b)?o[t.key][l]=m.get(b):m.set(b,o[t.key][l]),u.i===d&&(u.i=-1)}return[o[t.key][l],h,p]},J=function(e){var t=i(e);return function(n,r){var i,o=r.key;return"object"==typeof n?n:t?e.getIn([o,n]):null==(i=e[o])?void 0:i[n]}},P=function(e,t,n,r,i){if(void 0===r&&(r={}),void 0===i&&(i=new g),void 0===t)return[e,!0,!1,{}];if(void 0===e)return[void 0,!1,!1,{}];var o={},s=function(e,t,n,r){var i=J(e),o=[],s={i:-1};function a(e,n){if(!n)return[e,!0,!1];if(null===e)return[e,!0,!1];var c="function"==typeof n.denormalize;return c||"function"!=typeof n?void 0===e?[e,!1,!1]:c||"object"!=typeof n?u(n)?D(e,n,a,i,r,t,o,s):c?n.denormalize(e,a):[e,!0,!1]:(Array.isArray(n)?E:N)(n,e,a):e instanceof n||void 0===e?[e,!0,!1]:[new n(e),!0,!1]}return function(e,t){var r=a(e,t);return Object(e)!==e?r:(o.push(e),n.has(o)?[n.get(o),r[1],r[2]]:(n.set(o,r[0]),r))}}(n,r,i,o);return[].concat(s(e,t),[o])};var I=function e(t,n,r,i,o,s){return t&&i?i.normalize&&"function"==typeof i.normalize?"object"!=typeof t?t:i.normalize(t,n,r,e,o,s):"function"==typeof i?new i(t):"object"!=typeof t||"object"!=typeof i?t:(Array.isArray(i)?j:_)(i,t,n,r,e,o,s):t};var M=function(e,n,r,i,o,s){if(void 0===r&&(r={}),void 0===i&&(i={}),void 0===o&&(o={}),void 0===s&&(s={date:Date.now(),expiresAt:1/0,fetchedAt:0}),void 0===n)return{entities:r,indexes:i,result:e,entityMeta:o};var a=function(e){return["object","function"].includes(typeof e)?"object":typeof e}(n);if(null===e||typeof e!==a&&(void 0===n.key||"string"!=typeof e)){if("production"!==process.env.NODE_ENV){throw"string"==typeof e&&function(e){try{return"string"!=typeof JSON.parse(e)}catch(e){return!1}}(e)?new Error('Normalizing a string, but this does match schema.\n\nParsing this input string as JSON worked. This likely indicates fetch function did not parse\nthe JSON. By default, this only happens if "content-type" header includes "json".\nSee https://resthooks.io/docs/guides/custom-networking for more information\n\n Schema: '+JSON.stringify(n,void 0,2)+'\n Input: "'+e+'"'):new Error('Unexpected input given to normalize. Expected type to be "'+a+'", found "'+(null===e?"null":typeof e)+'".\n\n Schema: '+JSON.stringify(n,void 0,2)+'\n Input: "'+e+'"')}throw new Error('Unexpected input given to normalize. Expected type to be "'+a+'", found "'+(null===e?"null":typeof e)+'".')}var u=Object.assign({},r),f=Object.assign({},i),l=Object.assign({},o),h=function(e,n,r,i,o,s){return function(a,u,f){var l=a.key;l in e||(e[l]={},r[l]=Object.assign({},r[l]),o[l]=Object.assign({},o[l]));var h=e[l][f];if(h)e[l][f]=a.merge(h,u);else{var p=a.expiresAt?a.expiresAt(s,u):s.expiresAt,d=r[l][f];if(d){var y,m,v,g,b,O,k=o[l][f],w=!k||(a.useIncoming&&s.fetchedAt?a.useIncoming(k,s,d,u):o[l][f].date<=s.date);e[l][f]=w?typeof u!=typeof d?u:a.merge(d,u):d,o[l][f]={expiresAt:Math.max(p,null==(y=o[l][f])?void 0:y.expiresAt),date:Math.max(s.date,null!=(m=null==(v=o[l][f])?void 0:v.date)?m:0),fetchedAt:Math.max(null!=(g=s.fetchedAt)?g:0,null!=(b=null==(O=o[l][f])?void 0:O.fetchedAt)?b:0)}}else{var j;e[l][f]=u,o[l][f]={expiresAt:p,date:s.date,fetchedAt:null!=(j=s.fetchedAt)?j:s.date}}}if(Array.isArray(a.indexes)){var E=e[l][f];l in n||(n[l]={},i[l]=Object.assign({},i[l]));for(var S,A=t(a.indexes);!(S=A()).done;){var _=S.value;_ in n[l]||(i[l][_]=n[l][_]={});var N=n[l][_];h&&delete N[h[_]],r[l]&&r[l][f]&&r[l][f][_]!==E[_]&&(N[r[l][f][_]]=c),_ in E?N[E[_]]=f:"production"!==process.env.NODE_ENV&&console.warn("Index not found in entity. Indexes must be top-level members of your entity.\nIndex: "+_+"\nEntity: "+JSON.stringify(E,void 0,2))}}r[l][f]=e[l][f]}}({},{},u,f,l,s);return{entities:u,indexes:f,result:I(e,e,void 0,n,h,{}),entityMeta:l}},T=function(e){function t(t,n){if(!n)throw new Error('Expected option "schemaAttribute" not found on UnionSchema.');return e.call(this,t,n)||this}l(t,e);var n=t.prototype;return n.normalize=function(e,t,n,r,i,o){return this.normalizeValue(e,t,n,r,i,o)},n.denormalize=function(e,t){return this.denormalizeValue(e,t)},n.infer=function(e,t,n){if(e[0]){var r=this.getSchemaAttribute(e[0],void 0,""),i=this.schema[r];if(void 0!==i)return{id:n(i,e,t),schema:r}}},t}(b),L=function(e){function t(){return e.apply(this,arguments)||this}l(t,e);var n=t.prototype;return n.normalize=function(e,t,n,r,i,o){var s=this;return Object.keys(e).reduce((function(t,n,a){var u,c=e[n];return null!=c?Object.assign({},t,((u={})[n]=s.normalizeValue(c,e,n,r,i,o),u)):t}),{})},n.denormalize=function(e,t){var n=this,r=!0,i=!1;return[Object.keys(e).reduce((function(o,s){var a,u=e[s],c=n.denormalizeValue(u,t),f=c[0],l=c[1],h=c[2];return l||(r=!1),h&&(i=!0),!l||h?o:Object.assign({},o,((a={})[s]=f,a))}),{}),r,i]},n.infer=function(e,t,n){},t}(b),U=function(){function e(e){if("production"!==process.env.NODE_ENV&&!e)throw new Error('Expected option "entity" not found on DeleteSchema.');this._entity=e}var t=e.prototype;return t.normalize=function(e,t,n,r,i,o){var s=this._entity.process(e,t,n),a=this._entity.pk(s,t,n);if("production"!==process.env.NODE_ENV&&(void 0===a||""===a)){var u,f=new Error("Missing usable primary key when normalizing response.\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n\n Delete(Entity): Delete("+(null!=(u=this._entity.name)?u:this._entity)+")\n Value: "+(e&&JSON.stringify(e,null,2))+"\n ");throw f.status=400,f}return i(this,c,a),a},t.infer=function(e,t,n){},t.denormalize=function(e,t){return t(e,this._entity)},t._denormalizeNullable=function(){return[]},t._normalizeNullable=function(){return[]},t.merge=function(e,t){return t},t.useIncoming=function(e,t,n,r){return e.date<=t.date},r(e,[{key:"key",get:function(){return this._entity.key}}]),e}(),R=Object.freeze({__proto__:null,Union:T,Values:L,Array:A,Object:z,Delete:U});function B(e,t,n){return function(e){return!!e&&"function"==typeof e.infer}(e)?e.infer(t,n,B):"object"==typeof e&&e?(Array.isArray(e)?S:x)(e,t,n,B):e}export{c as DELETED,s as Entity,g as WeakListMap,P as denormalize,B as inferResults,u as isEntity,M as normalize,R as schema}; | ||
function e(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function t(e,t){return e(t={exports:{}},t.exports),t.exports}var n=t((function(e){e.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r},e.exports.__esModule=!0,e.exports.default=e.exports}));e(n);var r=t((function(e){e.exports=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}},e.exports.__esModule=!0,e.exports.default=e.exports}));e(r);var o=e(t((function(e){e.exports=function(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(n)return(n=n.call(e)).next.bind(n);if(Array.isArray(e)||(n=r(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var o=0;return function(){return o>=e.length?{done:!0}:{done:!1,value:e[o++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")},e.exports.__esModule=!0,e.exports.default=e.exports}))),i=e(t((function(e){function t(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}e.exports=function(e,n,r){return n&&t(e.prototype,n),r&&t(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e},e.exports.__esModule=!0,e.exports.default=e.exports})));function s(e){return!("function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}function a(e,t,n){var r=!0,o=!1;return[Object.keys(e).reduce((function(t,i){var s=""+i,a=n(t.get(s),e[s]),u=a[0],c=a[1],f=a[2];return c||(r=!1),f&&(o=!0),t.has(s)?t.set(s,u):t}),t),r,o]}var u=function(){function e(){}return e.toJSON=function(){return{name:this.name,schema:this.schema,key:this.key}},e.pk=function(e,t,n){return this.prototype.pk.call(e,t,n)},e.useIncoming=function(e,t,n,r){return e.fetchedAt<=t.fetchedAt},e.merge=function(e,t){return Object.assign({},e,t)},e.fromJS=function(e){void 0===e&&(e={});var t=new this(e);return Object.assign(t,e),t},e.process=function(e){function t(t,n,r){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}((function(e,t,n){if("production"!==process.env.NODE_ENV&&"silent"!==this.automaticValidation&&Array.isArray(e)){var r="Attempted to initialize "+this.name+" with an array, but named members were expected\n\nThis is likely due to a malformed response.\nTry inspecting the network response or fetch() return value.\nOr use debugging tools: https://resthooks.io/docs/guides/debugging\nLearn more about schemas: https://resthooks.io/docs/api/schema\nIf this is a mistake, you can disable this check by setting static automaticValidation = 'silent'\n\nFirst three members: "+JSON.stringify(e.slice(0,3),null,2);if("warn"!==this.automaticValidation){var o=new Error(r);throw o.status=400,o}console.warn(r)}return Object.assign({},e)})),e.normalize=function(e,t,n,r,o,i){var s=this,a=this.process(e,t,n),u=this.pk(a,t,n);if(void 0!==u&&""!==u){var c=this.key;if(c in i||(i[c]={}),u in i[c]||(i[c][u]=[]),i[c][u].some((function(t){return t===e})))return u;var f=this.validate(a);if(f){var l=new Error(f);throw l.status=400,l}return i[c][u].push(e),Object.keys(this.schema).forEach((function(e){if(Object.prototype.hasOwnProperty.call(a,e)){var t=s.schema[e];a[e]=r(a[e],a,e,t,o,i)}})),o(this,a,u),u}if("production"!==process.env.NODE_ENV){var p=new Error("Missing usable primary key when normalizing response.\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n\n Entity: "+this.name+"\n Value (processed): "+(a&&JSON.stringify(a,null,2))+"\n ");throw p.status=400,p}},e.validate=function(e){if("production"!==process.env.NODE_ENV&&"silent"!==this.automaticValidation){for(var t=new Set(Object.keys(this.defaults)),n=Object.keys(e),r=[],i=[],s=[],a=0,u=n;a<u.length;a++){var c=u[a];t.has(c)?r.push(c):s.push(c)}for(var f,l=o(t);!(f=l()).done;){var p=f.value;r.includes(p)||i.push(p)}if(t.size){var h=Math.max(n.length/2,1)<=s.length&&t.size>Math.max(s.length,2)&&Math.pow(r.length,1.5)/2<=s.length,d=r.length<Math.min(1,t.size/2);if(h||d){var y="",m="substantially different than expected keys";d&&(y+="\n Missing: "+i,m="no matching keys found"),h&&(y+="\n Unexpected keys: "+s,m="a large number of unexpected keys found");var v="Attempted to initialize "+this.name+" with "+m+"\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n If this is a mistake, you can disable this check by setting static automaticValidation = 'silent'\n\n Expected keys:\n Found: "+r+y+"\n Value (processed): "+JSON.stringify(e,null,2);if(!(r.length>=4&&h||"warn"===this.automaticValidation))return v;console.warn(v)}}}if("production"!==process.env.NODE_ENV)for(var g=0,b=Object.keys(this.schema);g<b.length;g++){var O=b[g];if(!Object.prototype.hasOwnProperty.call(e,O)&&!Object.prototype.hasOwnProperty.call(this.defaults,O))return"Schema key is missing in Entity\n\n Be sure all schema members are also part of the entity\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about nesting schemas: https://resthooks.io/docs/guides/nested-response\n\n Entity keys: "+Object.keys(this.defaults)+"\n Schema key(missing): "+O+"\n "}},e.infer=function(e,t,n){if(e[0]){var r=this.pk(e[0],void 0,"");if(void 0!==r&&""!==r)return r;var o=function(e,t){return t?t.find((function(t){return Object.prototype.hasOwnProperty.call(e,t)})):void 0}(e[0],this.indexes);if(o&&t[this.key])return t[this.key][o][e[0][o]]}},e.expiresAt=function(e,t){return e.expiresAt},e.denormalize=function(e,t){var n=this;if(s(e)){if(this.validate(e.toJS()))return[void 0,!1,!0];null==t.setLocal||t.setLocal(e);var r=a(this.schema,e,t),o=r[0],i=r[1],u=r[2];return[this.fromJS(o.toObject()),i,u]}if(this.validate(e))return[void 0,!1,!0];var c=this.fromJS(e);null==t.setLocal||t.setLocal(c);var f=!1;return Object.keys(this.schema).forEach((function(r){var o=n.schema[r],i=Object.prototype.hasOwnProperty.call(e,r)?e[r]:void 0,s=t(i,o),a=s[0];!s[2]||Object.prototype.hasOwnProperty.call(e,r)&&!n.defaults[r]||(f=!0),Object.prototype.hasOwnProperty.call(e,r)&&e[r]!==a&&n.set(c,r,a)})),[c,!0,f]},e.set=function(e,t,n){e[t]=n},i(e,null,[{key:"key",get:function(){if("production"!==process.env.NODE_ENV&&(""===this.name||"Entity"===this.name||"_temp"===this.name))throw new Error("Entity classes without a name must define `static get key()`");return this.name}},{key:"defaults",get:function(){return Object.prototype.hasOwnProperty.call(this,"__defaults")||(this.__defaults=new this),this.__defaults}}]),e}();if(u.schema={},"production"!==process.env.NODE_ENV){var c=u.fromJS;u.fromJS=function(e){if(void 0===this.prototype.pk)throw new Error("cannot construct on abstract types");return c.call(this,e)}}function f(e){return null!==e&&void 0!==e.pk}var l=Symbol("ENTITY WAS DELETED"),p=t((function(e){function t(n,r){return e.exports=t=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},e.exports.__esModule=!0,e.exports.default=e.exports,t(n,r)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}));e(p);var h=e(t((function(e){e.exports=function(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,p(e,t)},e.exports.__esModule=!0,e.exports.default=e.exports}))),d=t((function(e){function t(n){return e.exports=t=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},e.exports.__esModule=!0,e.exports.default=e.exports,t(n)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}));e(d);var y=t((function(e){e.exports=function(e){return-1!==Function.toString.call(e).indexOf("[native code]")},e.exports.__esModule=!0,e.exports.default=e.exports}));e(y);var m=t((function(e){e.exports=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}},e.exports.__esModule=!0,e.exports.default=e.exports}));e(m);var v=t((function(e){function t(n,r,o){return m()?(e.exports=t=Reflect.construct,e.exports.__esModule=!0,e.exports.default=e.exports):(e.exports=t=function(e,t,n){var r=[null];r.push.apply(r,t);var o=new(Function.bind.apply(e,r));return n&&p(o,n.prototype),o},e.exports.__esModule=!0,e.exports.default=e.exports),t.apply(null,arguments)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}));e(v);var g=e(t((function(e){function t(n){var r="function"==typeof Map?new Map:void 0;return e.exports=t=function(e){if(null===e||!y(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==r){if(r.has(e))return r.get(e);r.set(e,t)}function t(){return v(e,arguments,d(this).constructor)}return t.prototype=Object.create(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),p(t,e)},e.exports.__esModule=!0,e.exports.default=e.exports,t(n)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports}))),b=function(){this.children=new WeakMap},O=function(e){function t(){for(var t,n=arguments.length,r=new Array(n),o=0;o<n;o++)r[o]=arguments[o];return(t=e.call.apply(e,[this].concat(r))||this).message="Keys must include at least one member",t}return h(t,e),t}(g(Error)),x=function(){function e(){this.first=new WeakMap}var t=e.prototype;return t.delete=function(e){var t=this.traverse(e);return null==t||delete t.value,!!t},t.get=function(e){var t=this.traverse(e);return null==t?void 0:t.value},t.has=function(e){var t=this.traverse(e);return!!t&&Object.prototype.hasOwnProperty.call(t,"value")},t.set=function(e,t){if(e.length<1)throw new O;for(var n,r=this.first,o=0;o<e.length;o++)r.has(e[o])?n=r.get(e[o]):(n=new b,r.set(e[o],n)),r=n.children,o===e.length-1&&(n.value=t);return this},t.traverse=function(e){for(var t,n=this.first,r=0;r<e.length;r++){if(!(t=n.get(e[r])))return;n=t.children}return t},e}(),k=function(){function e(e,t){this.schema=void 0,t&&(this._schemaAttribute="string"==typeof t?function(e){return e[t]}:t),this.define(e)}var t=e.prototype;return t.define=function(e){this.schema=e},t.getSchemaAttribute=function(e,t,n){return!this.isSingleSchema&&this._schemaAttribute(e,t,n)},t.inferSchema=function(e,t,n){if(this.isSingleSchema)return this.schema;var r=this.getSchemaAttribute(e,t,n);return this.schema[r]},t.normalizeValue=function(e,t,n,r,o,i){var s=this.inferSchema(e,t,n);if(!s){if("production"!==process.env.NODE_ENV){var a=this.getSchemaAttribute(e,t,n);console.warn("Schema attribute "+JSON.stringify(a,void 0,2)+" is not expected.\nExpected one of: "+Object.keys(this.schema).map((function(e){return'"'+e+'"'})).join(", ")+"\n\nValue: "+JSON.stringify(e,void 0,2))}return e}var u=r(e,t,n,s,o,i);return this.isSingleSchema||null==u?u:{id:u,schema:this.getSchemaAttribute(e,t,n)}},t.denormalizeValue=function(e,t){var n=s(e)?e.get("schema"):e.schema;return this.isSingleSchema||n?t((this.isSingleSchema?void 0:s(e)?e.get("id"):e.id)||e,this.isSingleSchema?this.schema:this.schema[n]):("production"!==process.env.NODE_ENV&&console.warn("TypeError: Unable to infer schema for "+this.constructor.name+"\nValue: "+JSON.stringify(e,void 0,2)+"."),[e,!0,!1])},i(e,[{key:"isSingleSchema",get:function(){return!this._schemaAttribute}}]),e}(),w=function(e){if(Array.isArray(e)&&e.length>1)throw new Error("Expected schema definition to be a single schema, but found "+e.length+".");return e[0]},_=function(e){return Array.isArray(e)?e:Object.keys(e).map((function(t){return e[t]}))},j=function(e){var t=e[0],n=e[2];return void 0!==t&&!n},E=function(e,t,n,r,o,i,s){return e=w(e),_(t).map((function(t,a){return o(t,n,r,e,i,s)}))},S=function(e,t,n){return e=w(e),[t.map?t.map((function(t){return n(t,e)})).filter(j).map((function(e){return e[0]})):t,!0,!1]};function A(e,t,n,r){}var N=function(e){function t(){return e.apply(this,arguments)||this}h(t,e);var n=t.prototype;return n.normalize=function(e,t,n,r,o,i){var s=this;return _(e).map((function(e,a){return s.normalizeValue(e,t,n,r,o,i)})).filter((function(e){return null!=e}))},n.denormalize=function(e,t){var n=this;return[e.map?e.map((function(e){return n.denormalizeValue(e,t)})).filter(j).map((function(e){return e[0]})):e,!0,!1]},n.infer=function(e,t,n){this.schema},t}(k),z=function(e,t,n,r,o,i,s){var a=Object.assign({},t);return Object.keys(e).forEach((function(n){var r=e[n],u=o(t[n],t,n,r,i,s);null==u?delete a[n]:a[n]=u})),a},M=function(e,t,n){if(s(t))return a(e,t,n);var r=Object.assign({},t),o=!0,i=!1;return Object.keys(e).forEach((function(t){var s=n(r[t],e[t]),a=s[0],u=s[1],c=s[2];void 0!==r[t]&&(r[t]=a),c&&(i=!0),u||(o=!1)})),[r,o,i]};function V(e,t,n,r){for(var o={},i=0,s=Object.keys(e);i<s.length;i++){var a=s[i];o[a]=r(e[a],t,n)}return o}var D=function(){function e(e){this.schema=void 0,this.define(e)}var t=e.prototype;return t.define=function(e){this.schema=Object.keys(e).reduce((function(t,n){var r,o=e[n];return Object.assign({},t,((r={})[n]=o,r))}),this.schema||{})},t.normalize=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return z.apply(void 0,[this.schema].concat(t))},t.denormalize=function(){for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return M.apply(void 0,[this.schema].concat(t))},t.infer=function(e,t,n){return V(this.schema,e,t,n)},e}(),P=Symbol("draft"),J=function(e,t,n,r,o,i,a,u){var c=r(e,t);if(c===l)return[void 0,!0,!0];if("production"!==process.env.NODE_ENV&&"symbol"==typeof c&&c.toString().includes("DELETED"))throw new Error("Unrecognized symbol detected.\nMake sure you do not have multiple versions of @rest-hooks/normalizr installed.");if("object"!=typeof c||null===c)return[c,!1,!1];var f="string"==typeof e?e:t.pk(s(c)?c.toJS():c);if(void 0===f||""===f)return[c,!1,!1];void 0===o[t.key]&&(o[t.key]=Object.create(null));var p=!0,h=!1;if(o[t.key][f]){if(Object.prototype.hasOwnProperty.call(o[t.key][f],P))return u.i=o[t.key][f].i,[o[t.key][f][P],p,h];a.push(c)}else{var d=a.length;a.push(c);var y=function(e){var t=e.og||e,n=function(e,n){return t(e,n)};return n.og=e,n}(n);y.setLocal=function(e){var n;return o[t.key][f]=((n={})[P]=e,n.i=d,n)};var m=function(e,t,n){e[t.key]||(e[t.key]={});e[t.key][n]||(e[t.key][n]=new x);return e[t.key][n]}(i,t,f),v=t.denormalize(c,y);o[t.key][f]=v[0],p=v[1],h=v[2];var g=a.slice(-1===u.i?d:u.i);m.has(g)?o[t.key][f]=m.get(g):m.set(g,o[t.key][f]),u.i===d&&(u.i=-1)}return[o[t.key][f],p,h]},I=function(e){var t=s(e);return function(n,r){var o,i=r.key;return"object"==typeof n?n:t?e.getIn([i,n]):null==(o=e[i])?void 0:o[n]}},T=function(e,t,n,r,o){if(void 0===r&&(r={}),void 0===o&&(o=new x),void 0===t)return[e,!0,!1,{}];if(void 0===e)return[void 0,!1,!1,{}];var i={},s=function(e,t,n,r){var o=I(e),i=[],s={i:-1};function a(e,n){if(!n)return[e,!0,!1];if(null===e)return[e,!0,!1];var u="function"==typeof n.denormalize;return u||"function"!=typeof n?void 0===e?[e,!1,!1]:u||"object"!=typeof n?f(n)?J(e,n,a,o,r,t,i,s):u?n.denormalize(e,a):[e,!0,!1]:(Array.isArray(n)?S:M)(n,e,a):e instanceof n||void 0===e?[e,!0,!1]:[new n(e),!0,!1]}return function(e,t){var r=a(e,t);return Object(e)!==e?r:(i.push(e),n.has(i)?[n.get(i),r[1],r[2]]:(n.set(i,r[0]),r))}}(n,r,o,i);return[].concat(s(e,t),[i])};var L=function e(t,n,r,o,i,s){return t&&o?o.normalize&&"function"==typeof o.normalize?"object"!=typeof t?t:o.normalize(t,n,r,e,i,s):"function"==typeof o?new o(t):"object"!=typeof t||"object"!=typeof o?t:(Array.isArray(o)?E:z)(o,t,n,r,e,i,s):t};var U=function(e,t,n,r,i,s){if(void 0===n&&(n={}),void 0===r&&(r={}),void 0===i&&(i={}),void 0===s&&(s={date:Date.now(),expiresAt:1/0,fetchedAt:0}),void 0===t)return{entities:n,indexes:r,result:e,entityMeta:i};var a=function(e){return["object","function"].includes(typeof e)?"object":typeof e}(t);if(null===e||typeof e!==a&&(void 0===t.key||"string"!=typeof e)){if("production"!==process.env.NODE_ENV){throw"string"==typeof e&&function(e){try{return"string"!=typeof JSON.parse(e)}catch(e){return!1}}(e)?new Error('Normalizing a string, but this does match schema.\n\nParsing this input string as JSON worked. This likely indicates fetch function did not parse\nthe JSON. By default, this only happens if "content-type" header includes "json".\nSee https://resthooks.io/docs/guides/custom-networking for more information\n\n Schema: '+JSON.stringify(t,void 0,2)+'\n Input: "'+e+'"'):new Error('Unexpected input given to normalize. Expected type to be "'+a+'", found "'+(null===e?"null":typeof e)+'".\n\n Schema: '+JSON.stringify(t,void 0,2)+'\n Input: "'+e+'"')}throw new Error('Unexpected input given to normalize. Expected type to be "'+a+'", found "'+(null===e?"null":typeof e)+'".')}var u=Object.assign({},n),c=Object.assign({},r),f=Object.assign({},i),p=function(e,t,n,r,i,s){return function(a,u,c){var f=a.key;f in e||(e[f]={},n[f]=Object.assign({},n[f]),i[f]=Object.assign({},i[f]));var p=e[f][c];if(p)e[f][c]=a.merge(p,u);else{var h=a.expiresAt?a.expiresAt(s,u):s.expiresAt,d=n[f][c];if(d){var y,m,v,g,b,O,x=i[f][c],k=!x||(a.useIncoming&&s.fetchedAt?a.useIncoming(x,s,d,u):i[f][c].date<=s.date);e[f][c]=k?typeof u!=typeof d?u:a.merge(d,u):d,i[f][c]={expiresAt:Math.max(h,null==(y=i[f][c])?void 0:y.expiresAt),date:Math.max(s.date,null!=(m=null==(v=i[f][c])?void 0:v.date)?m:0),fetchedAt:Math.max(null!=(g=s.fetchedAt)?g:0,null!=(b=null==(O=i[f][c])?void 0:O.fetchedAt)?b:0)}}else{var w;e[f][c]=u,i[f][c]={expiresAt:h,date:s.date,fetchedAt:null!=(w=s.fetchedAt)?w:s.date}}}if(Array.isArray(a.indexes)){var _=e[f][c];f in t||(t[f]={},r[f]=Object.assign({},r[f]));for(var j,E=o(a.indexes);!(j=E()).done;){var S=j.value;S in t[f]||(r[f][S]=t[f][S]={});var A=t[f][S];p&&delete A[p[S]],n[f]&&n[f][c]&&n[f][c][S]!==_[S]&&(A[n[f][c][S]]=l),S in _?A[_[S]]=c:"production"!==process.env.NODE_ENV&&console.warn("Index not found in entity. Indexes must be top-level members of your entity.\nIndex: "+S+"\nEntity: "+JSON.stringify(_,void 0,2))}}n[f][c]=e[f][c]}}({},{},u,c,f,s);return{entities:u,indexes:c,result:L(e,e,void 0,t,p,{}),entityMeta:f}},R=function(e){function t(t,n){if(!n)throw new Error('Expected option "schemaAttribute" not found on UnionSchema.');return e.call(this,t,n)||this}h(t,e);var n=t.prototype;return n.normalize=function(e,t,n,r,o,i){return this.normalizeValue(e,t,n,r,o,i)},n.denormalize=function(e,t){return this.denormalizeValue(e,t)},n.infer=function(e,t,n){if(e[0]){var r=this.getSchemaAttribute(e[0],void 0,""),o=this.schema[r];if(void 0!==o)return{id:n(o,e,t),schema:r}}},t}(k),B=function(e){function t(){return e.apply(this,arguments)||this}h(t,e);var n=t.prototype;return n.normalize=function(e,t,n,r,o,i){var s=this;return Object.keys(e).reduce((function(t,n,a){var u,c=e[n];return null!=c?Object.assign({},t,((u={})[n]=s.normalizeValue(c,e,n,r,o,i),u)):t}),{})},n.denormalize=function(e,t){var n=this,r=!0,o=!1;return[Object.keys(e).reduce((function(i,s){var a,u=e[s],c=n.denormalizeValue(u,t),f=c[0],l=c[1],p=c[2];return l||(r=!1),p&&(o=!0),!l||p?i:Object.assign({},i,((a={})[s]=f,a))}),{}),r,o]},n.infer=function(e,t,n){},t}(k),F=function(){function e(e){if("production"!==process.env.NODE_ENV&&!e)throw new Error('Expected option "entity" not found on DeleteSchema.');this._entity=e}var t=e.prototype;return t.normalize=function(e,t,n,r,o,i){var s=this._entity.process(e,t,n),a=this._entity.pk(s,t,n);if("production"!==process.env.NODE_ENV&&(void 0===a||""===a)){var u,c=new Error("Missing usable primary key when normalizing response.\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n\n Delete(Entity): Delete("+(null!=(u=this._entity.name)?u:this._entity)+")\n Value: "+(e&&JSON.stringify(e,null,2))+"\n ");throw c.status=400,c}return o(this,l,a),a},t.infer=function(e,t,n){},t.denormalize=function(e,t){return t(e,this._entity)},t._denormalizeNullable=function(){return[]},t._normalizeNullable=function(){return[]},t.merge=function(e,t){return t},t.useIncoming=function(e,t,n,r){return e.date<=t.date},i(e,[{key:"key",get:function(){return this._entity.key}}]),e}(),W=Object.freeze({__proto__:null,Union:R,Values:B,Array:N,Object:D,Delete:F});function C(e,t,n){return function(e){return!!e&&"function"==typeof e.infer}(e)?e.infer(t,n,C):"object"==typeof e&&e?(Array.isArray(e)?A:V)(e,t,n,C):e}export{l as DELETED,u as Entity,x as WeakListMap,T as denormalize,C as inferResults,f as isEntity,U as normalize,W as schema}; |
(function (global, factory) { | ||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : | ||
typeof define === 'function' && define.amd ? define(['exports'], factory) : | ||
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.rest_hooks_normalizr = {})); | ||
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : | ||
typeof define === 'function' && define.amd ? define(['exports'], factory) : | ||
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.rest_hooks_normalizr = {})); | ||
})(this, (function (exports) { 'use strict'; | ||
function _arrayLikeToArray(arr, len) { | ||
if (len == null || len > arr.length) len = arr.length; | ||
function unwrapExports (x) { | ||
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; | ||
} | ||
for (var i = 0, arr2 = new Array(len); i < len; i++) { | ||
arr2[i] = arr[i]; | ||
} | ||
function createCommonjsModule(fn, module) { | ||
return module = { exports: {} }, fn(module, module.exports), module.exports; | ||
} | ||
return arr2; | ||
} | ||
var arrayLikeToArray = createCommonjsModule(function (module) { | ||
function _arrayLikeToArray(arr, len) { | ||
if (len == null || len > arr.length) len = arr.length; | ||
function _unsupportedIterableToArray(o, minLen) { | ||
if (!o) return; | ||
if (typeof o === "string") return _arrayLikeToArray(o, minLen); | ||
var n = Object.prototype.toString.call(o).slice(8, -1); | ||
if (n === "Object" && o.constructor) n = o.constructor.name; | ||
if (n === "Map" || n === "Set") return Array.from(o); | ||
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); | ||
} | ||
for (var i = 0, arr2 = new Array(len); i < len; i++) { | ||
arr2[i] = arr[i]; | ||
} | ||
function _createForOfIteratorHelperLoose(o, allowArrayLike) { | ||
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; | ||
if (it) return (it = it.call(o)).next.bind(it); | ||
return arr2; | ||
} | ||
if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { | ||
if (it) o = it; | ||
var i = 0; | ||
return function () { | ||
if (i >= o.length) return { | ||
done: true | ||
}; | ||
return { | ||
done: false, | ||
value: o[i++] | ||
}; | ||
}; | ||
} | ||
module.exports = _arrayLikeToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); | ||
} | ||
unwrapExports(arrayLikeToArray); | ||
function _defineProperties(target, props) { | ||
for (var i = 0; i < props.length; i++) { | ||
var descriptor = props[i]; | ||
descriptor.enumerable = descriptor.enumerable || false; | ||
descriptor.configurable = true; | ||
if ("value" in descriptor) descriptor.writable = true; | ||
Object.defineProperty(target, descriptor.key, descriptor); | ||
} | ||
} | ||
var unsupportedIterableToArray = createCommonjsModule(function (module) { | ||
function _unsupportedIterableToArray(o, minLen) { | ||
if (!o) return; | ||
if (typeof o === "string") return arrayLikeToArray(o, minLen); | ||
var n = Object.prototype.toString.call(o).slice(8, -1); | ||
if (n === "Object" && o.constructor) n = o.constructor.name; | ||
if (n === "Map" || n === "Set") return Array.from(o); | ||
if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return arrayLikeToArray(o, minLen); | ||
} | ||
function _createClass(Constructor, protoProps, staticProps) { | ||
if (protoProps) _defineProperties(Constructor.prototype, protoProps); | ||
if (staticProps) _defineProperties(Constructor, staticProps); | ||
Object.defineProperty(Constructor, "prototype", { | ||
writable: false | ||
}); | ||
return Constructor; | ||
} | ||
module.exports = _unsupportedIterableToArray, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
/** | ||
* Helpers to enable Immutable compatibility *without* bringing in | ||
* the 'immutable' package as a dependency. | ||
*/ | ||
unwrapExports(unsupportedIterableToArray); | ||
/** | ||
* Check if an object is immutable by checking if it has a key specific | ||
* to the immutable library. | ||
* | ||
* @param {any} object | ||
* @return {bool} | ||
*/ | ||
// eslint-disable-next-line @typescript-eslint/ban-types | ||
function isImmutable(object) { | ||
return !!(typeof object.hasOwnProperty === 'function' && (Object.hasOwnProperty.call(object, '__ownerID') || // Immutable.Map | ||
object._map && Object.hasOwnProperty.call(object._map, '__ownerID'))); // Immutable.Record | ||
} | ||
/** | ||
* Denormalize an immutable entity. | ||
* | ||
* @param {Schema} schema | ||
* @param {Immutable.Map|Immutable.Record} input | ||
* @param {function} unvisit | ||
* @param {function} getDenormalizedEntity | ||
* @return {Immutable.Map|Immutable.Record} | ||
*/ | ||
var createForOfIteratorHelperLoose = createCommonjsModule(function (module) { | ||
function _createForOfIteratorHelperLoose(o, allowArrayLike) { | ||
var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; | ||
if (it) return (it = it.call(o)).next.bind(it); | ||
function denormalizeImmutable(schema, input, unvisit) { | ||
var found = true; | ||
var deleted = false; | ||
return [Object.keys(schema).reduce(function (object, key) { | ||
// Immutable maps cast keys to strings on write so we need to ensure | ||
// we're accessing them using string keys. | ||
var stringKey = "" + key; | ||
if (Array.isArray(o) || (it = unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { | ||
if (it) o = it; | ||
var i = 0; | ||
return function () { | ||
if (i >= o.length) return { | ||
done: true | ||
}; | ||
return { | ||
done: false, | ||
value: o[i++] | ||
}; | ||
}; | ||
} | ||
var _unvisit = unvisit(object.get(stringKey), schema[stringKey]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1], | ||
deletedItem = _unvisit[2]; | ||
throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); | ||
} | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
module.exports = _createForOfIteratorHelperLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
if (deletedItem) { | ||
deleted = true; | ||
} | ||
var _createForOfIteratorHelperLoose = unwrapExports(createForOfIteratorHelperLoose); | ||
if (object.has(stringKey)) { | ||
return object.set(stringKey, item); | ||
} else { | ||
return object; | ||
} | ||
}, input), found, deleted]; | ||
} | ||
var createClass = createCommonjsModule(function (module) { | ||
function _defineProperties(target, props) { | ||
for (var i = 0; i < props.length; i++) { | ||
var descriptor = props[i]; | ||
descriptor.enumerable = descriptor.enumerable || false; | ||
descriptor.configurable = true; | ||
if ("value" in descriptor) descriptor.writable = true; | ||
Object.defineProperty(target, descriptor.key, descriptor); | ||
} | ||
} | ||
/** | ||
* Represents data that should be deduped by specifying a primary key. | ||
* @see https://resthooks.io/docs/api/Entity | ||
*/ | ||
function _createClass(Constructor, protoProps, staticProps) { | ||
if (protoProps) _defineProperties(Constructor.prototype, protoProps); | ||
if (staticProps) _defineProperties(Constructor, staticProps); | ||
Object.defineProperty(Constructor, "prototype", { | ||
writable: false | ||
}); | ||
return Constructor; | ||
} | ||
var Entity = /*#__PURE__*/function () { | ||
function Entity() {} | ||
module.exports = _createClass, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
Entity.toJSON = function toJSON() { | ||
return { | ||
name: this.name, | ||
schema: this.schema, | ||
key: this.key | ||
}; | ||
} | ||
/** Defines nested entities */ | ||
var _createClass = unwrapExports(createClass); | ||
/** Returns the globally unique identifier for the static Entity */ | ||
; | ||
/** | ||
* Helpers to enable Immutable compatibility *without* bringing in | ||
* the 'immutable' package as a dependency. | ||
*/ | ||
/** Defines indexes to enable lookup by */ | ||
/** | ||
* Check if an object is immutable by checking if it has a key specific | ||
* to the immutable library. | ||
* | ||
* @param {any} object | ||
* @return {bool} | ||
*/ | ||
// eslint-disable-next-line @typescript-eslint/ban-types | ||
function isImmutable(object) { | ||
return !!(typeof object.hasOwnProperty === 'function' && (Object.hasOwnProperty.call(object, '__ownerID') || // Immutable.Map | ||
object._map && Object.hasOwnProperty.call(object._map, '__ownerID'))); // Immutable.Record | ||
} | ||
/** | ||
* Denormalize an immutable entity. | ||
* | ||
* @param {Schema} schema | ||
* @param {Immutable.Map|Immutable.Record} input | ||
* @param {function} unvisit | ||
* @param {function} getDenormalizedEntity | ||
* @return {Immutable.Map|Immutable.Record} | ||
*/ | ||
/** | ||
* A unique identifier for each Entity | ||
* | ||
* @param [value] POJO of the entity or subset used | ||
* @param [parent] When normalizing, the object which included the entity | ||
* @param [key] When normalizing, the key where this entity was found | ||
*/ | ||
Entity.pk = function pk(value, parent, key) { | ||
return this.prototype.pk.call(value, parent, key); | ||
} | ||
/** Return true to merge incoming data; false keeps existing entity */ | ||
; | ||
function denormalizeImmutable(schema, input, unvisit) { | ||
var found = true; | ||
var deleted = false; | ||
return [Object.keys(schema).reduce(function (object, key) { | ||
// Immutable maps cast keys to strings on write so we need to ensure | ||
// we're accessing them using string keys. | ||
var stringKey = "" + key; | ||
Entity.useIncoming = function useIncoming(existingMeta, incomingMeta, existing, incoming) { | ||
return existingMeta.fetchedAt <= incomingMeta.fetchedAt; | ||
} | ||
/** Creates new instance copying over defined values of arguments */ | ||
; | ||
var _unvisit = unvisit(object.get(stringKey), schema[stringKey]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1], | ||
deletedItem = _unvisit[2]; | ||
Entity.merge = function merge(existing, incoming) { | ||
return Object.assign({}, existing, incoming); | ||
} | ||
/** Factory method to convert from Plain JS Objects. | ||
* | ||
* @param [props] Plain Object of properties to assign. | ||
* @param [parent] When normalizing, the object which included the record | ||
* @param [key] When normalizing, the key where this record was found | ||
*/ | ||
; | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
Entity.fromJS = function fromJS( // TODO: this should only accept members that are not functions | ||
props) { | ||
if (props === void 0) { | ||
props = {}; | ||
} | ||
if (deletedItem) { | ||
deleted = true; | ||
} | ||
// we type guarded abstract case above, so ok to force typescript to allow constructor call | ||
var instance = new this(props); // we can't rely on constructors and override the defaults provided as property assignments | ||
// all occur after the constructor | ||
if (object.has(stringKey)) { | ||
return object.set(stringKey, item); | ||
} else { | ||
return object; | ||
} | ||
}, input), found, deleted]; | ||
} | ||
Object.assign(instance, props); | ||
return instance; | ||
} | ||
/** Do any transformations when first receiving input */ | ||
; | ||
/** | ||
* Represents data that should be deduped by specifying a primary key. | ||
* @see https://resthooks.io/docs/api/Entity | ||
*/ | ||
Entity.process = function (_process) { | ||
function process(_x, _x2, _x3) { | ||
return _process.apply(this, arguments); | ||
} | ||
var Entity = /*#__PURE__*/function () { | ||
function Entity() {} | ||
process.toString = function () { | ||
return _process.toString(); | ||
}; | ||
Entity.toJSON = function toJSON() { | ||
return { | ||
name: this.name, | ||
schema: this.schema, | ||
key: this.key | ||
}; | ||
} | ||
/** Defines nested entities */ | ||
return process; | ||
}(function (input, parent, key) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production' && this.automaticValidation !== 'silent') { | ||
if (Array.isArray(input)) { | ||
var errorMessage = "Attempted to initialize " + this.name + " with an array, but named members were expected\n\nThis is likely due to a malformed response.\nTry inspecting the network response or fetch() return value.\nOr use debugging tools: https://resthooks.io/docs/guides/debugging\nLearn more about schemas: https://resthooks.io/docs/api/schema\nIf this is a mistake, you can disable this check by setting static automaticValidation = 'silent'\n\nFirst three members: " + JSON.stringify(input.slice(0, 3), null, 2); | ||
/** Returns the globally unique identifier for the static Entity */ | ||
; | ||
if (this.automaticValidation !== 'warn') { | ||
var error = new Error(errorMessage); | ||
error.status = 400; | ||
throw error; | ||
} | ||
/** Defines indexes to enable lookup by */ | ||
console.warn(errorMessage); | ||
} | ||
} | ||
/** | ||
* A unique identifier for each Entity | ||
* | ||
* @param [value] POJO of the entity or subset used | ||
* @param [parent] When normalizing, the object which included the entity | ||
* @param [key] When normalizing, the key where this entity was found | ||
*/ | ||
Entity.pk = function pk(value, parent, key) { | ||
return this.prototype.pk.call(value, parent, key); | ||
} | ||
/** Return true to merge incoming data; false keeps existing entity */ | ||
; | ||
return Object.assign({}, input); | ||
}); | ||
Entity.useIncoming = function useIncoming(existingMeta, incomingMeta, existing, incoming) { | ||
return existingMeta.fetchedAt <= incomingMeta.fetchedAt; | ||
} | ||
/** Creates new instance copying over defined values of arguments */ | ||
; | ||
Entity.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
Entity.merge = function merge(existing, incoming) { | ||
return Object.assign({}, existing, incoming); | ||
} | ||
/** Factory method to convert from Plain JS Objects. | ||
* | ||
* @param [props] Plain Object of properties to assign. | ||
* @param [parent] When normalizing, the object which included the record | ||
* @param [key] When normalizing, the key where this record was found | ||
*/ | ||
; | ||
var processedEntity = this.process(input, parent, key); | ||
var id = this.pk(processedEntity, parent, key); | ||
Entity.fromJS = function fromJS( // TODO: this should only accept members that are not functions | ||
props) { | ||
if (props === void 0) { | ||
props = {}; | ||
} | ||
if (id === undefined || id === '') { | ||
if (process.env.NODE_ENV !== 'production') { | ||
var error = new Error("Missing usable primary key when normalizing response.\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n\n Entity: " + this.name + "\n Value (processed): " + (processedEntity && JSON.stringify(processedEntity, null, 2)) + "\n "); | ||
error.status = 400; | ||
throw error; | ||
} else { | ||
// these make the keys get deleted | ||
return undefined; | ||
} | ||
} | ||
// we type guarded abstract case above, so ok to force typescript to allow constructor call | ||
var instance = new this(props); // we can't rely on constructors and override the defaults provided as property assignments | ||
// all occur after the constructor | ||
var entityType = this.key; | ||
Object.assign(instance, props); | ||
return instance; | ||
} | ||
/** Do any transformations when first receiving input */ | ||
; | ||
if (!(entityType in visitedEntities)) { | ||
visitedEntities[entityType] = {}; | ||
} | ||
Entity.process = function (_process) { | ||
function process(_x, _x2, _x3) { | ||
return _process.apply(this, arguments); | ||
} | ||
if (!(id in visitedEntities[entityType])) { | ||
visitedEntities[entityType][id] = []; | ||
} | ||
process.toString = function () { | ||
return _process.toString(); | ||
}; | ||
if (visitedEntities[entityType][id].some(function (entity) { | ||
return entity === input; | ||
})) { | ||
return id; | ||
} | ||
return process; | ||
}(function (input, parent, key) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production' && this.automaticValidation !== 'silent') { | ||
if (Array.isArray(input)) { | ||
var errorMessage = "Attempted to initialize " + this.name + " with an array, but named members were expected\n\nThis is likely due to a malformed response.\nTry inspecting the network response or fetch() return value.\nOr use debugging tools: https://resthooks.io/docs/guides/debugging\nLearn more about schemas: https://resthooks.io/docs/api/schema\nIf this is a mistake, you can disable this check by setting static automaticValidation = 'silent'\n\nFirst three members: " + JSON.stringify(input.slice(0, 3), null, 2); | ||
var errorMessage = this.validate(processedEntity); | ||
if (this.automaticValidation !== 'warn') { | ||
var error = new Error(errorMessage); | ||
error.status = 400; | ||
throw error; | ||
} | ||
if (errorMessage) { | ||
var _error = new Error(errorMessage); | ||
console.warn(errorMessage); | ||
} | ||
} | ||
_error.status = 400; | ||
throw _error; | ||
} | ||
return Object.assign({}, input); | ||
}); | ||
visitedEntities[entityType][id].push(input); | ||
Object.keys(this.schema).forEach(function (key) { | ||
if (Object.prototype.hasOwnProperty.call(processedEntity, key)) { | ||
var schema = _this.schema[key]; | ||
processedEntity[key] = visit(processedEntity[key], processedEntity, key, schema, addEntity, visitedEntities); | ||
} | ||
}); | ||
addEntity(this, processedEntity, id); | ||
return id; | ||
}; | ||
Entity.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
Entity.validate = function validate(processedEntity) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production' && this.automaticValidation !== 'silent') { | ||
var keysOfRecord = new Set(Object.keys(this.defaults)); | ||
var keysOfProps = Object.keys(processedEntity); | ||
var found = [], | ||
missing = [], | ||
unexpected = []; | ||
var processedEntity = this.process(input, parent, key); | ||
var id = this.pk(processedEntity, parent, key); | ||
for (var _i = 0, _keysOfProps = keysOfProps; _i < _keysOfProps.length; _i++) { | ||
var keyOfProps = _keysOfProps[_i]; | ||
if (id === undefined || id === '') { | ||
if (process.env.NODE_ENV !== 'production') { | ||
var error = new Error("Missing usable primary key when normalizing response.\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n\n Entity: " + this.name + "\n Value (processed): " + (processedEntity && JSON.stringify(processedEntity, null, 2)) + "\n "); | ||
error.status = 400; | ||
throw error; | ||
} else { | ||
// these make the keys get deleted | ||
return undefined; | ||
} | ||
} | ||
if (keysOfRecord.has(keyOfProps)) { | ||
found.push(keyOfProps); | ||
} else { | ||
unexpected.push(keyOfProps); | ||
} | ||
} | ||
var entityType = this.key; | ||
for (var _iterator = _createForOfIteratorHelperLoose(keysOfRecord), _step; !(_step = _iterator()).done;) { | ||
var keyOfRecord = _step.value; | ||
if (!(entityType in visitedEntities)) { | ||
visitedEntities[entityType] = {}; | ||
} | ||
if (!found.includes(keyOfRecord)) { | ||
missing.push(keyOfRecord); | ||
} | ||
} // only bother with this if they used *any* defaults | ||
if (!(id in visitedEntities[entityType])) { | ||
visitedEntities[entityType][id] = []; | ||
} | ||
if (visitedEntities[entityType][id].some(function (entity) { | ||
return entity === input; | ||
})) { | ||
return id; | ||
} | ||
if (keysOfRecord.size) { | ||
var tooManyUnexpected = // unexpected compared to members in response | ||
Math.max(keysOfProps.length / 2, 1) <= unexpected.length && // unexpected compared to what we specified | ||
keysOfRecord.size > Math.max(unexpected.length, 2) && // as we find more and more be more easily assured it is correct | ||
Math.pow(found.length, 1.5) / 2 <= unexpected.length; | ||
var foundNothing = found.length < Math.min(1, keysOfRecord.size / 2); // if we find nothing (we expect at least one member for a pk) | ||
// or we find too many unexpected members | ||
var errorMessage = this.validate(processedEntity); | ||
if (tooManyUnexpected || foundNothing) { | ||
var extra = ''; | ||
var reason = 'substantially different than expected keys'; | ||
if (errorMessage) { | ||
var _error = new Error(errorMessage); | ||
if (foundNothing) { | ||
extra += "\n Missing: " + missing; | ||
reason = 'no matching keys found'; | ||
} | ||
_error.status = 400; | ||
throw _error; | ||
} | ||
if (tooManyUnexpected) { | ||
extra += "\n Unexpected keys: " + unexpected; | ||
reason = 'a large number of unexpected keys found'; | ||
} | ||
visitedEntities[entityType][id].push(input); | ||
Object.keys(this.schema).forEach(function (key) { | ||
if (Object.prototype.hasOwnProperty.call(processedEntity, key)) { | ||
var schema = _this.schema[key]; | ||
processedEntity[key] = visit(processedEntity[key], processedEntity, key, schema, addEntity, visitedEntities); | ||
} | ||
}); | ||
addEntity(this, processedEntity, id); | ||
return id; | ||
}; | ||
var errorMessage = "Attempted to initialize " + this.name + " with " + reason + "\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n If this is a mistake, you can disable this check by setting static automaticValidation = 'silent'\n\n Expected keys:\n Found: " + found + extra + "\n Value (processed): " + JSON.stringify(processedEntity, null, 2); | ||
Entity.validate = function validate(processedEntity) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production' && this.automaticValidation !== 'silent') { | ||
var keysOfRecord = new Set(Object.keys(this.defaults)); | ||
var keysOfProps = Object.keys(processedEntity); | ||
var found = [], | ||
missing = [], | ||
unexpected = []; | ||
if (found.length >= 4 && tooManyUnexpected || this.automaticValidation === 'warn') { | ||
console.warn(errorMessage); | ||
} else { | ||
return errorMessage; | ||
} | ||
} | ||
} | ||
} | ||
for (var _i = 0, _keysOfProps = keysOfProps; _i < _keysOfProps.length; _i++) { | ||
var keyOfProps = _keysOfProps[_i]; | ||
if (process.env.NODE_ENV !== 'production') { | ||
for (var _i2 = 0, _Object$keys = Object.keys(this.schema); _i2 < _Object$keys.length; _i2++) { | ||
var key = _Object$keys[_i2]; | ||
if (keysOfRecord.has(keyOfProps)) { | ||
found.push(keyOfProps); | ||
} else { | ||
unexpected.push(keyOfProps); | ||
} | ||
} | ||
if (!Object.prototype.hasOwnProperty.call(processedEntity, key)) { | ||
if (!Object.prototype.hasOwnProperty.call(this.defaults, key)) { | ||
return "Schema key is missing in Entity\n\n Be sure all schema members are also part of the entity\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about nesting schemas: https://resthooks.io/docs/guides/nested-response\n\n Entity keys: " + Object.keys(this.defaults) + "\n Schema key(missing): " + key + "\n "; | ||
} | ||
} | ||
} | ||
} | ||
}; | ||
for (var _iterator = _createForOfIteratorHelperLoose(keysOfRecord), _step; !(_step = _iterator()).done;) { | ||
var keyOfRecord = _step.value; | ||
Entity.infer = function infer(args, indexes, recurse) { | ||
if (!args[0]) return undefined; | ||
var id = this.pk(args[0], undefined, ''); // Was able to infer the entity's primary key from params | ||
if (!found.includes(keyOfRecord)) { | ||
missing.push(keyOfRecord); | ||
} | ||
} // only bother with this if they used *any* defaults | ||
if (id !== undefined && id !== '') return id; // now attempt lookup in indexes | ||
var indexName = indexFromParams(args[0], this.indexes); | ||
if (keysOfRecord.size) { | ||
var tooManyUnexpected = // unexpected compared to members in response | ||
Math.max(keysOfProps.length / 2, 1) <= unexpected.length && // unexpected compared to what we specified | ||
keysOfRecord.size > Math.max(unexpected.length, 2) && // as we find more and more be more easily assured it is correct | ||
Math.pow(found.length, 1.5) / 2 <= unexpected.length; | ||
var foundNothing = found.length < Math.min(1, keysOfRecord.size / 2); // if we find nothing (we expect at least one member for a pk) | ||
// or we find too many unexpected members | ||
if (indexName && indexes[this.key]) { | ||
// 'as Record<string, any>': indexName can only be found if params is a string key'd object | ||
var _id = indexes[this.key][indexName][args[0][indexName]]; | ||
return _id; | ||
} | ||
if (tooManyUnexpected || foundNothing) { | ||
var extra = ''; | ||
var reason = 'substantially different than expected keys'; | ||
return undefined; | ||
}; | ||
if (foundNothing) { | ||
extra += "\n Missing: " + missing; | ||
reason = 'no matching keys found'; | ||
} | ||
Entity.expiresAt = function expiresAt(meta, input) { | ||
return meta.expiresAt; | ||
}; | ||
if (tooManyUnexpected) { | ||
extra += "\n Unexpected keys: " + unexpected; | ||
reason = 'a large number of unexpected keys found'; | ||
} | ||
Entity.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
var errorMessage = "Attempted to initialize " + this.name + " with " + reason + "\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n If this is a mistake, you can disable this check by setting static automaticValidation = 'silent'\n\n Expected keys:\n Found: " + found + extra + "\n Value (processed): " + JSON.stringify(processedEntity, null, 2); | ||
if (isImmutable(input)) { | ||
if (this.validate(input.toJS())) return [undefined, false, true]; // Need to set this first so that if it is referenced further within the | ||
// denormalization the reference will already exist. | ||
if (found.length >= 4 && tooManyUnexpected || this.automaticValidation === 'warn') { | ||
console.warn(errorMessage); | ||
} else { | ||
return errorMessage; | ||
} | ||
} | ||
} | ||
} | ||
unvisit.setLocal == null ? void 0 : unvisit.setLocal(input); | ||
if (process.env.NODE_ENV !== 'production') { | ||
for (var _i2 = 0, _Object$keys = Object.keys(this.schema); _i2 < _Object$keys.length; _i2++) { | ||
var key = _Object$keys[_i2]; | ||
var _denormalizeImmutable = denormalizeImmutable(this.schema, input, unvisit), | ||
denormEntity = _denormalizeImmutable[0], | ||
found = _denormalizeImmutable[1], | ||
_deleted = _denormalizeImmutable[2]; | ||
if (!Object.prototype.hasOwnProperty.call(processedEntity, key)) { | ||
if (!Object.prototype.hasOwnProperty.call(this.defaults, key)) { | ||
return "Schema key is missing in Entity\n\n Be sure all schema members are also part of the entity\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about nesting schemas: https://resthooks.io/docs/guides/nested-response\n\n Entity keys: " + Object.keys(this.defaults) + "\n Schema key(missing): " + key + "\n "; | ||
} | ||
} | ||
} | ||
} | ||
}; | ||
return [this.fromJS(denormEntity.toObject()), found, _deleted]; | ||
} | ||
Entity.infer = function infer(args, indexes, recurse) { | ||
if (!args[0]) return undefined; | ||
var id = this.pk(args[0], undefined, ''); // Was able to infer the entity's primary key from params | ||
if (this.validate(input)) { | ||
return [undefined, false, true]; | ||
} | ||
if (id !== undefined && id !== '') return id; // now attempt lookup in indexes | ||
var entityCopy = this.fromJS(input); // Need to set this first so that if it is referenced further within the | ||
// denormalization the reference will already exist. | ||
var indexName = indexFromParams(args[0], this.indexes); | ||
unvisit.setLocal == null ? void 0 : unvisit.setLocal(entityCopy); | ||
var deleted = false; // note: iteration order must be stable | ||
if (indexName && indexes[this.key]) { | ||
// 'as Record<string, any>': indexName can only be found if params is a string key'd object | ||
var _id = indexes[this.key][indexName][args[0][indexName]]; | ||
return _id; | ||
} | ||
Object.keys(this.schema).forEach(function (key) { | ||
var schema = _this2.schema[key]; | ||
var nextInput = Object.prototype.hasOwnProperty.call(input, key) ? input[key] : undefined; | ||
return undefined; | ||
}; | ||
var _unvisit = unvisit(nextInput, schema), | ||
value = _unvisit[0], | ||
deletedItem = _unvisit[2]; | ||
Entity.expiresAt = function expiresAt(meta, input) { | ||
return meta.expiresAt; | ||
}; | ||
if (deletedItem && !(Object.prototype.hasOwnProperty.call(input, key) && !_this2.defaults[key])) { | ||
deleted = true; | ||
} | ||
Entity.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
if (Object.prototype.hasOwnProperty.call(input, key) && input[key] !== value) { | ||
_this2.set(entityCopy, key, value); | ||
} | ||
}); | ||
return [entityCopy, true, deleted]; | ||
} | ||
/** All instance defaults set */ | ||
; | ||
if (isImmutable(input)) { | ||
if (this.validate(input.toJS())) return [undefined, false, true]; // Need to set this first so that if it is referenced further within the | ||
// denormalization the reference will already exist. | ||
/** Used by denormalize to set nested members */ | ||
Entity.set = function set(entity, key, value) { | ||
entity[key] = value; | ||
}; | ||
unvisit.setLocal == null ? void 0 : unvisit.setLocal(input); | ||
_createClass(Entity, null, [{ | ||
key: "key", | ||
get: function get() { | ||
/* istanbul ignore next */ | ||
if (process.env.NODE_ENV !== 'production' && (this.name === '' || this.name === 'Entity' || this.name === '_temp')) throw new Error('Entity classes without a name must define `static get key()`'); | ||
return this.name; | ||
} | ||
}, { | ||
key: "defaults", | ||
get: function get() { | ||
if (!Object.prototype.hasOwnProperty.call(this, '__defaults')) this.__defaults = new this(); | ||
return this.__defaults; | ||
} | ||
}]); | ||
var _denormalizeImmutable = denormalizeImmutable(this.schema, input, unvisit), | ||
denormEntity = _denormalizeImmutable[0], | ||
found = _denormalizeImmutable[1], | ||
_deleted = _denormalizeImmutable[2]; | ||
return Entity; | ||
}(); | ||
Entity.schema = {}; | ||
return [this.fromJS(denormEntity.toObject()), found, _deleted]; | ||
} | ||
if (process.env.NODE_ENV !== 'production') { | ||
var superFrom = Entity.fromJS; // for those not using TypeScript this is a good catch to ensure they are defining | ||
// the abstract members | ||
if (this.validate(input)) { | ||
return [undefined, false, true]; | ||
} | ||
Entity.fromJS = function fromJS(props) { | ||
if (this.prototype.pk === undefined) throw new Error('cannot construct on abstract types'); | ||
return superFrom.call(this, props); | ||
}; | ||
} | ||
var entityCopy = this.fromJS(input); // Need to set this first so that if it is referenced further within the | ||
// denormalization the reference will already exist. | ||
function isEntity(schema) { | ||
return schema !== null && schema.pk !== undefined; | ||
} | ||
unvisit.setLocal == null ? void 0 : unvisit.setLocal(entityCopy); | ||
var deleted = false; // note: iteration order must be stable | ||
function indexFromParams(params, indexes) { | ||
if (!indexes) return undefined; | ||
return indexes.find(function (index) { | ||
return Object.prototype.hasOwnProperty.call(params, index); | ||
}); | ||
} | ||
Object.keys(this.schema).forEach(function (key) { | ||
var schema = _this2.schema[key]; | ||
var nextInput = Object.prototype.hasOwnProperty.call(input, key) ? input[key] : undefined; | ||
var DELETED = Symbol('ENTITY WAS DELETED'); | ||
var _unvisit = unvisit(nextInput, schema), | ||
value = _unvisit[0], | ||
deletedItem = _unvisit[2]; | ||
function _setPrototypeOf(o, p) { | ||
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}; | ||
if (deletedItem && !(Object.prototype.hasOwnProperty.call(input, key) && !_this2.defaults[key])) { | ||
deleted = true; | ||
} | ||
return _setPrototypeOf(o, p); | ||
} | ||
if (Object.prototype.hasOwnProperty.call(input, key) && input[key] !== value) { | ||
_this2.set(entityCopy, key, value); | ||
} | ||
}); | ||
return [entityCopy, true, deleted]; | ||
} | ||
/** All instance defaults set */ | ||
; | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
_setPrototypeOf(subClass, superClass); | ||
} | ||
/** Used by denormalize to set nested members */ | ||
Entity.set = function set(entity, key, value) { | ||
entity[key] = value; | ||
}; | ||
function _getPrototypeOf(o) { | ||
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { | ||
return o.__proto__ || Object.getPrototypeOf(o); | ||
}; | ||
return _getPrototypeOf(o); | ||
} | ||
_createClass(Entity, null, [{ | ||
key: "key", | ||
get: function get() { | ||
/* istanbul ignore next */ | ||
if (process.env.NODE_ENV !== 'production' && (this.name === '' || this.name === 'Entity' || this.name === '_temp')) throw new Error('Entity classes without a name must define `static get key()`'); | ||
return this.name; | ||
} | ||
}, { | ||
key: "defaults", | ||
get: function get() { | ||
if (!Object.prototype.hasOwnProperty.call(this, '__defaults')) this.__defaults = new this(); | ||
return this.__defaults; | ||
} | ||
}]); | ||
function _isNativeFunction(fn) { | ||
return Function.toString.call(fn).indexOf("[native code]") !== -1; | ||
} | ||
return Entity; | ||
}(); | ||
Entity.schema = {}; | ||
function _isNativeReflectConstruct() { | ||
if (typeof Reflect === "undefined" || !Reflect.construct) return false; | ||
if (Reflect.construct.sham) return false; | ||
if (typeof Proxy === "function") return true; | ||
if (process.env.NODE_ENV !== 'production') { | ||
var superFrom = Entity.fromJS; // for those not using TypeScript this is a good catch to ensure they are defining | ||
// the abstract members | ||
try { | ||
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
} | ||
Entity.fromJS = function fromJS(props) { | ||
if (this.prototype.pk === undefined) throw new Error('cannot construct on abstract types'); | ||
return superFrom.call(this, props); | ||
}; | ||
} | ||
function _construct(Parent, args, Class) { | ||
if (_isNativeReflectConstruct()) { | ||
_construct = Reflect.construct; | ||
} else { | ||
_construct = function _construct(Parent, args, Class) { | ||
var a = [null]; | ||
a.push.apply(a, args); | ||
var Constructor = Function.bind.apply(Parent, a); | ||
var instance = new Constructor(); | ||
if (Class) _setPrototypeOf(instance, Class.prototype); | ||
return instance; | ||
}; | ||
} | ||
function isEntity(schema) { | ||
return schema !== null && schema.pk !== undefined; | ||
} | ||
return _construct.apply(null, arguments); | ||
} | ||
function indexFromParams(params, indexes) { | ||
if (!indexes) return undefined; | ||
return indexes.find(function (index) { | ||
return Object.prototype.hasOwnProperty.call(params, index); | ||
}); | ||
} | ||
function _wrapNativeSuper(Class) { | ||
var _cache = typeof Map === "function" ? new Map() : undefined; | ||
var DELETED = Symbol('ENTITY WAS DELETED'); | ||
_wrapNativeSuper = function _wrapNativeSuper(Class) { | ||
if (Class === null || !_isNativeFunction(Class)) return Class; | ||
var setPrototypeOf = createCommonjsModule(function (module) { | ||
function _setPrototypeOf(o, p) { | ||
module.exports = _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { | ||
o.__proto__ = p; | ||
return o; | ||
}, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
return _setPrototypeOf(o, p); | ||
} | ||
if (typeof Class !== "function") { | ||
throw new TypeError("Super expression must either be null or a function"); | ||
} | ||
module.exports = _setPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
if (typeof _cache !== "undefined") { | ||
if (_cache.has(Class)) return _cache.get(Class); | ||
unwrapExports(setPrototypeOf); | ||
_cache.set(Class, Wrapper); | ||
} | ||
var inheritsLoose = createCommonjsModule(function (module) { | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
setPrototypeOf(subClass, superClass); | ||
} | ||
function Wrapper() { | ||
return _construct(Class, arguments, _getPrototypeOf(this).constructor); | ||
} | ||
module.exports = _inheritsLoose, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
Wrapper.prototype = Object.create(Class.prototype, { | ||
constructor: { | ||
value: Wrapper, | ||
enumerable: false, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
return _setPrototypeOf(Wrapper, Class); | ||
}; | ||
var _inheritsLoose = unwrapExports(inheritsLoose); | ||
return _wrapNativeSuper(Class); | ||
} | ||
var getPrototypeOf = createCommonjsModule(function (module) { | ||
function _getPrototypeOf(o) { | ||
module.exports = _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { | ||
return o.__proto__ || Object.getPrototypeOf(o); | ||
}, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
return _getPrototypeOf(o); | ||
} | ||
/** Link in a chain */ | ||
var Link = function Link() { | ||
this.children = new WeakMap(); | ||
}; | ||
module.exports = _getPrototypeOf, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
var KeySize = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(KeySize, _Error); | ||
unwrapExports(getPrototypeOf); | ||
function KeySize() { | ||
var _this; | ||
var isNativeFunction = createCommonjsModule(function (module) { | ||
function _isNativeFunction(fn) { | ||
return Function.toString.call(fn).indexOf("[native code]") !== -1; | ||
} | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
module.exports = _isNativeFunction, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
_this = _Error.call.apply(_Error, [this].concat(args)) || this; | ||
_this.message = 'Keys must include at least one member'; | ||
return _this; | ||
} | ||
unwrapExports(isNativeFunction); | ||
return KeySize; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
/** Maps from a list of objects (referentially) to any value | ||
* | ||
* If *any* members of the list get claned up, so does that key/value pair get removed. | ||
*/ | ||
var isNativeReflectConstruct = createCommonjsModule(function (module) { | ||
function _isNativeReflectConstruct() { | ||
if (typeof Reflect === "undefined" || !Reflect.construct) return false; | ||
if (Reflect.construct.sham) return false; | ||
if (typeof Proxy === "function") return true; | ||
try { | ||
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
} | ||
var WeakListMap = /*#__PURE__*/function () { | ||
function WeakListMap() { | ||
this.first = new WeakMap(); | ||
} | ||
module.exports = _isNativeReflectConstruct, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
var _proto = WeakListMap.prototype; | ||
unwrapExports(isNativeReflectConstruct); | ||
_proto.delete = function _delete(key) { | ||
var link = this.traverse(key); | ||
link == null ? true : delete link.value; | ||
return !!link; | ||
}; | ||
var construct = createCommonjsModule(function (module) { | ||
function _construct(Parent, args, Class) { | ||
if (isNativeReflectConstruct()) { | ||
module.exports = _construct = Reflect.construct, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
} else { | ||
module.exports = _construct = function _construct(Parent, args, Class) { | ||
var a = [null]; | ||
a.push.apply(a, args); | ||
var Constructor = Function.bind.apply(Parent, a); | ||
var instance = new Constructor(); | ||
if (Class) setPrototypeOf(instance, Class.prototype); | ||
return instance; | ||
}, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
} | ||
_proto.get = function get(key) { | ||
var link = this.traverse(key); | ||
return link == null ? void 0 : link.value; | ||
}; | ||
return _construct.apply(null, arguments); | ||
} | ||
_proto.has = function has(key) { | ||
var link = this.traverse(key); | ||
if (!link) return false; | ||
return Object.prototype.hasOwnProperty.call(link, 'value'); | ||
}; | ||
module.exports = _construct, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
_proto.set = function set(key, value) { | ||
if (key.length < 1) throw new KeySize(); | ||
var cur = this.first; | ||
var link; | ||
unwrapExports(construct); | ||
for (var i = 0; i < key.length; i++) { | ||
if (!cur.has(key[i])) { | ||
link = new Link(); | ||
cur.set(key[i], link); | ||
} else { | ||
link = cur.get(key[i]); | ||
} | ||
var wrapNativeSuper = createCommonjsModule(function (module) { | ||
function _wrapNativeSuper(Class) { | ||
var _cache = typeof Map === "function" ? new Map() : undefined; | ||
cur = link.children; // do on later iteration of loop. this makes typescript happy rather than putting after loop | ||
module.exports = _wrapNativeSuper = function _wrapNativeSuper(Class) { | ||
if (Class === null || !isNativeFunction(Class)) return Class; | ||
if (i === key.length - 1) { | ||
link.value = value; | ||
} | ||
} | ||
if (typeof Class !== "function") { | ||
throw new TypeError("Super expression must either be null or a function"); | ||
} | ||
return this; | ||
}; | ||
if (typeof _cache !== "undefined") { | ||
if (_cache.has(Class)) return _cache.get(Class); | ||
_proto.traverse = function traverse(key) { | ||
var cur = this.first; | ||
var link; | ||
_cache.set(Class, Wrapper); | ||
} | ||
for (var i = 0; i < key.length; i++) { | ||
link = cur.get(key[i]); | ||
if (!link) return; | ||
cur = link.children; | ||
} | ||
function Wrapper() { | ||
return construct(Class, arguments, getPrototypeOf(this).constructor); | ||
} | ||
return link; | ||
}; | ||
Wrapper.prototype = Object.create(Class.prototype, { | ||
constructor: { | ||
value: Wrapper, | ||
enumerable: false, | ||
writable: true, | ||
configurable: true | ||
} | ||
}); | ||
return setPrototypeOf(Wrapper, Class); | ||
}, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
return _wrapNativeSuper(Class); | ||
} | ||
return WeakListMap; | ||
}(); | ||
module.exports = _wrapNativeSuper, module.exports.__esModule = true, module.exports["default"] = module.exports; | ||
}); | ||
var PolymorphicSchema = /*#__PURE__*/function () { | ||
function PolymorphicSchema(definition, schemaAttribute) { | ||
this.schema = void 0; | ||
var _wrapNativeSuper = unwrapExports(wrapNativeSuper); | ||
if (schemaAttribute) { | ||
this._schemaAttribute = typeof schemaAttribute === 'string' ? function (input) { | ||
return input[schemaAttribute]; | ||
} : schemaAttribute; | ||
} | ||
/** Link in a chain */ | ||
var Link = function Link() { | ||
this.children = new WeakMap(); | ||
}; | ||
this.define(definition); | ||
} | ||
var KeySize = /*#__PURE__*/function (_Error) { | ||
_inheritsLoose(KeySize, _Error); | ||
var _proto = PolymorphicSchema.prototype; | ||
function KeySize() { | ||
var _this; | ||
_proto.define = function define(definition) { | ||
this.schema = definition; | ||
}; | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
_proto.getSchemaAttribute = function getSchemaAttribute(input, parent, key) { | ||
return !this.isSingleSchema && this._schemaAttribute(input, parent, key); | ||
}; | ||
_this = _Error.call.apply(_Error, [this].concat(args)) || this; | ||
_this.message = 'Keys must include at least one member'; | ||
return _this; | ||
} | ||
_proto.inferSchema = function inferSchema(input, parent, key) { | ||
if (this.isSingleSchema) { | ||
return this.schema; | ||
} | ||
return KeySize; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
/** Maps from a list of objects (referentially) to any value | ||
* | ||
* If *any* members of the list get claned up, so does that key/value pair get removed. | ||
*/ | ||
var attr = this.getSchemaAttribute(input, parent, key); | ||
return this.schema[attr]; | ||
}; | ||
_proto.normalizeValue = function normalizeValue(value, parent, key, visit, addEntity, visitedEntities) { | ||
var schema = this.inferSchema(value, parent, key); | ||
var WeakListMap = /*#__PURE__*/function () { | ||
function WeakListMap() { | ||
this.first = new WeakMap(); | ||
} | ||
if (!schema) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production') { | ||
var attr = this.getSchemaAttribute(value, parent, key); | ||
console.warn("Schema attribute " + JSON.stringify(attr, undefined, 2) + " is not expected.\nExpected one of: " + Object.keys(this.schema).map(function (k) { | ||
return "\"" + k + "\""; | ||
}).join(', ') + "\n\nValue: " + JSON.stringify(value, undefined, 2)); | ||
} | ||
var _proto = WeakListMap.prototype; | ||
return value; | ||
} | ||
_proto.delete = function _delete(key) { | ||
var link = this.traverse(key); | ||
link == null ? true : delete link.value; | ||
return !!link; | ||
}; | ||
var normalizedValue = visit(value, parent, key, schema, addEntity, visitedEntities); | ||
return this.isSingleSchema || normalizedValue === undefined || normalizedValue === null ? normalizedValue : { | ||
id: normalizedValue, | ||
schema: this.getSchemaAttribute(value, parent, key) | ||
}; | ||
} // value is guaranteed by caller to not be null | ||
; | ||
_proto.get = function get(key) { | ||
var link = this.traverse(key); | ||
return link == null ? void 0 : link.value; | ||
}; | ||
_proto.denormalizeValue = function denormalizeValue(value, unvisit) { | ||
var schemaKey = isImmutable(value) ? value.get('schema') : value.schema; | ||
_proto.has = function has(key) { | ||
var link = this.traverse(key); | ||
if (!link) return false; | ||
return Object.prototype.hasOwnProperty.call(link, 'value'); | ||
}; | ||
if (!this.isSingleSchema && !schemaKey) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production') { | ||
console.warn("TypeError: Unable to infer schema for " + this.constructor.name + "\nValue: " + JSON.stringify(value, undefined, 2) + "."); | ||
} | ||
_proto.set = function set(key, value) { | ||
if (key.length < 1) throw new KeySize(); | ||
var cur = this.first; | ||
var link; | ||
return [value, true, false]; | ||
} | ||
for (var i = 0; i < key.length; i++) { | ||
if (!cur.has(key[i])) { | ||
link = new Link(); | ||
cur.set(key[i], link); | ||
} else { | ||
link = cur.get(key[i]); | ||
} | ||
var id = this.isSingleSchema ? undefined : isImmutable(value) ? value.get('id') : value.id; | ||
var schema = this.isSingleSchema ? this.schema : this.schema[schemaKey]; | ||
return unvisit(id || value, schema); | ||
}; | ||
cur = link.children; // do on later iteration of loop. this makes typescript happy rather than putting after loop | ||
_createClass(PolymorphicSchema, [{ | ||
key: "isSingleSchema", | ||
get: function get() { | ||
return !this._schemaAttribute; | ||
} | ||
}]); | ||
if (i === key.length - 1) { | ||
link.value = value; | ||
} | ||
} | ||
return PolymorphicSchema; | ||
}(); | ||
return this; | ||
}; | ||
var validateSchema = function validateSchema(definition) { | ||
var isArray = Array.isArray(definition); | ||
_proto.traverse = function traverse(key) { | ||
var cur = this.first; | ||
var link; | ||
if (isArray && definition.length > 1) { | ||
throw new Error("Expected schema definition to be a single schema, but found " + definition.length + "."); | ||
} | ||
for (var i = 0; i < key.length; i++) { | ||
link = cur.get(key[i]); | ||
if (!link) return; | ||
cur = link.children; | ||
} | ||
return definition[0]; | ||
}; | ||
return link; | ||
}; | ||
var getValues = function getValues(input) { | ||
return Array.isArray(input) ? input : Object.keys(input).map(function (key) { | ||
return input[key]; | ||
}); | ||
}; | ||
return WeakListMap; | ||
}(); | ||
var filterEmpty = function filterEmpty(_ref) { | ||
var item = _ref[0], | ||
deletedItem = _ref[2]; | ||
return item !== undefined && !deletedItem; | ||
}; | ||
var PolymorphicSchema = /*#__PURE__*/function () { | ||
function PolymorphicSchema(definition, schemaAttribute) { | ||
this.schema = void 0; | ||
var normalize$1 = function normalize(schema, input, parent, key, visit, addEntity, visitedEntities) { | ||
schema = validateSchema(schema); | ||
var values = getValues(input); // Special case: Arrays pass *their* parent on to their children, since there | ||
// is not any special information that can be gathered from themselves directly | ||
if (schemaAttribute) { | ||
this._schemaAttribute = typeof schemaAttribute === 'string' ? function (input) { | ||
return input[schemaAttribute]; | ||
} : schemaAttribute; | ||
} | ||
return values.map(function (value, index) { | ||
return visit(value, parent, key, schema, addEntity, visitedEntities); | ||
}); | ||
}; | ||
var denormalize$1 = function denormalize(schema, input, unvisit) { | ||
schema = validateSchema(schema); | ||
return [input.map ? input.map(function (entityOrId) { | ||
return unvisit(entityOrId, schema); | ||
}).filter(filterEmpty).map(function (_ref2) { | ||
var value = _ref2[0]; | ||
return value; | ||
}) : input, true, false]; | ||
}; | ||
this.define(definition); | ||
} | ||
function _infer$1(schema, args, indexes, recurse) { | ||
return undefined; | ||
} | ||
var _proto = PolymorphicSchema.prototype; | ||
var ArraySchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ArraySchema, _PolymorphicSchema); | ||
_proto.define = function define(definition) { | ||
this.schema = definition; | ||
}; | ||
function ArraySchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
} | ||
_proto.getSchemaAttribute = function getSchemaAttribute(input, parent, key) { | ||
return !this.isSingleSchema && this._schemaAttribute(input, parent, key); | ||
}; | ||
var _proto = ArraySchema.prototype; | ||
_proto.inferSchema = function inferSchema(input, parent, key) { | ||
if (this.isSingleSchema) { | ||
return this.schema; | ||
} | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
var attr = this.getSchemaAttribute(input, parent, key); | ||
return this.schema[attr]; | ||
}; | ||
var values = getValues(input); | ||
return values.map(function (value, index) { | ||
return _this.normalizeValue(value, parent, key, visit, addEntity, visitedEntities); | ||
}).filter(function (value) { | ||
return value !== undefined && value !== null; | ||
}); | ||
}; | ||
_proto.normalizeValue = function normalizeValue(value, parent, key, visit, addEntity, visitedEntities) { | ||
var schema = this.inferSchema(value, parent, key); | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
if (!schema) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production') { | ||
var attr = this.getSchemaAttribute(value, parent, key); | ||
console.warn("Schema attribute " + JSON.stringify(attr, undefined, 2) + " is not expected.\nExpected one of: " + Object.keys(this.schema).map(function (k) { | ||
return "\"" + k + "\""; | ||
}).join(', ') + "\n\nValue: " + JSON.stringify(value, undefined, 2)); | ||
} | ||
return [input.map ? input.map(function (entityOrId) { | ||
return _this2.denormalizeValue(entityOrId, unvisit); | ||
}).filter(filterEmpty).map(function (_ref3) { | ||
var value = _ref3[0]; | ||
return value; | ||
}) : input, true, false]; | ||
}; | ||
return value; | ||
} | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return _infer$1(this.schema); | ||
}; | ||
var normalizedValue = visit(value, parent, key, schema, addEntity, visitedEntities); | ||
return this.isSingleSchema || normalizedValue === undefined || normalizedValue === null ? normalizedValue : { | ||
id: normalizedValue, | ||
schema: this.getSchemaAttribute(value, parent, key) | ||
}; | ||
} // value is guaranteed by caller to not be null | ||
; | ||
return ArraySchema; | ||
}(PolymorphicSchema); | ||
_proto.denormalizeValue = function denormalizeValue(value, unvisit) { | ||
var schemaKey = isImmutable(value) ? value.get('schema') : value.schema; | ||
var _normalize = function normalize(schema, input, parent, key, visit, addEntity, visitedEntities) { | ||
var object = Object.assign({}, input); | ||
Object.keys(schema).forEach(function (key) { | ||
var localSchema = schema[key]; | ||
var value = visit(input[key], input, key, localSchema, addEntity, visitedEntities); | ||
if (!this.isSingleSchema && !schemaKey) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production') { | ||
console.warn("TypeError: Unable to infer schema for " + this.constructor.name + "\nValue: " + JSON.stringify(value, undefined, 2) + "."); | ||
} | ||
if (value === undefined || value === null) { | ||
delete object[key]; | ||
} else { | ||
object[key] = value; | ||
} | ||
}); | ||
return object; | ||
}; | ||
return [value, true, false]; | ||
} | ||
var _denormalize = function denormalize(schema, input, unvisit) { | ||
if (isImmutable(input)) { | ||
return denormalizeImmutable(schema, input, unvisit); | ||
} | ||
var id = this.isSingleSchema ? undefined : isImmutable(value) ? value.get('id') : value.id; | ||
var schema = this.isSingleSchema ? this.schema : this.schema[schemaKey]; | ||
return unvisit(id || value, schema); | ||
}; | ||
var object = Object.assign({}, input); | ||
var found = true; | ||
var deleted = false; | ||
Object.keys(schema).forEach(function (key) { | ||
var _unvisit = unvisit(object[key], schema[key]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1], | ||
deletedItem = _unvisit[2]; | ||
_createClass(PolymorphicSchema, [{ | ||
key: "isSingleSchema", | ||
get: function get() { | ||
return !this._schemaAttribute; | ||
} | ||
}]); | ||
if (object[key] !== undefined) { | ||
object[key] = item; | ||
} | ||
return PolymorphicSchema; | ||
}(); | ||
if (deletedItem) { | ||
deleted = true; | ||
} | ||
var validateSchema = function validateSchema(definition) { | ||
var isArray = Array.isArray(definition); | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
}); | ||
return [object, found, deleted]; | ||
}; | ||
if (isArray && definition.length > 1) { | ||
throw new Error("Expected schema definition to be a single schema, but found " + definition.length + "."); | ||
} | ||
function _infer(schema, args, indexes, recurse) { | ||
var resultObject = {}; | ||
return definition[0]; | ||
}; | ||
for (var _i = 0, _Object$keys = Object.keys(schema); _i < _Object$keys.length; _i++) { | ||
var k = _Object$keys[_i]; | ||
resultObject[k] = recurse(schema[k], args, indexes); | ||
} | ||
var getValues = function getValues(input) { | ||
return Array.isArray(input) ? input : Object.keys(input).map(function (key) { | ||
return input[key]; | ||
}); | ||
}; | ||
return resultObject; | ||
} | ||
var filterEmpty = function filterEmpty(_ref) { | ||
var item = _ref[0], | ||
deletedItem = _ref[2]; | ||
return item !== undefined && !deletedItem; | ||
}; | ||
var ObjectSchema = /*#__PURE__*/function () { | ||
function ObjectSchema(definition) { | ||
this.schema = void 0; | ||
this.define(definition); | ||
} | ||
var normalize$1 = function normalize(schema, input, parent, key, visit, addEntity, visitedEntities) { | ||
schema = validateSchema(schema); | ||
var values = getValues(input); // Special case: Arrays pass *their* parent on to their children, since there | ||
// is not any special information that can be gathered from themselves directly | ||
var _proto = ObjectSchema.prototype; | ||
return values.map(function (value, index) { | ||
return visit(value, parent, key, schema, addEntity, visitedEntities); | ||
}); | ||
}; | ||
var denormalize$1 = function denormalize(schema, input, unvisit) { | ||
schema = validateSchema(schema); | ||
return [input.map ? input.map(function (entityOrId) { | ||
return unvisit(entityOrId, schema); | ||
}).filter(filterEmpty).map(function (_ref2) { | ||
var value = _ref2[0]; | ||
return value; | ||
}) : input, true, false]; | ||
}; | ||
_proto.define = function define(definition) { | ||
this.schema = Object.keys(definition).reduce(function (entitySchema, key) { | ||
var _Object$assign; | ||
function _infer$1(schema, args, indexes, recurse) { | ||
return undefined; | ||
} | ||
var schema = definition[key]; | ||
return Object.assign({}, entitySchema, (_Object$assign = {}, _Object$assign[key] = schema, _Object$assign)); | ||
}, this.schema || {}); | ||
}; | ||
var ArraySchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ArraySchema, _PolymorphicSchema); | ||
_proto.normalize = function normalize() { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
function ArraySchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
} | ||
return _normalize.apply(void 0, [this.schema].concat(args)); | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
; | ||
var _proto = ArraySchema.prototype; | ||
_proto.denormalize = function denormalize() { | ||
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
args[_key2] = arguments[_key2]; | ||
} | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
return _denormalize.apply(void 0, [this.schema].concat(args)); | ||
}; | ||
var values = getValues(input); | ||
return values.map(function (value, index) { | ||
return _this.normalizeValue(value, parent, key, visit, addEntity, visitedEntities); | ||
}).filter(function (value) { | ||
return value !== undefined && value !== null; | ||
}); | ||
}; | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return _infer(this.schema, args, indexes, recurse); | ||
}; | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
return ObjectSchema; | ||
}(); | ||
return [input.map ? input.map(function (entityOrId) { | ||
return _this2.denormalizeValue(entityOrId, unvisit); | ||
}).filter(filterEmpty).map(function (_ref3) { | ||
var value = _ref3[0]; | ||
return value; | ||
}) : input, true, false]; | ||
}; | ||
var DRAFT = Symbol('draft'); | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return _infer$1(this.schema, args, indexes, recurse); | ||
}; | ||
var unvisitEntity = function unvisitEntity(entityOrId, schema, unvisit, getEntity, localCache, entityCache, dependencies, cycleIndex) { | ||
var entity = getEntity(entityOrId, schema); | ||
return ArraySchema; | ||
}(PolymorphicSchema); | ||
if (entity === DELETED) { | ||
return [undefined, true, true]; | ||
} | ||
var _normalize = function normalize(schema, input, parent, key, visit, addEntity, visitedEntities) { | ||
var object = Object.assign({}, input); | ||
Object.keys(schema).forEach(function (key) { | ||
var localSchema = schema[key]; | ||
var value = visit(input[key], input, key, localSchema, addEntity, visitedEntities); | ||
if (process.env.NODE_ENV !== 'production' && typeof entity === 'symbol' && entity.toString().includes('DELETED')) { | ||
throw new Error("Unrecognized symbol detected.\nMake sure you do not have multiple versions of @rest-hooks/normalizr installed."); | ||
} | ||
if (value === undefined || value === null) { | ||
delete object[key]; | ||
} else { | ||
object[key] = value; | ||
} | ||
}); | ||
return object; | ||
}; | ||
if (typeof entity !== 'object' || entity === null) { | ||
return [entity, false, false]; | ||
} | ||
var _denormalize = function denormalize(schema, input, unvisit) { | ||
if (isImmutable(input)) { | ||
return denormalizeImmutable(schema, input, unvisit); | ||
} | ||
var pk = typeof entityOrId === 'string' ? entityOrId : schema.pk(isImmutable(entity) ? entity.toJS() : entity); | ||
var object = Object.assign({}, input); | ||
var found = true; | ||
var deleted = false; | ||
Object.keys(schema).forEach(function (key) { | ||
var _unvisit = unvisit(object[key], schema[key]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1], | ||
deletedItem = _unvisit[2]; | ||
if (pk === undefined || pk === '') { | ||
return [entity, false, false]; | ||
} | ||
if (object[key] !== undefined) { | ||
object[key] = item; | ||
} | ||
if (localCache[schema.key] === undefined) { | ||
localCache[schema.key] = Object.create(null); | ||
} | ||
if (deletedItem) { | ||
deleted = true; | ||
} | ||
var found = true; | ||
var deleted = false; | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
}); | ||
return [object, found, deleted]; | ||
}; | ||
if (!localCache[schema.key][pk]) { | ||
var trackingIndex = dependencies.length; | ||
dependencies.push(entity); | ||
var wrappedUnvisit = withTrackedEntities(unvisit); // { [DRAFT] } means we are still processing - which if found indicates a cycle | ||
function _infer(schema, args, indexes, recurse) { | ||
var resultObject = {}; | ||
wrappedUnvisit.setLocal = function (entityCopy) { | ||
var _localCache$schema$ke; | ||
for (var _i = 0, _Object$keys = Object.keys(schema); _i < _Object$keys.length; _i++) { | ||
var k = _Object$keys[_i]; | ||
resultObject[k] = recurse(schema[k], args, indexes); | ||
} | ||
return localCache[schema.key][pk] = (_localCache$schema$ke = {}, _localCache$schema$ke[DRAFT] = entityCopy, _localCache$schema$ke.i = trackingIndex, _localCache$schema$ke); | ||
}; | ||
return resultObject; | ||
} | ||
var globalCacheEntry = getGlobalCacheEntry(entityCache, schema, pk); | ||
var ObjectSchema = /*#__PURE__*/function () { | ||
function ObjectSchema(definition) { | ||
this.schema = void 0; | ||
this.define(definition); | ||
} | ||
var _schema$denormalize = schema.denormalize(entity, wrappedUnvisit); | ||
var _proto = ObjectSchema.prototype; | ||
localCache[schema.key][pk] = _schema$denormalize[0]; | ||
found = _schema$denormalize[1]; | ||
deleted = _schema$denormalize[2]; | ||
// if in cycle, use the start of the cycle to track all deps | ||
// otherwise, we use our own trackingIndex | ||
var localKey = dependencies.slice(cycleIndex.i === -1 ? trackingIndex : cycleIndex.i); | ||
_proto.define = function define(definition) { | ||
this.schema = Object.keys(definition).reduce(function (entitySchema, key) { | ||
var _Object$assign; | ||
if (!globalCacheEntry.has(localKey)) { | ||
globalCacheEntry.set(localKey, localCache[schema.key][pk]); | ||
} else { | ||
localCache[schema.key][pk] = globalCacheEntry.get(localKey); | ||
} // start of cycle - reset cycle detection | ||
var schema = definition[key]; | ||
return Object.assign({}, entitySchema, (_Object$assign = {}, _Object$assign[key] = schema, _Object$assign)); | ||
}, this.schema || {}); | ||
}; | ||
_proto.normalize = function normalize() { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
if (cycleIndex.i === trackingIndex) { | ||
cycleIndex.i = -1; | ||
} | ||
} else { | ||
// cycle detected | ||
if (Object.prototype.hasOwnProperty.call(localCache[schema.key][pk], DRAFT)) { | ||
cycleIndex.i = localCache[schema.key][pk].i; | ||
return [localCache[schema.key][pk][DRAFT], found, deleted]; | ||
} else { | ||
// with no cycle, globalCacheEntry will have already been set | ||
dependencies.push(entity); | ||
} | ||
} | ||
return _normalize.apply(void 0, [this.schema].concat(args)); | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
; | ||
return [localCache[schema.key][pk], found, deleted]; | ||
}; | ||
_proto.denormalize = function denormalize() { | ||
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
args[_key2] = arguments[_key2]; | ||
} | ||
var getUnvisit = function getUnvisit(entities, entityCache, resultCache, localCache) { | ||
var getEntity = getEntities(entities); | ||
var dependencies = []; | ||
var cycleIndex = { | ||
i: -1 | ||
}; | ||
return _denormalize.apply(void 0, [this.schema].concat(args)); | ||
}; | ||
function unvisit(input, schema) { | ||
if (!schema) return [input, true, false]; // null is considered intentional, thus always 'found' as true | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return _infer(this.schema, args, indexes, recurse); | ||
}; | ||
if (input === null) { | ||
return [input, true, false]; | ||
} | ||
return ObjectSchema; | ||
}(); | ||
var hasDenormalize = typeof schema.denormalize === 'function'; | ||
var DRAFT = Symbol('draft'); | ||
if (!hasDenormalize && typeof schema === 'function') { | ||
if (input instanceof schema) return [input, true, false]; // field deserialization should never count against 'found' (whether to used inferred results) | ||
var unvisitEntity = function unvisitEntity(entityOrId, schema, unvisit, getEntity, localCache, entityCache, dependencies, cycleIndex) { | ||
var entity = getEntity(entityOrId, schema); | ||
if (input === undefined) return [input, true, false]; | ||
return [new schema(input), true, false]; | ||
} | ||
if (entity === DELETED) { | ||
return [undefined, true, true]; | ||
} | ||
if (input === undefined) { | ||
return [input, false, false]; | ||
} | ||
if (process.env.NODE_ENV !== 'production' && typeof entity === 'symbol' && entity.toString().includes('DELETED')) { | ||
throw new Error("Unrecognized symbol detected.\nMake sure you do not have multiple versions of @rest-hooks/normalizr installed."); | ||
} | ||
if (!hasDenormalize && typeof schema === 'object') { | ||
var method = Array.isArray(schema) ? denormalize$1 : _denormalize; | ||
return method(schema, input, unvisit); | ||
} | ||
if (typeof entity !== 'object' || entity === null) { | ||
return [entity, false, false]; | ||
} | ||
if (isEntity(schema)) { | ||
return unvisitEntity(input, schema, unvisit, getEntity, localCache, entityCache, dependencies, cycleIndex); | ||
} | ||
var pk = typeof entityOrId === 'string' ? entityOrId : schema.pk(isImmutable(entity) ? entity.toJS() : entity); | ||
if (hasDenormalize) { | ||
return schema.denormalize(input, unvisit); | ||
} | ||
if (pk === undefined || pk === '') { | ||
return [entity, false, false]; | ||
} | ||
return [input, true, false]; | ||
} //const wrappedUnvisit = withTrackedEntities(unvisit, globalKey); | ||
if (localCache[schema.key] === undefined) { | ||
localCache[schema.key] = Object.create(null); | ||
} | ||
var found = true; | ||
var deleted = false; | ||
return function (input, schema) { | ||
var ret = unvisit(input, schema); // in the case where WeakMap cannot be used | ||
// this test ensures null is properly excluded from WeakMap | ||
if (!localCache[schema.key][pk]) { | ||
var trackingIndex = dependencies.length; | ||
dependencies.push(entity); | ||
var wrappedUnvisit = withTrackedEntities(unvisit); // { [DRAFT] } means we are still processing - which if found indicates a cycle | ||
if (Object(input) !== input) return ret; | ||
dependencies.push(input); | ||
wrappedUnvisit.setLocal = function (entityCopy) { | ||
var _localCache$schema$ke; | ||
if (!resultCache.has(dependencies)) { | ||
resultCache.set(dependencies, ret[0]); | ||
return ret; | ||
} else { | ||
return [resultCache.get(dependencies), ret[1], ret[2]]; | ||
} | ||
}; | ||
}; | ||
return localCache[schema.key][pk] = (_localCache$schema$ke = {}, _localCache$schema$ke[DRAFT] = entityCopy, _localCache$schema$ke.i = trackingIndex, _localCache$schema$ke); | ||
}; | ||
var getEntities = function getEntities(entities) { | ||
var entityIsImmutable = isImmutable(entities); | ||
return function (entityOrId, schema) { | ||
var _entities$schemaKey; | ||
var globalCacheEntry = getGlobalCacheEntry(entityCache, schema, pk); | ||
var schemaKey = schema.key; | ||
var _schema$denormalize = schema.denormalize(entity, wrappedUnvisit); | ||
if (typeof entityOrId === 'object') { | ||
return entityOrId; | ||
} | ||
localCache[schema.key][pk] = _schema$denormalize[0]; | ||
found = _schema$denormalize[1]; | ||
deleted = _schema$denormalize[2]; | ||
// if in cycle, use the start of the cycle to track all deps | ||
// otherwise, we use our own trackingIndex | ||
var localKey = dependencies.slice(cycleIndex.i === -1 ? trackingIndex : cycleIndex.i); | ||
if (entityIsImmutable) { | ||
return entities.getIn([schemaKey, entityOrId]); | ||
} | ||
if (!globalCacheEntry.has(localKey)) { | ||
globalCacheEntry.set(localKey, localCache[schema.key][pk]); | ||
} else { | ||
localCache[schema.key][pk] = globalCacheEntry.get(localKey); | ||
} // start of cycle - reset cycle detection | ||
return (_entities$schemaKey = entities[schemaKey]) == null ? void 0 : _entities$schemaKey[entityOrId]; | ||
}; | ||
}; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types | ||
if (cycleIndex.i === trackingIndex) { | ||
cycleIndex.i = -1; | ||
} | ||
} else { | ||
// cycle detected | ||
if (Object.prototype.hasOwnProperty.call(localCache[schema.key][pk], DRAFT)) { | ||
cycleIndex.i = localCache[schema.key][pk].i; | ||
return [localCache[schema.key][pk][DRAFT], found, deleted]; | ||
} else { | ||
// with no cycle, globalCacheEntry will have already been set | ||
dependencies.push(entity); | ||
} | ||
} | ||
var denormalize = function denormalize(input, schema, entities, entityCache, resultCache) { | ||
if (entityCache === void 0) { | ||
entityCache = {}; | ||
} | ||
return [localCache[schema.key][pk], found, deleted]; | ||
}; | ||
if (resultCache === void 0) { | ||
resultCache = new WeakListMap(); | ||
} | ||
var getUnvisit = function getUnvisit(entities, entityCache, resultCache, localCache) { | ||
var getEntity = getEntities(entities); | ||
var dependencies = []; | ||
var cycleIndex = { | ||
i: -1 | ||
}; | ||
// undefined mean don't do anything | ||
if (schema === undefined) { | ||
return [input, true, false, {}]; | ||
} | ||
function unvisit(input, schema) { | ||
if (!schema) return [input, true, false]; // null is considered intentional, thus always 'found' as true | ||
if (input === undefined) { | ||
return [undefined, false, false, {}]; | ||
} | ||
if (input === null) { | ||
return [input, true, false]; | ||
} | ||
var resolvedEntities = {}; | ||
var unvisit = getUnvisit(entities, entityCache, resultCache, resolvedEntities); | ||
return [].concat(unvisit(input, schema), [resolvedEntities]); | ||
}; | ||
var hasDenormalize = typeof schema.denormalize === 'function'; | ||
function getGlobalCacheEntry(entityCache, schema, id) { | ||
if (!entityCache[schema.key]) entityCache[schema.key] = {}; | ||
if (!entityCache[schema.key][id]) entityCache[schema.key][id] = new WeakListMap(); | ||
return entityCache[schema.key][id]; | ||
} | ||
if (!hasDenormalize && typeof schema === 'function') { | ||
if (input instanceof schema) return [input, true, false]; // field deserialization should never count against 'found' (whether to used inferred results) | ||
function withTrackedEntities(unvisit) { | ||
// every time we nest, we want to unwrap back to the top. | ||
// this is due to only needed the next level of nested entities for lookup | ||
var originalUnvisit = unvisit.og || unvisit; | ||
if (input === undefined) return [input, true, false]; | ||
return [new schema(input), true, false]; | ||
} | ||
var wrappedUnvisit = function wrappedUnvisit(input, schema) { | ||
return originalUnvisit(input, schema); | ||
}; | ||
if (input === undefined) { | ||
return [input, false, false]; | ||
} | ||
wrappedUnvisit.og = unvisit; | ||
return wrappedUnvisit; | ||
} | ||
if (!hasDenormalize && typeof schema === 'object') { | ||
var method = Array.isArray(schema) ? denormalize$1 : _denormalize; | ||
return method(schema, input, unvisit); | ||
} | ||
var visit = function visit(value, parent, key, schema, addEntity, visitedEntities) { | ||
if (!value || !schema) { | ||
return value; | ||
} | ||
if (isEntity(schema)) { | ||
return unvisitEntity(input, schema, unvisit, getEntity, localCache, entityCache, dependencies, cycleIndex); | ||
} | ||
if (schema.normalize && typeof schema.normalize === 'function') { | ||
if (typeof value !== 'object') return value; | ||
return schema.normalize(value, parent, key, visit, addEntity, visitedEntities); | ||
} // serializable | ||
if (hasDenormalize) { | ||
return schema.denormalize(input, unvisit); | ||
} | ||
return [input, true, false]; | ||
} //const wrappedUnvisit = withTrackedEntities(unvisit, globalKey); | ||
if (typeof schema === 'function') { | ||
return new schema(value); | ||
} | ||
if (typeof value !== 'object' || typeof schema !== 'object') return value; | ||
var method = Array.isArray(schema) ? normalize$1 : _normalize; | ||
return method(schema, value, parent, key, visit, addEntity, visitedEntities); | ||
}; | ||
return function (input, schema) { | ||
var ret = unvisit(input, schema); // in the case where WeakMap cannot be used | ||
// this test ensures null is properly excluded from WeakMap | ||
var addEntities = function addEntities(entities, indexes, existingEntities, existingIndexes, entityMeta, meta) { | ||
var _s = $RefreshSig$(); | ||
if (Object(input) !== input) return ret; | ||
dependencies.push(input); | ||
return _s(function (schema, processedEntity, id) { | ||
_s(); | ||
if (!resultCache.has(dependencies)) { | ||
resultCache.set(dependencies, ret[0]); | ||
return ret; | ||
} else { | ||
return [resultCache.get(dependencies), ret[1], ret[2]]; | ||
} | ||
}; | ||
}; | ||
var schemaKey = schema.key; | ||
var getEntities = function getEntities(entities) { | ||
var entityIsImmutable = isImmutable(entities); | ||
return function (entityOrId, schema) { | ||
var _entities$schemaKey; | ||
if (!(schemaKey in entities)) { | ||
entities[schemaKey] = {}; | ||
existingEntities[schemaKey] = Object.assign({}, existingEntities[schemaKey]); | ||
entityMeta[schemaKey] = Object.assign({}, entityMeta[schemaKey]); | ||
} | ||
var schemaKey = schema.key; | ||
var existingEntity = entities[schemaKey][id]; | ||
if (typeof entityOrId === 'object') { | ||
return entityOrId; | ||
} | ||
if (existingEntity) { | ||
entities[schemaKey][id] = schema.merge(existingEntity, processedEntity); | ||
} else { | ||
// TODO: eventually assume this exists and don't check for conditional. probably early 2022 | ||
var entityExpiresAt = schema.expiresAt ? schema.expiresAt(meta, processedEntity) : meta.expiresAt; | ||
var inStoreEntity = existingEntities[schemaKey][id]; // this case we already have this entity in store | ||
if (entityIsImmutable) { | ||
return entities.getIn([schemaKey, entityOrId]); | ||
} | ||
if (inStoreEntity) { | ||
var _entityMeta$schemaKey, _entityMeta$schemaKey2, _entityMeta$schemaKey3, _meta$fetchedAt, _entityMeta$schemaKey4, _entityMeta$schemaKey5; | ||
return (_entities$schemaKey = entities[schemaKey]) == null ? void 0 : _entities$schemaKey[entityOrId]; | ||
}; | ||
}; // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types | ||
var inStoreMeta = entityMeta[schemaKey][id]; | ||
var useIncoming = // we may have in store but not in meta; so this existance check is still important | ||
!inStoreMeta || ( // useIncoming should not be used with legacy optimistic | ||
schema.useIncoming && meta.fetchedAt ? schema.useIncoming(inStoreMeta, meta, inStoreEntity, processedEntity) : entityMeta[schemaKey][id].date <= meta.date); | ||
if (useIncoming) { | ||
if (typeof processedEntity !== typeof inStoreEntity) { | ||
entities[schemaKey][id] = processedEntity; | ||
} else { | ||
entities[schemaKey][id] = schema.merge(inStoreEntity, processedEntity); | ||
} | ||
} else { | ||
entities[schemaKey][id] = inStoreEntity; | ||
} | ||
var denormalize = function denormalize(input, schema, entities, entityCache, resultCache) { | ||
if (entityCache === void 0) { | ||
entityCache = {}; | ||
} | ||
entityMeta[schemaKey][id] = { | ||
expiresAt: Math.max(entityExpiresAt, (_entityMeta$schemaKey = entityMeta[schemaKey][id]) == null ? void 0 : _entityMeta$schemaKey.expiresAt), | ||
date: Math.max(meta.date, (_entityMeta$schemaKey2 = (_entityMeta$schemaKey3 = entityMeta[schemaKey][id]) == null ? void 0 : _entityMeta$schemaKey3.date) != null ? _entityMeta$schemaKey2 : 0), | ||
fetchedAt: Math.max((_meta$fetchedAt = meta.fetchedAt) != null ? _meta$fetchedAt : 0, (_entityMeta$schemaKey4 = (_entityMeta$schemaKey5 = entityMeta[schemaKey][id]) == null ? void 0 : _entityMeta$schemaKey5.fetchedAt) != null ? _entityMeta$schemaKey4 : 0) | ||
}; | ||
} else { | ||
var _meta$fetchedAt2; | ||
if (resultCache === void 0) { | ||
resultCache = new WeakListMap(); | ||
} | ||
entities[schemaKey][id] = processedEntity; | ||
entityMeta[schemaKey][id] = { | ||
expiresAt: entityExpiresAt, | ||
date: meta.date, | ||
fetchedAt: (_meta$fetchedAt2 = meta.fetchedAt) != null ? _meta$fetchedAt2 : meta.date | ||
}; | ||
} | ||
} // update index | ||
// undefined mean don't do anything | ||
if (schema === undefined) { | ||
return [input, true, false, {}]; | ||
} | ||
if (input === undefined) { | ||
return [undefined, false, false, {}]; | ||
} | ||
if (Array.isArray(schema.indexes)) { | ||
var entity = entities[schemaKey][id]; | ||
var resolvedEntities = {}; | ||
var unvisit = getUnvisit(entities, entityCache, resultCache, resolvedEntities); | ||
return [].concat(unvisit(input, schema), [resolvedEntities]); | ||
}; | ||
if (!(schemaKey in indexes)) { | ||
indexes[schemaKey] = {}; | ||
existingIndexes[schemaKey] = Object.assign({}, existingIndexes[schemaKey]); | ||
} | ||
function getGlobalCacheEntry(entityCache, schema, id) { | ||
if (!entityCache[schema.key]) entityCache[schema.key] = {}; | ||
if (!entityCache[schema.key][id]) entityCache[schema.key][id] = new WeakListMap(); | ||
return entityCache[schema.key][id]; | ||
} | ||
for (var _iterator = _createForOfIteratorHelperLoose(schema.indexes), _step; !(_step = _iterator()).done;) { | ||
var index = _step.value; | ||
function withTrackedEntities(unvisit) { | ||
// every time we nest, we want to unwrap back to the top. | ||
// this is due to only needed the next level of nested entities for lookup | ||
var originalUnvisit = unvisit.og || unvisit; | ||
if (!(index in indexes[schemaKey])) { | ||
existingIndexes[schemaKey][index] = indexes[schemaKey][index] = {}; | ||
} | ||
var wrappedUnvisit = function wrappedUnvisit(input, schema) { | ||
return originalUnvisit(input, schema); | ||
}; | ||
var indexMap = indexes[schemaKey][index]; | ||
wrappedUnvisit.og = unvisit; | ||
return wrappedUnvisit; | ||
} | ||
if (existingEntity) { | ||
delete indexMap[existingEntity[index]]; | ||
} // entity already in cache but the index changed | ||
var visit = function visit(value, parent, key, schema, addEntity, visitedEntities) { | ||
if (!value || !schema) { | ||
return value; | ||
} | ||
if (schema.normalize && typeof schema.normalize === 'function') { | ||
if (typeof value !== 'object') return value; | ||
return schema.normalize(value, parent, key, visit, addEntity, visitedEntities); | ||
} // serializable | ||
if (existingEntities[schemaKey] && existingEntities[schemaKey][id] && existingEntities[schemaKey][id][index] !== entity[index]) { | ||
indexMap[existingEntities[schemaKey][id][index]] = DELETED; | ||
} | ||
if (index in entity) { | ||
indexMap[entity[index]] = id; | ||
} | ||
/* istanbul ignore next */ | ||
else if ( // eslint-disable-next-line no-undef | ||
process.env.NODE_ENV !== 'production') { | ||
console.warn("Index not found in entity. Indexes must be top-level members of your entity.\nIndex: " + index + "\nEntity: " + JSON.stringify(entity, undefined, 2)); | ||
} | ||
} | ||
} // set this after index updates so we know what indexes to remove from | ||
if (typeof schema === 'function') { | ||
return new schema(value); | ||
} | ||
if (typeof value !== 'object' || typeof schema !== 'object') return value; | ||
var method = Array.isArray(schema) ? normalize$1 : _normalize; | ||
return method(schema, value, parent, key, visit, addEntity, visitedEntities); | ||
}; | ||
existingEntities[schemaKey][id] = entities[schemaKey][id]; | ||
}, "RSHyr3aBwsmLX8s7SwDQGEQTEhQ=", false, function () { | ||
return [schema.useIncoming]; | ||
}); | ||
}; | ||
var addEntities = function addEntities(entities, indexes, existingEntities, existingIndexes, entityMeta, meta) { | ||
var _s = $RefreshSig$(); | ||
function expectedSchemaType(schema) { | ||
return ['object', 'function'].includes(typeof schema) ? 'object' : typeof schema; | ||
} // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types | ||
return _s(function (schema, processedEntity, id) { | ||
_s(); | ||
var schemaKey = schema.key; | ||
var normalize = function normalize(input, schema, existingEntities, existingIndexes, existingEntityMeta, meta) { | ||
if (existingEntities === void 0) { | ||
existingEntities = {}; | ||
} | ||
if (!(schemaKey in entities)) { | ||
entities[schemaKey] = {}; | ||
existingEntities[schemaKey] = Object.assign({}, existingEntities[schemaKey]); | ||
entityMeta[schemaKey] = Object.assign({}, entityMeta[schemaKey]); | ||
} | ||
if (existingIndexes === void 0) { | ||
existingIndexes = {}; | ||
} | ||
var existingEntity = entities[schemaKey][id]; | ||
if (existingEntityMeta === void 0) { | ||
existingEntityMeta = {}; | ||
} | ||
if (existingEntity) { | ||
entities[schemaKey][id] = schema.merge(existingEntity, processedEntity); | ||
} else { | ||
// TODO: eventually assume this exists and don't check for conditional. probably early 2022 | ||
var entityExpiresAt = schema.expiresAt ? schema.expiresAt(meta, processedEntity) : meta.expiresAt; | ||
var inStoreEntity = existingEntities[schemaKey][id]; // this case we already have this entity in store | ||
if (meta === void 0) { | ||
meta = { | ||
date: Date.now(), | ||
expiresAt: Infinity, | ||
fetchedAt: 0 | ||
}; | ||
} | ||
if (inStoreEntity) { | ||
var _entityMeta$schemaKey, _entityMeta$schemaKey2, _entityMeta$schemaKey3, _meta$fetchedAt, _entityMeta$schemaKey4, _entityMeta$schemaKey5; | ||
// no schema means we don't process at all | ||
if (schema === undefined) return { | ||
entities: existingEntities, | ||
indexes: existingIndexes, | ||
result: input, | ||
entityMeta: existingEntityMeta | ||
}; | ||
var schemaType = expectedSchemaType(schema); | ||
var inStoreMeta = entityMeta[schemaKey][id]; | ||
var useIncoming = // we may have in store but not in meta; so this existance check is still important | ||
!inStoreMeta || ( // useIncoming should not be used with legacy optimistic | ||
schema.useIncoming && meta.fetchedAt ? schema.useIncoming(inStoreMeta, meta, inStoreEntity, processedEntity) : entityMeta[schemaKey][id].date <= meta.date); | ||
if (input === null || typeof input !== schemaType && !(schema.key !== undefined && typeof input === 'string')) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production') { | ||
var parseWorks = function parseWorks(input) { | ||
try { | ||
return typeof JSON.parse(input) !== 'string'; | ||
} catch (e) { | ||
return false; | ||
} | ||
}; | ||
if (useIncoming) { | ||
if (typeof processedEntity !== typeof inStoreEntity) { | ||
entities[schemaKey][id] = processedEntity; | ||
} else { | ||
entities[schemaKey][id] = schema.merge(inStoreEntity, processedEntity); | ||
} | ||
} else { | ||
entities[schemaKey][id] = inStoreEntity; | ||
} | ||
if (typeof input === 'string' && parseWorks(input)) { | ||
throw new Error("Normalizing a string, but this does match schema.\n\nParsing this input string as JSON worked. This likely indicates fetch function did not parse\nthe JSON. By default, this only happens if \"content-type\" header includes \"json\".\nSee https://resthooks.io/docs/guides/custom-networking for more information\n\n Schema: " + JSON.stringify(schema, undefined, 2) + "\n Input: \"" + input + "\""); | ||
} else { | ||
throw new Error("Unexpected input given to normalize. Expected type to be \"" + schemaType + "\", found \"" + (input === null ? 'null' : typeof input) + "\".\n\n Schema: " + JSON.stringify(schema, undefined, 2) + "\n Input: \"" + input + "\""); | ||
} | ||
} else { | ||
throw new Error("Unexpected input given to normalize. Expected type to be \"" + schemaType + "\", found \"" + (input === null ? 'null' : typeof input) + "\"."); | ||
} | ||
} | ||
entityMeta[schemaKey][id] = { | ||
expiresAt: Math.max(entityExpiresAt, (_entityMeta$schemaKey = entityMeta[schemaKey][id]) == null ? void 0 : _entityMeta$schemaKey.expiresAt), | ||
date: Math.max(meta.date, (_entityMeta$schemaKey2 = (_entityMeta$schemaKey3 = entityMeta[schemaKey][id]) == null ? void 0 : _entityMeta$schemaKey3.date) != null ? _entityMeta$schemaKey2 : 0), | ||
fetchedAt: Math.max((_meta$fetchedAt = meta.fetchedAt) != null ? _meta$fetchedAt : 0, (_entityMeta$schemaKey4 = (_entityMeta$schemaKey5 = entityMeta[schemaKey][id]) == null ? void 0 : _entityMeta$schemaKey5.fetchedAt) != null ? _entityMeta$schemaKey4 : 0) | ||
}; | ||
} else { | ||
var _meta$fetchedAt2; | ||
var newEntities = {}; | ||
var newIndexes = {}; | ||
var entities = Object.assign({}, existingEntities); | ||
var indexes = Object.assign({}, existingIndexes); | ||
var entityMeta = Object.assign({}, existingEntityMeta); | ||
var addEntity = addEntities(newEntities, newIndexes, entities, indexes, entityMeta, meta); | ||
var visitedEntities = {}; | ||
var result = visit(input, input, undefined, schema, addEntity, visitedEntities); | ||
return { | ||
entities: entities, | ||
indexes: indexes, | ||
result: result, | ||
entityMeta: entityMeta | ||
}; | ||
}; | ||
entities[schemaKey][id] = processedEntity; | ||
entityMeta[schemaKey][id] = { | ||
expiresAt: entityExpiresAt, | ||
date: meta.date, | ||
fetchedAt: (_meta$fetchedAt2 = meta.fetchedAt) != null ? _meta$fetchedAt2 : meta.date | ||
}; | ||
} | ||
} // update index | ||
/** | ||
* Represents polymorphic values. | ||
* @see https://resthooks.io/docs/api/Union | ||
*/ | ||
var UnionSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(UnionSchema, _PolymorphicSchema); | ||
if (Array.isArray(schema.indexes)) { | ||
var entity = entities[schemaKey][id]; | ||
function UnionSchema(definition, schemaAttribute) { | ||
if (!schemaAttribute) { | ||
throw new Error('Expected option "schemaAttribute" not found on UnionSchema.'); | ||
} | ||
if (!(schemaKey in indexes)) { | ||
indexes[schemaKey] = {}; | ||
existingIndexes[schemaKey] = Object.assign({}, existingIndexes[schemaKey]); | ||
} | ||
return _PolymorphicSchema.call(this, definition, schemaAttribute) || this; | ||
} | ||
for (var _iterator = _createForOfIteratorHelperLoose(schema.indexes), _step; !(_step = _iterator()).done;) { | ||
var index = _step.value; | ||
var _proto = UnionSchema.prototype; | ||
if (!(index in indexes[schemaKey])) { | ||
existingIndexes[schemaKey][index] = indexes[schemaKey][index] = {}; | ||
} | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
return this.normalizeValue(input, parent, key, visit, addEntity, visitedEntities); | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
; | ||
var indexMap = indexes[schemaKey][index]; | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
return this.denormalizeValue(input, unvisit); | ||
}; | ||
if (existingEntity) { | ||
delete indexMap[existingEntity[index]]; | ||
} // entity already in cache but the index changed | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
if (!args[0]) return undefined; | ||
var attr = this.getSchemaAttribute(args[0], undefined, ''); | ||
var discriminatedSchema = this.schema[attr]; // Was unable to infer the entity's schema from params | ||
if (discriminatedSchema === undefined) return undefined; | ||
return { | ||
id: recurse(discriminatedSchema, args, indexes), | ||
schema: attr | ||
}; | ||
}; | ||
if (existingEntities[schemaKey] && existingEntities[schemaKey][id] && existingEntities[schemaKey][id][index] !== entity[index]) { | ||
indexMap[existingEntities[schemaKey][id][index]] = DELETED; | ||
} | ||
return UnionSchema; | ||
}(PolymorphicSchema); | ||
if (index in entity) { | ||
indexMap[entity[index]] = id; | ||
} | ||
/* istanbul ignore next */ | ||
else if ( // eslint-disable-next-line no-undef | ||
process.env.NODE_ENV !== 'production') { | ||
console.warn("Index not found in entity. Indexes must be top-level members of your entity.\nIndex: " + index + "\nEntity: " + JSON.stringify(entity, undefined, 2)); | ||
} | ||
} | ||
} // set this after index updates so we know what indexes to remove from | ||
/** | ||
* Represents variably sized objects | ||
* @see https://resthooks.io/docs/api/Values | ||
*/ | ||
var ValuesSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ValuesSchema, _PolymorphicSchema); | ||
existingEntities[schemaKey][id] = entities[schemaKey][id]; | ||
}, "RSHyr3aBwsmLX8s7SwDQGEQTEhQ=", false, function () { | ||
return [schema.useIncoming]; | ||
}); | ||
}; | ||
function ValuesSchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
} | ||
function expectedSchemaType(schema) { | ||
return ['object', 'function'].includes(typeof schema) ? 'object' : typeof schema; | ||
} // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types | ||
var _proto = ValuesSchema.prototype; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
var normalize = function normalize(input, schema, existingEntities, existingIndexes, existingEntityMeta, meta) { | ||
if (existingEntities === void 0) { | ||
existingEntities = {}; | ||
} | ||
return Object.keys(input).reduce(function (output, key, index) { | ||
var _Object$assign; | ||
if (existingIndexes === void 0) { | ||
existingIndexes = {}; | ||
} | ||
var value = input[key]; | ||
return value !== undefined && value !== null ? Object.assign({}, output, (_Object$assign = {}, _Object$assign[key] = _this.normalizeValue(value, input, key, visit, addEntity, visitedEntities), _Object$assign)) : output; | ||
}, {}); | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
; | ||
if (existingEntityMeta === void 0) { | ||
existingEntityMeta = {}; | ||
} | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
if (meta === void 0) { | ||
meta = { | ||
date: Date.now(), | ||
expiresAt: Infinity, | ||
fetchedAt: 0 | ||
}; | ||
} | ||
var found = true; | ||
var deleted = false; | ||
return [Object.keys(input).reduce(function (output, key) { | ||
var _Object$assign2; | ||
// no schema means we don't process at all | ||
if (schema === undefined) return { | ||
entities: existingEntities, | ||
indexes: existingIndexes, | ||
result: input, | ||
entityMeta: existingEntityMeta | ||
}; | ||
var schemaType = expectedSchemaType(schema); | ||
var entityOrId = input[key]; | ||
if (input === null || typeof input !== schemaType && !(schema.key !== undefined && typeof input === 'string')) { | ||
/* istanbul ignore else */ | ||
if (process.env.NODE_ENV !== 'production') { | ||
var parseWorks = function parseWorks(input) { | ||
try { | ||
return typeof JSON.parse(input) !== 'string'; | ||
} catch (e) { | ||
return false; | ||
} | ||
}; | ||
var _this2$denormalizeVal = _this2.denormalizeValue(entityOrId, unvisit), | ||
value = _this2$denormalizeVal[0], | ||
foundItem = _this2$denormalizeVal[1], | ||
deletedItem = _this2$denormalizeVal[2]; | ||
if (typeof input === 'string' && parseWorks(input)) { | ||
throw new Error("Normalizing a string, but this does match schema.\n\nParsing this input string as JSON worked. This likely indicates fetch function did not parse\nthe JSON. By default, this only happens if \"content-type\" header includes \"json\".\nSee https://resthooks.io/docs/guides/custom-networking for more information\n\n Schema: " + JSON.stringify(schema, undefined, 2) + "\n Input: \"" + input + "\""); | ||
} else { | ||
throw new Error("Unexpected input given to normalize. Expected type to be \"" + schemaType + "\", found \"" + (input === null ? 'null' : typeof input) + "\".\n\n Schema: " + JSON.stringify(schema, undefined, 2) + "\n Input: \"" + input + "\""); | ||
} | ||
} else { | ||
throw new Error("Unexpected input given to normalize. Expected type to be \"" + schemaType + "\", found \"" + (input === null ? 'null' : typeof input) + "\"."); | ||
} | ||
} | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
var newEntities = {}; | ||
var newIndexes = {}; | ||
var entities = Object.assign({}, existingEntities); | ||
var indexes = Object.assign({}, existingIndexes); | ||
var entityMeta = Object.assign({}, existingEntityMeta); | ||
var addEntity = addEntities(newEntities, newIndexes, entities, indexes, entityMeta, meta); | ||
var visitedEntities = {}; | ||
var result = visit(input, input, undefined, schema, addEntity, visitedEntities); | ||
return { | ||
entities: entities, | ||
indexes: indexes, | ||
result: result, | ||
entityMeta: entityMeta | ||
}; | ||
}; | ||
if (deletedItem) { | ||
deleted = true; | ||
} | ||
/** | ||
* Represents polymorphic values. | ||
* @see https://resthooks.io/docs/api/Union | ||
*/ | ||
if (!foundItem || deletedItem) return output; | ||
return Object.assign({}, output, (_Object$assign2 = {}, _Object$assign2[key] = value, _Object$assign2)); | ||
}, {}), found, deleted]; | ||
}; | ||
var UnionSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(UnionSchema, _PolymorphicSchema); | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return undefined; | ||
}; | ||
function UnionSchema(definition, schemaAttribute) { | ||
if (!schemaAttribute) { | ||
throw new Error('Expected option "schemaAttribute" not found on UnionSchema.'); | ||
} | ||
return ValuesSchema; | ||
}(PolymorphicSchema); | ||
return _PolymorphicSchema.call(this, definition, schemaAttribute) || this; | ||
} | ||
/** | ||
* Marks entity as deleted. | ||
* @see https://resthooks.io/docs/api/Delete | ||
*/ | ||
var _proto = UnionSchema.prototype; | ||
var Delete = /*#__PURE__*/function () { | ||
function Delete(entity) { | ||
if (process.env.NODE_ENV !== 'production' && !entity) { | ||
throw new Error('Expected option "entity" not found on DeleteSchema.'); | ||
} | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
return this.normalizeValue(input, parent, key, visit, addEntity, visitedEntities); | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
; | ||
this._entity = entity; | ||
} | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
return this.denormalizeValue(input, unvisit); | ||
}; | ||
var _proto = Delete.prototype; | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
if (!args[0]) return undefined; | ||
var attr = this.getSchemaAttribute(args[0], undefined, ''); | ||
var discriminatedSchema = this.schema[attr]; // Was unable to infer the entity's schema from params | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
// TODO: what's store needs to be a differing type from fromJS | ||
var processedEntity = this._entity.process(input, parent, key); | ||
if (discriminatedSchema === undefined) return undefined; | ||
return { | ||
id: recurse(discriminatedSchema, args, indexes), | ||
schema: attr | ||
}; | ||
}; | ||
var id = this._entity.pk(processedEntity, parent, key); | ||
return UnionSchema; | ||
}(PolymorphicSchema); | ||
if (process.env.NODE_ENV !== 'production' && (id === undefined || id === '')) { | ||
var _name; | ||
/** | ||
* Represents variably sized objects | ||
* @see https://resthooks.io/docs/api/Values | ||
*/ | ||
var error = new Error("Missing usable primary key when normalizing response.\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n\n Delete(Entity): Delete(" + ((_name = this._entity.name) != null ? _name : this._entity) + ")\n Value: " + (input && JSON.stringify(input, null, 2)) + "\n "); | ||
error.status = 400; | ||
throw error; | ||
} | ||
var ValuesSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ValuesSchema, _PolymorphicSchema); | ||
addEntity(this, DELETED, id); | ||
return id; | ||
}; | ||
function ValuesSchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
} | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return undefined; | ||
}; | ||
var _proto = ValuesSchema.prototype; | ||
_proto.denormalize = function denormalize(id, unvisit) { | ||
return unvisit(id, this._entity); | ||
} | ||
/* istanbul ignore next */ | ||
; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
_proto._denormalizeNullable = function _denormalizeNullable() { | ||
return []; | ||
} | ||
/* istanbul ignore next */ | ||
; | ||
return Object.keys(input).reduce(function (output, key, index) { | ||
var _Object$assign; | ||
_proto._normalizeNullable = function _normalizeNullable() { | ||
return []; | ||
} | ||
/* istanbul ignore next */ | ||
; | ||
var value = input[key]; | ||
return value !== undefined && value !== null ? Object.assign({}, output, (_Object$assign = {}, _Object$assign[key] = _this.normalizeValue(value, input, key, visit, addEntity, visitedEntities), _Object$assign)) : output; | ||
}, {}); | ||
} // eslint-disable-next-line @typescript-eslint/ban-types | ||
; | ||
_proto.merge = function merge(existing, incoming) { | ||
return incoming; | ||
}; | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
_proto.useIncoming = function useIncoming(existingMeta, incomingMeta, existing, incoming) { | ||
return existingMeta.date <= incomingMeta.date; | ||
}; | ||
var found = true; | ||
var deleted = false; | ||
return [Object.keys(input).reduce(function (output, key) { | ||
var _Object$assign2; | ||
_createClass(Delete, [{ | ||
key: "key", | ||
get: function get() { | ||
return this._entity.key; | ||
} | ||
}]); | ||
var entityOrId = input[key]; | ||
return Delete; | ||
}(); | ||
var _this2$denormalizeVal = _this2.denormalizeValue(entityOrId, unvisit), | ||
value = _this2$denormalizeVal[0], | ||
foundItem = _this2$denormalizeVal[1], | ||
deletedItem = _this2$denormalizeVal[2]; | ||
/* istanbul ignore file */ | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
var schema$1 = /*#__PURE__*/Object.freeze({ | ||
__proto__: null, | ||
Union: UnionSchema, | ||
Values: ValuesSchema, | ||
Array: ArraySchema, | ||
Object: ObjectSchema, | ||
Delete: Delete | ||
}); | ||
if (deletedItem) { | ||
deleted = true; | ||
} | ||
/** | ||
* Build the result parameter to denormalize from schema alone. | ||
* Tries to compute the entity ids from params. | ||
*/ | ||
if (!foundItem || deletedItem) return output; | ||
return Object.assign({}, output, (_Object$assign2 = {}, _Object$assign2[key] = value, _Object$assign2)); | ||
}, {}), found, deleted]; | ||
}; | ||
function inferResults(schema, args, indexes) { | ||
// schema classes | ||
if (canInfer(schema)) { | ||
return schema.infer(args, indexes, inferResults); | ||
} // plain case | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return undefined; | ||
}; | ||
return ValuesSchema; | ||
}(PolymorphicSchema); | ||
if (typeof schema === 'object' && schema) { | ||
var method = Array.isArray(schema) ? _infer$1 : _infer; | ||
return method(schema, args, indexes, inferResults); | ||
} // fallback for things like null or undefined | ||
/** | ||
* Marks entity as deleted. | ||
* @see https://resthooks.io/docs/api/Delete | ||
*/ | ||
var Delete = /*#__PURE__*/function () { | ||
function Delete(entity) { | ||
if (process.env.NODE_ENV !== 'production' && !entity) { | ||
throw new Error('Expected option "entity" not found on DeleteSchema.'); | ||
} | ||
return schema; | ||
} | ||
this._entity = entity; | ||
} | ||
function canInfer(schema) { | ||
return !!schema && typeof schema.infer === 'function'; | ||
} | ||
var _proto = Delete.prototype; | ||
exports.DELETED = DELETED; | ||
exports.Entity = Entity; | ||
exports.WeakListMap = WeakListMap; | ||
exports.denormalize = denormalize; | ||
exports.inferResults = inferResults; | ||
exports.isEntity = isEntity; | ||
exports.normalize = normalize; | ||
exports.schema = schema$1; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
// TODO: what's store needs to be a differing type from fromJS | ||
var processedEntity = this._entity.process(input, parent, key); | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
var id = this._entity.pk(processedEntity, parent, key); | ||
if (process.env.NODE_ENV !== 'production' && (id === undefined || id === '')) { | ||
var _name; | ||
var error = new Error("Missing usable primary key when normalizing response.\n\n This is likely due to a malformed response.\n Try inspecting the network response or fetch() return value.\n Or use debugging tools: https://resthooks.io/docs/guides/debugging\n Learn more about schemas: https://resthooks.io/docs/api/schema\n\n Delete(Entity): Delete(" + ((_name = this._entity.name) != null ? _name : this._entity) + ")\n Value: " + (input && JSON.stringify(input, null, 2)) + "\n "); | ||
error.status = 400; | ||
throw error; | ||
} | ||
addEntity(this, DELETED, id); | ||
return id; | ||
}; | ||
_proto.infer = function infer(args, indexes, recurse) { | ||
return undefined; | ||
}; | ||
_proto.denormalize = function denormalize(id, unvisit) { | ||
return unvisit(id, this._entity); | ||
} | ||
/* istanbul ignore next */ | ||
; | ||
_proto._denormalizeNullable = function _denormalizeNullable() { | ||
return []; | ||
} | ||
/* istanbul ignore next */ | ||
; | ||
_proto._normalizeNullable = function _normalizeNullable() { | ||
return []; | ||
} | ||
/* istanbul ignore next */ | ||
; | ||
_proto.merge = function merge(existing, incoming) { | ||
return incoming; | ||
}; | ||
_proto.useIncoming = function useIncoming(existingMeta, incomingMeta, existing, incoming) { | ||
return existingMeta.date <= incomingMeta.date; | ||
}; | ||
_createClass(Delete, [{ | ||
key: "key", | ||
get: function get() { | ||
return this._entity.key; | ||
} | ||
}]); | ||
return Delete; | ||
}(); | ||
/* istanbul ignore file */ | ||
var schema$1 = /*#__PURE__*/Object.freeze({ | ||
__proto__: null, | ||
Union: UnionSchema, | ||
Values: ValuesSchema, | ||
Array: ArraySchema, | ||
Object: ObjectSchema, | ||
Delete: Delete | ||
}); | ||
/** | ||
* Build the result parameter to denormalize from schema alone. | ||
* Tries to compute the entity ids from params. | ||
*/ | ||
function inferResults(schema, args, indexes) { | ||
// schema classes | ||
if (canInfer(schema)) { | ||
return schema.infer(args, indexes, inferResults); | ||
} // plain case | ||
if (typeof schema === 'object' && schema) { | ||
var method = Array.isArray(schema) ? _infer$1 : _infer; | ||
return method(schema, args, indexes, inferResults); | ||
} // fallback for things like null or undefined | ||
return schema; | ||
} | ||
function canInfer(schema) { | ||
return !!schema && typeof schema.infer === 'function'; | ||
} | ||
exports.DELETED = DELETED; | ||
exports.Entity = Entity; | ||
exports.WeakListMap = WeakListMap; | ||
exports.denormalize = denormalize; | ||
exports.inferResults = inferResults; | ||
exports.isEntity = isEntity; | ||
exports.normalize = normalize; | ||
exports.schema = schema$1; | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
})); |
{ | ||
"name": "@rest-hooks/normalizr", | ||
"version": "8.2.5", | ||
"version": "8.2.6", | ||
"description": "Normalizes and denormalizes JSON according to schema for Redux and Flux applications", | ||
@@ -97,3 +97,3 @@ "homepage": "https://github.com/coinbase/rest-hooks/tree/master/packages/normalizr#readme", | ||
"devDependencies": { | ||
"immutable": "^4.0.0", | ||
"immutable": "4.1.0", | ||
"npm-run-all": "^4.1.5", | ||
@@ -103,5 +103,5 @@ "run-p": "^0.0.0" | ||
"dependencies": { | ||
"@babel/runtime": "^7.7.2" | ||
"@babel/runtime": "^7.13.0" | ||
}, | ||
"gitHead": "f490c35cb1a91a4f740488d28b92d3e3b3a98ffe" | ||
"gitHead": "3ef33e89500d586bdfbef12ac7f559a9a647df88" | ||
} |
673236
78
7481
Updated@babel/runtime@^7.13.0