@rest-hooks/normalizr
Advanced tools
Comparing version 5.0.6 to 6.0.0-beta.0
@@ -6,2 +6,32 @@ # Change Log | ||
## [6.0.0-beta.0](https://github.com/coinbase/rest-hooks/compare/@rest-hooks/normalizr@5.0.6...@rest-hooks/normalizr@6.0.0-beta.0) (2020-04-26) | ||
### ⚠ 💥 BREAKING CHANGES | ||
* TypeScript 3.7 or higher is required. This uses type | ||
recursion. | ||
### 🚀 Features | ||
* Simplified Entity class ([#315](https://github.com/coinbase/rest-hooks/issues/315)) ([0e6bfcb](https://github.com/coinbase/rest-hooks/commit/0e6bfcb3620006e285510d4e5121fce743214d55)) | ||
### 💅 Enhancement | ||
* More readable array return types ([#314](https://github.com/coinbase/rest-hooks/issues/314)) ([4ac8918](https://github.com/coinbase/rest-hooks/commit/4ac8918df19a4d386ff717c3ceef40e151c60c1f)) | ||
### 📦 Package | ||
* Bump internal pkgs ([#306](https://github.com/coinbase/rest-hooks/issues/306)) ([46bebad](https://github.com/coinbase/rest-hooks/commit/46bebad79d848404d02423fd2a3e2d647ee5bbbb)) | ||
### 🏠 Internal | ||
* Hoist coveralls to root, since testing is done there ([3b1dbaa](https://github.com/coinbase/rest-hooks/commit/3b1dbaac303048a1b1e543f99fb9758b21feb083)) | ||
* Update packages in redux example ([dbba679](https://github.com/coinbase/rest-hooks/commit/dbba67935a7b756d66ce7b6cb9e2d93e7f2ce44a)) | ||
### [5.0.6](https://github.com/coinbase/rest-hooks/compare/@rest-hooks/normalizr@5.0.5...@rest-hooks/normalizr@5.0.6) (2020-03-13) | ||
@@ -8,0 +38,0 @@ |
@@ -30,12 +30,9 @@ define(['exports'], function (exports) { 'use strict'; | ||
function denormalizeImmutable(schema, input, unvisit) { | ||
var found = true; | ||
return [Object.keys(schema).reduce(function (object, key) { | ||
let found = true; | ||
return [Object.keys(schema).reduce((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; | ||
const stringKey = `${key}`; | ||
const [item, foundItem] = unvisit(object.get(stringKey), schema[stringKey]); | ||
var _unvisit = unvisit(object.get(stringKey), schema[stringKey]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1]; | ||
if (!foundItem) { | ||
@@ -53,30 +50,6 @@ found = false; | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
subClass.__proto__ = superClass; | ||
} | ||
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); | ||
} | ||
} | ||
function _createClass(Constructor, protoProps, staticProps) { | ||
if (protoProps) _defineProperties(Constructor.prototype, protoProps); | ||
if (staticProps) _defineProperties(Constructor, staticProps); | ||
return Constructor; | ||
} | ||
var PolymorphicSchema = /*#__PURE__*/function () { | ||
function PolymorphicSchema(definition, schemaAttribute) { | ||
class PolymorphicSchema { | ||
constructor(definition, schemaAttribute) { | ||
if (schemaAttribute) { | ||
this._schemaAttribute = typeof schemaAttribute === 'string' ? function (input) { | ||
return input[schemaAttribute]; | ||
} : schemaAttribute; | ||
this._schemaAttribute = typeof schemaAttribute === 'string' ? input => input[schemaAttribute] : schemaAttribute; | ||
} | ||
@@ -87,13 +60,15 @@ | ||
var _proto = PolymorphicSchema.prototype; | ||
get isSingleSchema() { | ||
return !this._schemaAttribute; | ||
} | ||
_proto.define = function define(definition) { | ||
define(definition) { | ||
this.schema = definition; | ||
}; | ||
} | ||
_proto.getSchemaAttribute = function getSchemaAttribute(input, parent, key) { | ||
getSchemaAttribute(input, parent, key) { | ||
return !this.isSingleSchema && this._schemaAttribute(input, parent, key); | ||
}; | ||
} | ||
_proto.inferSchema = function inferSchema(input, parent, key) { | ||
inferSchema(input, parent, key) { | ||
if (this.isSingleSchema) { | ||
@@ -103,8 +78,8 @@ return this.schema; | ||
var attr = this.getSchemaAttribute(input, parent, key); | ||
const 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); | ||
normalizeValue(value, parent, key, visit, addEntity, visitedEntities) { | ||
const schema = this.inferSchema(value, parent, key); | ||
@@ -115,3 +90,3 @@ if (!schema) { | ||
var normalizedValue = visit(value, parent, key, schema, addEntity, visitedEntities); | ||
const normalizedValue = visit(value, parent, key, schema, addEntity, visitedEntities); | ||
return this.isSingleSchema || normalizedValue === undefined || normalizedValue === null ? normalizedValue : { | ||
@@ -121,6 +96,6 @@ id: normalizedValue, | ||
}; | ||
}; | ||
} | ||
_proto.denormalizeValue = function denormalizeValue(value, unvisit) { | ||
var schemaKey = isImmutable(value) ? value.get('schema') : value.schema; | ||
denormalizeValue(value, unvisit) { | ||
const schemaKey = isImmutable(value) ? value.get('schema') : value.schema; | ||
@@ -131,22 +106,14 @@ if (!this.isSingleSchema && !schemaKey) { | ||
var id = this.isSingleSchema ? undefined : isImmutable(value) ? value.get('id') : value.id; | ||
var schema = this.isSingleSchema ? this.schema : this.schema[schemaKey]; | ||
const id = this.isSingleSchema ? undefined : isImmutable(value) ? value.get('id') : value.id; | ||
const schema = this.isSingleSchema ? this.schema : this.schema[schemaKey]; | ||
return unvisit(id || value, schema); | ||
}; | ||
} | ||
_createClass(PolymorphicSchema, [{ | ||
key: "isSingleSchema", | ||
get: function get() { | ||
return !this._schemaAttribute; | ||
} | ||
}]); | ||
} | ||
return PolymorphicSchema; | ||
}(); | ||
const validateSchema = definition => { | ||
const isArray = Array.isArray(definition); | ||
var validateSchema = function validateSchema(definition) { | ||
var isArray = Array.isArray(definition); | ||
if (isArray && definition.length > 1) { | ||
throw new Error("Expected schema definition to be a single schema, but found " + definition.length + "."); | ||
throw new Error(`Expected schema definition to be a single schema, but found ${definition.length}.`); | ||
} | ||
@@ -157,88 +124,45 @@ | ||
var getValues = function getValues(input) { | ||
return Array.isArray(input) ? input : Object.keys(input).map(function (key) { | ||
return input[key]; | ||
}); | ||
}; | ||
const getValues = input => Array.isArray(input) ? input : Object.keys(input).map(key => input[key]); | ||
var normalize = function normalize(schema, input, parent, key, visit, addEntity, visitedEntities) { | ||
const 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 | ||
const 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 | ||
return values.map(function (value, index) { | ||
return visit(value, parent, key, schema, addEntity, visitedEntities); | ||
}); | ||
return values.map((value, index) => visit(value, parent, key, schema, addEntity, visitedEntities)); | ||
}; | ||
var denormalize = function denormalize(schema, input, unvisit) { | ||
const denormalize = (schema, input, unvisit) => { | ||
schema = validateSchema(schema); | ||
var found = true; | ||
let found = true; | ||
if (input === undefined && schema) { | ||
var _unvisit = unvisit(undefined, schema); | ||
found = _unvisit[1]; | ||
[, found] = unvisit(undefined, schema); | ||
} | ||
return [input && input.map ? input.map(function (entityOrId) { | ||
return unvisit(entityOrId, schema); | ||
}).filter(function (_ref) { | ||
var foundItem = _ref[1]; | ||
return foundItem; | ||
}).map(function (_ref2) { | ||
var value = _ref2[0]; | ||
return value; | ||
}) : input, found]; | ||
return [input && input.map ? input.map(entityOrId => unvisit(entityOrId, schema)).filter(([, foundItem]) => foundItem).map(([value]) => value) : input, found]; | ||
}; | ||
var ArraySchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ArraySchema, _PolymorphicSchema); | ||
function ArraySchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
class ArraySchema extends PolymorphicSchema { | ||
normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
const values = getValues(input); | ||
return values.map((value, index) => this.normalizeValue(value, parent, key, visit, addEntity, visitedEntities)).filter(value => value !== undefined && value !== null); | ||
} | ||
var _proto = ArraySchema.prototype; | ||
denormalize(input, unvisit) { | ||
let found = true; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
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.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
var found = true; | ||
if (input === undefined && this.schema) { | ||
var _unvisit2 = unvisit(undefined, this.schema); | ||
found = _unvisit2[1]; | ||
[, found] = unvisit(undefined, this.schema); | ||
} | ||
return [input && input.map ? input.map(function (entityOrId) { | ||
return _this2.denormalizeValue(entityOrId, unvisit); | ||
}).filter(function (_ref3) { | ||
var foundItem = _ref3[1]; | ||
return foundItem; | ||
}).map(function (_ref4) { | ||
var value = _ref4[0]; | ||
return value; | ||
}) : input, found]; | ||
}; | ||
return [input && input.map ? input.map(entityOrId => this.denormalizeValue(entityOrId, unvisit)).filter(([, foundItem]) => foundItem).map(([value]) => value) : input, found]; | ||
} | ||
return ArraySchema; | ||
}(PolymorphicSchema); | ||
} | ||
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); | ||
const normalize$1 = (schema, input, parent, key, visit, addEntity, visitedEntities) => { | ||
const object = { ...input | ||
}; | ||
Object.keys(schema).forEach(key => { | ||
const localSchema = schema[key]; | ||
const value = visit(input[key], input, key, localSchema, addEntity, visitedEntities); | ||
@@ -253,4 +177,3 @@ if (value === undefined || value === null) { | ||
}; | ||
var _denormalize = function denormalize(schema, input, unvisit) { | ||
const denormalize$1 = (schema, input, unvisit) => { | ||
if (isImmutable(input)) { | ||
@@ -260,8 +183,7 @@ return denormalizeImmutable(schema, input, unvisit); | ||
var object = Object.assign({}, input); | ||
var found = true; | ||
Object.keys(schema).forEach(function (key) { | ||
var _unvisit = unvisit(object[key], schema[key]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1]; | ||
const object = { ...input | ||
}; | ||
let found = true; | ||
Object.keys(schema).forEach(key => { | ||
const [item, foundItem] = unvisit(object[key], schema[key]); | ||
@@ -278,40 +200,202 @@ if (object[key] !== undefined) { | ||
}; | ||
var ObjectSchema = /*#__PURE__*/function () { | ||
function ObjectSchema(definition) { | ||
class ObjectSchema { | ||
constructor(definition) { | ||
this.define(definition); | ||
} | ||
var _proto = ObjectSchema.prototype; | ||
define(definition) { | ||
this.schema = Object.keys(definition).reduce((entitySchema, key) => { | ||
const schema = definition[key]; | ||
return { ...entitySchema, | ||
[key]: schema | ||
}; | ||
}, this.schema || {}); | ||
} | ||
_proto.define = function define(definition) { | ||
this.schema = Object.keys(definition).reduce(function (entitySchema, key) { | ||
var _Object$assign; | ||
normalize(...args) { | ||
return normalize$1(this.schema, ...args); | ||
} | ||
var schema = definition[key]; | ||
return Object.assign({}, entitySchema, (_Object$assign = {}, _Object$assign[key] = schema, _Object$assign)); | ||
}, this.schema || {}); | ||
}; | ||
denormalize(...args) { | ||
return denormalize$1(this.schema, ...args); | ||
} | ||
_proto.normalize = function normalize() { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
const DefinedMembersKey = Symbol('Defined Members'); | ||
const UniqueIdentifierKey = Symbol('unq'); | ||
/** Immutable record that keeps track of which members are defined vs defaults. */ | ||
class SimpleRecord { | ||
toString() { | ||
// we don't make _unq a member so it doesn't play a role in type compatibility | ||
return this[UniqueIdentifierKey]; | ||
} | ||
/** 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 | ||
*/ | ||
static fromJS( // TODO: this should only accept members that are not functions | ||
props = {}, parent, key) { | ||
// we type guarded abstract case above, so ok to force typescript to allow constructor call | ||
const instance = new this(props); | ||
Object.defineProperty(instance, DefinedMembersKey, { | ||
value: Object.keys(props), | ||
writable: false | ||
}); // a 'unique' identifier to make referential equality comparisons easy | ||
Object.defineProperty(instance, UniqueIdentifierKey, { | ||
value: `${Math.random()}`, | ||
writable: false | ||
}); | ||
Object.assign(instance, props); | ||
return instance; | ||
} | ||
/** Creates new instance copying over defined values of arguments */ | ||
static merge(first, second) { | ||
const props = Object.assign(this.toObjectDefined(first), this.toObjectDefined(second)); | ||
return this.fromJS(props); | ||
} | ||
/** Whether key is non-default */ | ||
static hasDefined(instance, key) { | ||
return instance[DefinedMembersKey].includes(key); | ||
} | ||
/** Returns simple object with all the non-default members */ | ||
static toObjectDefined(instance) { | ||
const defined = {}; | ||
for (const member of instance[DefinedMembersKey]) { | ||
defined[member] = instance[member]; | ||
} | ||
return _normalize.apply(void 0, [this.schema].concat(args)); | ||
}; | ||
return defined; | ||
} | ||
/** Returns array of all keys that have values defined in instance */ | ||
_proto.denormalize = function denormalize() { | ||
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
args[_key2] = arguments[_key2]; | ||
static keysDefined(instance) { | ||
return instance[DefinedMembersKey]; | ||
} | ||
} | ||
/** Represents data that should be deduped by specifying a primary key. */ | ||
class Entity extends SimpleRecord { | ||
/** | ||
* A unique identifier for each Entity | ||
* | ||
* @param [parent] When normalizing, the object which included the entity | ||
* @param [key] When normalizing, the key where this entity was found | ||
*/ | ||
/** Returns the globally unique identifier for the static Entity */ | ||
static get key() { | ||
/* istanbul ignore next */ | ||
if (process.env.NODE_ENV !== 'production' && this.name === '') throw new Error('Entity classes without a name must define `static get key()`'); | ||
return this.name; | ||
} | ||
/** Defines nested entities */ | ||
/** | ||
* 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 | ||
*/ | ||
static pk(value, parent, key) { | ||
return this.prototype.pk.call(value, parent, key) || key; | ||
} | ||
/** Returns this to be used in a schema definition. | ||
* This is essential to capture the correct type to be used in inferencing. | ||
*/ | ||
static asSchema() { | ||
return this; | ||
} | ||
static normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
// TODO: what's store needs to be a differing type from fromJS | ||
const processedEntity = this.fromJS(input, parent, key); | ||
const id = processedEntity.pk(parent, key); | ||
/* istanbul ignore next */ | ||
if (id === undefined) { | ||
if (process.env.NODE_ENV !== 'production' && id === undefined) { | ||
throw new Error(`Missing usable resource key when normalizing response. | ||
This is likely due to a malformed response. | ||
Try inspecting the network response or fetch() return value. | ||
Entity: ${this} | ||
Value: ${input && JSON.stringify(input, null, 2)} | ||
`); | ||
} else { | ||
throw new Error('undefined pk'); | ||
} | ||
} | ||
return _denormalize.apply(void 0, [this.schema].concat(args)); | ||
const entityType = this.key; | ||
if (!(entityType in visitedEntities)) { | ||
visitedEntities[entityType] = {}; | ||
} | ||
if (!(id in visitedEntities[entityType])) { | ||
visitedEntities[entityType][id] = []; | ||
} | ||
if (visitedEntities[entityType][id].some(entity => entity === input)) { | ||
return id; | ||
} | ||
visitedEntities[entityType][id].push(input); | ||
Object.keys(this.schema).forEach(key => { | ||
if (Object.hasOwnProperty.call(processedEntity, key) && typeof processedEntity[key] === 'object') { | ||
const schema = this.schema[key]; | ||
processedEntity[key] = visit(processedEntity[key], processedEntity, key, schema, addEntity, visitedEntities); | ||
} | ||
}); | ||
addEntity(this, processedEntity, input, parent, key); | ||
return id; | ||
} // TODO: Add denormalizing capability | ||
static denormalize(entity, unvisit) { | ||
return [entity, true]; | ||
} | ||
} | ||
/* istanbul ignore next */ | ||
Entity.schema = {}; | ||
if (process.env.NODE_ENV !== 'production') { | ||
// for those not using TypeScript this is a good catch to ensure they are defining | ||
// the abstract members | ||
Entity.fromJS = function fromJS(props) { | ||
if (this.prototype.pk === undefined) throw new Error('cannot construct on abstract types'); | ||
return SimpleRecord.fromJS.call(this, props); | ||
}; | ||
} | ||
return ObjectSchema; | ||
}(); | ||
function isEntity(schema) { | ||
return schema !== null && schema.pk !== undefined; | ||
} | ||
var unvisitEntity = function unvisitEntity(id, schema, unvisit, getEntity, cache) { | ||
var entity = getEntity(id, schema); | ||
const unvisitEntity = (id, schema, unvisit, getEntity, cache) => { | ||
const entity = getEntity(id, schema); | ||
@@ -326,15 +410,12 @@ if (typeof entity !== 'object' || entity === null) { | ||
var found = true; | ||
let found = true; | ||
if (!cache[schema.key][id]) { | ||
// Ensure we don't mutate it non-immutable objects | ||
var entityCopy = isImmutable(entity) ? entity : Object.assign({}, entity); // Need to set this first so that if it is referenced further within the | ||
const entityCopy = isImmutable(entity) || entity instanceof SimpleRecord ? entity : { ...entity | ||
}; // Need to set this first so that if it is referenced further within the | ||
// denormalization the reference will already exist. | ||
cache[schema.key][id] = entityCopy; | ||
var _schema$denormalize = schema.denormalize(entityCopy, unvisit); | ||
cache[schema.key][id] = _schema$denormalize[0]; | ||
found = _schema$denormalize[1]; | ||
[cache[schema.key][id], found] = schema.denormalize(entityCopy, unvisit); | ||
} | ||
@@ -345,5 +426,5 @@ | ||
var getUnvisit = function getUnvisit(entities) { | ||
var cache = {}; | ||
var getEntity = getEntities(entities); | ||
const getUnvisit = entities => { | ||
const cache = {}; | ||
const getEntity = getEntities(entities); | ||
return [function unvisit(input, schema) { | ||
@@ -353,3 +434,3 @@ if (!schema) return [input, true]; | ||
if (typeof schema === 'object' && (!schema.denormalize || typeof schema.denormalize !== 'function')) { | ||
var method = Array.isArray(schema) ? denormalize : _denormalize; | ||
const method = Array.isArray(schema) ? denormalize : denormalize$1; | ||
return method(schema, input, unvisit); | ||
@@ -363,3 +444,3 @@ } // null is considered intentional, thus always 'found' as true | ||
if (typeof schema.getId === 'function' && typeof schema.normalize === 'function') { | ||
if (isEntity(schema)) { | ||
// unvisitEntity just can't handle undefined | ||
@@ -381,6 +462,6 @@ if (input === undefined) { | ||
var getEntities = function getEntities(entities) { | ||
var isImmutable$1 = isImmutable(entities); | ||
return function (entityOrId, schema) { | ||
var schemaKey = schema.key; | ||
const getEntities = entities => { | ||
const isImmutable$1 = isImmutable(entities); | ||
return (entityOrId, schema) => { | ||
const schemaKey = schema.key; | ||
@@ -399,3 +480,3 @@ if (typeof entityOrId === 'object') { | ||
var denormalize$1 = function denormalize(input, schema, entities) { | ||
const denormalize$2 = (input, schema, entities) => { | ||
/* istanbul ignore next */ | ||
@@ -406,7 +487,4 @@ // eslint-disable-next-line no-undef | ||
if (typeof input !== 'undefined') { | ||
var _getUnvisit = getUnvisit(entities), | ||
unvisit = _getUnvisit[0], | ||
cache = _getUnvisit[1]; | ||
return [].concat(unvisit(input, schema), [cache]); | ||
const [unvisit, cache] = getUnvisit(entities); | ||
return [...unvisit(input, schema), cache]; | ||
} | ||
@@ -417,139 +495,89 @@ | ||
var getDefaultGetId = function getDefaultGetId(idAttribute) { | ||
return function (input) { | ||
return isImmutable(input) ? input.get(idAttribute) : input[idAttribute]; | ||
}; | ||
}; | ||
const visit = (value, parent, key, schema, addEntity, visitedEntities) => { | ||
if (typeof value !== 'object' || !value || !schema) { | ||
return value; | ||
} | ||
var EntitySchema = /*#__PURE__*/function () { | ||
function EntitySchema(key, definition, options) { | ||
if (definition === void 0) { | ||
definition = {}; | ||
} | ||
if (typeof schema === 'object' && (!schema.normalize || typeof schema.normalize !== 'function')) { | ||
const method = Array.isArray(schema) ? normalize : normalize$1; | ||
return method(schema, value, parent, key, visit, addEntity, visitedEntities); | ||
} | ||
if (options === void 0) { | ||
options = {}; | ||
} | ||
return schema.normalize(value, parent, key, visit, addEntity, visitedEntities); | ||
}; | ||
if (!key || typeof key !== 'string') { | ||
throw new Error("Expected a string key for Entity, but found " + key + "."); | ||
} | ||
const addEntities = (entities, indexes) => (schema, processedEntity, value, parent, key) => { | ||
const schemaKey = schema.key; | ||
const id = schema.pk(processedEntity, parent, key); | ||
var _options = options, | ||
_options$idAttribute = _options.idAttribute, | ||
idAttribute = _options$idAttribute === void 0 ? 'id' : _options$idAttribute, | ||
_options$mergeStrateg = _options.mergeStrategy, | ||
mergeStrategy = _options$mergeStrateg === void 0 ? function (entityA, entityB) { | ||
return Object.assign({}, entityA, {}, entityB); | ||
} : _options$mergeStrateg, | ||
_options$processStrat = _options.processStrategy, | ||
processStrategy = _options$processStrat === void 0 ? function (input) { | ||
return Object.assign({}, input); | ||
} : _options$processStrat; | ||
this._key = key; | ||
this._getId = typeof idAttribute === 'function' ? idAttribute : getDefaultGetId(idAttribute); | ||
this._idAttribute = idAttribute; | ||
this._mergeStrategy = mergeStrategy; | ||
this._processStrategy = processStrategy; | ||
this.define(definition); | ||
if (!(schemaKey in entities)) { | ||
entities[schemaKey] = {}; | ||
} | ||
var _proto = EntitySchema.prototype; | ||
const existingEntity = entities[schemaKey][id]; | ||
_proto.define = function define(definition) { | ||
this.schema = Object.keys(definition).reduce(function (entitySchema, key) { | ||
var _Object$assign; | ||
if (existingEntity) { | ||
entities[schemaKey][id] = schema.merge(existingEntity, processedEntity); | ||
} else { | ||
entities[schemaKey][id] = processedEntity; | ||
} // update index | ||
var schema = definition[key]; | ||
return Object.assign({}, entitySchema, (_Object$assign = {}, _Object$assign[key] = schema, _Object$assign)); | ||
}, this.schema || {}); | ||
}; | ||
_proto.getId = function getId(input, parent, key) { | ||
return this._getId(input, parent, key); | ||
}; | ||
if (Array.isArray(schema.indexes)) { | ||
const entity = entities[schemaKey][id]; | ||
_proto.merge = function merge(entityA, entityB) { | ||
return this._mergeStrategy(entityA, entityB); | ||
}; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
var id = this.getId(input, parent, key); | ||
var entityType = this.key; | ||
if (!(entityType in visitedEntities)) { | ||
visitedEntities[entityType] = {}; | ||
if (!(schemaKey in indexes)) { | ||
indexes[schemaKey] = {}; | ||
} | ||
if (!(id in visitedEntities[entityType])) { | ||
visitedEntities[entityType][id] = []; | ||
} | ||
for (const index of schema.indexes) { | ||
if (!(index in indexes[schemaKey])) { | ||
indexes[schemaKey][index] = {}; | ||
} | ||
if (visitedEntities[entityType][id].some(function (entity) { | ||
return entity === input; | ||
})) { | ||
return id; | ||
} | ||
const indexMap = indexes[schemaKey][index]; | ||
visitedEntities[entityType][id].push(input); | ||
if (existingEntity) { | ||
delete indexMap[existingEntity[index]]; | ||
} | ||
var processedEntity = this._processStrategy(input, parent, key); | ||
Object.keys(this.schema).forEach(function (key) { | ||
if (Object.hasOwnProperty.call(processedEntity, key) && typeof processedEntity[key] === 'object') { | ||
var schema = _this.schema[key]; | ||
processedEntity[key] = visit(processedEntity[key], processedEntity, key, schema, addEntity, visitedEntities); | ||
if (index in entity) { | ||
indexMap[entity[index]] = id; | ||
} | ||
}); | ||
addEntity(this, processedEntity, input, parent, key); | ||
return id; | ||
}; | ||
_proto.denormalize = function denormalize(entity, unvisit) { | ||
var _this2 = this; | ||
if (isImmutable(entity)) { | ||
return denormalizeImmutable(this.schema, entity, unvisit); | ||
/* 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. | ||
Index: ${index} | ||
Entity: ${JSON.stringify(entity, undefined, 2)}`); | ||
} | ||
} | ||
} | ||
}; | ||
var found = true; | ||
Object.keys(this.schema).forEach(function (key) { | ||
var schema = _this2.schema[key]; | ||
function expectedSchemaType(schema) { | ||
return ['object', 'function'].includes(typeof schema) ? 'object' : typeof schema; | ||
} | ||
var _unvisit = unvisit(entity[key], schema), | ||
value = _unvisit[0], | ||
foundItem = _unvisit[1]; | ||
const normalize$2 = (input, schema) => { | ||
const schemaType = expectedSchemaType(schema); | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
if (input === null || typeof input !== schemaType) { | ||
throw new Error(`Unexpected input given to normalize. Expected type to be "${schemaType}", found "${input === null ? 'null' : typeof input}".`); | ||
} | ||
if (Object.hasOwnProperty.call(entity, key)) { | ||
entity[key] = value; | ||
} | ||
}); | ||
return [entity, found]; | ||
const entities = {}; | ||
const indexes = {}; | ||
const addEntity = addEntities(entities, indexes); | ||
const visitedEntities = {}; | ||
const result = visit(input, input, undefined, schema, addEntity, visitedEntities); | ||
return { | ||
entities, | ||
indexes, | ||
result | ||
}; | ||
}; | ||
_createClass(EntitySchema, [{ | ||
key: "key", | ||
get: function get() { | ||
return this._key; | ||
} | ||
}, { | ||
key: "idAttribute", | ||
get: function get() { | ||
return this._idAttribute; | ||
} | ||
}]); | ||
return EntitySchema; | ||
}(); | ||
var UnionSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(UnionSchema, _PolymorphicSchema); | ||
function UnionSchema(definition, schemaAttribute) { | ||
class UnionSchema extends PolymorphicSchema { | ||
constructor(definition, schemaAttribute) { | ||
if (!schemaAttribute) { | ||
@@ -559,51 +587,31 @@ throw new Error('Expected option "schemaAttribute" not found on UnionSchema.'); | ||
return _PolymorphicSchema.call(this, definition, schemaAttribute) || this; | ||
super(definition, schemaAttribute); | ||
} | ||
var _proto = UnionSchema.prototype; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
return this.normalizeValue(input, parent, key, visit, addEntity, visitedEntities); | ||
}; | ||
} | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
denormalize(input, unvisit) { | ||
return this.denormalizeValue(input, unvisit); | ||
}; | ||
return UnionSchema; | ||
}(PolymorphicSchema); | ||
var ValuesSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ValuesSchema, _PolymorphicSchema); | ||
function ValuesSchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
} | ||
var _proto = ValuesSchema.prototype; | ||
} | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
return Object.keys(input).reduce(function (output, key, index) { | ||
var _Object$assign; | ||
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; | ||
class ValuesSchema extends PolymorphicSchema { | ||
normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
return Object.keys(input).reduce((output, key, index) => { | ||
const value = input[key]; | ||
return value !== undefined && value !== null ? { ...output, | ||
[key]: this.normalizeValue(value, input, key, visit, addEntity, visitedEntities) | ||
} : output; | ||
}, {}); | ||
}; | ||
} | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
denormalize(input, unvisit) { | ||
let found = true; | ||
return [Object.keys(input).reduce((output, key) => { | ||
const entityOrId = input[key]; | ||
const [value, foundItem] = this.denormalizeValue(entityOrId, unvisit); | ||
var found = true; | ||
return [Object.keys(input).reduce(function (output, key) { | ||
var _Object$assign2; | ||
var entityOrId = input[key]; | ||
var _this2$denormalizeVal = _this2.denormalizeValue(entityOrId, unvisit), | ||
value = _this2$denormalizeVal[0], | ||
foundItem = _this2$denormalizeVal[1]; | ||
if (!foundItem) { | ||
@@ -613,117 +621,32 @@ found = false; | ||
return Object.assign({}, output, (_Object$assign2 = {}, _Object$assign2[key] = value, _Object$assign2)); | ||
return { ...output, | ||
[key]: value | ||
}; | ||
}, {}), found]; | ||
}; | ||
return ValuesSchema; | ||
}(PolymorphicSchema); | ||
var visit = function visit(value, parent, key, schema, addEntity, visitedEntities) { | ||
if (typeof value !== 'object' || !value || !schema) { | ||
return value; | ||
} | ||
if (typeof schema === 'object' && (!schema.normalize || typeof schema.normalize !== 'function')) { | ||
var method = Array.isArray(schema) ? normalize : _normalize; | ||
return method(schema, value, parent, key, visit, addEntity, visitedEntities); | ||
} | ||
} | ||
return schema.normalize(value, parent, key, visit, addEntity, visitedEntities); | ||
}; | ||
var addEntities = function addEntities(entities, indexes) { | ||
return function (schema, processedEntity, value, parent, key) { | ||
var schemaKey = schema.key; | ||
var id = schema.getId(value, parent, key); | ||
if (!(schemaKey in entities)) { | ||
entities[schemaKey] = {}; | ||
} | ||
var existingEntity = entities[schemaKey][id]; | ||
if (existingEntity) { | ||
entities[schemaKey][id] = schema.merge(existingEntity, processedEntity); | ||
} else { | ||
entities[schemaKey][id] = processedEntity; | ||
} // update index | ||
if (Array.isArray(schema.indexes)) { | ||
var entity = entities[schemaKey][id]; | ||
if (!(schemaKey in indexes)) { | ||
indexes[schemaKey] = {}; | ||
} | ||
for (var _iterator = schema.indexes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { | ||
var _ref; | ||
if (_isArray) { | ||
if (_i >= _iterator.length) break; | ||
_ref = _iterator[_i++]; | ||
} else { | ||
_i = _iterator.next(); | ||
if (_i.done) break; | ||
_ref = _i.value; | ||
} | ||
var index = _ref; | ||
if (!(index in indexes[schemaKey])) { | ||
indexes[schemaKey][index] = {}; | ||
} | ||
var indexMap = indexes[schemaKey][index]; | ||
if (existingEntity) { | ||
delete indexMap[existingEntity[index]]; | ||
} | ||
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)); | ||
} | ||
} | ||
} | ||
}; | ||
}; | ||
var schema = { | ||
var schema = /*#__PURE__*/Object.freeze({ | ||
__proto__: null, | ||
Union: UnionSchema, | ||
Values: ValuesSchema, | ||
Array: ArraySchema, | ||
Entity: EntitySchema, | ||
Object: ObjectSchema, | ||
Union: UnionSchema, | ||
Values: ValuesSchema | ||
}; | ||
Object: ObjectSchema | ||
}); | ||
function expectedSchemaType(schema) { | ||
return ['object', 'function'].includes(typeof schema) ? 'object' : typeof schema; | ||
} | ||
var normalize$1 = function normalize(input, schema) { | ||
var schemaType = expectedSchemaType(schema); | ||
if (input === null || typeof input !== schemaType) { | ||
throw new Error("Unexpected input given to normalize. Expected type to be \"" + schemaType + "\", found \"" + (input === null ? 'null' : typeof input) + "\"."); | ||
class NotImplementedError extends Error { | ||
constructor(...args) { | ||
super(...args); | ||
this.message = process.env.NODE_ENV === 'production' ? 'Not Implemented' : 'Not Implemented. You must provide an override for this method.'; | ||
} | ||
var entities = {}; | ||
var indexes = {}; | ||
var addEntity = addEntities(entities, indexes); | ||
var visitedEntities = {}; | ||
var result = visit(input, input, undefined, schema, addEntity, visitedEntities); | ||
return { | ||
entities: entities, | ||
indexes: indexes, | ||
result: result | ||
}; | ||
}; | ||
} | ||
exports.denormalize = denormalize$1; | ||
exports.normalize = normalize$1; | ||
exports.Entity = Entity; | ||
exports.NotImplementedError = NotImplementedError; | ||
exports.SimpleRecord = SimpleRecord; | ||
exports.denormalize = denormalize$2; | ||
exports.isEntity = isEntity; | ||
exports.normalize = normalize$2; | ||
exports.schema = schema; | ||
@@ -730,0 +653,0 @@ |
@@ -1,1 +0,1 @@ | ||
define(["exports"],(function(e){"use strict";function t(e){return!(!e||"function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}function n(e,t,n){let r=!0;return[Object.keys(e).reduce((t,i)=>{const s=""+i,[o,c]=n(t.get(s),e[s]);return c||(r=!1),t.has(s)?t.set(s,o):t},t),r]}class r{constructor(e,t){t&&(this._schemaAttribute="string"==typeof t?e=>e[t]:t),this.define(e)}get isSingleSchema(){return!this._schemaAttribute}define(e){this.schema=e}getSchemaAttribute(e,t,n){return!this.isSingleSchema&&this._schemaAttribute(e,t,n)}inferSchema(e,t,n){if(this.isSingleSchema)return this.schema;const r=this.getSchemaAttribute(e,t,n);return this.schema[r]}normalizeValue(e,t,n,r,i,s){const o=this.inferSchema(e,t,n);if(!o)return e;const c=r(e,t,n,o,i,s);return this.isSingleSchema||null==c?c:{id:c,schema:this.getSchemaAttribute(e,t,n)}}denormalizeValue(e,n){const r=t(e)?e.get("schema"):e.schema;return this.isSingleSchema||r?n((this.isSingleSchema?void 0:t(e)?e.get("id"):e.id)||e,this.isSingleSchema?this.schema:this.schema[r]):[e,!0]}}const i=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]},s=e=>Array.isArray(e)?e:Object.keys(e).map(t=>e[t]),o=(e,t,n,r,o,c,a)=>(e=i(e),s(t).map((t,i)=>o(t,n,r,e,c,a))),c=(e,t,n)=>{e=i(e);let r=!0;return void 0===t&&e&&([,r]=n(void 0,e)),[t&&t.map?t.map(t=>n(t,e)).filter(([,e])=>e).map(([e])=>e):t,r]};const a=(e,t,n,r,i,s,o)=>{const c=Object.assign({},t);return Object.keys(e).forEach(n=>{const r=e[n],a=i(t[n],t,n,r,s,o);null==a?delete c[n]:c[n]=a}),c},u=(e,r,i)=>{if(t(r))return n(e,r,i);const s=Object.assign({},r);let o=!0;return Object.keys(e).forEach(t=>{const[n,r]=i(s[t],e[t]);void 0!==s[t]&&(s[t]=n),r||(o=!1)}),[s,o]};const h=e=>{const n={},r=l(e);return[function e(i,s){if(!s)return[i,!0];if("object"==typeof s&&(!s.denormalize||"function"!=typeof s.denormalize)){return(Array.isArray(s)?c:u)(s,i,e)}return null===i?[i,!0]:"function"==typeof s.getId&&"function"==typeof s.normalize?void 0===i?[i,!1]:((e,n,r,i,s)=>{const o=i(e,n);if("object"!=typeof o||null===o)return[o,!1];s[n.key]||(s[n.key]={});let c=!0;if(!s[n.key][e]){const i=t(o)?o:Object.assign({},o);s[n.key][e]=i,[s[n.key][e],c]=n.denormalize(i,r)}return[s[n.key][e],c]})(i,s,e,r,n):"function"==typeof s.denormalize?s.denormalize(i,e):[i,!0]},n]},l=e=>{const n=t(e);return(t,r)=>{const i=r.key;return"object"==typeof t?t:n?e.getIn([i,t.toString()]):e[i]&&e[i][t]}};const m=(e,t,n,r,i,s)=>{if("object"!=typeof e||!e||!r)return e;if("object"==typeof r&&(!r.normalize||"function"!=typeof r.normalize)){return(Array.isArray(r)?o:a)(r,e,t,n,m,i,s)}return r.normalize(e,t,n,m,i,s)},d={Array:class extends r{normalize(e,t,n,r,i,o){return s(e).map((e,s)=>this.normalizeValue(e,t,n,r,i,o)).filter(e=>null!=e)}denormalize(e,t){let n=!0;return void 0===e&&this.schema&&([,n]=t(void 0,this.schema)),[e&&e.map?e.map(e=>this.denormalizeValue(e,t)).filter(([,e])=>e).map(([e])=>e):e,n]}},Entity:class{constructor(e,n={},r={}){if(!e||"string"!=typeof e)throw new Error("Expected a string key for Entity, but found "+e+".");const{idAttribute:i="id",mergeStrategy:s=((e,t)=>Object.assign({},e,{},t)),processStrategy:o=(e=>Object.assign({},e))}=r;this._key=e,this._getId="function"==typeof i?i:(e=>n=>t(n)?n.get(e):n[e])(i),this._idAttribute=i,this._mergeStrategy=s,this._processStrategy=o,this.define(n)}get key(){return this._key}get idAttribute(){return this._idAttribute}define(e){this.schema=Object.keys(e).reduce((t,n)=>{const r=e[n];return Object.assign({},t,{[n]:r})},this.schema||{})}getId(e,t,n){return this._getId(e,t,n)}merge(e,t){return this._mergeStrategy(e,t)}normalize(e,t,n,r,i,s){const o=this.getId(e,t,n),c=this.key;if(c in s||(s[c]={}),o in s[c]||(s[c][o]=[]),s[c][o].some(t=>t===e))return o;s[c][o].push(e);const a=this._processStrategy(e,t,n);return Object.keys(this.schema).forEach(e=>{if(Object.hasOwnProperty.call(a,e)&&"object"==typeof a[e]){const t=this.schema[e];a[e]=r(a[e],a,e,t,i,s)}}),i(this,a,e,t,n),o}denormalize(e,r){if(t(e))return n(this.schema,e,r);let i=!0;return Object.keys(this.schema).forEach(t=>{const n=this.schema[t],[s,o]=r(e[t],n);o||(i=!1),Object.hasOwnProperty.call(e,t)&&(e[t]=s)}),[e,i]}},Object:class{constructor(e){this.define(e)}define(e){this.schema=Object.keys(e).reduce((t,n)=>{const r=e[n];return Object.assign({},t,{[n]:r})},this.schema||{})}normalize(...e){return a(this.schema,...e)}denormalize(...e){return u(this.schema,...e)}},Union:class extends r{constructor(e,t){if(!t)throw new Error('Expected option "schemaAttribute" not found on UnionSchema.');super(e,t)}normalize(e,t,n,r,i,s){return this.normalizeValue(e,t,n,r,i,s)}denormalize(e,t){return this.denormalizeValue(e,t)}},Values:class extends r{normalize(e,t,n,r,i,s){return Object.keys(e).reduce((t,n,o)=>{const c=e[n];return null!=c?Object.assign({},t,{[n]:this.normalizeValue(c,e,n,r,i,s)}):t},{})}denormalize(e,t){let n=!0;return[Object.keys(e).reduce((r,i)=>{const s=e[i],[o,c]=this.denormalizeValue(s,t);return c||(n=!1),Object.assign({},r,{[i]:o})},{}),n]}}};e.denormalize=(e,t,n)=>{if("production"!==process.env.NODE_ENV&&void 0===t)throw new Error("shema needed");if(void 0!==e){const[r,i]=h(n);return[...r(e,t),i]}return[void 0,!1,{}]},e.normalize=(e,t)=>{const n=function(e){return["object","function"].includes(typeof e)?"object":typeof e}(t);if(null===e||typeof e!==n)throw new Error('Unexpected input given to normalize. Expected type to be "'+n+'", found "'+(null===e?"null":typeof e)+'".');const r={},i={},s=((e,t)=>(n,r,i,s,o)=>{const c=n.key,a=n.getId(i,s,o);c in e||(e[c]={});const u=e[c][a];if(e[c][a]=u?n.merge(u,r):r,Array.isArray(n.indexes)){const r=e[c][a];c in t||(t[c]={});for(const e of n.indexes){e in t[c]||(t[c][e]={});const n=t[c][e];u&&delete n[u[e]],e in r?n[r[e]]=a:"production"!==process.env.NODE_ENV&&console.warn("Index not found in entity. Indexes must be top-level members of your entity.\nIndex: "+e+"\nEntity: "+JSON.stringify(r,void 0,2))}}})(r,i);return{entities:r,indexes:i,result:m(e,e,void 0,t,s,{})}},e.schema=d,Object.defineProperty(e,"__esModule",{value:!0})})); | ||
define(["exports"],(function(e){"use strict";function t(e){return!(!e||"function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}class n{constructor(e,t){t&&(this._schemaAttribute="string"==typeof t?e=>e[t]:t),this.define(e)}get isSingleSchema(){return!this._schemaAttribute}define(e){this.schema=e}getSchemaAttribute(e,t,n){return!this.isSingleSchema&&this._schemaAttribute(e,t,n)}inferSchema(e,t,n){if(this.isSingleSchema)return this.schema;const r=this.getSchemaAttribute(e,t,n);return this.schema[r]}normalizeValue(e,t,n,r,i,s){const o=this.inferSchema(e,t,n);if(!o)return e;const c=r(e,t,n,o,i,s);return this.isSingleSchema||null==c?c:{id:c,schema:this.getSchemaAttribute(e,t,n)}}denormalizeValue(e,n){const r=t(e)?e.get("schema"):e.schema;return this.isSingleSchema||r?n((this.isSingleSchema?void 0:t(e)?e.get("id"):e.id)||e,this.isSingleSchema?this.schema:this.schema[r]):[e,!0]}}const r=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]},i=e=>Array.isArray(e)?e:Object.keys(e).map(t=>e[t]),s=(e,t,n,s,o,c,a)=>(e=r(e),i(t).map((t,r)=>o(t,n,s,e,c,a))),o=(e,t,n)=>{e=r(e);let i=!0;return void 0===t&&e&&([,i]=n(void 0,e)),[t&&t.map?t.map(t=>n(t,e)).filter(([,e])=>e).map(([e])=>e):t,i]};const c=(e,t,n,r,i,s,o)=>{const c=Object.assign({},t);return Object.keys(e).forEach(n=>{const r=e[n],a=i(t[n],t,n,r,s,o);null==a?delete c[n]:c[n]=a}),c},a=(e,n,r)=>{if(t(n))return function(e,t,n){let r=!0;return[Object.keys(e).reduce((t,i)=>{const s=`${i}`,[o,c]=n(t.get(s),e[s]);return c||(r=!1),t.has(s)?t.set(s,o):t},t),r]}(e,n,r);const i=Object.assign({},n);let s=!0;return Object.keys(e).forEach(t=>{const[n,o]=r(i[t],e[t]);void 0!==i[t]&&(i[t]=n),o||(s=!1)}),[i,s]};const u=Symbol("Defined Members"),l=Symbol("unq");class h{toString(){return this[l]}static fromJS(e={},t,n){const r=new this(e);return Object.defineProperty(r,u,{value:Object.keys(e),writable:!1}),Object.defineProperty(r,l,{value:`${Math.random()}`,writable:!1}),Object.assign(r,e),r}static merge(e,t){const n=Object.assign(this.toObjectDefined(e),this.toObjectDefined(t));return this.fromJS(n)}static hasDefined(e,t){return e[u].includes(t)}static toObjectDefined(e){const t={};for(const n of e[u])t[n]=e[n];return t}static keysDefined(e){return e[u]}}class m extends h{static get key(){if("production"!==process.env.NODE_ENV&&""===this.name)throw new Error("Entity classes without a name must define `static get key()`");return this.name}static pk(e,t,n){return this.prototype.pk.call(e,t,n)||n}static asSchema(){return this}static normalize(e,t,n,r,i,s){const o=this.fromJS(e,t,n),c=o.pk(t,n);if(void 0===c)throw"production"!==process.env.NODE_ENV&&void 0===c?new Error(`Missing usable resource 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\n Entity: ${this}\n Value: ${e&&JSON.stringify(e,null,2)}\n `):new Error("undefined pk");const a=this.key;return a in s||(s[a]={}),c in s[a]||(s[a][c]=[]),s[a][c].some(t=>t===e)||(s[a][c].push(e),Object.keys(this.schema).forEach(e=>{if(Object.hasOwnProperty.call(o,e)&&"object"==typeof o[e]){const t=this.schema[e];o[e]=r(o[e],o,e,t,i,s)}}),i(this,o,e,t,n)),c}static denormalize(e,t){return[e,!0]}}function d(e){return null!==e&&void 0!==e.pk}m.schema={},"production"!==process.env.NODE_ENV&&(m.fromJS=function(e){if(void 0===this.prototype.pk)throw new Error("cannot construct on abstract types");return h.fromJS.call(this,e)});const f=e=>{const n={},r=p(e);return[function e(i,s){if(!s)return[i,!0];if("object"==typeof s&&(!s.denormalize||"function"!=typeof s.denormalize)){return(Array.isArray(s)?o:a)(s,i,e)}return null===i?[i,!0]:d(s)?void 0===i?[i,!1]:((e,n,r,i,s)=>{const o=i(e,n);if("object"!=typeof o||null===o)return[o,!1];s[n.key]||(s[n.key]={});let c=!0;if(!s[n.key][e]){const i=t(o)||o instanceof h?o:Object.assign({},o);s[n.key][e]=i,[s[n.key][e],c]=n.denormalize(i,r)}return[s[n.key][e],c]})(i,s,e,r,n):"function"==typeof s.denormalize?s.denormalize(i,e):[i,!0]},n]},p=e=>{const n=t(e);return(t,r)=>{const i=r.key;return"object"==typeof t?t:n?e.getIn([i,t.toString()]):e[i]&&e[i][t]}},y=(e,t,n,r,i,o)=>{if("object"!=typeof e||!e||!r)return e;if("object"==typeof r&&(!r.normalize||"function"!=typeof r.normalize)){return(Array.isArray(r)?s:c)(r,e,t,n,y,i,o)}return r.normalize(e,t,n,y,i,o)};var b=Object.freeze({__proto__:null,Union:class extends n{constructor(e,t){if(!t)throw new Error('Expected option "schemaAttribute" not found on UnionSchema.');super(e,t)}normalize(e,t,n,r,i,s){return this.normalizeValue(e,t,n,r,i,s)}denormalize(e,t){return this.denormalizeValue(e,t)}},Values:class extends n{normalize(e,t,n,r,i,s){return Object.keys(e).reduce((t,n,o)=>{const c=e[n];return null!=c?Object.assign({},t,{[n]:this.normalizeValue(c,e,n,r,i,s)}):t},{})}denormalize(e,t){let n=!0;return[Object.keys(e).reduce((r,i)=>{const s=e[i],[o,c]=this.denormalizeValue(s,t);return c||(n=!1),Object.assign({},r,{[i]:o})},{}),n]}},Array:class extends n{normalize(e,t,n,r,s,o){return i(e).map((e,i)=>this.normalizeValue(e,t,n,r,s,o)).filter(e=>null!=e)}denormalize(e,t){let n=!0;return void 0===e&&this.schema&&([,n]=t(void 0,this.schema)),[e&&e.map?e.map(e=>this.denormalizeValue(e,t)).filter(([,e])=>e).map(([e])=>e):e,n]}},Object:class{constructor(e){this.define(e)}define(e){this.schema=Object.keys(e).reduce((t,n)=>{const r=e[n];return Object.assign({},t,{[n]:r})},this.schema||{})}normalize(...e){return c(this.schema,...e)}denormalize(...e){return a(this.schema,...e)}}});class g extends Error{constructor(...e){super(...e),this.message="production"===process.env.NODE_ENV?"Not Implemented":"Not Implemented. You must provide an override for this method."}}e.Entity=m,e.NotImplementedError=g,e.SimpleRecord=h,e.denormalize=(e,t,n)=>{if("production"!==process.env.NODE_ENV&&void 0===t)throw new Error("shema needed");if(void 0!==e){const[r,i]=f(n);return[...r(e,t),i]}return[void 0,!1,{}]},e.isEntity=d,e.normalize=(e,t)=>{const n=function(e){return["object","function"].includes(typeof e)?"object":typeof e}(t);if(null===e||typeof e!==n)throw new Error(`Unexpected input given to normalize. Expected type to be "${n}", found "${null===e?"null":typeof e}".`);const r={},i={},s=((e,t)=>(n,r,i,s,o)=>{const c=n.key,a=n.pk(r,s,o);c in e||(e[c]={});const u=e[c][a];if(e[c][a]=u?n.merge(u,r):r,Array.isArray(n.indexes)){const r=e[c][a];c in t||(t[c]={});for(const e of n.indexes){e in t[c]||(t[c][e]={});const n=t[c][e];u&&delete n[u[e]],e in r?n[r[e]]=a:"production"!==process.env.NODE_ENV&&console.warn(`Index not found in entity. Indexes must be top-level members of your entity.\nIndex: ${e}\nEntity: ${JSON.stringify(r,void 0,2)}`)}}})(r,i);return{entities:r,indexes:i,result:y(e,e,void 0,t,s,{})}},e.schema=b,Object.defineProperty(e,"__esModule",{value:!0})})); |
@@ -31,12 +31,9 @@ var rest_hooks_normalizr = (function (exports) { | ||
function denormalizeImmutable(schema, input, unvisit) { | ||
var found = true; | ||
return [Object.keys(schema).reduce(function (object, key) { | ||
let found = true; | ||
return [Object.keys(schema).reduce((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; | ||
const stringKey = `${key}`; | ||
const [item, foundItem] = unvisit(object.get(stringKey), schema[stringKey]); | ||
var _unvisit = unvisit(object.get(stringKey), schema[stringKey]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1]; | ||
if (!foundItem) { | ||
@@ -54,30 +51,6 @@ found = false; | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
subClass.__proto__ = superClass; | ||
} | ||
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); | ||
} | ||
} | ||
function _createClass(Constructor, protoProps, staticProps) { | ||
if (protoProps) _defineProperties(Constructor.prototype, protoProps); | ||
if (staticProps) _defineProperties(Constructor, staticProps); | ||
return Constructor; | ||
} | ||
var PolymorphicSchema = /*#__PURE__*/function () { | ||
function PolymorphicSchema(definition, schemaAttribute) { | ||
class PolymorphicSchema { | ||
constructor(definition, schemaAttribute) { | ||
if (schemaAttribute) { | ||
this._schemaAttribute = typeof schemaAttribute === 'string' ? function (input) { | ||
return input[schemaAttribute]; | ||
} : schemaAttribute; | ||
this._schemaAttribute = typeof schemaAttribute === 'string' ? input => input[schemaAttribute] : schemaAttribute; | ||
} | ||
@@ -88,13 +61,15 @@ | ||
var _proto = PolymorphicSchema.prototype; | ||
get isSingleSchema() { | ||
return !this._schemaAttribute; | ||
} | ||
_proto.define = function define(definition) { | ||
define(definition) { | ||
this.schema = definition; | ||
}; | ||
} | ||
_proto.getSchemaAttribute = function getSchemaAttribute(input, parent, key) { | ||
getSchemaAttribute(input, parent, key) { | ||
return !this.isSingleSchema && this._schemaAttribute(input, parent, key); | ||
}; | ||
} | ||
_proto.inferSchema = function inferSchema(input, parent, key) { | ||
inferSchema(input, parent, key) { | ||
if (this.isSingleSchema) { | ||
@@ -104,8 +79,8 @@ return this.schema; | ||
var attr = this.getSchemaAttribute(input, parent, key); | ||
const 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); | ||
normalizeValue(value, parent, key, visit, addEntity, visitedEntities) { | ||
const schema = this.inferSchema(value, parent, key); | ||
@@ -116,3 +91,3 @@ if (!schema) { | ||
var normalizedValue = visit(value, parent, key, schema, addEntity, visitedEntities); | ||
const normalizedValue = visit(value, parent, key, schema, addEntity, visitedEntities); | ||
return this.isSingleSchema || normalizedValue === undefined || normalizedValue === null ? normalizedValue : { | ||
@@ -122,6 +97,6 @@ id: normalizedValue, | ||
}; | ||
}; | ||
} | ||
_proto.denormalizeValue = function denormalizeValue(value, unvisit) { | ||
var schemaKey = isImmutable(value) ? value.get('schema') : value.schema; | ||
denormalizeValue(value, unvisit) { | ||
const schemaKey = isImmutable(value) ? value.get('schema') : value.schema; | ||
@@ -132,22 +107,14 @@ if (!this.isSingleSchema && !schemaKey) { | ||
var id = this.isSingleSchema ? undefined : isImmutable(value) ? value.get('id') : value.id; | ||
var schema = this.isSingleSchema ? this.schema : this.schema[schemaKey]; | ||
const id = this.isSingleSchema ? undefined : isImmutable(value) ? value.get('id') : value.id; | ||
const schema = this.isSingleSchema ? this.schema : this.schema[schemaKey]; | ||
return unvisit(id || value, schema); | ||
}; | ||
} | ||
_createClass(PolymorphicSchema, [{ | ||
key: "isSingleSchema", | ||
get: function get() { | ||
return !this._schemaAttribute; | ||
} | ||
}]); | ||
} | ||
return PolymorphicSchema; | ||
}(); | ||
const validateSchema = definition => { | ||
const isArray = Array.isArray(definition); | ||
var validateSchema = function validateSchema(definition) { | ||
var isArray = Array.isArray(definition); | ||
if (isArray && definition.length > 1) { | ||
throw new Error("Expected schema definition to be a single schema, but found " + definition.length + "."); | ||
throw new Error(`Expected schema definition to be a single schema, but found ${definition.length}.`); | ||
} | ||
@@ -158,88 +125,45 @@ | ||
var getValues = function getValues(input) { | ||
return Array.isArray(input) ? input : Object.keys(input).map(function (key) { | ||
return input[key]; | ||
}); | ||
}; | ||
const getValues = input => Array.isArray(input) ? input : Object.keys(input).map(key => input[key]); | ||
var normalize = function normalize(schema, input, parent, key, visit, addEntity, visitedEntities) { | ||
const 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 | ||
const 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 | ||
return values.map(function (value, index) { | ||
return visit(value, parent, key, schema, addEntity, visitedEntities); | ||
}); | ||
return values.map((value, index) => visit(value, parent, key, schema, addEntity, visitedEntities)); | ||
}; | ||
var denormalize = function denormalize(schema, input, unvisit) { | ||
const denormalize = (schema, input, unvisit) => { | ||
schema = validateSchema(schema); | ||
var found = true; | ||
let found = true; | ||
if (input === undefined && schema) { | ||
var _unvisit = unvisit(undefined, schema); | ||
found = _unvisit[1]; | ||
[, found] = unvisit(undefined, schema); | ||
} | ||
return [input && input.map ? input.map(function (entityOrId) { | ||
return unvisit(entityOrId, schema); | ||
}).filter(function (_ref) { | ||
var foundItem = _ref[1]; | ||
return foundItem; | ||
}).map(function (_ref2) { | ||
var value = _ref2[0]; | ||
return value; | ||
}) : input, found]; | ||
return [input && input.map ? input.map(entityOrId => unvisit(entityOrId, schema)).filter(([, foundItem]) => foundItem).map(([value]) => value) : input, found]; | ||
}; | ||
var ArraySchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ArraySchema, _PolymorphicSchema); | ||
function ArraySchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
class ArraySchema extends PolymorphicSchema { | ||
normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
const values = getValues(input); | ||
return values.map((value, index) => this.normalizeValue(value, parent, key, visit, addEntity, visitedEntities)).filter(value => value !== undefined && value !== null); | ||
} | ||
var _proto = ArraySchema.prototype; | ||
denormalize(input, unvisit) { | ||
let found = true; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
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.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
var found = true; | ||
if (input === undefined && this.schema) { | ||
var _unvisit2 = unvisit(undefined, this.schema); | ||
found = _unvisit2[1]; | ||
[, found] = unvisit(undefined, this.schema); | ||
} | ||
return [input && input.map ? input.map(function (entityOrId) { | ||
return _this2.denormalizeValue(entityOrId, unvisit); | ||
}).filter(function (_ref3) { | ||
var foundItem = _ref3[1]; | ||
return foundItem; | ||
}).map(function (_ref4) { | ||
var value = _ref4[0]; | ||
return value; | ||
}) : input, found]; | ||
}; | ||
return [input && input.map ? input.map(entityOrId => this.denormalizeValue(entityOrId, unvisit)).filter(([, foundItem]) => foundItem).map(([value]) => value) : input, found]; | ||
} | ||
return ArraySchema; | ||
}(PolymorphicSchema); | ||
} | ||
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); | ||
const normalize$1 = (schema, input, parent, key, visit, addEntity, visitedEntities) => { | ||
const object = { ...input | ||
}; | ||
Object.keys(schema).forEach(key => { | ||
const localSchema = schema[key]; | ||
const value = visit(input[key], input, key, localSchema, addEntity, visitedEntities); | ||
@@ -254,4 +178,3 @@ if (value === undefined || value === null) { | ||
}; | ||
var _denormalize = function denormalize(schema, input, unvisit) { | ||
const denormalize$1 = (schema, input, unvisit) => { | ||
if (isImmutable(input)) { | ||
@@ -261,8 +184,7 @@ return denormalizeImmutable(schema, input, unvisit); | ||
var object = Object.assign({}, input); | ||
var found = true; | ||
Object.keys(schema).forEach(function (key) { | ||
var _unvisit = unvisit(object[key], schema[key]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1]; | ||
const object = { ...input | ||
}; | ||
let found = true; | ||
Object.keys(schema).forEach(key => { | ||
const [item, foundItem] = unvisit(object[key], schema[key]); | ||
@@ -279,40 +201,202 @@ if (object[key] !== undefined) { | ||
}; | ||
var ObjectSchema = /*#__PURE__*/function () { | ||
function ObjectSchema(definition) { | ||
class ObjectSchema { | ||
constructor(definition) { | ||
this.define(definition); | ||
} | ||
var _proto = ObjectSchema.prototype; | ||
define(definition) { | ||
this.schema = Object.keys(definition).reduce((entitySchema, key) => { | ||
const schema = definition[key]; | ||
return { ...entitySchema, | ||
[key]: schema | ||
}; | ||
}, this.schema || {}); | ||
} | ||
_proto.define = function define(definition) { | ||
this.schema = Object.keys(definition).reduce(function (entitySchema, key) { | ||
var _Object$assign; | ||
normalize(...args) { | ||
return normalize$1(this.schema, ...args); | ||
} | ||
var schema = definition[key]; | ||
return Object.assign({}, entitySchema, (_Object$assign = {}, _Object$assign[key] = schema, _Object$assign)); | ||
}, this.schema || {}); | ||
}; | ||
denormalize(...args) { | ||
return denormalize$1(this.schema, ...args); | ||
} | ||
_proto.normalize = function normalize() { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
const DefinedMembersKey = Symbol('Defined Members'); | ||
const UniqueIdentifierKey = Symbol('unq'); | ||
/** Immutable record that keeps track of which members are defined vs defaults. */ | ||
class SimpleRecord { | ||
toString() { | ||
// we don't make _unq a member so it doesn't play a role in type compatibility | ||
return this[UniqueIdentifierKey]; | ||
} | ||
/** 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 | ||
*/ | ||
static fromJS( // TODO: this should only accept members that are not functions | ||
props = {}, parent, key) { | ||
// we type guarded abstract case above, so ok to force typescript to allow constructor call | ||
const instance = new this(props); | ||
Object.defineProperty(instance, DefinedMembersKey, { | ||
value: Object.keys(props), | ||
writable: false | ||
}); // a 'unique' identifier to make referential equality comparisons easy | ||
Object.defineProperty(instance, UniqueIdentifierKey, { | ||
value: `${Math.random()}`, | ||
writable: false | ||
}); | ||
Object.assign(instance, props); | ||
return instance; | ||
} | ||
/** Creates new instance copying over defined values of arguments */ | ||
static merge(first, second) { | ||
const props = Object.assign(this.toObjectDefined(first), this.toObjectDefined(second)); | ||
return this.fromJS(props); | ||
} | ||
/** Whether key is non-default */ | ||
static hasDefined(instance, key) { | ||
return instance[DefinedMembersKey].includes(key); | ||
} | ||
/** Returns simple object with all the non-default members */ | ||
static toObjectDefined(instance) { | ||
const defined = {}; | ||
for (const member of instance[DefinedMembersKey]) { | ||
defined[member] = instance[member]; | ||
} | ||
return _normalize.apply(void 0, [this.schema].concat(args)); | ||
}; | ||
return defined; | ||
} | ||
/** Returns array of all keys that have values defined in instance */ | ||
_proto.denormalize = function denormalize() { | ||
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
args[_key2] = arguments[_key2]; | ||
static keysDefined(instance) { | ||
return instance[DefinedMembersKey]; | ||
} | ||
} | ||
/** Represents data that should be deduped by specifying a primary key. */ | ||
class Entity extends SimpleRecord { | ||
/** | ||
* A unique identifier for each Entity | ||
* | ||
* @param [parent] When normalizing, the object which included the entity | ||
* @param [key] When normalizing, the key where this entity was found | ||
*/ | ||
/** Returns the globally unique identifier for the static Entity */ | ||
static get key() { | ||
/* istanbul ignore next */ | ||
if (process.env.NODE_ENV !== 'production' && this.name === '') throw new Error('Entity classes without a name must define `static get key()`'); | ||
return this.name; | ||
} | ||
/** Defines nested entities */ | ||
/** | ||
* 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 | ||
*/ | ||
static pk(value, parent, key) { | ||
return this.prototype.pk.call(value, parent, key) || key; | ||
} | ||
/** Returns this to be used in a schema definition. | ||
* This is essential to capture the correct type to be used in inferencing. | ||
*/ | ||
static asSchema() { | ||
return this; | ||
} | ||
static normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
// TODO: what's store needs to be a differing type from fromJS | ||
const processedEntity = this.fromJS(input, parent, key); | ||
const id = processedEntity.pk(parent, key); | ||
/* istanbul ignore next */ | ||
if (id === undefined) { | ||
if (process.env.NODE_ENV !== 'production' && id === undefined) { | ||
throw new Error(`Missing usable resource key when normalizing response. | ||
This is likely due to a malformed response. | ||
Try inspecting the network response or fetch() return value. | ||
Entity: ${this} | ||
Value: ${input && JSON.stringify(input, null, 2)} | ||
`); | ||
} else { | ||
throw new Error('undefined pk'); | ||
} | ||
} | ||
return _denormalize.apply(void 0, [this.schema].concat(args)); | ||
const entityType = this.key; | ||
if (!(entityType in visitedEntities)) { | ||
visitedEntities[entityType] = {}; | ||
} | ||
if (!(id in visitedEntities[entityType])) { | ||
visitedEntities[entityType][id] = []; | ||
} | ||
if (visitedEntities[entityType][id].some(entity => entity === input)) { | ||
return id; | ||
} | ||
visitedEntities[entityType][id].push(input); | ||
Object.keys(this.schema).forEach(key => { | ||
if (Object.hasOwnProperty.call(processedEntity, key) && typeof processedEntity[key] === 'object') { | ||
const schema = this.schema[key]; | ||
processedEntity[key] = visit(processedEntity[key], processedEntity, key, schema, addEntity, visitedEntities); | ||
} | ||
}); | ||
addEntity(this, processedEntity, input, parent, key); | ||
return id; | ||
} // TODO: Add denormalizing capability | ||
static denormalize(entity, unvisit) { | ||
return [entity, true]; | ||
} | ||
} | ||
/* istanbul ignore next */ | ||
Entity.schema = {}; | ||
if (process.env.NODE_ENV !== 'production') { | ||
// for those not using TypeScript this is a good catch to ensure they are defining | ||
// the abstract members | ||
Entity.fromJS = function fromJS(props) { | ||
if (this.prototype.pk === undefined) throw new Error('cannot construct on abstract types'); | ||
return SimpleRecord.fromJS.call(this, props); | ||
}; | ||
} | ||
return ObjectSchema; | ||
}(); | ||
function isEntity(schema) { | ||
return schema !== null && schema.pk !== undefined; | ||
} | ||
var unvisitEntity = function unvisitEntity(id, schema, unvisit, getEntity, cache) { | ||
var entity = getEntity(id, schema); | ||
const unvisitEntity = (id, schema, unvisit, getEntity, cache) => { | ||
const entity = getEntity(id, schema); | ||
@@ -327,15 +411,12 @@ if (typeof entity !== 'object' || entity === null) { | ||
var found = true; | ||
let found = true; | ||
if (!cache[schema.key][id]) { | ||
// Ensure we don't mutate it non-immutable objects | ||
var entityCopy = isImmutable(entity) ? entity : Object.assign({}, entity); // Need to set this first so that if it is referenced further within the | ||
const entityCopy = isImmutable(entity) || entity instanceof SimpleRecord ? entity : { ...entity | ||
}; // Need to set this first so that if it is referenced further within the | ||
// denormalization the reference will already exist. | ||
cache[schema.key][id] = entityCopy; | ||
var _schema$denormalize = schema.denormalize(entityCopy, unvisit); | ||
cache[schema.key][id] = _schema$denormalize[0]; | ||
found = _schema$denormalize[1]; | ||
[cache[schema.key][id], found] = schema.denormalize(entityCopy, unvisit); | ||
} | ||
@@ -346,5 +427,5 @@ | ||
var getUnvisit = function getUnvisit(entities) { | ||
var cache = {}; | ||
var getEntity = getEntities(entities); | ||
const getUnvisit = entities => { | ||
const cache = {}; | ||
const getEntity = getEntities(entities); | ||
return [function unvisit(input, schema) { | ||
@@ -354,3 +435,3 @@ if (!schema) return [input, true]; | ||
if (typeof schema === 'object' && (!schema.denormalize || typeof schema.denormalize !== 'function')) { | ||
var method = Array.isArray(schema) ? denormalize : _denormalize; | ||
const method = Array.isArray(schema) ? denormalize : denormalize$1; | ||
return method(schema, input, unvisit); | ||
@@ -364,3 +445,3 @@ } // null is considered intentional, thus always 'found' as true | ||
if (typeof schema.getId === 'function' && typeof schema.normalize === 'function') { | ||
if (isEntity(schema)) { | ||
// unvisitEntity just can't handle undefined | ||
@@ -382,6 +463,6 @@ if (input === undefined) { | ||
var getEntities = function getEntities(entities) { | ||
var isImmutable$1 = isImmutable(entities); | ||
return function (entityOrId, schema) { | ||
var schemaKey = schema.key; | ||
const getEntities = entities => { | ||
const isImmutable$1 = isImmutable(entities); | ||
return (entityOrId, schema) => { | ||
const schemaKey = schema.key; | ||
@@ -400,3 +481,3 @@ if (typeof entityOrId === 'object') { | ||
var denormalize$1 = function denormalize(input, schema, entities) { | ||
const denormalize$2 = (input, schema, entities) => { | ||
/* istanbul ignore next */ | ||
@@ -407,7 +488,4 @@ // eslint-disable-next-line no-undef | ||
if (typeof input !== 'undefined') { | ||
var _getUnvisit = getUnvisit(entities), | ||
unvisit = _getUnvisit[0], | ||
cache = _getUnvisit[1]; | ||
return [].concat(unvisit(input, schema), [cache]); | ||
const [unvisit, cache] = getUnvisit(entities); | ||
return [...unvisit(input, schema), cache]; | ||
} | ||
@@ -418,139 +496,89 @@ | ||
var getDefaultGetId = function getDefaultGetId(idAttribute) { | ||
return function (input) { | ||
return isImmutable(input) ? input.get(idAttribute) : input[idAttribute]; | ||
}; | ||
}; | ||
const visit = (value, parent, key, schema, addEntity, visitedEntities) => { | ||
if (typeof value !== 'object' || !value || !schema) { | ||
return value; | ||
} | ||
var EntitySchema = /*#__PURE__*/function () { | ||
function EntitySchema(key, definition, options) { | ||
if (definition === void 0) { | ||
definition = {}; | ||
} | ||
if (typeof schema === 'object' && (!schema.normalize || typeof schema.normalize !== 'function')) { | ||
const method = Array.isArray(schema) ? normalize : normalize$1; | ||
return method(schema, value, parent, key, visit, addEntity, visitedEntities); | ||
} | ||
if (options === void 0) { | ||
options = {}; | ||
} | ||
return schema.normalize(value, parent, key, visit, addEntity, visitedEntities); | ||
}; | ||
if (!key || typeof key !== 'string') { | ||
throw new Error("Expected a string key for Entity, but found " + key + "."); | ||
} | ||
const addEntities = (entities, indexes) => (schema, processedEntity, value, parent, key) => { | ||
const schemaKey = schema.key; | ||
const id = schema.pk(processedEntity, parent, key); | ||
var _options = options, | ||
_options$idAttribute = _options.idAttribute, | ||
idAttribute = _options$idAttribute === void 0 ? 'id' : _options$idAttribute, | ||
_options$mergeStrateg = _options.mergeStrategy, | ||
mergeStrategy = _options$mergeStrateg === void 0 ? function (entityA, entityB) { | ||
return Object.assign({}, entityA, {}, entityB); | ||
} : _options$mergeStrateg, | ||
_options$processStrat = _options.processStrategy, | ||
processStrategy = _options$processStrat === void 0 ? function (input) { | ||
return Object.assign({}, input); | ||
} : _options$processStrat; | ||
this._key = key; | ||
this._getId = typeof idAttribute === 'function' ? idAttribute : getDefaultGetId(idAttribute); | ||
this._idAttribute = idAttribute; | ||
this._mergeStrategy = mergeStrategy; | ||
this._processStrategy = processStrategy; | ||
this.define(definition); | ||
if (!(schemaKey in entities)) { | ||
entities[schemaKey] = {}; | ||
} | ||
var _proto = EntitySchema.prototype; | ||
const existingEntity = entities[schemaKey][id]; | ||
_proto.define = function define(definition) { | ||
this.schema = Object.keys(definition).reduce(function (entitySchema, key) { | ||
var _Object$assign; | ||
if (existingEntity) { | ||
entities[schemaKey][id] = schema.merge(existingEntity, processedEntity); | ||
} else { | ||
entities[schemaKey][id] = processedEntity; | ||
} // update index | ||
var schema = definition[key]; | ||
return Object.assign({}, entitySchema, (_Object$assign = {}, _Object$assign[key] = schema, _Object$assign)); | ||
}, this.schema || {}); | ||
}; | ||
_proto.getId = function getId(input, parent, key) { | ||
return this._getId(input, parent, key); | ||
}; | ||
if (Array.isArray(schema.indexes)) { | ||
const entity = entities[schemaKey][id]; | ||
_proto.merge = function merge(entityA, entityB) { | ||
return this._mergeStrategy(entityA, entityB); | ||
}; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
var id = this.getId(input, parent, key); | ||
var entityType = this.key; | ||
if (!(entityType in visitedEntities)) { | ||
visitedEntities[entityType] = {}; | ||
if (!(schemaKey in indexes)) { | ||
indexes[schemaKey] = {}; | ||
} | ||
if (!(id in visitedEntities[entityType])) { | ||
visitedEntities[entityType][id] = []; | ||
} | ||
for (const index of schema.indexes) { | ||
if (!(index in indexes[schemaKey])) { | ||
indexes[schemaKey][index] = {}; | ||
} | ||
if (visitedEntities[entityType][id].some(function (entity) { | ||
return entity === input; | ||
})) { | ||
return id; | ||
} | ||
const indexMap = indexes[schemaKey][index]; | ||
visitedEntities[entityType][id].push(input); | ||
if (existingEntity) { | ||
delete indexMap[existingEntity[index]]; | ||
} | ||
var processedEntity = this._processStrategy(input, parent, key); | ||
Object.keys(this.schema).forEach(function (key) { | ||
if (Object.hasOwnProperty.call(processedEntity, key) && typeof processedEntity[key] === 'object') { | ||
var schema = _this.schema[key]; | ||
processedEntity[key] = visit(processedEntity[key], processedEntity, key, schema, addEntity, visitedEntities); | ||
if (index in entity) { | ||
indexMap[entity[index]] = id; | ||
} | ||
}); | ||
addEntity(this, processedEntity, input, parent, key); | ||
return id; | ||
}; | ||
_proto.denormalize = function denormalize(entity, unvisit) { | ||
var _this2 = this; | ||
if (isImmutable(entity)) { | ||
return denormalizeImmutable(this.schema, entity, unvisit); | ||
/* 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. | ||
Index: ${index} | ||
Entity: ${JSON.stringify(entity, undefined, 2)}`); | ||
} | ||
} | ||
} | ||
}; | ||
var found = true; | ||
Object.keys(this.schema).forEach(function (key) { | ||
var schema = _this2.schema[key]; | ||
function expectedSchemaType(schema) { | ||
return ['object', 'function'].includes(typeof schema) ? 'object' : typeof schema; | ||
} | ||
var _unvisit = unvisit(entity[key], schema), | ||
value = _unvisit[0], | ||
foundItem = _unvisit[1]; | ||
const normalize$2 = (input, schema) => { | ||
const schemaType = expectedSchemaType(schema); | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
if (input === null || typeof input !== schemaType) { | ||
throw new Error(`Unexpected input given to normalize. Expected type to be "${schemaType}", found "${input === null ? 'null' : typeof input}".`); | ||
} | ||
if (Object.hasOwnProperty.call(entity, key)) { | ||
entity[key] = value; | ||
} | ||
}); | ||
return [entity, found]; | ||
const entities = {}; | ||
const indexes = {}; | ||
const addEntity = addEntities(entities, indexes); | ||
const visitedEntities = {}; | ||
const result = visit(input, input, undefined, schema, addEntity, visitedEntities); | ||
return { | ||
entities, | ||
indexes, | ||
result | ||
}; | ||
}; | ||
_createClass(EntitySchema, [{ | ||
key: "key", | ||
get: function get() { | ||
return this._key; | ||
} | ||
}, { | ||
key: "idAttribute", | ||
get: function get() { | ||
return this._idAttribute; | ||
} | ||
}]); | ||
return EntitySchema; | ||
}(); | ||
var UnionSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(UnionSchema, _PolymorphicSchema); | ||
function UnionSchema(definition, schemaAttribute) { | ||
class UnionSchema extends PolymorphicSchema { | ||
constructor(definition, schemaAttribute) { | ||
if (!schemaAttribute) { | ||
@@ -560,51 +588,31 @@ throw new Error('Expected option "schemaAttribute" not found on UnionSchema.'); | ||
return _PolymorphicSchema.call(this, definition, schemaAttribute) || this; | ||
super(definition, schemaAttribute); | ||
} | ||
var _proto = UnionSchema.prototype; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
return this.normalizeValue(input, parent, key, visit, addEntity, visitedEntities); | ||
}; | ||
} | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
denormalize(input, unvisit) { | ||
return this.denormalizeValue(input, unvisit); | ||
}; | ||
return UnionSchema; | ||
}(PolymorphicSchema); | ||
var ValuesSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ValuesSchema, _PolymorphicSchema); | ||
function ValuesSchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
} | ||
var _proto = ValuesSchema.prototype; | ||
} | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
return Object.keys(input).reduce(function (output, key, index) { | ||
var _Object$assign; | ||
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; | ||
class ValuesSchema extends PolymorphicSchema { | ||
normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
return Object.keys(input).reduce((output, key, index) => { | ||
const value = input[key]; | ||
return value !== undefined && value !== null ? { ...output, | ||
[key]: this.normalizeValue(value, input, key, visit, addEntity, visitedEntities) | ||
} : output; | ||
}, {}); | ||
}; | ||
} | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
denormalize(input, unvisit) { | ||
let found = true; | ||
return [Object.keys(input).reduce((output, key) => { | ||
const entityOrId = input[key]; | ||
const [value, foundItem] = this.denormalizeValue(entityOrId, unvisit); | ||
var found = true; | ||
return [Object.keys(input).reduce(function (output, key) { | ||
var _Object$assign2; | ||
var entityOrId = input[key]; | ||
var _this2$denormalizeVal = _this2.denormalizeValue(entityOrId, unvisit), | ||
value = _this2$denormalizeVal[0], | ||
foundItem = _this2$denormalizeVal[1]; | ||
if (!foundItem) { | ||
@@ -614,117 +622,32 @@ found = false; | ||
return Object.assign({}, output, (_Object$assign2 = {}, _Object$assign2[key] = value, _Object$assign2)); | ||
return { ...output, | ||
[key]: value | ||
}; | ||
}, {}), found]; | ||
}; | ||
return ValuesSchema; | ||
}(PolymorphicSchema); | ||
var visit = function visit(value, parent, key, schema, addEntity, visitedEntities) { | ||
if (typeof value !== 'object' || !value || !schema) { | ||
return value; | ||
} | ||
if (typeof schema === 'object' && (!schema.normalize || typeof schema.normalize !== 'function')) { | ||
var method = Array.isArray(schema) ? normalize : _normalize; | ||
return method(schema, value, parent, key, visit, addEntity, visitedEntities); | ||
} | ||
} | ||
return schema.normalize(value, parent, key, visit, addEntity, visitedEntities); | ||
}; | ||
var addEntities = function addEntities(entities, indexes) { | ||
return function (schema, processedEntity, value, parent, key) { | ||
var schemaKey = schema.key; | ||
var id = schema.getId(value, parent, key); | ||
if (!(schemaKey in entities)) { | ||
entities[schemaKey] = {}; | ||
} | ||
var existingEntity = entities[schemaKey][id]; | ||
if (existingEntity) { | ||
entities[schemaKey][id] = schema.merge(existingEntity, processedEntity); | ||
} else { | ||
entities[schemaKey][id] = processedEntity; | ||
} // update index | ||
if (Array.isArray(schema.indexes)) { | ||
var entity = entities[schemaKey][id]; | ||
if (!(schemaKey in indexes)) { | ||
indexes[schemaKey] = {}; | ||
} | ||
for (var _iterator = schema.indexes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { | ||
var _ref; | ||
if (_isArray) { | ||
if (_i >= _iterator.length) break; | ||
_ref = _iterator[_i++]; | ||
} else { | ||
_i = _iterator.next(); | ||
if (_i.done) break; | ||
_ref = _i.value; | ||
} | ||
var index = _ref; | ||
if (!(index in indexes[schemaKey])) { | ||
indexes[schemaKey][index] = {}; | ||
} | ||
var indexMap = indexes[schemaKey][index]; | ||
if (existingEntity) { | ||
delete indexMap[existingEntity[index]]; | ||
} | ||
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)); | ||
} | ||
} | ||
} | ||
}; | ||
}; | ||
var schema = { | ||
var schema = /*#__PURE__*/Object.freeze({ | ||
__proto__: null, | ||
Union: UnionSchema, | ||
Values: ValuesSchema, | ||
Array: ArraySchema, | ||
Entity: EntitySchema, | ||
Object: ObjectSchema, | ||
Union: UnionSchema, | ||
Values: ValuesSchema | ||
}; | ||
Object: ObjectSchema | ||
}); | ||
function expectedSchemaType(schema) { | ||
return ['object', 'function'].includes(typeof schema) ? 'object' : typeof schema; | ||
} | ||
var normalize$1 = function normalize(input, schema) { | ||
var schemaType = expectedSchemaType(schema); | ||
if (input === null || typeof input !== schemaType) { | ||
throw new Error("Unexpected input given to normalize. Expected type to be \"" + schemaType + "\", found \"" + (input === null ? 'null' : typeof input) + "\"."); | ||
class NotImplementedError extends Error { | ||
constructor(...args) { | ||
super(...args); | ||
this.message = process.env.NODE_ENV === 'production' ? 'Not Implemented' : 'Not Implemented. You must provide an override for this method.'; | ||
} | ||
var entities = {}; | ||
var indexes = {}; | ||
var addEntity = addEntities(entities, indexes); | ||
var visitedEntities = {}; | ||
var result = visit(input, input, undefined, schema, addEntity, visitedEntities); | ||
return { | ||
entities: entities, | ||
indexes: indexes, | ||
result: result | ||
}; | ||
}; | ||
} | ||
exports.denormalize = denormalize$1; | ||
exports.normalize = normalize$1; | ||
exports.Entity = Entity; | ||
exports.NotImplementedError = NotImplementedError; | ||
exports.SimpleRecord = SimpleRecord; | ||
exports.denormalize = denormalize$2; | ||
exports.isEntity = isEntity; | ||
exports.normalize = normalize$2; | ||
exports.schema = schema; | ||
@@ -731,0 +654,0 @@ |
@@ -1,1 +0,1 @@ | ||
var rest_hooks_normalizr=function(e){"use strict";function t(e){return!(!e||"function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}function r(e,t,r){let n=!0;return[Object.keys(e).reduce((t,i)=>{const s=""+i,[o,c]=r(t.get(s),e[s]);return c||(n=!1),t.has(s)?t.set(s,o):t},t),n]}class n{constructor(e,t){t&&(this._schemaAttribute="string"==typeof t?e=>e[t]:t),this.define(e)}get isSingleSchema(){return!this._schemaAttribute}define(e){this.schema=e}getSchemaAttribute(e,t,r){return!this.isSingleSchema&&this._schemaAttribute(e,t,r)}inferSchema(e,t,r){if(this.isSingleSchema)return this.schema;const n=this.getSchemaAttribute(e,t,r);return this.schema[n]}normalizeValue(e,t,r,n,i,s){const o=this.inferSchema(e,t,r);if(!o)return e;const c=n(e,t,r,o,i,s);return this.isSingleSchema||null==c?c:{id:c,schema:this.getSchemaAttribute(e,t,r)}}denormalizeValue(e,r){const n=t(e)?e.get("schema"):e.schema;return this.isSingleSchema||n?r((this.isSingleSchema?void 0:t(e)?e.get("id"):e.id)||e,this.isSingleSchema?this.schema:this.schema[n]):[e,!0]}}const i=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]},s=e=>Array.isArray(e)?e:Object.keys(e).map(t=>e[t]),o=(e,t,r,n,o,c,a)=>(e=i(e),s(t).map((t,i)=>o(t,r,n,e,c,a))),c=(e,t,r)=>{e=i(e);let n=!0;return void 0===t&&e&&([,n]=r(void 0,e)),[t&&t.map?t.map(t=>r(t,e)).filter(([,e])=>e).map(([e])=>e):t,n]};const a=(e,t,r,n,i,s,o)=>{const c=Object.assign({},t);return Object.keys(e).forEach(r=>{const n=e[r],a=i(t[r],t,r,n,s,o);null==a?delete c[r]:c[r]=a}),c},u=(e,n,i)=>{if(t(n))return r(e,n,i);const s=Object.assign({},n);let o=!0;return Object.keys(e).forEach(t=>{const[r,n]=i(s[t],e[t]);void 0!==s[t]&&(s[t]=r),n||(o=!1)}),[s,o]};const h=e=>{const r={},n=l(e);return[function e(i,s){if(!s)return[i,!0];if("object"==typeof s&&(!s.denormalize||"function"!=typeof s.denormalize)){return(Array.isArray(s)?c:u)(s,i,e)}return null===i?[i,!0]:"function"==typeof s.getId&&"function"==typeof s.normalize?void 0===i?[i,!1]:((e,r,n,i,s)=>{const o=i(e,r);if("object"!=typeof o||null===o)return[o,!1];s[r.key]||(s[r.key]={});let c=!0;if(!s[r.key][e]){const i=t(o)?o:Object.assign({},o);s[r.key][e]=i,[s[r.key][e],c]=r.denormalize(i,n)}return[s[r.key][e],c]})(i,s,e,n,r):"function"==typeof s.denormalize?s.denormalize(i,e):[i,!0]},r]},l=e=>{const r=t(e);return(t,n)=>{const i=n.key;return"object"==typeof t?t:r?e.getIn([i,t.toString()]):e[i]&&e[i][t]}};const m=(e,t,r,n,i,s)=>{if("object"!=typeof e||!e||!n)return e;if("object"==typeof n&&(!n.normalize||"function"!=typeof n.normalize)){return(Array.isArray(n)?o:a)(n,e,t,r,m,i,s)}return n.normalize(e,t,r,m,i,s)},d={Array:class extends n{normalize(e,t,r,n,i,o){return s(e).map((e,s)=>this.normalizeValue(e,t,r,n,i,o)).filter(e=>null!=e)}denormalize(e,t){let r=!0;return void 0===e&&this.schema&&([,r]=t(void 0,this.schema)),[e&&e.map?e.map(e=>this.denormalizeValue(e,t)).filter(([,e])=>e).map(([e])=>e):e,r]}},Entity:class{constructor(e,r={},n={}){if(!e||"string"!=typeof e)throw new Error("Expected a string key for Entity, but found "+e+".");const{idAttribute:i="id",mergeStrategy:s=((e,t)=>Object.assign({},e,{},t)),processStrategy:o=(e=>Object.assign({},e))}=n;this._key=e,this._getId="function"==typeof i?i:(e=>r=>t(r)?r.get(e):r[e])(i),this._idAttribute=i,this._mergeStrategy=s,this._processStrategy=o,this.define(r)}get key(){return this._key}get idAttribute(){return this._idAttribute}define(e){this.schema=Object.keys(e).reduce((t,r)=>{const n=e[r];return Object.assign({},t,{[r]:n})},this.schema||{})}getId(e,t,r){return this._getId(e,t,r)}merge(e,t){return this._mergeStrategy(e,t)}normalize(e,t,r,n,i,s){const o=this.getId(e,t,r),c=this.key;if(c in s||(s[c]={}),o in s[c]||(s[c][o]=[]),s[c][o].some(t=>t===e))return o;s[c][o].push(e);const a=this._processStrategy(e,t,r);return Object.keys(this.schema).forEach(e=>{if(Object.hasOwnProperty.call(a,e)&&"object"==typeof a[e]){const t=this.schema[e];a[e]=n(a[e],a,e,t,i,s)}}),i(this,a,e,t,r),o}denormalize(e,n){if(t(e))return r(this.schema,e,n);let i=!0;return Object.keys(this.schema).forEach(t=>{const r=this.schema[t],[s,o]=n(e[t],r);o||(i=!1),Object.hasOwnProperty.call(e,t)&&(e[t]=s)}),[e,i]}},Object:class{constructor(e){this.define(e)}define(e){this.schema=Object.keys(e).reduce((t,r)=>{const n=e[r];return Object.assign({},t,{[r]:n})},this.schema||{})}normalize(...e){return a(this.schema,...e)}denormalize(...e){return u(this.schema,...e)}},Union:class extends n{constructor(e,t){if(!t)throw new Error('Expected option "schemaAttribute" not found on UnionSchema.');super(e,t)}normalize(e,t,r,n,i,s){return this.normalizeValue(e,t,r,n,i,s)}denormalize(e,t){return this.denormalizeValue(e,t)}},Values:class extends n{normalize(e,t,r,n,i,s){return Object.keys(e).reduce((t,r,o)=>{const c=e[r];return null!=c?Object.assign({},t,{[r]:this.normalizeValue(c,e,r,n,i,s)}):t},{})}denormalize(e,t){let r=!0;return[Object.keys(e).reduce((n,i)=>{const s=e[i],[o,c]=this.denormalizeValue(s,t);return c||(r=!1),Object.assign({},n,{[i]:o})},{}),r]}}};return e.denormalize=(e,t,r)=>{if("production"!==process.env.NODE_ENV&&void 0===t)throw new Error("shema needed");if(void 0!==e){const[n,i]=h(r);return[...n(e,t),i]}return[void 0,!1,{}]},e.normalize=(e,t)=>{const r=function(e){return["object","function"].includes(typeof e)?"object":typeof e}(t);if(null===e||typeof e!==r)throw new Error('Unexpected input given to normalize. Expected type to be "'+r+'", found "'+(null===e?"null":typeof e)+'".');const n={},i={},s=((e,t)=>(r,n,i,s,o)=>{const c=r.key,a=r.getId(i,s,o);c in e||(e[c]={});const u=e[c][a];if(e[c][a]=u?r.merge(u,n):n,Array.isArray(r.indexes)){const n=e[c][a];c in t||(t[c]={});for(const e of r.indexes){e in t[c]||(t[c][e]={});const r=t[c][e];u&&delete r[u[e]],e in n?r[n[e]]=a:"production"!==process.env.NODE_ENV&&console.warn("Index not found in entity. Indexes must be top-level members of your entity.\nIndex: "+e+"\nEntity: "+JSON.stringify(n,void 0,2))}}})(n,i);return{entities:n,indexes:i,result:m(e,e,void 0,t,s,{})}},e.schema=d,e}({}); | ||
var rest_hooks_normalizr=function(e){"use strict";function t(e){return!(!e||"function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}class n{constructor(e,t){t&&(this._schemaAttribute="string"==typeof t?e=>e[t]:t),this.define(e)}get isSingleSchema(){return!this._schemaAttribute}define(e){this.schema=e}getSchemaAttribute(e,t,n){return!this.isSingleSchema&&this._schemaAttribute(e,t,n)}inferSchema(e,t,n){if(this.isSingleSchema)return this.schema;const r=this.getSchemaAttribute(e,t,n);return this.schema[r]}normalizeValue(e,t,n,r,i,s){const o=this.inferSchema(e,t,n);if(!o)return e;const c=r(e,t,n,o,i,s);return this.isSingleSchema||null==c?c:{id:c,schema:this.getSchemaAttribute(e,t,n)}}denormalizeValue(e,n){const r=t(e)?e.get("schema"):e.schema;return this.isSingleSchema||r?n((this.isSingleSchema?void 0:t(e)?e.get("id"):e.id)||e,this.isSingleSchema?this.schema:this.schema[r]):[e,!0]}}const r=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]},i=e=>Array.isArray(e)?e:Object.keys(e).map(t=>e[t]),s=(e,t,n,s,o,c,a)=>(e=r(e),i(t).map((t,r)=>o(t,n,s,e,c,a))),o=(e,t,n)=>{e=r(e);let i=!0;return void 0===t&&e&&([,i]=n(void 0,e)),[t&&t.map?t.map(t=>n(t,e)).filter(([,e])=>e).map(([e])=>e):t,i]};const c=(e,t,n,r,i,s,o)=>{const c=Object.assign({},t);return Object.keys(e).forEach(n=>{const r=e[n],a=i(t[n],t,n,r,s,o);null==a?delete c[n]:c[n]=a}),c},a=(e,n,r)=>{if(t(n))return function(e,t,n){let r=!0;return[Object.keys(e).reduce((t,i)=>{const s=`${i}`,[o,c]=n(t.get(s),e[s]);return c||(r=!1),t.has(s)?t.set(s,o):t},t),r]}(e,n,r);const i=Object.assign({},n);let s=!0;return Object.keys(e).forEach(t=>{const[n,o]=r(i[t],e[t]);void 0!==i[t]&&(i[t]=n),o||(s=!1)}),[i,s]};const u=Symbol("Defined Members"),l=Symbol("unq");class h{toString(){return this[l]}static fromJS(e={},t,n){const r=new this(e);return Object.defineProperty(r,u,{value:Object.keys(e),writable:!1}),Object.defineProperty(r,l,{value:`${Math.random()}`,writable:!1}),Object.assign(r,e),r}static merge(e,t){const n=Object.assign(this.toObjectDefined(e),this.toObjectDefined(t));return this.fromJS(n)}static hasDefined(e,t){return e[u].includes(t)}static toObjectDefined(e){const t={};for(const n of e[u])t[n]=e[n];return t}static keysDefined(e){return e[u]}}class m extends h{static get key(){if("production"!==process.env.NODE_ENV&&""===this.name)throw new Error("Entity classes without a name must define `static get key()`");return this.name}static pk(e,t,n){return this.prototype.pk.call(e,t,n)||n}static asSchema(){return this}static normalize(e,t,n,r,i,s){const o=this.fromJS(e,t,n),c=o.pk(t,n);if(void 0===c)throw"production"!==process.env.NODE_ENV&&void 0===c?new Error(`Missing usable resource 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\n Entity: ${this}\n Value: ${e&&JSON.stringify(e,null,2)}\n `):new Error("undefined pk");const a=this.key;return a in s||(s[a]={}),c in s[a]||(s[a][c]=[]),s[a][c].some(t=>t===e)||(s[a][c].push(e),Object.keys(this.schema).forEach(e=>{if(Object.hasOwnProperty.call(o,e)&&"object"==typeof o[e]){const t=this.schema[e];o[e]=r(o[e],o,e,t,i,s)}}),i(this,o,e,t,n)),c}static denormalize(e,t){return[e,!0]}}function d(e){return null!==e&&void 0!==e.pk}m.schema={},"production"!==process.env.NODE_ENV&&(m.fromJS=function(e){if(void 0===this.prototype.pk)throw new Error("cannot construct on abstract types");return h.fromJS.call(this,e)});const f=e=>{const n={},r=p(e);return[function e(i,s){if(!s)return[i,!0];if("object"==typeof s&&(!s.denormalize||"function"!=typeof s.denormalize)){return(Array.isArray(s)?o:a)(s,i,e)}return null===i?[i,!0]:d(s)?void 0===i?[i,!1]:((e,n,r,i,s)=>{const o=i(e,n);if("object"!=typeof o||null===o)return[o,!1];s[n.key]||(s[n.key]={});let c=!0;if(!s[n.key][e]){const i=t(o)||o instanceof h?o:Object.assign({},o);s[n.key][e]=i,[s[n.key][e],c]=n.denormalize(i,r)}return[s[n.key][e],c]})(i,s,e,r,n):"function"==typeof s.denormalize?s.denormalize(i,e):[i,!0]},n]},p=e=>{const n=t(e);return(t,r)=>{const i=r.key;return"object"==typeof t?t:n?e.getIn([i,t.toString()]):e[i]&&e[i][t]}},y=(e,t,n,r,i,o)=>{if("object"!=typeof e||!e||!r)return e;if("object"==typeof r&&(!r.normalize||"function"!=typeof r.normalize)){return(Array.isArray(r)?s:c)(r,e,t,n,y,i,o)}return r.normalize(e,t,n,y,i,o)};var b=Object.freeze({__proto__:null,Union:class extends n{constructor(e,t){if(!t)throw new Error('Expected option "schemaAttribute" not found on UnionSchema.');super(e,t)}normalize(e,t,n,r,i,s){return this.normalizeValue(e,t,n,r,i,s)}denormalize(e,t){return this.denormalizeValue(e,t)}},Values:class extends n{normalize(e,t,n,r,i,s){return Object.keys(e).reduce((t,n,o)=>{const c=e[n];return null!=c?Object.assign({},t,{[n]:this.normalizeValue(c,e,n,r,i,s)}):t},{})}denormalize(e,t){let n=!0;return[Object.keys(e).reduce((r,i)=>{const s=e[i],[o,c]=this.denormalizeValue(s,t);return c||(n=!1),Object.assign({},r,{[i]:o})},{}),n]}},Array:class extends n{normalize(e,t,n,r,s,o){return i(e).map((e,i)=>this.normalizeValue(e,t,n,r,s,o)).filter(e=>null!=e)}denormalize(e,t){let n=!0;return void 0===e&&this.schema&&([,n]=t(void 0,this.schema)),[e&&e.map?e.map(e=>this.denormalizeValue(e,t)).filter(([,e])=>e).map(([e])=>e):e,n]}},Object:class{constructor(e){this.define(e)}define(e){this.schema=Object.keys(e).reduce((t,n)=>{const r=e[n];return Object.assign({},t,{[n]:r})},this.schema||{})}normalize(...e){return c(this.schema,...e)}denormalize(...e){return a(this.schema,...e)}}});class g extends Error{constructor(...e){super(...e),this.message="production"===process.env.NODE_ENV?"Not Implemented":"Not Implemented. You must provide an override for this method."}}return e.Entity=m,e.NotImplementedError=g,e.SimpleRecord=h,e.denormalize=(e,t,n)=>{if("production"!==process.env.NODE_ENV&&void 0===t)throw new Error("shema needed");if(void 0!==e){const[r,i]=f(n);return[...r(e,t),i]}return[void 0,!1,{}]},e.isEntity=d,e.normalize=(e,t)=>{const n=function(e){return["object","function"].includes(typeof e)?"object":typeof e}(t);if(null===e||typeof e!==n)throw new Error(`Unexpected input given to normalize. Expected type to be "${n}", found "${null===e?"null":typeof e}".`);const r={},i={},s=((e,t)=>(n,r,i,s,o)=>{const c=n.key,a=n.pk(r,s,o);c in e||(e[c]={});const u=e[c][a];if(e[c][a]=u?n.merge(u,r):r,Array.isArray(n.indexes)){const r=e[c][a];c in t||(t[c]={});for(const e of n.indexes){e in t[c]||(t[c][e]={});const n=t[c][e];u&&delete n[u[e]],e in r?n[r[e]]=a:"production"!==process.env.NODE_ENV&&console.warn(`Index not found in entity. Indexes must be top-level members of your entity.\nIndex: ${e}\nEntity: ${JSON.stringify(r,void 0,2)}`)}}})(r,i);return{entities:r,indexes:i,result:y(e,e,void 0,t,s,{})}},e.schema=b,e}({}); |
@@ -32,3 +32,3 @@ /** | ||
// we're accessing them using string keys. | ||
const stringKey = "" + key; | ||
const stringKey = `${key}`; | ||
const [item, foundItem] = unvisit(object.get(stringKey), schema[stringKey]); | ||
@@ -110,3 +110,3 @@ | ||
if (isArray && definition.length > 1) { | ||
throw new Error("Expected schema definition to be a single schema, but found " + definition.length + "."); | ||
throw new Error(`Expected schema definition to be a single schema, but found ${definition.length}.`); | ||
} | ||
@@ -212,2 +212,176 @@ | ||
const DefinedMembersKey = Symbol('Defined Members'); | ||
const UniqueIdentifierKey = Symbol('unq'); | ||
/** Immutable record that keeps track of which members are defined vs defaults. */ | ||
class SimpleRecord { | ||
toString() { | ||
// we don't make _unq a member so it doesn't play a role in type compatibility | ||
return this[UniqueIdentifierKey]; | ||
} | ||
/** 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 | ||
*/ | ||
static fromJS( // TODO: this should only accept members that are not functions | ||
props = {}, parent, key) { | ||
// we type guarded abstract case above, so ok to force typescript to allow constructor call | ||
const instance = new this(props); | ||
Object.defineProperty(instance, DefinedMembersKey, { | ||
value: Object.keys(props), | ||
writable: false | ||
}); // a 'unique' identifier to make referential equality comparisons easy | ||
Object.defineProperty(instance, UniqueIdentifierKey, { | ||
value: `${Math.random()}`, | ||
writable: false | ||
}); | ||
Object.assign(instance, props); | ||
return instance; | ||
} | ||
/** Creates new instance copying over defined values of arguments */ | ||
static merge(first, second) { | ||
const props = Object.assign(this.toObjectDefined(first), this.toObjectDefined(second)); | ||
return this.fromJS(props); | ||
} | ||
/** Whether key is non-default */ | ||
static hasDefined(instance, key) { | ||
return instance[DefinedMembersKey].includes(key); | ||
} | ||
/** Returns simple object with all the non-default members */ | ||
static toObjectDefined(instance) { | ||
const defined = {}; | ||
for (const member of instance[DefinedMembersKey]) { | ||
defined[member] = instance[member]; | ||
} | ||
return defined; | ||
} | ||
/** Returns array of all keys that have values defined in instance */ | ||
static keysDefined(instance) { | ||
return instance[DefinedMembersKey]; | ||
} | ||
} | ||
/** Represents data that should be deduped by specifying a primary key. */ | ||
class Entity extends SimpleRecord { | ||
/** | ||
* A unique identifier for each Entity | ||
* | ||
* @param [parent] When normalizing, the object which included the entity | ||
* @param [key] When normalizing, the key where this entity was found | ||
*/ | ||
/** Returns the globally unique identifier for the static Entity */ | ||
static get key() { | ||
/* istanbul ignore next */ | ||
if (process.env.NODE_ENV !== 'production' && this.name === '') throw new Error('Entity classes without a name must define `static get key()`'); | ||
return this.name; | ||
} | ||
/** Defines nested entities */ | ||
/** | ||
* 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 | ||
*/ | ||
static pk(value, parent, key) { | ||
return this.prototype.pk.call(value, parent, key) || key; | ||
} | ||
/** Returns this to be used in a schema definition. | ||
* This is essential to capture the correct type to be used in inferencing. | ||
*/ | ||
static asSchema() { | ||
return this; | ||
} | ||
static normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
// TODO: what's store needs to be a differing type from fromJS | ||
const processedEntity = this.fromJS(input, parent, key); | ||
const id = processedEntity.pk(parent, key); | ||
/* istanbul ignore next */ | ||
if (id === undefined) { | ||
if (process.env.NODE_ENV !== 'production' && id === undefined) { | ||
throw new Error(`Missing usable resource key when normalizing response. | ||
This is likely due to a malformed response. | ||
Try inspecting the network response or fetch() return value. | ||
Entity: ${this} | ||
Value: ${input && JSON.stringify(input, null, 2)} | ||
`); | ||
} else { | ||
throw new Error('undefined pk'); | ||
} | ||
} | ||
const entityType = this.key; | ||
if (!(entityType in visitedEntities)) { | ||
visitedEntities[entityType] = {}; | ||
} | ||
if (!(id in visitedEntities[entityType])) { | ||
visitedEntities[entityType][id] = []; | ||
} | ||
if (visitedEntities[entityType][id].some(entity => entity === input)) { | ||
return id; | ||
} | ||
visitedEntities[entityType][id].push(input); | ||
Object.keys(this.schema).forEach(key => { | ||
if (Object.hasOwnProperty.call(processedEntity, key) && typeof processedEntity[key] === 'object') { | ||
const schema = this.schema[key]; | ||
processedEntity[key] = visit(processedEntity[key], processedEntity, key, schema, addEntity, visitedEntities); | ||
} | ||
}); | ||
addEntity(this, processedEntity, input, parent, key); | ||
return id; | ||
} // TODO: Add denormalizing capability | ||
static denormalize(entity, unvisit) { | ||
return [entity, true]; | ||
} | ||
} | ||
/* istanbul ignore next */ | ||
Entity.schema = {}; | ||
if (process.env.NODE_ENV !== 'production') { | ||
// for those not using TypeScript this is a good catch to ensure they are defining | ||
// the abstract members | ||
Entity.fromJS = function fromJS(props) { | ||
if (this.prototype.pk === undefined) throw new Error('cannot construct on abstract types'); | ||
return SimpleRecord.fromJS.call(this, props); | ||
}; | ||
} | ||
function isEntity(schema) { | ||
return schema !== null && schema.pk !== undefined; | ||
} | ||
const unvisitEntity = (id, schema, unvisit, getEntity, cache) => { | ||
@@ -228,3 +402,3 @@ const entity = getEntity(id, schema); | ||
// Ensure we don't mutate it non-immutable objects | ||
const entityCopy = isImmutable(entity) ? entity : Object.assign({}, entity); // Need to set this first so that if it is referenced further within the | ||
const entityCopy = isImmutable(entity) || entity instanceof SimpleRecord ? entity : Object.assign({}, entity); // Need to set this first so that if it is referenced further within the | ||
// denormalization the reference will already exist. | ||
@@ -255,3 +429,3 @@ | ||
if (typeof schema.getId === 'function' && typeof schema.normalize === 'function') { | ||
if (isEntity(schema)) { | ||
// unvisitEntity just can't handle undefined | ||
@@ -303,150 +477,2 @@ if (input === undefined) { | ||
const getDefaultGetId = idAttribute => input => isImmutable(input) ? input.get(idAttribute) : input[idAttribute]; | ||
class EntitySchema { | ||
constructor(key, definition = {}, options = {}) { | ||
if (!key || typeof key !== 'string') { | ||
throw new Error("Expected a string key for Entity, but found " + key + "."); | ||
} | ||
const { | ||
idAttribute = 'id', | ||
mergeStrategy = (entityA, entityB) => { | ||
return Object.assign({}, entityA, {}, entityB); | ||
}, | ||
processStrategy = input => Object.assign({}, input) | ||
} = options; | ||
this._key = key; | ||
this._getId = typeof idAttribute === 'function' ? idAttribute : getDefaultGetId(idAttribute); | ||
this._idAttribute = idAttribute; | ||
this._mergeStrategy = mergeStrategy; | ||
this._processStrategy = processStrategy; | ||
this.define(definition); | ||
} | ||
get key() { | ||
return this._key; | ||
} | ||
get idAttribute() { | ||
return this._idAttribute; | ||
} | ||
define(definition) { | ||
this.schema = Object.keys(definition).reduce((entitySchema, key) => { | ||
const schema = definition[key]; | ||
return Object.assign({}, entitySchema, { | ||
[key]: schema | ||
}); | ||
}, this.schema || {}); | ||
} | ||
getId(input, parent, key) { | ||
return this._getId(input, parent, key); | ||
} | ||
merge(entityA, entityB) { | ||
return this._mergeStrategy(entityA, entityB); | ||
} | ||
normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
const id = this.getId(input, parent, key); | ||
const entityType = this.key; | ||
if (!(entityType in visitedEntities)) { | ||
visitedEntities[entityType] = {}; | ||
} | ||
if (!(id in visitedEntities[entityType])) { | ||
visitedEntities[entityType][id] = []; | ||
} | ||
if (visitedEntities[entityType][id].some(entity => entity === input)) { | ||
return id; | ||
} | ||
visitedEntities[entityType][id].push(input); | ||
const processedEntity = this._processStrategy(input, parent, key); | ||
Object.keys(this.schema).forEach(key => { | ||
if (Object.hasOwnProperty.call(processedEntity, key) && typeof processedEntity[key] === 'object') { | ||
const schema = this.schema[key]; | ||
processedEntity[key] = visit(processedEntity[key], processedEntity, key, schema, addEntity, visitedEntities); | ||
} | ||
}); | ||
addEntity(this, processedEntity, input, parent, key); | ||
return id; | ||
} | ||
denormalize(entity, unvisit) { | ||
if (isImmutable(entity)) { | ||
return denormalizeImmutable(this.schema, entity, unvisit); | ||
} | ||
let found = true; | ||
Object.keys(this.schema).forEach(key => { | ||
const schema = this.schema[key]; | ||
const [value, foundItem] = unvisit(entity[key], schema); | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
if (Object.hasOwnProperty.call(entity, key)) { | ||
entity[key] = value; | ||
} | ||
}); | ||
return [entity, found]; | ||
} | ||
} | ||
class UnionSchema extends PolymorphicSchema { | ||
constructor(definition, schemaAttribute) { | ||
if (!schemaAttribute) { | ||
throw new Error('Expected option "schemaAttribute" not found on UnionSchema.'); | ||
} | ||
super(definition, schemaAttribute); | ||
} | ||
normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
return this.normalizeValue(input, parent, key, visit, addEntity, visitedEntities); | ||
} | ||
denormalize(input, unvisit) { | ||
return this.denormalizeValue(input, unvisit); | ||
} | ||
} | ||
class ValuesSchema extends PolymorphicSchema { | ||
normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
return Object.keys(input).reduce((output, key, index) => { | ||
const value = input[key]; | ||
return value !== undefined && value !== null ? Object.assign({}, output, { | ||
[key]: this.normalizeValue(value, input, key, visit, addEntity, visitedEntities) | ||
}) : output; | ||
}, {}); | ||
} | ||
denormalize(input, unvisit) { | ||
let found = true; | ||
return [Object.keys(input).reduce((output, key) => { | ||
const entityOrId = input[key]; | ||
const [value, foundItem] = this.denormalizeValue(entityOrId, unvisit); | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
return Object.assign({}, output, { | ||
[key]: value | ||
}); | ||
}, {}), found]; | ||
} | ||
} | ||
const visit = (value, parent, key, schema, addEntity, visitedEntities) => { | ||
@@ -467,3 +493,3 @@ if (typeof value !== 'object' || !value || !schema) { | ||
const schemaKey = schema.key; | ||
const id = schema.getId(value, parent, key); | ||
const id = schema.pk(processedEntity, parent, key); | ||
@@ -507,3 +533,5 @@ if (!(schemaKey in entities)) { | ||
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)); | ||
console.warn(`Index not found in entity. Indexes must be top-level members of your entity. | ||
Index: ${index} | ||
Entity: ${JSON.stringify(entity, undefined, 2)}`); | ||
} | ||
@@ -514,10 +542,2 @@ } | ||
const schema = { | ||
Array: ArraySchema, | ||
Entity: EntitySchema, | ||
Object: ObjectSchema, | ||
Union: UnionSchema, | ||
Values: ValuesSchema | ||
}; | ||
function expectedSchemaType(schema) { | ||
@@ -531,3 +551,3 @@ return ['object', 'function'].includes(typeof schema) ? 'object' : typeof schema; | ||
if (input === null || typeof input !== schemaType) { | ||
throw new Error("Unexpected input given to normalize. Expected type to be \"" + schemaType + "\", found \"" + (input === null ? 'null' : typeof input) + "\"."); | ||
throw new Error(`Unexpected input given to normalize. Expected type to be "${schemaType}", found "${input === null ? 'null' : typeof input}".`); | ||
} | ||
@@ -547,2 +567,65 @@ | ||
export { denormalize$2 as denormalize, normalize$2 as normalize, schema }; | ||
class UnionSchema extends PolymorphicSchema { | ||
constructor(definition, schemaAttribute) { | ||
if (!schemaAttribute) { | ||
throw new Error('Expected option "schemaAttribute" not found on UnionSchema.'); | ||
} | ||
super(definition, schemaAttribute); | ||
} | ||
normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
return this.normalizeValue(input, parent, key, visit, addEntity, visitedEntities); | ||
} | ||
denormalize(input, unvisit) { | ||
return this.denormalizeValue(input, unvisit); | ||
} | ||
} | ||
class ValuesSchema extends PolymorphicSchema { | ||
normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
return Object.keys(input).reduce((output, key, index) => { | ||
const value = input[key]; | ||
return value !== undefined && value !== null ? Object.assign({}, output, { | ||
[key]: this.normalizeValue(value, input, key, visit, addEntity, visitedEntities) | ||
}) : output; | ||
}, {}); | ||
} | ||
denormalize(input, unvisit) { | ||
let found = true; | ||
return [Object.keys(input).reduce((output, key) => { | ||
const entityOrId = input[key]; | ||
const [value, foundItem] = this.denormalizeValue(entityOrId, unvisit); | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
return Object.assign({}, output, { | ||
[key]: value | ||
}); | ||
}, {}), found]; | ||
} | ||
} | ||
var schema = /*#__PURE__*/Object.freeze({ | ||
__proto__: null, | ||
Union: UnionSchema, | ||
Values: ValuesSchema, | ||
Array: ArraySchema, | ||
Object: ObjectSchema | ||
}); | ||
class NotImplementedError extends Error { | ||
constructor(...args) { | ||
super(...args); | ||
this.message = process.env.NODE_ENV === 'production' ? 'Not Implemented' : 'Not Implemented. You must provide an override for this method.'; | ||
} | ||
} | ||
export { Entity, NotImplementedError, SimpleRecord, denormalize$2 as denormalize, isEntity, normalize$2 as normalize, schema }; |
@@ -1,1 +0,1 @@ | ||
function e(e){return!(!e||"function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}function t(e,t,n){let r=!0;return[Object.keys(e).reduce((t,i)=>{const s=""+i,[o,c]=n(t.get(s),e[s]);return c||(r=!1),t.has(s)?t.set(s,o):t},t),r]}class n{constructor(e,t){t&&(this._schemaAttribute="string"==typeof t?e=>e[t]:t),this.define(e)}get isSingleSchema(){return!this._schemaAttribute}define(e){this.schema=e}getSchemaAttribute(e,t,n){return!this.isSingleSchema&&this._schemaAttribute(e,t,n)}inferSchema(e,t,n){if(this.isSingleSchema)return this.schema;const r=this.getSchemaAttribute(e,t,n);return this.schema[r]}normalizeValue(e,t,n,r,i,s){const o=this.inferSchema(e,t,n);if(!o)return e;const c=r(e,t,n,o,i,s);return this.isSingleSchema||null==c?c:{id:c,schema:this.getSchemaAttribute(e,t,n)}}denormalizeValue(t,n){const r=e(t)?t.get("schema"):t.schema;return this.isSingleSchema||r?n((this.isSingleSchema?void 0:e(t)?t.get("id"):t.id)||t,this.isSingleSchema?this.schema:this.schema[r]):[t,!0]}}const r=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]},i=e=>Array.isArray(e)?e:Object.keys(e).map(t=>e[t]),s=(e,t,n,s,o,c,a)=>(e=r(e),i(t).map((t,r)=>o(t,n,s,e,c,a))),o=(e,t,n)=>{e=r(e);let i=!0;return void 0===t&&e&&([,i]=n(void 0,e)),[t&&t.map?t.map(t=>n(t,e)).filter(([,e])=>e).map(([e])=>e):t,i]};const c=(e,t,n,r,i,s,o)=>{const c=Object.assign({},t);return Object.keys(e).forEach(n=>{const r=e[n],a=i(t[n],t,n,r,s,o);null==a?delete c[n]:c[n]=a}),c},a=(n,r,i)=>{if(e(r))return t(n,r,i);const s=Object.assign({},r);let o=!0;return Object.keys(n).forEach(e=>{const[t,r]=i(s[e],n[e]);void 0!==s[e]&&(s[e]=t),r||(o=!1)}),[s,o]};const u=t=>{const n={},r=h(t);return[function t(i,s){if(!s)return[i,!0];if("object"==typeof s&&(!s.denormalize||"function"!=typeof s.denormalize)){return(Array.isArray(s)?o:a)(s,i,t)}return null===i?[i,!0]:"function"==typeof s.getId&&"function"==typeof s.normalize?void 0===i?[i,!1]:((t,n,r,i,s)=>{const o=i(t,n);if("object"!=typeof o||null===o)return[o,!1];s[n.key]||(s[n.key]={});let c=!0;if(!s[n.key][t]){const i=e(o)?o:Object.assign({},o);s[n.key][t]=i,[s[n.key][t],c]=n.denormalize(i,r)}return[s[n.key][t],c]})(i,s,t,r,n):"function"==typeof s.denormalize?s.denormalize(i,t):[i,!0]},n]},h=t=>{const n=e(t);return(e,r)=>{const i=r.key;return"object"==typeof e?e:n?t.getIn([i,e.toString()]):t[i]&&t[i][e]}},l=(e,t,n)=>{if("production"!==process.env.NODE_ENV&&void 0===t)throw new Error("shema needed");if(void 0!==e){const[r,i]=u(n);return[...r(e,t),i]}return[void 0,!1,{}]};const m=(e,t,n,r,i,o)=>{if("object"!=typeof e||!e||!r)return e;if("object"==typeof r&&(!r.normalize||"function"!=typeof r.normalize)){return(Array.isArray(r)?s:c)(r,e,t,n,m,i,o)}return r.normalize(e,t,n,m,i,o)},d={Array:class extends n{normalize(e,t,n,r,s,o){return i(e).map((e,i)=>this.normalizeValue(e,t,n,r,s,o)).filter(e=>null!=e)}denormalize(e,t){let n=!0;return void 0===e&&this.schema&&([,n]=t(void 0,this.schema)),[e&&e.map?e.map(e=>this.denormalizeValue(e,t)).filter(([,e])=>e).map(([e])=>e):e,n]}},Entity:class{constructor(t,n={},r={}){if(!t||"string"!=typeof t)throw new Error("Expected a string key for Entity, but found "+t+".");const{idAttribute:i="id",mergeStrategy:s=((e,t)=>Object.assign({},e,{},t)),processStrategy:o=(e=>Object.assign({},e))}=r;this._key=t,this._getId="function"==typeof i?i:(t=>n=>e(n)?n.get(t):n[t])(i),this._idAttribute=i,this._mergeStrategy=s,this._processStrategy=o,this.define(n)}get key(){return this._key}get idAttribute(){return this._idAttribute}define(e){this.schema=Object.keys(e).reduce((t,n)=>{const r=e[n];return Object.assign({},t,{[n]:r})},this.schema||{})}getId(e,t,n){return this._getId(e,t,n)}merge(e,t){return this._mergeStrategy(e,t)}normalize(e,t,n,r,i,s){const o=this.getId(e,t,n),c=this.key;if(c in s||(s[c]={}),o in s[c]||(s[c][o]=[]),s[c][o].some(t=>t===e))return o;s[c][o].push(e);const a=this._processStrategy(e,t,n);return Object.keys(this.schema).forEach(e=>{if(Object.hasOwnProperty.call(a,e)&&"object"==typeof a[e]){const t=this.schema[e];a[e]=r(a[e],a,e,t,i,s)}}),i(this,a,e,t,n),o}denormalize(n,r){if(e(n))return t(this.schema,n,r);let i=!0;return Object.keys(this.schema).forEach(e=>{const t=this.schema[e],[s,o]=r(n[e],t);o||(i=!1),Object.hasOwnProperty.call(n,e)&&(n[e]=s)}),[n,i]}},Object:class{constructor(e){this.define(e)}define(e){this.schema=Object.keys(e).reduce((t,n)=>{const r=e[n];return Object.assign({},t,{[n]:r})},this.schema||{})}normalize(...e){return c(this.schema,...e)}denormalize(...e){return a(this.schema,...e)}},Union:class extends n{constructor(e,t){if(!t)throw new Error('Expected option "schemaAttribute" not found on UnionSchema.');super(e,t)}normalize(e,t,n,r,i,s){return this.normalizeValue(e,t,n,r,i,s)}denormalize(e,t){return this.denormalizeValue(e,t)}},Values:class extends n{normalize(e,t,n,r,i,s){return Object.keys(e).reduce((t,n,o)=>{const c=e[n];return null!=c?Object.assign({},t,{[n]:this.normalizeValue(c,e,n,r,i,s)}):t},{})}denormalize(e,t){let n=!0;return[Object.keys(e).reduce((r,i)=>{const s=e[i],[o,c]=this.denormalizeValue(s,t);return c||(n=!1),Object.assign({},r,{[i]:o})},{}),n]}}};const f=(e,t)=>{const n=function(e){return["object","function"].includes(typeof e)?"object":typeof e}(t);if(null===e||typeof e!==n)throw new Error('Unexpected input given to normalize. Expected type to be "'+n+'", found "'+(null===e?"null":typeof e)+'".');const r={},i={},s=((e,t)=>(n,r,i,s,o)=>{const c=n.key,a=n.getId(i,s,o);c in e||(e[c]={});const u=e[c][a];if(e[c][a]=u?n.merge(u,r):r,Array.isArray(n.indexes)){const r=e[c][a];c in t||(t[c]={});for(const e of n.indexes){e in t[c]||(t[c][e]={});const n=t[c][e];u&&delete n[u[e]],e in r?n[r[e]]=a:"production"!==process.env.NODE_ENV&&console.warn("Index not found in entity. Indexes must be top-level members of your entity.\nIndex: "+e+"\nEntity: "+JSON.stringify(r,void 0,2))}}})(r,i);return{entities:r,indexes:i,result:m(e,e,void 0,t,s,{})}};export{l as denormalize,f as normalize,d as schema}; | ||
function e(e){return!(!e||"function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}class t{constructor(e,t){t&&(this._schemaAttribute="string"==typeof t?e=>e[t]:t),this.define(e)}get isSingleSchema(){return!this._schemaAttribute}define(e){this.schema=e}getSchemaAttribute(e,t,n){return!this.isSingleSchema&&this._schemaAttribute(e,t,n)}inferSchema(e,t,n){if(this.isSingleSchema)return this.schema;const r=this.getSchemaAttribute(e,t,n);return this.schema[r]}normalizeValue(e,t,n,r,s,i){const o=this.inferSchema(e,t,n);if(!o)return e;const c=r(e,t,n,o,s,i);return this.isSingleSchema||null==c?c:{id:c,schema:this.getSchemaAttribute(e,t,n)}}denormalizeValue(t,n){const r=e(t)?t.get("schema"):t.schema;return this.isSingleSchema||r?n((this.isSingleSchema?void 0:e(t)?t.get("id"):t.id)||t,this.isSingleSchema?this.schema:this.schema[r]):[t,!0]}}const n=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]},r=e=>Array.isArray(e)?e:Object.keys(e).map(t=>e[t]),s=(e,t,s,i,o,c,a)=>(e=n(e),r(t).map((t,n)=>o(t,s,i,e,c,a))),i=(e,t,r)=>{e=n(e);let s=!0;return void 0===t&&e&&([,s]=r(void 0,e)),[t&&t.map?t.map(t=>r(t,e)).filter(([,e])=>e).map(([e])=>e):t,s]};const o=(e,t,n,r,s,i,o)=>{const c=Object.assign({},t);return Object.keys(e).forEach(n=>{const r=e[n],a=s(t[n],t,n,r,i,o);null==a?delete c[n]:c[n]=a}),c},c=(t,n,r)=>{if(e(n))return function(e,t,n){let r=!0;return[Object.keys(e).reduce((t,s)=>{const i=`${s}`,[o,c]=n(t.get(i),e[i]);return c||(r=!1),t.has(i)?t.set(i,o):t},t),r]}(t,n,r);const s=Object.assign({},n);let i=!0;return Object.keys(t).forEach(e=>{const[n,o]=r(s[e],t[e]);void 0!==s[e]&&(s[e]=n),o||(i=!1)}),[s,i]};const a=Symbol("Defined Members"),u=Symbol("unq");class l{toString(){return this[u]}static fromJS(e={},t,n){const r=new this(e);return Object.defineProperty(r,a,{value:Object.keys(e),writable:!1}),Object.defineProperty(r,u,{value:`${Math.random()}`,writable:!1}),Object.assign(r,e),r}static merge(e,t){const n=Object.assign(this.toObjectDefined(e),this.toObjectDefined(t));return this.fromJS(n)}static hasDefined(e,t){return e[a].includes(t)}static toObjectDefined(e){const t={};for(const n of e[a])t[n]=e[n];return t}static keysDefined(e){return e[a]}}class h extends l{static get key(){if("production"!==process.env.NODE_ENV&&""===this.name)throw new Error("Entity classes without a name must define `static get key()`");return this.name}static pk(e,t,n){return this.prototype.pk.call(e,t,n)||n}static asSchema(){return this}static normalize(e,t,n,r,s,i){const o=this.fromJS(e,t,n),c=o.pk(t,n);if(void 0===c)throw"production"!==process.env.NODE_ENV&&void 0===c?new Error(`Missing usable resource 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\n Entity: ${this}\n Value: ${e&&JSON.stringify(e,null,2)}\n `):new Error("undefined pk");const a=this.key;return a in i||(i[a]={}),c in i[a]||(i[a][c]=[]),i[a][c].some(t=>t===e)||(i[a][c].push(e),Object.keys(this.schema).forEach(e=>{if(Object.hasOwnProperty.call(o,e)&&"object"==typeof o[e]){const t=this.schema[e];o[e]=r(o[e],o,e,t,s,i)}}),s(this,o,e,t,n)),c}static denormalize(e,t){return[e,!0]}}function m(e){return null!==e&&void 0!==e.pk}h.schema={},"production"!==process.env.NODE_ENV&&(h.fromJS=function(e){if(void 0===this.prototype.pk)throw new Error("cannot construct on abstract types");return l.fromJS.call(this,e)});const d=t=>{const n={},r=f(t);return[function t(s,o){if(!o)return[s,!0];if("object"==typeof o&&(!o.denormalize||"function"!=typeof o.denormalize)){return(Array.isArray(o)?i:c)(o,s,t)}return null===s?[s,!0]:m(o)?void 0===s?[s,!1]:((t,n,r,s,i)=>{const o=s(t,n);if("object"!=typeof o||null===o)return[o,!1];i[n.key]||(i[n.key]={});let c=!0;if(!i[n.key][t]){const s=e(o)||o instanceof l?o:Object.assign({},o);i[n.key][t]=s,[i[n.key][t],c]=n.denormalize(s,r)}return[i[n.key][t],c]})(s,o,t,r,n):"function"==typeof o.denormalize?o.denormalize(s,t):[s,!0]},n]},f=t=>{const n=e(t);return(e,r)=>{const s=r.key;return"object"==typeof e?e:n?t.getIn([s,e.toString()]):t[s]&&t[s][e]}},p=(e,t,n)=>{if("production"!==process.env.NODE_ENV&&void 0===t)throw new Error("shema needed");if(void 0!==e){const[r,s]=d(n);return[...r(e,t),s]}return[void 0,!1,{}]},y=(e,t,n,r,i,c)=>{if("object"!=typeof e||!e||!r)return e;if("object"==typeof r&&(!r.normalize||"function"!=typeof r.normalize)){return(Array.isArray(r)?s:o)(r,e,t,n,y,i,c)}return r.normalize(e,t,n,y,i,c)};const b=(e,t)=>{const n=function(e){return["object","function"].includes(typeof e)?"object":typeof e}(t);if(null===e||typeof e!==n)throw new Error(`Unexpected input given to normalize. Expected type to be "${n}", found "${null===e?"null":typeof e}".`);const r={},s={},i=((e,t)=>(n,r,s,i,o)=>{const c=n.key,a=n.pk(r,i,o);c in e||(e[c]={});const u=e[c][a];if(e[c][a]=u?n.merge(u,r):r,Array.isArray(n.indexes)){const r=e[c][a];c in t||(t[c]={});for(const e of n.indexes){e in t[c]||(t[c][e]={});const n=t[c][e];u&&delete n[u[e]],e in r?n[r[e]]=a:"production"!==process.env.NODE_ENV&&console.warn(`Index not found in entity. Indexes must be top-level members of your entity.\nIndex: ${e}\nEntity: ${JSON.stringify(r,void 0,2)}`)}}})(r,s);return{entities:r,indexes:s,result:y(e,e,void 0,t,i,{})}};var g=Object.freeze({__proto__:null,Union:class extends t{constructor(e,t){if(!t)throw new Error('Expected option "schemaAttribute" not found on UnionSchema.');super(e,t)}normalize(e,t,n,r,s,i){return this.normalizeValue(e,t,n,r,s,i)}denormalize(e,t){return this.denormalizeValue(e,t)}},Values:class extends t{normalize(e,t,n,r,s,i){return Object.keys(e).reduce((t,n,o)=>{const c=e[n];return null!=c?Object.assign({},t,{[n]:this.normalizeValue(c,e,n,r,s,i)}):t},{})}denormalize(e,t){let n=!0;return[Object.keys(e).reduce((r,s)=>{const i=e[s],[o,c]=this.denormalizeValue(i,t);return c||(n=!1),Object.assign({},r,{[s]:o})},{}),n]}},Array:class extends t{normalize(e,t,n,s,i,o){return r(e).map((e,r)=>this.normalizeValue(e,t,n,s,i,o)).filter(e=>null!=e)}denormalize(e,t){let n=!0;return void 0===e&&this.schema&&([,n]=t(void 0,this.schema)),[e&&e.map?e.map(e=>this.denormalizeValue(e,t)).filter(([,e])=>e).map(([e])=>e):e,n]}},Object:class{constructor(e){this.define(e)}define(e){this.schema=Object.keys(e).reduce((t,n)=>{const r=e[n];return Object.assign({},t,{[n]:r})},this.schema||{})}normalize(...e){return o(this.schema,...e)}denormalize(...e){return c(this.schema,...e)}}});class O extends Error{constructor(...e){super(...e),this.message="production"===process.env.NODE_ENV?"Not Implemented":"Not Implemented. You must provide an override for this method."}}export{h as Entity,O as NotImplementedError,l as SimpleRecord,p as denormalize,m as isEntity,b as normalize,g as schema}; |
@@ -32,12 +32,9 @@ 'use strict'; | ||
function denormalizeImmutable(schema, input, unvisit) { | ||
var found = true; | ||
return [Object.keys(schema).reduce(function (object, key) { | ||
let found = true; | ||
return [Object.keys(schema).reduce((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; | ||
const stringKey = `${key}`; | ||
const [item, foundItem] = unvisit(object.get(stringKey), schema[stringKey]); | ||
var _unvisit = unvisit(object.get(stringKey), schema[stringKey]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1]; | ||
if (!foundItem) { | ||
@@ -55,30 +52,6 @@ found = false; | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
subClass.__proto__ = superClass; | ||
} | ||
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); | ||
} | ||
} | ||
function _createClass(Constructor, protoProps, staticProps) { | ||
if (protoProps) _defineProperties(Constructor.prototype, protoProps); | ||
if (staticProps) _defineProperties(Constructor, staticProps); | ||
return Constructor; | ||
} | ||
var PolymorphicSchema = /*#__PURE__*/function () { | ||
function PolymorphicSchema(definition, schemaAttribute) { | ||
class PolymorphicSchema { | ||
constructor(definition, schemaAttribute) { | ||
if (schemaAttribute) { | ||
this._schemaAttribute = typeof schemaAttribute === 'string' ? function (input) { | ||
return input[schemaAttribute]; | ||
} : schemaAttribute; | ||
this._schemaAttribute = typeof schemaAttribute === 'string' ? input => input[schemaAttribute] : schemaAttribute; | ||
} | ||
@@ -89,13 +62,15 @@ | ||
var _proto = PolymorphicSchema.prototype; | ||
get isSingleSchema() { | ||
return !this._schemaAttribute; | ||
} | ||
_proto.define = function define(definition) { | ||
define(definition) { | ||
this.schema = definition; | ||
}; | ||
} | ||
_proto.getSchemaAttribute = function getSchemaAttribute(input, parent, key) { | ||
getSchemaAttribute(input, parent, key) { | ||
return !this.isSingleSchema && this._schemaAttribute(input, parent, key); | ||
}; | ||
} | ||
_proto.inferSchema = function inferSchema(input, parent, key) { | ||
inferSchema(input, parent, key) { | ||
if (this.isSingleSchema) { | ||
@@ -105,8 +80,8 @@ return this.schema; | ||
var attr = this.getSchemaAttribute(input, parent, key); | ||
const 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); | ||
normalizeValue(value, parent, key, visit, addEntity, visitedEntities) { | ||
const schema = this.inferSchema(value, parent, key); | ||
@@ -117,3 +92,3 @@ if (!schema) { | ||
var normalizedValue = visit(value, parent, key, schema, addEntity, visitedEntities); | ||
const normalizedValue = visit(value, parent, key, schema, addEntity, visitedEntities); | ||
return this.isSingleSchema || normalizedValue === undefined || normalizedValue === null ? normalizedValue : { | ||
@@ -123,6 +98,6 @@ id: normalizedValue, | ||
}; | ||
}; | ||
} | ||
_proto.denormalizeValue = function denormalizeValue(value, unvisit) { | ||
var schemaKey = isImmutable(value) ? value.get('schema') : value.schema; | ||
denormalizeValue(value, unvisit) { | ||
const schemaKey = isImmutable(value) ? value.get('schema') : value.schema; | ||
@@ -133,22 +108,14 @@ if (!this.isSingleSchema && !schemaKey) { | ||
var id = this.isSingleSchema ? undefined : isImmutable(value) ? value.get('id') : value.id; | ||
var schema = this.isSingleSchema ? this.schema : this.schema[schemaKey]; | ||
const id = this.isSingleSchema ? undefined : isImmutable(value) ? value.get('id') : value.id; | ||
const schema = this.isSingleSchema ? this.schema : this.schema[schemaKey]; | ||
return unvisit(id || value, schema); | ||
}; | ||
} | ||
_createClass(PolymorphicSchema, [{ | ||
key: "isSingleSchema", | ||
get: function get() { | ||
return !this._schemaAttribute; | ||
} | ||
}]); | ||
} | ||
return PolymorphicSchema; | ||
}(); | ||
const validateSchema = definition => { | ||
const isArray = Array.isArray(definition); | ||
var validateSchema = function validateSchema(definition) { | ||
var isArray = Array.isArray(definition); | ||
if (isArray && definition.length > 1) { | ||
throw new Error("Expected schema definition to be a single schema, but found " + definition.length + "."); | ||
throw new Error(`Expected schema definition to be a single schema, but found ${definition.length}.`); | ||
} | ||
@@ -159,88 +126,45 @@ | ||
var getValues = function getValues(input) { | ||
return Array.isArray(input) ? input : Object.keys(input).map(function (key) { | ||
return input[key]; | ||
}); | ||
}; | ||
const getValues = input => Array.isArray(input) ? input : Object.keys(input).map(key => input[key]); | ||
var normalize = function normalize(schema, input, parent, key, visit, addEntity, visitedEntities) { | ||
const 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 | ||
const 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 | ||
return values.map(function (value, index) { | ||
return visit(value, parent, key, schema, addEntity, visitedEntities); | ||
}); | ||
return values.map((value, index) => visit(value, parent, key, schema, addEntity, visitedEntities)); | ||
}; | ||
var denormalize = function denormalize(schema, input, unvisit) { | ||
const denormalize = (schema, input, unvisit) => { | ||
schema = validateSchema(schema); | ||
var found = true; | ||
let found = true; | ||
if (input === undefined && schema) { | ||
var _unvisit = unvisit(undefined, schema); | ||
found = _unvisit[1]; | ||
[, found] = unvisit(undefined, schema); | ||
} | ||
return [input && input.map ? input.map(function (entityOrId) { | ||
return unvisit(entityOrId, schema); | ||
}).filter(function (_ref) { | ||
var foundItem = _ref[1]; | ||
return foundItem; | ||
}).map(function (_ref2) { | ||
var value = _ref2[0]; | ||
return value; | ||
}) : input, found]; | ||
return [input && input.map ? input.map(entityOrId => unvisit(entityOrId, schema)).filter(([, foundItem]) => foundItem).map(([value]) => value) : input, found]; | ||
}; | ||
var ArraySchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ArraySchema, _PolymorphicSchema); | ||
function ArraySchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
class ArraySchema extends PolymorphicSchema { | ||
normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
const values = getValues(input); | ||
return values.map((value, index) => this.normalizeValue(value, parent, key, visit, addEntity, visitedEntities)).filter(value => value !== undefined && value !== null); | ||
} | ||
var _proto = ArraySchema.prototype; | ||
denormalize(input, unvisit) { | ||
let found = true; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
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.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
var found = true; | ||
if (input === undefined && this.schema) { | ||
var _unvisit2 = unvisit(undefined, this.schema); | ||
found = _unvisit2[1]; | ||
[, found] = unvisit(undefined, this.schema); | ||
} | ||
return [input && input.map ? input.map(function (entityOrId) { | ||
return _this2.denormalizeValue(entityOrId, unvisit); | ||
}).filter(function (_ref3) { | ||
var foundItem = _ref3[1]; | ||
return foundItem; | ||
}).map(function (_ref4) { | ||
var value = _ref4[0]; | ||
return value; | ||
}) : input, found]; | ||
}; | ||
return [input && input.map ? input.map(entityOrId => this.denormalizeValue(entityOrId, unvisit)).filter(([, foundItem]) => foundItem).map(([value]) => value) : input, found]; | ||
} | ||
return ArraySchema; | ||
}(PolymorphicSchema); | ||
} | ||
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); | ||
const normalize$1 = (schema, input, parent, key, visit, addEntity, visitedEntities) => { | ||
const object = { ...input | ||
}; | ||
Object.keys(schema).forEach(key => { | ||
const localSchema = schema[key]; | ||
const value = visit(input[key], input, key, localSchema, addEntity, visitedEntities); | ||
@@ -255,4 +179,3 @@ if (value === undefined || value === null) { | ||
}; | ||
var _denormalize = function denormalize(schema, input, unvisit) { | ||
const denormalize$1 = (schema, input, unvisit) => { | ||
if (isImmutable(input)) { | ||
@@ -262,8 +185,7 @@ return denormalizeImmutable(schema, input, unvisit); | ||
var object = Object.assign({}, input); | ||
var found = true; | ||
Object.keys(schema).forEach(function (key) { | ||
var _unvisit = unvisit(object[key], schema[key]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1]; | ||
const object = { ...input | ||
}; | ||
let found = true; | ||
Object.keys(schema).forEach(key => { | ||
const [item, foundItem] = unvisit(object[key], schema[key]); | ||
@@ -280,40 +202,202 @@ if (object[key] !== undefined) { | ||
}; | ||
var ObjectSchema = /*#__PURE__*/function () { | ||
function ObjectSchema(definition) { | ||
class ObjectSchema { | ||
constructor(definition) { | ||
this.define(definition); | ||
} | ||
var _proto = ObjectSchema.prototype; | ||
define(definition) { | ||
this.schema = Object.keys(definition).reduce((entitySchema, key) => { | ||
const schema = definition[key]; | ||
return { ...entitySchema, | ||
[key]: schema | ||
}; | ||
}, this.schema || {}); | ||
} | ||
_proto.define = function define(definition) { | ||
this.schema = Object.keys(definition).reduce(function (entitySchema, key) { | ||
var _Object$assign; | ||
normalize(...args) { | ||
return normalize$1(this.schema, ...args); | ||
} | ||
var schema = definition[key]; | ||
return Object.assign({}, entitySchema, (_Object$assign = {}, _Object$assign[key] = schema, _Object$assign)); | ||
}, this.schema || {}); | ||
}; | ||
denormalize(...args) { | ||
return denormalize$1(this.schema, ...args); | ||
} | ||
_proto.normalize = function normalize() { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
const DefinedMembersKey = Symbol('Defined Members'); | ||
const UniqueIdentifierKey = Symbol('unq'); | ||
/** Immutable record that keeps track of which members are defined vs defaults. */ | ||
class SimpleRecord { | ||
toString() { | ||
// we don't make _unq a member so it doesn't play a role in type compatibility | ||
return this[UniqueIdentifierKey]; | ||
} | ||
/** 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 | ||
*/ | ||
static fromJS( // TODO: this should only accept members that are not functions | ||
props = {}, parent, key) { | ||
// we type guarded abstract case above, so ok to force typescript to allow constructor call | ||
const instance = new this(props); | ||
Object.defineProperty(instance, DefinedMembersKey, { | ||
value: Object.keys(props), | ||
writable: false | ||
}); // a 'unique' identifier to make referential equality comparisons easy | ||
Object.defineProperty(instance, UniqueIdentifierKey, { | ||
value: `${Math.random()}`, | ||
writable: false | ||
}); | ||
Object.assign(instance, props); | ||
return instance; | ||
} | ||
/** Creates new instance copying over defined values of arguments */ | ||
static merge(first, second) { | ||
const props = Object.assign(this.toObjectDefined(first), this.toObjectDefined(second)); | ||
return this.fromJS(props); | ||
} | ||
/** Whether key is non-default */ | ||
static hasDefined(instance, key) { | ||
return instance[DefinedMembersKey].includes(key); | ||
} | ||
/** Returns simple object with all the non-default members */ | ||
static toObjectDefined(instance) { | ||
const defined = {}; | ||
for (const member of instance[DefinedMembersKey]) { | ||
defined[member] = instance[member]; | ||
} | ||
return _normalize.apply(void 0, [this.schema].concat(args)); | ||
}; | ||
return defined; | ||
} | ||
/** Returns array of all keys that have values defined in instance */ | ||
_proto.denormalize = function denormalize() { | ||
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
args[_key2] = arguments[_key2]; | ||
static keysDefined(instance) { | ||
return instance[DefinedMembersKey]; | ||
} | ||
} | ||
/** Represents data that should be deduped by specifying a primary key. */ | ||
class Entity extends SimpleRecord { | ||
/** | ||
* A unique identifier for each Entity | ||
* | ||
* @param [parent] When normalizing, the object which included the entity | ||
* @param [key] When normalizing, the key where this entity was found | ||
*/ | ||
/** Returns the globally unique identifier for the static Entity */ | ||
static get key() { | ||
/* istanbul ignore next */ | ||
if (process.env.NODE_ENV !== 'production' && this.name === '') throw new Error('Entity classes without a name must define `static get key()`'); | ||
return this.name; | ||
} | ||
/** Defines nested entities */ | ||
/** | ||
* 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 | ||
*/ | ||
static pk(value, parent, key) { | ||
return this.prototype.pk.call(value, parent, key) || key; | ||
} | ||
/** Returns this to be used in a schema definition. | ||
* This is essential to capture the correct type to be used in inferencing. | ||
*/ | ||
static asSchema() { | ||
return this; | ||
} | ||
static normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
// TODO: what's store needs to be a differing type from fromJS | ||
const processedEntity = this.fromJS(input, parent, key); | ||
const id = processedEntity.pk(parent, key); | ||
/* istanbul ignore next */ | ||
if (id === undefined) { | ||
if (process.env.NODE_ENV !== 'production' && id === undefined) { | ||
throw new Error(`Missing usable resource key when normalizing response. | ||
This is likely due to a malformed response. | ||
Try inspecting the network response or fetch() return value. | ||
Entity: ${this} | ||
Value: ${input && JSON.stringify(input, null, 2)} | ||
`); | ||
} else { | ||
throw new Error('undefined pk'); | ||
} | ||
} | ||
return _denormalize.apply(void 0, [this.schema].concat(args)); | ||
const entityType = this.key; | ||
if (!(entityType in visitedEntities)) { | ||
visitedEntities[entityType] = {}; | ||
} | ||
if (!(id in visitedEntities[entityType])) { | ||
visitedEntities[entityType][id] = []; | ||
} | ||
if (visitedEntities[entityType][id].some(entity => entity === input)) { | ||
return id; | ||
} | ||
visitedEntities[entityType][id].push(input); | ||
Object.keys(this.schema).forEach(key => { | ||
if (Object.hasOwnProperty.call(processedEntity, key) && typeof processedEntity[key] === 'object') { | ||
const schema = this.schema[key]; | ||
processedEntity[key] = visit(processedEntity[key], processedEntity, key, schema, addEntity, visitedEntities); | ||
} | ||
}); | ||
addEntity(this, processedEntity, input, parent, key); | ||
return id; | ||
} // TODO: Add denormalizing capability | ||
static denormalize(entity, unvisit) { | ||
return [entity, true]; | ||
} | ||
} | ||
/* istanbul ignore next */ | ||
Entity.schema = {}; | ||
if (process.env.NODE_ENV !== 'production') { | ||
// for those not using TypeScript this is a good catch to ensure they are defining | ||
// the abstract members | ||
Entity.fromJS = function fromJS(props) { | ||
if (this.prototype.pk === undefined) throw new Error('cannot construct on abstract types'); | ||
return SimpleRecord.fromJS.call(this, props); | ||
}; | ||
} | ||
return ObjectSchema; | ||
}(); | ||
function isEntity(schema) { | ||
return schema !== null && schema.pk !== undefined; | ||
} | ||
var unvisitEntity = function unvisitEntity(id, schema, unvisit, getEntity, cache) { | ||
var entity = getEntity(id, schema); | ||
const unvisitEntity = (id, schema, unvisit, getEntity, cache) => { | ||
const entity = getEntity(id, schema); | ||
@@ -328,15 +412,12 @@ if (typeof entity !== 'object' || entity === null) { | ||
var found = true; | ||
let found = true; | ||
if (!cache[schema.key][id]) { | ||
// Ensure we don't mutate it non-immutable objects | ||
var entityCopy = isImmutable(entity) ? entity : Object.assign({}, entity); // Need to set this first so that if it is referenced further within the | ||
const entityCopy = isImmutable(entity) || entity instanceof SimpleRecord ? entity : { ...entity | ||
}; // Need to set this first so that if it is referenced further within the | ||
// denormalization the reference will already exist. | ||
cache[schema.key][id] = entityCopy; | ||
var _schema$denormalize = schema.denormalize(entityCopy, unvisit); | ||
cache[schema.key][id] = _schema$denormalize[0]; | ||
found = _schema$denormalize[1]; | ||
[cache[schema.key][id], found] = schema.denormalize(entityCopy, unvisit); | ||
} | ||
@@ -347,5 +428,5 @@ | ||
var getUnvisit = function getUnvisit(entities) { | ||
var cache = {}; | ||
var getEntity = getEntities(entities); | ||
const getUnvisit = entities => { | ||
const cache = {}; | ||
const getEntity = getEntities(entities); | ||
return [function unvisit(input, schema) { | ||
@@ -355,3 +436,3 @@ if (!schema) return [input, true]; | ||
if (typeof schema === 'object' && (!schema.denormalize || typeof schema.denormalize !== 'function')) { | ||
var method = Array.isArray(schema) ? denormalize : _denormalize; | ||
const method = Array.isArray(schema) ? denormalize : denormalize$1; | ||
return method(schema, input, unvisit); | ||
@@ -365,3 +446,3 @@ } // null is considered intentional, thus always 'found' as true | ||
if (typeof schema.getId === 'function' && typeof schema.normalize === 'function') { | ||
if (isEntity(schema)) { | ||
// unvisitEntity just can't handle undefined | ||
@@ -383,6 +464,6 @@ if (input === undefined) { | ||
var getEntities = function getEntities(entities) { | ||
var isImmutable$1 = isImmutable(entities); | ||
return function (entityOrId, schema) { | ||
var schemaKey = schema.key; | ||
const getEntities = entities => { | ||
const isImmutable$1 = isImmutable(entities); | ||
return (entityOrId, schema) => { | ||
const schemaKey = schema.key; | ||
@@ -401,3 +482,3 @@ if (typeof entityOrId === 'object') { | ||
var denormalize$1 = function denormalize(input, schema, entities) { | ||
const denormalize$2 = (input, schema, entities) => { | ||
/* istanbul ignore next */ | ||
@@ -408,7 +489,4 @@ // eslint-disable-next-line no-undef | ||
if (typeof input !== 'undefined') { | ||
var _getUnvisit = getUnvisit(entities), | ||
unvisit = _getUnvisit[0], | ||
cache = _getUnvisit[1]; | ||
return [].concat(unvisit(input, schema), [cache]); | ||
const [unvisit, cache] = getUnvisit(entities); | ||
return [...unvisit(input, schema), cache]; | ||
} | ||
@@ -419,139 +497,89 @@ | ||
var getDefaultGetId = function getDefaultGetId(idAttribute) { | ||
return function (input) { | ||
return isImmutable(input) ? input.get(idAttribute) : input[idAttribute]; | ||
}; | ||
}; | ||
const visit = (value, parent, key, schema, addEntity, visitedEntities) => { | ||
if (typeof value !== 'object' || !value || !schema) { | ||
return value; | ||
} | ||
var EntitySchema = /*#__PURE__*/function () { | ||
function EntitySchema(key, definition, options) { | ||
if (definition === void 0) { | ||
definition = {}; | ||
} | ||
if (typeof schema === 'object' && (!schema.normalize || typeof schema.normalize !== 'function')) { | ||
const method = Array.isArray(schema) ? normalize : normalize$1; | ||
return method(schema, value, parent, key, visit, addEntity, visitedEntities); | ||
} | ||
if (options === void 0) { | ||
options = {}; | ||
} | ||
return schema.normalize(value, parent, key, visit, addEntity, visitedEntities); | ||
}; | ||
if (!key || typeof key !== 'string') { | ||
throw new Error("Expected a string key for Entity, but found " + key + "."); | ||
} | ||
const addEntities = (entities, indexes) => (schema, processedEntity, value, parent, key) => { | ||
const schemaKey = schema.key; | ||
const id = schema.pk(processedEntity, parent, key); | ||
var _options = options, | ||
_options$idAttribute = _options.idAttribute, | ||
idAttribute = _options$idAttribute === void 0 ? 'id' : _options$idAttribute, | ||
_options$mergeStrateg = _options.mergeStrategy, | ||
mergeStrategy = _options$mergeStrateg === void 0 ? function (entityA, entityB) { | ||
return Object.assign({}, entityA, {}, entityB); | ||
} : _options$mergeStrateg, | ||
_options$processStrat = _options.processStrategy, | ||
processStrategy = _options$processStrat === void 0 ? function (input) { | ||
return Object.assign({}, input); | ||
} : _options$processStrat; | ||
this._key = key; | ||
this._getId = typeof idAttribute === 'function' ? idAttribute : getDefaultGetId(idAttribute); | ||
this._idAttribute = idAttribute; | ||
this._mergeStrategy = mergeStrategy; | ||
this._processStrategy = processStrategy; | ||
this.define(definition); | ||
if (!(schemaKey in entities)) { | ||
entities[schemaKey] = {}; | ||
} | ||
var _proto = EntitySchema.prototype; | ||
const existingEntity = entities[schemaKey][id]; | ||
_proto.define = function define(definition) { | ||
this.schema = Object.keys(definition).reduce(function (entitySchema, key) { | ||
var _Object$assign; | ||
if (existingEntity) { | ||
entities[schemaKey][id] = schema.merge(existingEntity, processedEntity); | ||
} else { | ||
entities[schemaKey][id] = processedEntity; | ||
} // update index | ||
var schema = definition[key]; | ||
return Object.assign({}, entitySchema, (_Object$assign = {}, _Object$assign[key] = schema, _Object$assign)); | ||
}, this.schema || {}); | ||
}; | ||
_proto.getId = function getId(input, parent, key) { | ||
return this._getId(input, parent, key); | ||
}; | ||
if (Array.isArray(schema.indexes)) { | ||
const entity = entities[schemaKey][id]; | ||
_proto.merge = function merge(entityA, entityB) { | ||
return this._mergeStrategy(entityA, entityB); | ||
}; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
var id = this.getId(input, parent, key); | ||
var entityType = this.key; | ||
if (!(entityType in visitedEntities)) { | ||
visitedEntities[entityType] = {}; | ||
if (!(schemaKey in indexes)) { | ||
indexes[schemaKey] = {}; | ||
} | ||
if (!(id in visitedEntities[entityType])) { | ||
visitedEntities[entityType][id] = []; | ||
} | ||
for (const index of schema.indexes) { | ||
if (!(index in indexes[schemaKey])) { | ||
indexes[schemaKey][index] = {}; | ||
} | ||
if (visitedEntities[entityType][id].some(function (entity) { | ||
return entity === input; | ||
})) { | ||
return id; | ||
} | ||
const indexMap = indexes[schemaKey][index]; | ||
visitedEntities[entityType][id].push(input); | ||
if (existingEntity) { | ||
delete indexMap[existingEntity[index]]; | ||
} | ||
var processedEntity = this._processStrategy(input, parent, key); | ||
Object.keys(this.schema).forEach(function (key) { | ||
if (Object.hasOwnProperty.call(processedEntity, key) && typeof processedEntity[key] === 'object') { | ||
var schema = _this.schema[key]; | ||
processedEntity[key] = visit(processedEntity[key], processedEntity, key, schema, addEntity, visitedEntities); | ||
if (index in entity) { | ||
indexMap[entity[index]] = id; | ||
} | ||
}); | ||
addEntity(this, processedEntity, input, parent, key); | ||
return id; | ||
}; | ||
_proto.denormalize = function denormalize(entity, unvisit) { | ||
var _this2 = this; | ||
if (isImmutable(entity)) { | ||
return denormalizeImmutable(this.schema, entity, unvisit); | ||
/* 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. | ||
Index: ${index} | ||
Entity: ${JSON.stringify(entity, undefined, 2)}`); | ||
} | ||
} | ||
} | ||
}; | ||
var found = true; | ||
Object.keys(this.schema).forEach(function (key) { | ||
var schema = _this2.schema[key]; | ||
function expectedSchemaType(schema) { | ||
return ['object', 'function'].includes(typeof schema) ? 'object' : typeof schema; | ||
} | ||
var _unvisit = unvisit(entity[key], schema), | ||
value = _unvisit[0], | ||
foundItem = _unvisit[1]; | ||
const normalize$2 = (input, schema) => { | ||
const schemaType = expectedSchemaType(schema); | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
if (input === null || typeof input !== schemaType) { | ||
throw new Error(`Unexpected input given to normalize. Expected type to be "${schemaType}", found "${input === null ? 'null' : typeof input}".`); | ||
} | ||
if (Object.hasOwnProperty.call(entity, key)) { | ||
entity[key] = value; | ||
} | ||
}); | ||
return [entity, found]; | ||
const entities = {}; | ||
const indexes = {}; | ||
const addEntity = addEntities(entities, indexes); | ||
const visitedEntities = {}; | ||
const result = visit(input, input, undefined, schema, addEntity, visitedEntities); | ||
return { | ||
entities, | ||
indexes, | ||
result | ||
}; | ||
}; | ||
_createClass(EntitySchema, [{ | ||
key: "key", | ||
get: function get() { | ||
return this._key; | ||
} | ||
}, { | ||
key: "idAttribute", | ||
get: function get() { | ||
return this._idAttribute; | ||
} | ||
}]); | ||
return EntitySchema; | ||
}(); | ||
var UnionSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(UnionSchema, _PolymorphicSchema); | ||
function UnionSchema(definition, schemaAttribute) { | ||
class UnionSchema extends PolymorphicSchema { | ||
constructor(definition, schemaAttribute) { | ||
if (!schemaAttribute) { | ||
@@ -561,51 +589,31 @@ throw new Error('Expected option "schemaAttribute" not found on UnionSchema.'); | ||
return _PolymorphicSchema.call(this, definition, schemaAttribute) || this; | ||
super(definition, schemaAttribute); | ||
} | ||
var _proto = UnionSchema.prototype; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
return this.normalizeValue(input, parent, key, visit, addEntity, visitedEntities); | ||
}; | ||
} | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
denormalize(input, unvisit) { | ||
return this.denormalizeValue(input, unvisit); | ||
}; | ||
return UnionSchema; | ||
}(PolymorphicSchema); | ||
var ValuesSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ValuesSchema, _PolymorphicSchema); | ||
function ValuesSchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
} | ||
var _proto = ValuesSchema.prototype; | ||
} | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
return Object.keys(input).reduce(function (output, key, index) { | ||
var _Object$assign; | ||
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; | ||
class ValuesSchema extends PolymorphicSchema { | ||
normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
return Object.keys(input).reduce((output, key, index) => { | ||
const value = input[key]; | ||
return value !== undefined && value !== null ? { ...output, | ||
[key]: this.normalizeValue(value, input, key, visit, addEntity, visitedEntities) | ||
} : output; | ||
}, {}); | ||
}; | ||
} | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
denormalize(input, unvisit) { | ||
let found = true; | ||
return [Object.keys(input).reduce((output, key) => { | ||
const entityOrId = input[key]; | ||
const [value, foundItem] = this.denormalizeValue(entityOrId, unvisit); | ||
var found = true; | ||
return [Object.keys(input).reduce(function (output, key) { | ||
var _Object$assign2; | ||
var entityOrId = input[key]; | ||
var _this2$denormalizeVal = _this2.denormalizeValue(entityOrId, unvisit), | ||
value = _this2$denormalizeVal[0], | ||
foundItem = _this2$denormalizeVal[1]; | ||
if (!foundItem) { | ||
@@ -615,117 +623,32 @@ found = false; | ||
return Object.assign({}, output, (_Object$assign2 = {}, _Object$assign2[key] = value, _Object$assign2)); | ||
return { ...output, | ||
[key]: value | ||
}; | ||
}, {}), found]; | ||
}; | ||
return ValuesSchema; | ||
}(PolymorphicSchema); | ||
var visit = function visit(value, parent, key, schema, addEntity, visitedEntities) { | ||
if (typeof value !== 'object' || !value || !schema) { | ||
return value; | ||
} | ||
if (typeof schema === 'object' && (!schema.normalize || typeof schema.normalize !== 'function')) { | ||
var method = Array.isArray(schema) ? normalize : _normalize; | ||
return method(schema, value, parent, key, visit, addEntity, visitedEntities); | ||
} | ||
} | ||
return schema.normalize(value, parent, key, visit, addEntity, visitedEntities); | ||
}; | ||
var addEntities = function addEntities(entities, indexes) { | ||
return function (schema, processedEntity, value, parent, key) { | ||
var schemaKey = schema.key; | ||
var id = schema.getId(value, parent, key); | ||
if (!(schemaKey in entities)) { | ||
entities[schemaKey] = {}; | ||
} | ||
var existingEntity = entities[schemaKey][id]; | ||
if (existingEntity) { | ||
entities[schemaKey][id] = schema.merge(existingEntity, processedEntity); | ||
} else { | ||
entities[schemaKey][id] = processedEntity; | ||
} // update index | ||
if (Array.isArray(schema.indexes)) { | ||
var entity = entities[schemaKey][id]; | ||
if (!(schemaKey in indexes)) { | ||
indexes[schemaKey] = {}; | ||
} | ||
for (var _iterator = schema.indexes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { | ||
var _ref; | ||
if (_isArray) { | ||
if (_i >= _iterator.length) break; | ||
_ref = _iterator[_i++]; | ||
} else { | ||
_i = _iterator.next(); | ||
if (_i.done) break; | ||
_ref = _i.value; | ||
} | ||
var index = _ref; | ||
if (!(index in indexes[schemaKey])) { | ||
indexes[schemaKey][index] = {}; | ||
} | ||
var indexMap = indexes[schemaKey][index]; | ||
if (existingEntity) { | ||
delete indexMap[existingEntity[index]]; | ||
} | ||
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)); | ||
} | ||
} | ||
} | ||
}; | ||
}; | ||
var schema = { | ||
var schema = /*#__PURE__*/Object.freeze({ | ||
__proto__: null, | ||
Union: UnionSchema, | ||
Values: ValuesSchema, | ||
Array: ArraySchema, | ||
Entity: EntitySchema, | ||
Object: ObjectSchema, | ||
Union: UnionSchema, | ||
Values: ValuesSchema | ||
}; | ||
Object: ObjectSchema | ||
}); | ||
function expectedSchemaType(schema) { | ||
return ['object', 'function'].includes(typeof schema) ? 'object' : typeof schema; | ||
} | ||
var normalize$1 = function normalize(input, schema) { | ||
var schemaType = expectedSchemaType(schema); | ||
if (input === null || typeof input !== schemaType) { | ||
throw new Error("Unexpected input given to normalize. Expected type to be \"" + schemaType + "\", found \"" + (input === null ? 'null' : typeof input) + "\"."); | ||
class NotImplementedError extends Error { | ||
constructor(...args) { | ||
super(...args); | ||
this.message = process.env.NODE_ENV === 'production' ? 'Not Implemented' : 'Not Implemented. You must provide an override for this method.'; | ||
} | ||
var entities = {}; | ||
var indexes = {}; | ||
var addEntity = addEntities(entities, indexes); | ||
var visitedEntities = {}; | ||
var result = visit(input, input, undefined, schema, addEntity, visitedEntities); | ||
return { | ||
entities: entities, | ||
indexes: indexes, | ||
result: result | ||
}; | ||
}; | ||
} | ||
exports.denormalize = denormalize$1; | ||
exports.normalize = normalize$1; | ||
exports.Entity = Entity; | ||
exports.NotImplementedError = NotImplementedError; | ||
exports.SimpleRecord = SimpleRecord; | ||
exports.denormalize = denormalize$2; | ||
exports.isEntity = isEntity; | ||
exports.normalize = normalize$2; | ||
exports.schema = schema; |
@@ -1,1 +0,1 @@ | ||
"use strict";function e(e){return!(!e||"function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}function t(e,t,r){let n=!0;return[Object.keys(e).reduce((t,i)=>{const s=""+i,[o,c]=r(t.get(s),e[s]);return c||(n=!1),t.has(s)?t.set(s,o):t},t),n]}Object.defineProperty(exports,"__esModule",{value:!0});class r{constructor(e,t){t&&(this._schemaAttribute="string"==typeof t?e=>e[t]:t),this.define(e)}get isSingleSchema(){return!this._schemaAttribute}define(e){this.schema=e}getSchemaAttribute(e,t,r){return!this.isSingleSchema&&this._schemaAttribute(e,t,r)}inferSchema(e,t,r){if(this.isSingleSchema)return this.schema;const n=this.getSchemaAttribute(e,t,r);return this.schema[n]}normalizeValue(e,t,r,n,i,s){const o=this.inferSchema(e,t,r);if(!o)return e;const c=n(e,t,r,o,i,s);return this.isSingleSchema||null==c?c:{id:c,schema:this.getSchemaAttribute(e,t,r)}}denormalizeValue(t,r){const n=e(t)?t.get("schema"):t.schema;return this.isSingleSchema||n?r((this.isSingleSchema?void 0:e(t)?t.get("id"):t.id)||t,this.isSingleSchema?this.schema:this.schema[n]):[t,!0]}}const n=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]},i=e=>Array.isArray(e)?e:Object.keys(e).map(t=>e[t]),s=(e,t,r,s,o,c,a)=>(e=n(e),i(t).map((t,n)=>o(t,r,s,e,c,a))),o=(e,t,r)=>{e=n(e);let i=!0;return void 0===t&&e&&([,i]=r(void 0,e)),[t&&t.map?t.map(t=>r(t,e)).filter(([,e])=>e).map(([e])=>e):t,i]};const c=(e,t,r,n,i,s,o)=>{const c=Object.assign({},t);return Object.keys(e).forEach(r=>{const n=e[r],a=i(t[r],t,r,n,s,o);null==a?delete c[r]:c[r]=a}),c},a=(r,n,i)=>{if(e(n))return t(r,n,i);const s=Object.assign({},n);let o=!0;return Object.keys(r).forEach(e=>{const[t,n]=i(s[e],r[e]);void 0!==s[e]&&(s[e]=t),n||(o=!1)}),[s,o]};const u=t=>{const r={},n=h(t);return[function t(i,s){if(!s)return[i,!0];if("object"==typeof s&&(!s.denormalize||"function"!=typeof s.denormalize)){return(Array.isArray(s)?o:a)(s,i,t)}return null===i?[i,!0]:"function"==typeof s.getId&&"function"==typeof s.normalize?void 0===i?[i,!1]:((t,r,n,i,s)=>{const o=i(t,r);if("object"!=typeof o||null===o)return[o,!1];s[r.key]||(s[r.key]={});let c=!0;if(!s[r.key][t]){const i=e(o)?o:Object.assign({},o);s[r.key][t]=i,[s[r.key][t],c]=r.denormalize(i,n)}return[s[r.key][t],c]})(i,s,t,n,r):"function"==typeof s.denormalize?s.denormalize(i,t):[i,!0]},r]},h=t=>{const r=e(t);return(e,n)=>{const i=n.key;return"object"==typeof e?e:r?t.getIn([i,e.toString()]):t[i]&&t[i][e]}};const l=(e,t,r,n,i,o)=>{if("object"!=typeof e||!e||!n)return e;if("object"==typeof n&&(!n.normalize||"function"!=typeof n.normalize)){return(Array.isArray(n)?s:c)(n,e,t,r,l,i,o)}return n.normalize(e,t,r,l,i,o)},m={Array:class extends r{normalize(e,t,r,n,s,o){return i(e).map((e,i)=>this.normalizeValue(e,t,r,n,s,o)).filter(e=>null!=e)}denormalize(e,t){let r=!0;return void 0===e&&this.schema&&([,r]=t(void 0,this.schema)),[e&&e.map?e.map(e=>this.denormalizeValue(e,t)).filter(([,e])=>e).map(([e])=>e):e,r]}},Entity:class{constructor(t,r={},n={}){if(!t||"string"!=typeof t)throw new Error("Expected a string key for Entity, but found "+t+".");const{idAttribute:i="id",mergeStrategy:s=((e,t)=>Object.assign({},e,{},t)),processStrategy:o=(e=>Object.assign({},e))}=n;this._key=t,this._getId="function"==typeof i?i:(t=>r=>e(r)?r.get(t):r[t])(i),this._idAttribute=i,this._mergeStrategy=s,this._processStrategy=o,this.define(r)}get key(){return this._key}get idAttribute(){return this._idAttribute}define(e){this.schema=Object.keys(e).reduce((t,r)=>{const n=e[r];return Object.assign({},t,{[r]:n})},this.schema||{})}getId(e,t,r){return this._getId(e,t,r)}merge(e,t){return this._mergeStrategy(e,t)}normalize(e,t,r,n,i,s){const o=this.getId(e,t,r),c=this.key;if(c in s||(s[c]={}),o in s[c]||(s[c][o]=[]),s[c][o].some(t=>t===e))return o;s[c][o].push(e);const a=this._processStrategy(e,t,r);return Object.keys(this.schema).forEach(e=>{if(Object.hasOwnProperty.call(a,e)&&"object"==typeof a[e]){const t=this.schema[e];a[e]=n(a[e],a,e,t,i,s)}}),i(this,a,e,t,r),o}denormalize(r,n){if(e(r))return t(this.schema,r,n);let i=!0;return Object.keys(this.schema).forEach(e=>{const t=this.schema[e],[s,o]=n(r[e],t);o||(i=!1),Object.hasOwnProperty.call(r,e)&&(r[e]=s)}),[r,i]}},Object:class{constructor(e){this.define(e)}define(e){this.schema=Object.keys(e).reduce((t,r)=>{const n=e[r];return Object.assign({},t,{[r]:n})},this.schema||{})}normalize(...e){return c(this.schema,...e)}denormalize(...e){return a(this.schema,...e)}},Union:class extends r{constructor(e,t){if(!t)throw new Error('Expected option "schemaAttribute" not found on UnionSchema.');super(e,t)}normalize(e,t,r,n,i,s){return this.normalizeValue(e,t,r,n,i,s)}denormalize(e,t){return this.denormalizeValue(e,t)}},Values:class extends r{normalize(e,t,r,n,i,s){return Object.keys(e).reduce((t,r,o)=>{const c=e[r];return null!=c?Object.assign({},t,{[r]:this.normalizeValue(c,e,r,n,i,s)}):t},{})}denormalize(e,t){let r=!0;return[Object.keys(e).reduce((n,i)=>{const s=e[i],[o,c]=this.denormalizeValue(s,t);return c||(r=!1),Object.assign({},n,{[i]:o})},{}),r]}}};exports.denormalize=(e,t,r)=>{if("production"!==process.env.NODE_ENV&&void 0===t)throw new Error("shema needed");if(void 0!==e){const[n,i]=u(r);return[...n(e,t),i]}return[void 0,!1,{}]},exports.normalize=(e,t)=>{const r=function(e){return["object","function"].includes(typeof e)?"object":typeof e}(t);if(null===e||typeof e!==r)throw new Error('Unexpected input given to normalize. Expected type to be "'+r+'", found "'+(null===e?"null":typeof e)+'".');const n={},i={},s=((e,t)=>(r,n,i,s,o)=>{const c=r.key,a=r.getId(i,s,o);c in e||(e[c]={});const u=e[c][a];if(e[c][a]=u?r.merge(u,n):n,Array.isArray(r.indexes)){const n=e[c][a];c in t||(t[c]={});for(const e of r.indexes){e in t[c]||(t[c][e]={});const r=t[c][e];u&&delete r[u[e]],e in n?r[n[e]]=a:"production"!==process.env.NODE_ENV&&console.warn("Index not found in entity. Indexes must be top-level members of your entity.\nIndex: "+e+"\nEntity: "+JSON.stringify(n,void 0,2))}}})(n,i);return{entities:n,indexes:i,result:l(e,e,void 0,t,s,{})}},exports.schema=m; | ||
"use strict";function e(e){return!(!e||"function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}Object.defineProperty(exports,"__esModule",{value:!0});class t{constructor(e,t){t&&(this._schemaAttribute="string"==typeof t?e=>e[t]:t),this.define(e)}get isSingleSchema(){return!this._schemaAttribute}define(e){this.schema=e}getSchemaAttribute(e,t,n){return!this.isSingleSchema&&this._schemaAttribute(e,t,n)}inferSchema(e,t,n){if(this.isSingleSchema)return this.schema;const r=this.getSchemaAttribute(e,t,n);return this.schema[r]}normalizeValue(e,t,n,r,s,i){const o=this.inferSchema(e,t,n);if(!o)return e;const c=r(e,t,n,o,s,i);return this.isSingleSchema||null==c?c:{id:c,schema:this.getSchemaAttribute(e,t,n)}}denormalizeValue(t,n){const r=e(t)?t.get("schema"):t.schema;return this.isSingleSchema||r?n((this.isSingleSchema?void 0:e(t)?t.get("id"):t.id)||t,this.isSingleSchema?this.schema:this.schema[r]):[t,!0]}}const n=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]},r=e=>Array.isArray(e)?e:Object.keys(e).map(t=>e[t]),s=(e,t,s,i,o,c,a)=>(e=n(e),r(t).map((t,n)=>o(t,s,i,e,c,a))),i=(e,t,r)=>{e=n(e);let s=!0;return void 0===t&&e&&([,s]=r(void 0,e)),[t&&t.map?t.map(t=>r(t,e)).filter(([,e])=>e).map(([e])=>e):t,s]};const o=(e,t,n,r,s,i,o)=>{const c=Object.assign({},t);return Object.keys(e).forEach(n=>{const r=e[n],a=s(t[n],t,n,r,i,o);null==a?delete c[n]:c[n]=a}),c},c=(t,n,r)=>{if(e(n))return function(e,t,n){let r=!0;return[Object.keys(e).reduce((t,s)=>{const i=`${s}`,[o,c]=n(t.get(i),e[i]);return c||(r=!1),t.has(i)?t.set(i,o):t},t),r]}(t,n,r);const s=Object.assign({},n);let i=!0;return Object.keys(t).forEach(e=>{const[n,o]=r(s[e],t[e]);void 0!==s[e]&&(s[e]=n),o||(i=!1)}),[s,i]};const a=Symbol("Defined Members"),u=Symbol("unq");class l{toString(){return this[u]}static fromJS(e={},t,n){const r=new this(e);return Object.defineProperty(r,a,{value:Object.keys(e),writable:!1}),Object.defineProperty(r,u,{value:`${Math.random()}`,writable:!1}),Object.assign(r,e),r}static merge(e,t){const n=Object.assign(this.toObjectDefined(e),this.toObjectDefined(t));return this.fromJS(n)}static hasDefined(e,t){return e[a].includes(t)}static toObjectDefined(e){const t={};for(const n of e[a])t[n]=e[n];return t}static keysDefined(e){return e[a]}}class h extends l{static get key(){if("production"!==process.env.NODE_ENV&&""===this.name)throw new Error("Entity classes without a name must define `static get key()`");return this.name}static pk(e,t,n){return this.prototype.pk.call(e,t,n)||n}static asSchema(){return this}static normalize(e,t,n,r,s,i){const o=this.fromJS(e,t,n),c=o.pk(t,n);if(void 0===c)throw"production"!==process.env.NODE_ENV&&void 0===c?new Error(`Missing usable resource 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\n Entity: ${this}\n Value: ${e&&JSON.stringify(e,null,2)}\n `):new Error("undefined pk");const a=this.key;return a in i||(i[a]={}),c in i[a]||(i[a][c]=[]),i[a][c].some(t=>t===e)||(i[a][c].push(e),Object.keys(this.schema).forEach(e=>{if(Object.hasOwnProperty.call(o,e)&&"object"==typeof o[e]){const t=this.schema[e];o[e]=r(o[e],o,e,t,s,i)}}),s(this,o,e,t,n)),c}static denormalize(e,t){return[e,!0]}}function m(e){return null!==e&&void 0!==e.pk}h.schema={},"production"!==process.env.NODE_ENV&&(h.fromJS=function(e){if(void 0===this.prototype.pk)throw new Error("cannot construct on abstract types");return l.fromJS.call(this,e)});const d=t=>{const n={},r=f(t);return[function t(s,o){if(!o)return[s,!0];if("object"==typeof o&&(!o.denormalize||"function"!=typeof o.denormalize)){return(Array.isArray(o)?i:c)(o,s,t)}return null===s?[s,!0]:m(o)?void 0===s?[s,!1]:((t,n,r,s,i)=>{const o=s(t,n);if("object"!=typeof o||null===o)return[o,!1];i[n.key]||(i[n.key]={});let c=!0;if(!i[n.key][t]){const s=e(o)||o instanceof l?o:Object.assign({},o);i[n.key][t]=s,[i[n.key][t],c]=n.denormalize(s,r)}return[i[n.key][t],c]})(s,o,t,r,n):"function"==typeof o.denormalize?o.denormalize(s,t):[s,!0]},n]},f=t=>{const n=e(t);return(e,r)=>{const s=r.key;return"object"==typeof e?e:n?t.getIn([s,e.toString()]):t[s]&&t[s][e]}},p=(e,t,n,r,i,c)=>{if("object"!=typeof e||!e||!r)return e;if("object"==typeof r&&(!r.normalize||"function"!=typeof r.normalize)){return(Array.isArray(r)?s:o)(r,e,t,n,p,i,c)}return r.normalize(e,t,n,p,i,c)};var y=Object.freeze({__proto__:null,Union:class extends t{constructor(e,t){if(!t)throw new Error('Expected option "schemaAttribute" not found on UnionSchema.');super(e,t)}normalize(e,t,n,r,s,i){return this.normalizeValue(e,t,n,r,s,i)}denormalize(e,t){return this.denormalizeValue(e,t)}},Values:class extends t{normalize(e,t,n,r,s,i){return Object.keys(e).reduce((t,n,o)=>{const c=e[n];return null!=c?Object.assign({},t,{[n]:this.normalizeValue(c,e,n,r,s,i)}):t},{})}denormalize(e,t){let n=!0;return[Object.keys(e).reduce((r,s)=>{const i=e[s],[o,c]=this.denormalizeValue(i,t);return c||(n=!1),Object.assign({},r,{[s]:o})},{}),n]}},Array:class extends t{normalize(e,t,n,s,i,o){return r(e).map((e,r)=>this.normalizeValue(e,t,n,s,i,o)).filter(e=>null!=e)}denormalize(e,t){let n=!0;return void 0===e&&this.schema&&([,n]=t(void 0,this.schema)),[e&&e.map?e.map(e=>this.denormalizeValue(e,t)).filter(([,e])=>e).map(([e])=>e):e,n]}},Object:class{constructor(e){this.define(e)}define(e){this.schema=Object.keys(e).reduce((t,n)=>{const r=e[n];return Object.assign({},t,{[n]:r})},this.schema||{})}normalize(...e){return o(this.schema,...e)}denormalize(...e){return c(this.schema,...e)}}});class b extends Error{constructor(...e){super(...e),this.message="production"===process.env.NODE_ENV?"Not Implemented":"Not Implemented. You must provide an override for this method."}}exports.Entity=h,exports.NotImplementedError=b,exports.SimpleRecord=l,exports.denormalize=(e,t,n)=>{if("production"!==process.env.NODE_ENV&&void 0===t)throw new Error("shema needed");if(void 0!==e){const[r,s]=d(n);return[...r(e,t),s]}return[void 0,!1,{}]},exports.isEntity=m,exports.normalize=(e,t)=>{const n=function(e){return["object","function"].includes(typeof e)?"object":typeof e}(t);if(null===e||typeof e!==n)throw new Error(`Unexpected input given to normalize. Expected type to be "${n}", found "${null===e?"null":typeof e}".`);const r={},s={},i=((e,t)=>(n,r,s,i,o)=>{const c=n.key,a=n.pk(r,i,o);c in e||(e[c]={});const u=e[c][a];if(e[c][a]=u?n.merge(u,r):r,Array.isArray(n.indexes)){const r=e[c][a];c in t||(t[c]={});for(const e of n.indexes){e in t[c]||(t[c][e]={});const n=t[c][e];u&&delete n[u[e]],e in r?n[r[e]]=a:"production"!==process.env.NODE_ENV&&console.warn(`Index not found in entity. Indexes must be top-level members of your entity.\nIndex: ${e}\nEntity: ${JSON.stringify(r,void 0,2)}`)}}})(r,s);return{entities:r,indexes:s,result:p(e,e,void 0,t,i,{})}},exports.schema=y; |
@@ -34,12 +34,9 @@ (function (global, factory) { | ||
function denormalizeImmutable(schema, input, unvisit) { | ||
var found = true; | ||
return [Object.keys(schema).reduce(function (object, key) { | ||
let found = true; | ||
return [Object.keys(schema).reduce((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; | ||
const stringKey = `${key}`; | ||
const [item, foundItem] = unvisit(object.get(stringKey), schema[stringKey]); | ||
var _unvisit = unvisit(object.get(stringKey), schema[stringKey]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1]; | ||
if (!foundItem) { | ||
@@ -57,30 +54,6 @@ found = false; | ||
function _inheritsLoose(subClass, superClass) { | ||
subClass.prototype = Object.create(superClass.prototype); | ||
subClass.prototype.constructor = subClass; | ||
subClass.__proto__ = superClass; | ||
} | ||
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); | ||
} | ||
} | ||
function _createClass(Constructor, protoProps, staticProps) { | ||
if (protoProps) _defineProperties(Constructor.prototype, protoProps); | ||
if (staticProps) _defineProperties(Constructor, staticProps); | ||
return Constructor; | ||
} | ||
var PolymorphicSchema = /*#__PURE__*/function () { | ||
function PolymorphicSchema(definition, schemaAttribute) { | ||
class PolymorphicSchema { | ||
constructor(definition, schemaAttribute) { | ||
if (schemaAttribute) { | ||
this._schemaAttribute = typeof schemaAttribute === 'string' ? function (input) { | ||
return input[schemaAttribute]; | ||
} : schemaAttribute; | ||
this._schemaAttribute = typeof schemaAttribute === 'string' ? input => input[schemaAttribute] : schemaAttribute; | ||
} | ||
@@ -91,13 +64,15 @@ | ||
var _proto = PolymorphicSchema.prototype; | ||
get isSingleSchema() { | ||
return !this._schemaAttribute; | ||
} | ||
_proto.define = function define(definition) { | ||
define(definition) { | ||
this.schema = definition; | ||
}; | ||
} | ||
_proto.getSchemaAttribute = function getSchemaAttribute(input, parent, key) { | ||
getSchemaAttribute(input, parent, key) { | ||
return !this.isSingleSchema && this._schemaAttribute(input, parent, key); | ||
}; | ||
} | ||
_proto.inferSchema = function inferSchema(input, parent, key) { | ||
inferSchema(input, parent, key) { | ||
if (this.isSingleSchema) { | ||
@@ -107,8 +82,8 @@ return this.schema; | ||
var attr = this.getSchemaAttribute(input, parent, key); | ||
const 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); | ||
normalizeValue(value, parent, key, visit, addEntity, visitedEntities) { | ||
const schema = this.inferSchema(value, parent, key); | ||
@@ -119,3 +94,3 @@ if (!schema) { | ||
var normalizedValue = visit(value, parent, key, schema, addEntity, visitedEntities); | ||
const normalizedValue = visit(value, parent, key, schema, addEntity, visitedEntities); | ||
return this.isSingleSchema || normalizedValue === undefined || normalizedValue === null ? normalizedValue : { | ||
@@ -125,6 +100,6 @@ id: normalizedValue, | ||
}; | ||
}; | ||
} | ||
_proto.denormalizeValue = function denormalizeValue(value, unvisit) { | ||
var schemaKey = isImmutable(value) ? value.get('schema') : value.schema; | ||
denormalizeValue(value, unvisit) { | ||
const schemaKey = isImmutable(value) ? value.get('schema') : value.schema; | ||
@@ -135,22 +110,14 @@ if (!this.isSingleSchema && !schemaKey) { | ||
var id = this.isSingleSchema ? undefined : isImmutable(value) ? value.get('id') : value.id; | ||
var schema = this.isSingleSchema ? this.schema : this.schema[schemaKey]; | ||
const id = this.isSingleSchema ? undefined : isImmutable(value) ? value.get('id') : value.id; | ||
const schema = this.isSingleSchema ? this.schema : this.schema[schemaKey]; | ||
return unvisit(id || value, schema); | ||
}; | ||
} | ||
_createClass(PolymorphicSchema, [{ | ||
key: "isSingleSchema", | ||
get: function get() { | ||
return !this._schemaAttribute; | ||
} | ||
}]); | ||
} | ||
return PolymorphicSchema; | ||
}(); | ||
const validateSchema = definition => { | ||
const isArray = Array.isArray(definition); | ||
var validateSchema = function validateSchema(definition) { | ||
var isArray = Array.isArray(definition); | ||
if (isArray && definition.length > 1) { | ||
throw new Error("Expected schema definition to be a single schema, but found " + definition.length + "."); | ||
throw new Error(`Expected schema definition to be a single schema, but found ${definition.length}.`); | ||
} | ||
@@ -161,88 +128,45 @@ | ||
var getValues = function getValues(input) { | ||
return Array.isArray(input) ? input : Object.keys(input).map(function (key) { | ||
return input[key]; | ||
}); | ||
}; | ||
const getValues = input => Array.isArray(input) ? input : Object.keys(input).map(key => input[key]); | ||
var normalize = function normalize(schema, input, parent, key, visit, addEntity, visitedEntities) { | ||
const 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 | ||
const 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 | ||
return values.map(function (value, index) { | ||
return visit(value, parent, key, schema, addEntity, visitedEntities); | ||
}); | ||
return values.map((value, index) => visit(value, parent, key, schema, addEntity, visitedEntities)); | ||
}; | ||
var denormalize = function denormalize(schema, input, unvisit) { | ||
const denormalize = (schema, input, unvisit) => { | ||
schema = validateSchema(schema); | ||
var found = true; | ||
let found = true; | ||
if (input === undefined && schema) { | ||
var _unvisit = unvisit(undefined, schema); | ||
found = _unvisit[1]; | ||
[, found] = unvisit(undefined, schema); | ||
} | ||
return [input && input.map ? input.map(function (entityOrId) { | ||
return unvisit(entityOrId, schema); | ||
}).filter(function (_ref) { | ||
var foundItem = _ref[1]; | ||
return foundItem; | ||
}).map(function (_ref2) { | ||
var value = _ref2[0]; | ||
return value; | ||
}) : input, found]; | ||
return [input && input.map ? input.map(entityOrId => unvisit(entityOrId, schema)).filter(([, foundItem]) => foundItem).map(([value]) => value) : input, found]; | ||
}; | ||
var ArraySchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ArraySchema, _PolymorphicSchema); | ||
function ArraySchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
class ArraySchema extends PolymorphicSchema { | ||
normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
const values = getValues(input); | ||
return values.map((value, index) => this.normalizeValue(value, parent, key, visit, addEntity, visitedEntities)).filter(value => value !== undefined && value !== null); | ||
} | ||
var _proto = ArraySchema.prototype; | ||
denormalize(input, unvisit) { | ||
let found = true; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
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.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
var found = true; | ||
if (input === undefined && this.schema) { | ||
var _unvisit2 = unvisit(undefined, this.schema); | ||
found = _unvisit2[1]; | ||
[, found] = unvisit(undefined, this.schema); | ||
} | ||
return [input && input.map ? input.map(function (entityOrId) { | ||
return _this2.denormalizeValue(entityOrId, unvisit); | ||
}).filter(function (_ref3) { | ||
var foundItem = _ref3[1]; | ||
return foundItem; | ||
}).map(function (_ref4) { | ||
var value = _ref4[0]; | ||
return value; | ||
}) : input, found]; | ||
}; | ||
return [input && input.map ? input.map(entityOrId => this.denormalizeValue(entityOrId, unvisit)).filter(([, foundItem]) => foundItem).map(([value]) => value) : input, found]; | ||
} | ||
return ArraySchema; | ||
}(PolymorphicSchema); | ||
} | ||
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); | ||
const normalize$1 = (schema, input, parent, key, visit, addEntity, visitedEntities) => { | ||
const object = { ...input | ||
}; | ||
Object.keys(schema).forEach(key => { | ||
const localSchema = schema[key]; | ||
const value = visit(input[key], input, key, localSchema, addEntity, visitedEntities); | ||
@@ -257,4 +181,3 @@ if (value === undefined || value === null) { | ||
}; | ||
var _denormalize = function denormalize(schema, input, unvisit) { | ||
const denormalize$1 = (schema, input, unvisit) => { | ||
if (isImmutable(input)) { | ||
@@ -264,8 +187,7 @@ return denormalizeImmutable(schema, input, unvisit); | ||
var object = Object.assign({}, input); | ||
var found = true; | ||
Object.keys(schema).forEach(function (key) { | ||
var _unvisit = unvisit(object[key], schema[key]), | ||
item = _unvisit[0], | ||
foundItem = _unvisit[1]; | ||
const object = { ...input | ||
}; | ||
let found = true; | ||
Object.keys(schema).forEach(key => { | ||
const [item, foundItem] = unvisit(object[key], schema[key]); | ||
@@ -282,40 +204,202 @@ if (object[key] !== undefined) { | ||
}; | ||
var ObjectSchema = /*#__PURE__*/function () { | ||
function ObjectSchema(definition) { | ||
class ObjectSchema { | ||
constructor(definition) { | ||
this.define(definition); | ||
} | ||
var _proto = ObjectSchema.prototype; | ||
define(definition) { | ||
this.schema = Object.keys(definition).reduce((entitySchema, key) => { | ||
const schema = definition[key]; | ||
return { ...entitySchema, | ||
[key]: schema | ||
}; | ||
}, this.schema || {}); | ||
} | ||
_proto.define = function define(definition) { | ||
this.schema = Object.keys(definition).reduce(function (entitySchema, key) { | ||
var _Object$assign; | ||
normalize(...args) { | ||
return normalize$1(this.schema, ...args); | ||
} | ||
var schema = definition[key]; | ||
return Object.assign({}, entitySchema, (_Object$assign = {}, _Object$assign[key] = schema, _Object$assign)); | ||
}, this.schema || {}); | ||
}; | ||
denormalize(...args) { | ||
return denormalize$1(this.schema, ...args); | ||
} | ||
_proto.normalize = function normalize() { | ||
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { | ||
args[_key] = arguments[_key]; | ||
} | ||
const DefinedMembersKey = Symbol('Defined Members'); | ||
const UniqueIdentifierKey = Symbol('unq'); | ||
/** Immutable record that keeps track of which members are defined vs defaults. */ | ||
class SimpleRecord { | ||
toString() { | ||
// we don't make _unq a member so it doesn't play a role in type compatibility | ||
return this[UniqueIdentifierKey]; | ||
} | ||
/** 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 | ||
*/ | ||
static fromJS( // TODO: this should only accept members that are not functions | ||
props = {}, parent, key) { | ||
// we type guarded abstract case above, so ok to force typescript to allow constructor call | ||
const instance = new this(props); | ||
Object.defineProperty(instance, DefinedMembersKey, { | ||
value: Object.keys(props), | ||
writable: false | ||
}); // a 'unique' identifier to make referential equality comparisons easy | ||
Object.defineProperty(instance, UniqueIdentifierKey, { | ||
value: `${Math.random()}`, | ||
writable: false | ||
}); | ||
Object.assign(instance, props); | ||
return instance; | ||
} | ||
/** Creates new instance copying over defined values of arguments */ | ||
static merge(first, second) { | ||
const props = Object.assign(this.toObjectDefined(first), this.toObjectDefined(second)); | ||
return this.fromJS(props); | ||
} | ||
/** Whether key is non-default */ | ||
static hasDefined(instance, key) { | ||
return instance[DefinedMembersKey].includes(key); | ||
} | ||
/** Returns simple object with all the non-default members */ | ||
static toObjectDefined(instance) { | ||
const defined = {}; | ||
for (const member of instance[DefinedMembersKey]) { | ||
defined[member] = instance[member]; | ||
} | ||
return _normalize.apply(void 0, [this.schema].concat(args)); | ||
}; | ||
return defined; | ||
} | ||
/** Returns array of all keys that have values defined in instance */ | ||
_proto.denormalize = function denormalize() { | ||
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
args[_key2] = arguments[_key2]; | ||
static keysDefined(instance) { | ||
return instance[DefinedMembersKey]; | ||
} | ||
} | ||
/** Represents data that should be deduped by specifying a primary key. */ | ||
class Entity extends SimpleRecord { | ||
/** | ||
* A unique identifier for each Entity | ||
* | ||
* @param [parent] When normalizing, the object which included the entity | ||
* @param [key] When normalizing, the key where this entity was found | ||
*/ | ||
/** Returns the globally unique identifier for the static Entity */ | ||
static get key() { | ||
/* istanbul ignore next */ | ||
if (process.env.NODE_ENV !== 'production' && this.name === '') throw new Error('Entity classes without a name must define `static get key()`'); | ||
return this.name; | ||
} | ||
/** Defines nested entities */ | ||
/** | ||
* 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 | ||
*/ | ||
static pk(value, parent, key) { | ||
return this.prototype.pk.call(value, parent, key) || key; | ||
} | ||
/** Returns this to be used in a schema definition. | ||
* This is essential to capture the correct type to be used in inferencing. | ||
*/ | ||
static asSchema() { | ||
return this; | ||
} | ||
static normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
// TODO: what's store needs to be a differing type from fromJS | ||
const processedEntity = this.fromJS(input, parent, key); | ||
const id = processedEntity.pk(parent, key); | ||
/* istanbul ignore next */ | ||
if (id === undefined) { | ||
if (process.env.NODE_ENV !== 'production' && id === undefined) { | ||
throw new Error(`Missing usable resource key when normalizing response. | ||
This is likely due to a malformed response. | ||
Try inspecting the network response or fetch() return value. | ||
Entity: ${this} | ||
Value: ${input && JSON.stringify(input, null, 2)} | ||
`); | ||
} else { | ||
throw new Error('undefined pk'); | ||
} | ||
} | ||
return _denormalize.apply(void 0, [this.schema].concat(args)); | ||
const entityType = this.key; | ||
if (!(entityType in visitedEntities)) { | ||
visitedEntities[entityType] = {}; | ||
} | ||
if (!(id in visitedEntities[entityType])) { | ||
visitedEntities[entityType][id] = []; | ||
} | ||
if (visitedEntities[entityType][id].some(entity => entity === input)) { | ||
return id; | ||
} | ||
visitedEntities[entityType][id].push(input); | ||
Object.keys(this.schema).forEach(key => { | ||
if (Object.hasOwnProperty.call(processedEntity, key) && typeof processedEntity[key] === 'object') { | ||
const schema = this.schema[key]; | ||
processedEntity[key] = visit(processedEntity[key], processedEntity, key, schema, addEntity, visitedEntities); | ||
} | ||
}); | ||
addEntity(this, processedEntity, input, parent, key); | ||
return id; | ||
} // TODO: Add denormalizing capability | ||
static denormalize(entity, unvisit) { | ||
return [entity, true]; | ||
} | ||
} | ||
/* istanbul ignore next */ | ||
Entity.schema = {}; | ||
if (process.env.NODE_ENV !== 'production') { | ||
// for those not using TypeScript this is a good catch to ensure they are defining | ||
// the abstract members | ||
Entity.fromJS = function fromJS(props) { | ||
if (this.prototype.pk === undefined) throw new Error('cannot construct on abstract types'); | ||
return SimpleRecord.fromJS.call(this, props); | ||
}; | ||
} | ||
return ObjectSchema; | ||
}(); | ||
function isEntity(schema) { | ||
return schema !== null && schema.pk !== undefined; | ||
} | ||
var unvisitEntity = function unvisitEntity(id, schema, unvisit, getEntity, cache) { | ||
var entity = getEntity(id, schema); | ||
const unvisitEntity = (id, schema, unvisit, getEntity, cache) => { | ||
const entity = getEntity(id, schema); | ||
@@ -330,15 +414,12 @@ if (typeof entity !== 'object' || entity === null) { | ||
var found = true; | ||
let found = true; | ||
if (!cache[schema.key][id]) { | ||
// Ensure we don't mutate it non-immutable objects | ||
var entityCopy = isImmutable(entity) ? entity : Object.assign({}, entity); // Need to set this first so that if it is referenced further within the | ||
const entityCopy = isImmutable(entity) || entity instanceof SimpleRecord ? entity : { ...entity | ||
}; // Need to set this first so that if it is referenced further within the | ||
// denormalization the reference will already exist. | ||
cache[schema.key][id] = entityCopy; | ||
var _schema$denormalize = schema.denormalize(entityCopy, unvisit); | ||
cache[schema.key][id] = _schema$denormalize[0]; | ||
found = _schema$denormalize[1]; | ||
[cache[schema.key][id], found] = schema.denormalize(entityCopy, unvisit); | ||
} | ||
@@ -349,5 +430,5 @@ | ||
var getUnvisit = function getUnvisit(entities) { | ||
var cache = {}; | ||
var getEntity = getEntities(entities); | ||
const getUnvisit = entities => { | ||
const cache = {}; | ||
const getEntity = getEntities(entities); | ||
return [function unvisit(input, schema) { | ||
@@ -357,3 +438,3 @@ if (!schema) return [input, true]; | ||
if (typeof schema === 'object' && (!schema.denormalize || typeof schema.denormalize !== 'function')) { | ||
var method = Array.isArray(schema) ? denormalize : _denormalize; | ||
const method = Array.isArray(schema) ? denormalize : denormalize$1; | ||
return method(schema, input, unvisit); | ||
@@ -367,3 +448,3 @@ } // null is considered intentional, thus always 'found' as true | ||
if (typeof schema.getId === 'function' && typeof schema.normalize === 'function') { | ||
if (isEntity(schema)) { | ||
// unvisitEntity just can't handle undefined | ||
@@ -385,6 +466,6 @@ if (input === undefined) { | ||
var getEntities = function getEntities(entities) { | ||
var isImmutable$1 = isImmutable(entities); | ||
return function (entityOrId, schema) { | ||
var schemaKey = schema.key; | ||
const getEntities = entities => { | ||
const isImmutable$1 = isImmutable(entities); | ||
return (entityOrId, schema) => { | ||
const schemaKey = schema.key; | ||
@@ -403,3 +484,3 @@ if (typeof entityOrId === 'object') { | ||
var denormalize$1 = function denormalize(input, schema, entities) { | ||
const denormalize$2 = (input, schema, entities) => { | ||
/* istanbul ignore next */ | ||
@@ -410,7 +491,4 @@ // eslint-disable-next-line no-undef | ||
if (typeof input !== 'undefined') { | ||
var _getUnvisit = getUnvisit(entities), | ||
unvisit = _getUnvisit[0], | ||
cache = _getUnvisit[1]; | ||
return [].concat(unvisit(input, schema), [cache]); | ||
const [unvisit, cache] = getUnvisit(entities); | ||
return [...unvisit(input, schema), cache]; | ||
} | ||
@@ -421,139 +499,89 @@ | ||
var getDefaultGetId = function getDefaultGetId(idAttribute) { | ||
return function (input) { | ||
return isImmutable(input) ? input.get(idAttribute) : input[idAttribute]; | ||
}; | ||
}; | ||
const visit = (value, parent, key, schema, addEntity, visitedEntities) => { | ||
if (typeof value !== 'object' || !value || !schema) { | ||
return value; | ||
} | ||
var EntitySchema = /*#__PURE__*/function () { | ||
function EntitySchema(key, definition, options) { | ||
if (definition === void 0) { | ||
definition = {}; | ||
} | ||
if (typeof schema === 'object' && (!schema.normalize || typeof schema.normalize !== 'function')) { | ||
const method = Array.isArray(schema) ? normalize : normalize$1; | ||
return method(schema, value, parent, key, visit, addEntity, visitedEntities); | ||
} | ||
if (options === void 0) { | ||
options = {}; | ||
} | ||
return schema.normalize(value, parent, key, visit, addEntity, visitedEntities); | ||
}; | ||
if (!key || typeof key !== 'string') { | ||
throw new Error("Expected a string key for Entity, but found " + key + "."); | ||
} | ||
const addEntities = (entities, indexes) => (schema, processedEntity, value, parent, key) => { | ||
const schemaKey = schema.key; | ||
const id = schema.pk(processedEntity, parent, key); | ||
var _options = options, | ||
_options$idAttribute = _options.idAttribute, | ||
idAttribute = _options$idAttribute === void 0 ? 'id' : _options$idAttribute, | ||
_options$mergeStrateg = _options.mergeStrategy, | ||
mergeStrategy = _options$mergeStrateg === void 0 ? function (entityA, entityB) { | ||
return Object.assign({}, entityA, {}, entityB); | ||
} : _options$mergeStrateg, | ||
_options$processStrat = _options.processStrategy, | ||
processStrategy = _options$processStrat === void 0 ? function (input) { | ||
return Object.assign({}, input); | ||
} : _options$processStrat; | ||
this._key = key; | ||
this._getId = typeof idAttribute === 'function' ? idAttribute : getDefaultGetId(idAttribute); | ||
this._idAttribute = idAttribute; | ||
this._mergeStrategy = mergeStrategy; | ||
this._processStrategy = processStrategy; | ||
this.define(definition); | ||
if (!(schemaKey in entities)) { | ||
entities[schemaKey] = {}; | ||
} | ||
var _proto = EntitySchema.prototype; | ||
const existingEntity = entities[schemaKey][id]; | ||
_proto.define = function define(definition) { | ||
this.schema = Object.keys(definition).reduce(function (entitySchema, key) { | ||
var _Object$assign; | ||
if (existingEntity) { | ||
entities[schemaKey][id] = schema.merge(existingEntity, processedEntity); | ||
} else { | ||
entities[schemaKey][id] = processedEntity; | ||
} // update index | ||
var schema = definition[key]; | ||
return Object.assign({}, entitySchema, (_Object$assign = {}, _Object$assign[key] = schema, _Object$assign)); | ||
}, this.schema || {}); | ||
}; | ||
_proto.getId = function getId(input, parent, key) { | ||
return this._getId(input, parent, key); | ||
}; | ||
if (Array.isArray(schema.indexes)) { | ||
const entity = entities[schemaKey][id]; | ||
_proto.merge = function merge(entityA, entityB) { | ||
return this._mergeStrategy(entityA, entityB); | ||
}; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
var id = this.getId(input, parent, key); | ||
var entityType = this.key; | ||
if (!(entityType in visitedEntities)) { | ||
visitedEntities[entityType] = {}; | ||
if (!(schemaKey in indexes)) { | ||
indexes[schemaKey] = {}; | ||
} | ||
if (!(id in visitedEntities[entityType])) { | ||
visitedEntities[entityType][id] = []; | ||
} | ||
for (const index of schema.indexes) { | ||
if (!(index in indexes[schemaKey])) { | ||
indexes[schemaKey][index] = {}; | ||
} | ||
if (visitedEntities[entityType][id].some(function (entity) { | ||
return entity === input; | ||
})) { | ||
return id; | ||
} | ||
const indexMap = indexes[schemaKey][index]; | ||
visitedEntities[entityType][id].push(input); | ||
if (existingEntity) { | ||
delete indexMap[existingEntity[index]]; | ||
} | ||
var processedEntity = this._processStrategy(input, parent, key); | ||
Object.keys(this.schema).forEach(function (key) { | ||
if (Object.hasOwnProperty.call(processedEntity, key) && typeof processedEntity[key] === 'object') { | ||
var schema = _this.schema[key]; | ||
processedEntity[key] = visit(processedEntity[key], processedEntity, key, schema, addEntity, visitedEntities); | ||
if (index in entity) { | ||
indexMap[entity[index]] = id; | ||
} | ||
}); | ||
addEntity(this, processedEntity, input, parent, key); | ||
return id; | ||
}; | ||
_proto.denormalize = function denormalize(entity, unvisit) { | ||
var _this2 = this; | ||
if (isImmutable(entity)) { | ||
return denormalizeImmutable(this.schema, entity, unvisit); | ||
/* 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. | ||
Index: ${index} | ||
Entity: ${JSON.stringify(entity, undefined, 2)}`); | ||
} | ||
} | ||
} | ||
}; | ||
var found = true; | ||
Object.keys(this.schema).forEach(function (key) { | ||
var schema = _this2.schema[key]; | ||
function expectedSchemaType(schema) { | ||
return ['object', 'function'].includes(typeof schema) ? 'object' : typeof schema; | ||
} | ||
var _unvisit = unvisit(entity[key], schema), | ||
value = _unvisit[0], | ||
foundItem = _unvisit[1]; | ||
const normalize$2 = (input, schema) => { | ||
const schemaType = expectedSchemaType(schema); | ||
if (!foundItem) { | ||
found = false; | ||
} | ||
if (input === null || typeof input !== schemaType) { | ||
throw new Error(`Unexpected input given to normalize. Expected type to be "${schemaType}", found "${input === null ? 'null' : typeof input}".`); | ||
} | ||
if (Object.hasOwnProperty.call(entity, key)) { | ||
entity[key] = value; | ||
} | ||
}); | ||
return [entity, found]; | ||
const entities = {}; | ||
const indexes = {}; | ||
const addEntity = addEntities(entities, indexes); | ||
const visitedEntities = {}; | ||
const result = visit(input, input, undefined, schema, addEntity, visitedEntities); | ||
return { | ||
entities, | ||
indexes, | ||
result | ||
}; | ||
}; | ||
_createClass(EntitySchema, [{ | ||
key: "key", | ||
get: function get() { | ||
return this._key; | ||
} | ||
}, { | ||
key: "idAttribute", | ||
get: function get() { | ||
return this._idAttribute; | ||
} | ||
}]); | ||
return EntitySchema; | ||
}(); | ||
var UnionSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(UnionSchema, _PolymorphicSchema); | ||
function UnionSchema(definition, schemaAttribute) { | ||
class UnionSchema extends PolymorphicSchema { | ||
constructor(definition, schemaAttribute) { | ||
if (!schemaAttribute) { | ||
@@ -563,51 +591,31 @@ throw new Error('Expected option "schemaAttribute" not found on UnionSchema.'); | ||
return _PolymorphicSchema.call(this, definition, schemaAttribute) || this; | ||
super(definition, schemaAttribute); | ||
} | ||
var _proto = UnionSchema.prototype; | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
return this.normalizeValue(input, parent, key, visit, addEntity, visitedEntities); | ||
}; | ||
} | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
denormalize(input, unvisit) { | ||
return this.denormalizeValue(input, unvisit); | ||
}; | ||
return UnionSchema; | ||
}(PolymorphicSchema); | ||
var ValuesSchema = /*#__PURE__*/function (_PolymorphicSchema) { | ||
_inheritsLoose(ValuesSchema, _PolymorphicSchema); | ||
function ValuesSchema() { | ||
return _PolymorphicSchema.apply(this, arguments) || this; | ||
} | ||
var _proto = ValuesSchema.prototype; | ||
} | ||
_proto.normalize = function normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
var _this = this; | ||
return Object.keys(input).reduce(function (output, key, index) { | ||
var _Object$assign; | ||
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; | ||
class ValuesSchema extends PolymorphicSchema { | ||
normalize(input, parent, key, visit, addEntity, visitedEntities) { | ||
return Object.keys(input).reduce((output, key, index) => { | ||
const value = input[key]; | ||
return value !== undefined && value !== null ? { ...output, | ||
[key]: this.normalizeValue(value, input, key, visit, addEntity, visitedEntities) | ||
} : output; | ||
}, {}); | ||
}; | ||
} | ||
_proto.denormalize = function denormalize(input, unvisit) { | ||
var _this2 = this; | ||
denormalize(input, unvisit) { | ||
let found = true; | ||
return [Object.keys(input).reduce((output, key) => { | ||
const entityOrId = input[key]; | ||
const [value, foundItem] = this.denormalizeValue(entityOrId, unvisit); | ||
var found = true; | ||
return [Object.keys(input).reduce(function (output, key) { | ||
var _Object$assign2; | ||
var entityOrId = input[key]; | ||
var _this2$denormalizeVal = _this2.denormalizeValue(entityOrId, unvisit), | ||
value = _this2$denormalizeVal[0], | ||
foundItem = _this2$denormalizeVal[1]; | ||
if (!foundItem) { | ||
@@ -617,117 +625,32 @@ found = false; | ||
return Object.assign({}, output, (_Object$assign2 = {}, _Object$assign2[key] = value, _Object$assign2)); | ||
return { ...output, | ||
[key]: value | ||
}; | ||
}, {}), found]; | ||
}; | ||
return ValuesSchema; | ||
}(PolymorphicSchema); | ||
var visit = function visit(value, parent, key, schema, addEntity, visitedEntities) { | ||
if (typeof value !== 'object' || !value || !schema) { | ||
return value; | ||
} | ||
if (typeof schema === 'object' && (!schema.normalize || typeof schema.normalize !== 'function')) { | ||
var method = Array.isArray(schema) ? normalize : _normalize; | ||
return method(schema, value, parent, key, visit, addEntity, visitedEntities); | ||
} | ||
} | ||
return schema.normalize(value, parent, key, visit, addEntity, visitedEntities); | ||
}; | ||
var addEntities = function addEntities(entities, indexes) { | ||
return function (schema, processedEntity, value, parent, key) { | ||
var schemaKey = schema.key; | ||
var id = schema.getId(value, parent, key); | ||
if (!(schemaKey in entities)) { | ||
entities[schemaKey] = {}; | ||
} | ||
var existingEntity = entities[schemaKey][id]; | ||
if (existingEntity) { | ||
entities[schemaKey][id] = schema.merge(existingEntity, processedEntity); | ||
} else { | ||
entities[schemaKey][id] = processedEntity; | ||
} // update index | ||
if (Array.isArray(schema.indexes)) { | ||
var entity = entities[schemaKey][id]; | ||
if (!(schemaKey in indexes)) { | ||
indexes[schemaKey] = {}; | ||
} | ||
for (var _iterator = schema.indexes, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { | ||
var _ref; | ||
if (_isArray) { | ||
if (_i >= _iterator.length) break; | ||
_ref = _iterator[_i++]; | ||
} else { | ||
_i = _iterator.next(); | ||
if (_i.done) break; | ||
_ref = _i.value; | ||
} | ||
var index = _ref; | ||
if (!(index in indexes[schemaKey])) { | ||
indexes[schemaKey][index] = {}; | ||
} | ||
var indexMap = indexes[schemaKey][index]; | ||
if (existingEntity) { | ||
delete indexMap[existingEntity[index]]; | ||
} | ||
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)); | ||
} | ||
} | ||
} | ||
}; | ||
}; | ||
var schema = { | ||
var schema = /*#__PURE__*/Object.freeze({ | ||
__proto__: null, | ||
Union: UnionSchema, | ||
Values: ValuesSchema, | ||
Array: ArraySchema, | ||
Entity: EntitySchema, | ||
Object: ObjectSchema, | ||
Union: UnionSchema, | ||
Values: ValuesSchema | ||
}; | ||
Object: ObjectSchema | ||
}); | ||
function expectedSchemaType(schema) { | ||
return ['object', 'function'].includes(typeof schema) ? 'object' : typeof schema; | ||
} | ||
var normalize$1 = function normalize(input, schema) { | ||
var schemaType = expectedSchemaType(schema); | ||
if (input === null || typeof input !== schemaType) { | ||
throw new Error("Unexpected input given to normalize. Expected type to be \"" + schemaType + "\", found \"" + (input === null ? 'null' : typeof input) + "\"."); | ||
class NotImplementedError extends Error { | ||
constructor(...args) { | ||
super(...args); | ||
this.message = process.env.NODE_ENV === 'production' ? 'Not Implemented' : 'Not Implemented. You must provide an override for this method.'; | ||
} | ||
var entities = {}; | ||
var indexes = {}; | ||
var addEntity = addEntities(entities, indexes); | ||
var visitedEntities = {}; | ||
var result = visit(input, input, undefined, schema, addEntity, visitedEntities); | ||
return { | ||
entities: entities, | ||
indexes: indexes, | ||
result: result | ||
}; | ||
}; | ||
} | ||
exports.denormalize = denormalize$1; | ||
exports.normalize = normalize$1; | ||
exports.Entity = Entity; | ||
exports.NotImplementedError = NotImplementedError; | ||
exports.SimpleRecord = SimpleRecord; | ||
exports.denormalize = denormalize$2; | ||
exports.isEntity = isEntity; | ||
exports.normalize = normalize$2; | ||
exports.schema = schema; | ||
@@ -734,0 +657,0 @@ |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).rest_hooks_normalizr={})}(this,(function(e){"use strict";function t(e){return!(!e||"function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}function n(e,t,n){let r=!0;return[Object.keys(e).reduce((t,i)=>{const s=""+i,[o,c]=n(t.get(s),e[s]);return c||(r=!1),t.has(s)?t.set(s,o):t},t),r]}class r{constructor(e,t){t&&(this._schemaAttribute="string"==typeof t?e=>e[t]:t),this.define(e)}get isSingleSchema(){return!this._schemaAttribute}define(e){this.schema=e}getSchemaAttribute(e,t,n){return!this.isSingleSchema&&this._schemaAttribute(e,t,n)}inferSchema(e,t,n){if(this.isSingleSchema)return this.schema;const r=this.getSchemaAttribute(e,t,n);return this.schema[r]}normalizeValue(e,t,n,r,i,s){const o=this.inferSchema(e,t,n);if(!o)return e;const c=r(e,t,n,o,i,s);return this.isSingleSchema||null==c?c:{id:c,schema:this.getSchemaAttribute(e,t,n)}}denormalizeValue(e,n){const r=t(e)?e.get("schema"):e.schema;return this.isSingleSchema||r?n((this.isSingleSchema?void 0:t(e)?e.get("id"):e.id)||e,this.isSingleSchema?this.schema:this.schema[r]):[e,!0]}}const i=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]},s=e=>Array.isArray(e)?e:Object.keys(e).map(t=>e[t]),o=(e,t,n,r,o,c,a)=>(e=i(e),s(t).map((t,i)=>o(t,n,r,e,c,a))),c=(e,t,n)=>{e=i(e);let r=!0;return void 0===t&&e&&([,r]=n(void 0,e)),[t&&t.map?t.map(t=>n(t,e)).filter(([,e])=>e).map(([e])=>e):t,r]};const a=(e,t,n,r,i,s,o)=>{const c=Object.assign({},t);return Object.keys(e).forEach(n=>{const r=e[n],a=i(t[n],t,n,r,s,o);null==a?delete c[n]:c[n]=a}),c},u=(e,r,i)=>{if(t(r))return n(e,r,i);const s=Object.assign({},r);let o=!0;return Object.keys(e).forEach(t=>{const[n,r]=i(s[t],e[t]);void 0!==s[t]&&(s[t]=n),r||(o=!1)}),[s,o]};const h=e=>{const n={},r=l(e);return[function e(i,s){if(!s)return[i,!0];if("object"==typeof s&&(!s.denormalize||"function"!=typeof s.denormalize)){return(Array.isArray(s)?c:u)(s,i,e)}return null===i?[i,!0]:"function"==typeof s.getId&&"function"==typeof s.normalize?void 0===i?[i,!1]:((e,n,r,i,s)=>{const o=i(e,n);if("object"!=typeof o||null===o)return[o,!1];s[n.key]||(s[n.key]={});let c=!0;if(!s[n.key][e]){const i=t(o)?o:Object.assign({},o);s[n.key][e]=i,[s[n.key][e],c]=n.denormalize(i,r)}return[s[n.key][e],c]})(i,s,e,r,n):"function"==typeof s.denormalize?s.denormalize(i,e):[i,!0]},n]},l=e=>{const n=t(e);return(t,r)=>{const i=r.key;return"object"==typeof t?t:n?e.getIn([i,t.toString()]):e[i]&&e[i][t]}};const m=(e,t,n,r,i,s)=>{if("object"!=typeof e||!e||!r)return e;if("object"==typeof r&&(!r.normalize||"function"!=typeof r.normalize)){return(Array.isArray(r)?o:a)(r,e,t,n,m,i,s)}return r.normalize(e,t,n,m,i,s)},d={Array:class extends r{normalize(e,t,n,r,i,o){return s(e).map((e,s)=>this.normalizeValue(e,t,n,r,i,o)).filter(e=>null!=e)}denormalize(e,t){let n=!0;return void 0===e&&this.schema&&([,n]=t(void 0,this.schema)),[e&&e.map?e.map(e=>this.denormalizeValue(e,t)).filter(([,e])=>e).map(([e])=>e):e,n]}},Entity:class{constructor(e,n={},r={}){if(!e||"string"!=typeof e)throw new Error("Expected a string key for Entity, but found "+e+".");const{idAttribute:i="id",mergeStrategy:s=((e,t)=>Object.assign({},e,{},t)),processStrategy:o=(e=>Object.assign({},e))}=r;this._key=e,this._getId="function"==typeof i?i:(e=>n=>t(n)?n.get(e):n[e])(i),this._idAttribute=i,this._mergeStrategy=s,this._processStrategy=o,this.define(n)}get key(){return this._key}get idAttribute(){return this._idAttribute}define(e){this.schema=Object.keys(e).reduce((t,n)=>{const r=e[n];return Object.assign({},t,{[n]:r})},this.schema||{})}getId(e,t,n){return this._getId(e,t,n)}merge(e,t){return this._mergeStrategy(e,t)}normalize(e,t,n,r,i,s){const o=this.getId(e,t,n),c=this.key;if(c in s||(s[c]={}),o in s[c]||(s[c][o]=[]),s[c][o].some(t=>t===e))return o;s[c][o].push(e);const a=this._processStrategy(e,t,n);return Object.keys(this.schema).forEach(e=>{if(Object.hasOwnProperty.call(a,e)&&"object"==typeof a[e]){const t=this.schema[e];a[e]=r(a[e],a,e,t,i,s)}}),i(this,a,e,t,n),o}denormalize(e,r){if(t(e))return n(this.schema,e,r);let i=!0;return Object.keys(this.schema).forEach(t=>{const n=this.schema[t],[s,o]=r(e[t],n);o||(i=!1),Object.hasOwnProperty.call(e,t)&&(e[t]=s)}),[e,i]}},Object:class{constructor(e){this.define(e)}define(e){this.schema=Object.keys(e).reduce((t,n)=>{const r=e[n];return Object.assign({},t,{[n]:r})},this.schema||{})}normalize(...e){return a(this.schema,...e)}denormalize(...e){return u(this.schema,...e)}},Union:class extends r{constructor(e,t){if(!t)throw new Error('Expected option "schemaAttribute" not found on UnionSchema.');super(e,t)}normalize(e,t,n,r,i,s){return this.normalizeValue(e,t,n,r,i,s)}denormalize(e,t){return this.denormalizeValue(e,t)}},Values:class extends r{normalize(e,t,n,r,i,s){return Object.keys(e).reduce((t,n,o)=>{const c=e[n];return null!=c?Object.assign({},t,{[n]:this.normalizeValue(c,e,n,r,i,s)}):t},{})}denormalize(e,t){let n=!0;return[Object.keys(e).reduce((r,i)=>{const s=e[i],[o,c]=this.denormalizeValue(s,t);return c||(n=!1),Object.assign({},r,{[i]:o})},{}),n]}}};e.denormalize=(e,t,n)=>{if("production"!==process.env.NODE_ENV&&void 0===t)throw new Error("shema needed");if(void 0!==e){const[r,i]=h(n);return[...r(e,t),i]}return[void 0,!1,{}]},e.normalize=(e,t)=>{const n=function(e){return["object","function"].includes(typeof e)?"object":typeof e}(t);if(null===e||typeof e!==n)throw new Error('Unexpected input given to normalize. Expected type to be "'+n+'", found "'+(null===e?"null":typeof e)+'".');const r={},i={},s=((e,t)=>(n,r,i,s,o)=>{const c=n.key,a=n.getId(i,s,o);c in e||(e[c]={});const u=e[c][a];if(e[c][a]=u?n.merge(u,r):r,Array.isArray(n.indexes)){const r=e[c][a];c in t||(t[c]={});for(const e of n.indexes){e in t[c]||(t[c][e]={});const n=t[c][e];u&&delete n[u[e]],e in r?n[r[e]]=a:"production"!==process.env.NODE_ENV&&console.warn("Index not found in entity. Indexes must be top-level members of your entity.\nIndex: "+e+"\nEntity: "+JSON.stringify(r,void 0,2))}}})(r,i);return{entities:r,indexes:i,result:m(e,e,void 0,t,s,{})}},e.schema=d,Object.defineProperty(e,"__esModule",{value:!0})})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).rest_hooks_normalizr={})}(this,(function(e){"use strict";function t(e){return!(!e||"function"!=typeof e.hasOwnProperty||!(Object.hasOwnProperty.call(e,"__ownerID")||e._map&&Object.hasOwnProperty.call(e._map,"__ownerID")))}class n{constructor(e,t){t&&(this._schemaAttribute="string"==typeof t?e=>e[t]:t),this.define(e)}get isSingleSchema(){return!this._schemaAttribute}define(e){this.schema=e}getSchemaAttribute(e,t,n){return!this.isSingleSchema&&this._schemaAttribute(e,t,n)}inferSchema(e,t,n){if(this.isSingleSchema)return this.schema;const r=this.getSchemaAttribute(e,t,n);return this.schema[r]}normalizeValue(e,t,n,r,i,s){const o=this.inferSchema(e,t,n);if(!o)return e;const c=r(e,t,n,o,i,s);return this.isSingleSchema||null==c?c:{id:c,schema:this.getSchemaAttribute(e,t,n)}}denormalizeValue(e,n){const r=t(e)?e.get("schema"):e.schema;return this.isSingleSchema||r?n((this.isSingleSchema?void 0:t(e)?e.get("id"):e.id)||e,this.isSingleSchema?this.schema:this.schema[r]):[e,!0]}}const r=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]},i=e=>Array.isArray(e)?e:Object.keys(e).map(t=>e[t]),s=(e,t,n,s,o,c,a)=>(e=r(e),i(t).map((t,r)=>o(t,n,s,e,c,a))),o=(e,t,n)=>{e=r(e);let i=!0;return void 0===t&&e&&([,i]=n(void 0,e)),[t&&t.map?t.map(t=>n(t,e)).filter(([,e])=>e).map(([e])=>e):t,i]};const c=(e,t,n,r,i,s,o)=>{const c=Object.assign({},t);return Object.keys(e).forEach(n=>{const r=e[n],a=i(t[n],t,n,r,s,o);null==a?delete c[n]:c[n]=a}),c},a=(e,n,r)=>{if(t(n))return function(e,t,n){let r=!0;return[Object.keys(e).reduce((t,i)=>{const s=`${i}`,[o,c]=n(t.get(s),e[s]);return c||(r=!1),t.has(s)?t.set(s,o):t},t),r]}(e,n,r);const i=Object.assign({},n);let s=!0;return Object.keys(e).forEach(t=>{const[n,o]=r(i[t],e[t]);void 0!==i[t]&&(i[t]=n),o||(s=!1)}),[i,s]};const u=Symbol("Defined Members"),l=Symbol("unq");class h{toString(){return this[l]}static fromJS(e={},t,n){const r=new this(e);return Object.defineProperty(r,u,{value:Object.keys(e),writable:!1}),Object.defineProperty(r,l,{value:`${Math.random()}`,writable:!1}),Object.assign(r,e),r}static merge(e,t){const n=Object.assign(this.toObjectDefined(e),this.toObjectDefined(t));return this.fromJS(n)}static hasDefined(e,t){return e[u].includes(t)}static toObjectDefined(e){const t={};for(const n of e[u])t[n]=e[n];return t}static keysDefined(e){return e[u]}}class m extends h{static get key(){if("production"!==process.env.NODE_ENV&&""===this.name)throw new Error("Entity classes without a name must define `static get key()`");return this.name}static pk(e,t,n){return this.prototype.pk.call(e,t,n)||n}static asSchema(){return this}static normalize(e,t,n,r,i,s){const o=this.fromJS(e,t,n),c=o.pk(t,n);if(void 0===c)throw"production"!==process.env.NODE_ENV&&void 0===c?new Error(`Missing usable resource 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\n Entity: ${this}\n Value: ${e&&JSON.stringify(e,null,2)}\n `):new Error("undefined pk");const a=this.key;return a in s||(s[a]={}),c in s[a]||(s[a][c]=[]),s[a][c].some(t=>t===e)||(s[a][c].push(e),Object.keys(this.schema).forEach(e=>{if(Object.hasOwnProperty.call(o,e)&&"object"==typeof o[e]){const t=this.schema[e];o[e]=r(o[e],o,e,t,i,s)}}),i(this,o,e,t,n)),c}static denormalize(e,t){return[e,!0]}}function d(e){return null!==e&&void 0!==e.pk}m.schema={},"production"!==process.env.NODE_ENV&&(m.fromJS=function(e){if(void 0===this.prototype.pk)throw new Error("cannot construct on abstract types");return h.fromJS.call(this,e)});const f=e=>{const n={},r=p(e);return[function e(i,s){if(!s)return[i,!0];if("object"==typeof s&&(!s.denormalize||"function"!=typeof s.denormalize)){return(Array.isArray(s)?o:a)(s,i,e)}return null===i?[i,!0]:d(s)?void 0===i?[i,!1]:((e,n,r,i,s)=>{const o=i(e,n);if("object"!=typeof o||null===o)return[o,!1];s[n.key]||(s[n.key]={});let c=!0;if(!s[n.key][e]){const i=t(o)||o instanceof h?o:Object.assign({},o);s[n.key][e]=i,[s[n.key][e],c]=n.denormalize(i,r)}return[s[n.key][e],c]})(i,s,e,r,n):"function"==typeof s.denormalize?s.denormalize(i,e):[i,!0]},n]},p=e=>{const n=t(e);return(t,r)=>{const i=r.key;return"object"==typeof t?t:n?e.getIn([i,t.toString()]):e[i]&&e[i][t]}},y=(e,t,n,r,i,o)=>{if("object"!=typeof e||!e||!r)return e;if("object"==typeof r&&(!r.normalize||"function"!=typeof r.normalize)){return(Array.isArray(r)?s:c)(r,e,t,n,y,i,o)}return r.normalize(e,t,n,y,i,o)};var b=Object.freeze({__proto__:null,Union:class extends n{constructor(e,t){if(!t)throw new Error('Expected option "schemaAttribute" not found on UnionSchema.');super(e,t)}normalize(e,t,n,r,i,s){return this.normalizeValue(e,t,n,r,i,s)}denormalize(e,t){return this.denormalizeValue(e,t)}},Values:class extends n{normalize(e,t,n,r,i,s){return Object.keys(e).reduce((t,n,o)=>{const c=e[n];return null!=c?Object.assign({},t,{[n]:this.normalizeValue(c,e,n,r,i,s)}):t},{})}denormalize(e,t){let n=!0;return[Object.keys(e).reduce((r,i)=>{const s=e[i],[o,c]=this.denormalizeValue(s,t);return c||(n=!1),Object.assign({},r,{[i]:o})},{}),n]}},Array:class extends n{normalize(e,t,n,r,s,o){return i(e).map((e,i)=>this.normalizeValue(e,t,n,r,s,o)).filter(e=>null!=e)}denormalize(e,t){let n=!0;return void 0===e&&this.schema&&([,n]=t(void 0,this.schema)),[e&&e.map?e.map(e=>this.denormalizeValue(e,t)).filter(([,e])=>e).map(([e])=>e):e,n]}},Object:class{constructor(e){this.define(e)}define(e){this.schema=Object.keys(e).reduce((t,n)=>{const r=e[n];return Object.assign({},t,{[n]:r})},this.schema||{})}normalize(...e){return c(this.schema,...e)}denormalize(...e){return a(this.schema,...e)}}});class g extends Error{constructor(...e){super(...e),this.message="production"===process.env.NODE_ENV?"Not Implemented":"Not Implemented. You must provide an override for this method."}}e.Entity=m,e.NotImplementedError=g,e.SimpleRecord=h,e.denormalize=(e,t,n)=>{if("production"!==process.env.NODE_ENV&&void 0===t)throw new Error("shema needed");if(void 0!==e){const[r,i]=f(n);return[...r(e,t),i]}return[void 0,!1,{}]},e.isEntity=d,e.normalize=(e,t)=>{const n=function(e){return["object","function"].includes(typeof e)?"object":typeof e}(t);if(null===e||typeof e!==n)throw new Error(`Unexpected input given to normalize. Expected type to be "${n}", found "${null===e?"null":typeof e}".`);const r={},i={},s=((e,t)=>(n,r,i,s,o)=>{const c=n.key,a=n.pk(r,s,o);c in e||(e[c]={});const u=e[c][a];if(e[c][a]=u?n.merge(u,r):r,Array.isArray(n.indexes)){const r=e[c][a];c in t||(t[c]={});for(const e of n.indexes){e in t[c]||(t[c][e]={});const n=t[c][e];u&&delete n[u[e]],e in r?n[r[e]]=a:"production"!==process.env.NODE_ENV&&console.warn(`Index not found in entity. Indexes must be top-level members of your entity.\nIndex: ${e}\nEntity: ${JSON.stringify(r,void 0,2)}`)}}})(r,i);return{entities:r,indexes:i,result:y(e,e,void 0,t,s,{})}},e.schema=b,Object.defineProperty(e,"__esModule",{value:!0})})); |
{ | ||
"name": "@rest-hooks/normalizr", | ||
"version": "5.0.6", | ||
"version": "6.0.0-beta.0", | ||
"description": "Normalizes and denormalizes JSON according to schema for Redux and Flux applications", | ||
@@ -24,3 +24,2 @@ "homepage": "https://github.com/coinbase/rest-hooks/tree/master/packages/normalizr#readme", | ||
"dist/", | ||
"src/index.d.ts", | ||
"LICENSE", | ||
@@ -31,15 +30,14 @@ "README.md" | ||
"module": "dist/normalizr.es.js", | ||
"typings": "src/index.d.ts", | ||
"typings": "dist/index.d.ts", | ||
"sideEffects": false, | ||
"scripts": { | ||
"build": "npm run clean && run-p build:*", | ||
"build:development": "NODE_ENV=development rollup -c", | ||
"build:production": "NODE_ENV=production rollup -c", | ||
"build:es_development": "BROWSERSLIST_ENV=production NODE_ENV=development rollup -c", | ||
"build:bundle": "BROWSERSLIST_ENV=production NODE_ENV=production rollup -c", | ||
"clean": "rimraf dist", | ||
"build": "run-p build:js:*", | ||
"build:js:development": "NODE_ENV=development rollup -c", | ||
"build:js:production": "NODE_ENV=production rollup -c", | ||
"build:js:es_development": "BROWSERSLIST_ENV=production NODE_ENV=development rollup -c", | ||
"build:js:bundle": "BROWSERSLIST_ENV=production NODE_ENV=production rollup -c", | ||
"build:clean": "rimraf dist *.tsbuildinfo", | ||
"lint": "yarn lint:cmd --fix", | ||
"lint:ci": "yarn lint:cmd", | ||
"lint:cmd": "eslint . --ext '.js,.json,.snap' --cache", | ||
"prebuild": "npm run clean", | ||
"precommit": "flow check && lint-staged", | ||
@@ -50,4 +48,4 @@ "prepublishOnly": "npm run build", | ||
"test:coverage": "npm run test -- --coverage", | ||
"tsc:ci": "tsc --noEmit typescript-tests/*", | ||
"typecheck": "run-p tsc:ci" | ||
"tsc:ci": "ttsc --project tsconfig.test.json ", | ||
"typecheck": "yarn run tsc:ci" | ||
}, | ||
@@ -61,3 +59,2 @@ "author": "Nathaniel Tucker", | ||
"devDependencies": { | ||
"coveralls": "^3.0.9", | ||
"immutable": "^3.8.1", | ||
@@ -69,3 +66,3 @@ "npm-run-all": "^4.1.5" | ||
}, | ||
"gitHead": "e75e14696b2e8dca6c56992c5213b910435c659f" | ||
"gitHead": "67b7eceef1582d8323e0e1ece15da09248b1afc6" | ||
} |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
No v1
QualityPackage is not semver >=1. This means it is not stable and does not support ^ ranges.
Found 1 instance in 1 package
166505
2
31
2949
1
1