react-transporter
Advanced tools
Comparing version 1.0.0-alpha.2 to 1.0.0-alpha.3
@@ -420,2 +420,20 @@ 'use strict'; | ||
var LoadingError = /*#__PURE__*/function (_Error) { | ||
_inherits(LoadingError, _Error); | ||
var _super = _createSuper(LoadingError); | ||
function LoadingError() { | ||
var _this; | ||
_classCallCheck(this, LoadingError); | ||
_this = _super.call(this, 'Loading proxy resource.'); | ||
_this.name = 'LoadingError'; | ||
return _this; | ||
} | ||
return LoadingError; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
/* eslint-disable react/prop-types */ | ||
@@ -438,2 +456,6 @@ | ||
React.useSyncExternalStore(store.subscribe, store.getSnapshot, function () { | ||
return null; | ||
}); | ||
try { | ||
@@ -474,2 +496,6 @@ var _Resource$all = Resource.all([function () { | ||
throw error; | ||
} | ||
if (error instanceof LoadingError) { | ||
return options.loading; | ||
} // If SSR is enabled and an error occured after loading an async | ||
@@ -698,3 +724,3 @@ // resource, we render the loading component, so that the resource will | ||
if (!config.component) { | ||
throw new Error("You must define a container \"component\"."); | ||
throw new Error('React Transporter Node: You must define a node component.'); | ||
} | ||
@@ -706,2 +732,8 @@ | ||
var isWrappedInContainer = !!store.parentStore.parentStore; | ||
if (!isWrappedInContainer) { | ||
throw new Error('React Transporter Node: A node must be wrapped in a container.'); | ||
} | ||
var getValues = options.data || function () { | ||
@@ -719,16 +751,53 @@ return null; | ||
var _this = undefined; | ||
var Link = /*#__PURE__*/function () { | ||
function Link() { | ||
var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; | ||
var filterByValues = function filterByValues(items, values) { | ||
var result = values.filter(function (value) { | ||
if (!value[REF_KEY]) { | ||
return _this.items.includes(value); | ||
_classCallCheck(this, Link); | ||
_defineProperty(this, "ref", void 0); | ||
if (value === null) { | ||
this.ref = null; | ||
} else { | ||
this.ref = _defineProperty({}, REF_KEY, [value[TYPENAME], value[ID]]); | ||
} | ||
} | ||
return !items.some(function (_ref) { | ||
var _ref2 = _slicedToArray(_ref, 2), | ||
type = _ref2[0], | ||
id = _ref2[1]; | ||
_createClass(Link, [{ | ||
key: "toNative", | ||
value: function toNative() { | ||
return this.ref; | ||
} | ||
}], [{ | ||
key: "fromNative", | ||
value: function fromNative(ref) { | ||
var instance = new Link(); | ||
instance.ref = ref; | ||
return instance; | ||
} | ||
}]); | ||
return type === value[0] && id === value[1]; | ||
return Link; | ||
}(); | ||
var convertToRefs = function convertToRefs(input) { | ||
var values = Array.isArray(input) ? input : [input]; | ||
return values.map(function (value) { | ||
return _defineProperty({}, REF_KEY, [value[TYPENAME], value[ID]]); | ||
}); | ||
}; | ||
var removeDuplicateRefs = function removeDuplicateRefs(currentRefs, refs) { | ||
var result = refs.filter(function (ref) { | ||
var _ref$REF_KEY = _slicedToArray(ref[REF_KEY], 2), | ||
refType = _ref$REF_KEY[0], | ||
refId = _ref$REF_KEY[1]; | ||
return !currentRefs.some(function (_ref2) { | ||
var _ref2$REF_KEY = _slicedToArray(_ref2[REF_KEY], 2), | ||
type = _ref2$REF_KEY[0], | ||
id = _ref2$REF_KEY[1]; | ||
return type === refType && id === refId; | ||
}); | ||
@@ -739,21 +808,17 @@ }); | ||
var ReferenceMap = /*#__PURE__*/function () { | ||
function ReferenceMap() { | ||
var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; | ||
var ManyLink = /*#__PURE__*/function () { | ||
function ManyLink() { | ||
var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; | ||
_classCallCheck(this, ReferenceMap); | ||
_classCallCheck(this, ManyLink); | ||
_defineProperty(this, "items", void 0); | ||
_defineProperty(this, "refs", void 0); | ||
this.items = items; | ||
this.refs = convertToRefs(input); | ||
} | ||
_createClass(ReferenceMap, [{ | ||
_createClass(ManyLink, [{ | ||
key: "prepend", | ||
value: function prepend() { | ||
for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) { | ||
values[_key] = arguments[_key]; | ||
} | ||
this.items = [].concat(values, _toConsumableArray(this.items)); | ||
value: function prepend(input) { | ||
this.refs = [].concat(_toConsumableArray(convertToRefs(input)), _toConsumableArray(this.refs)); | ||
return this; | ||
@@ -763,8 +828,4 @@ } | ||
key: "append", | ||
value: function append() { | ||
for (var _len2 = arguments.length, values = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
values[_key2] = arguments[_key2]; | ||
} | ||
this.items = [].concat(_toConsumableArray(this.items), values); | ||
value: function append(input) { | ||
this.refs = [].concat(_toConsumableArray(this.refs), _toConsumableArray(convertToRefs(input))); | ||
return this; | ||
@@ -774,9 +835,6 @@ } | ||
key: "syncPrepend", | ||
value: function syncPrepend() { | ||
for (var _len3 = arguments.length, values = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { | ||
values[_key3] = arguments[_key3]; | ||
} | ||
var filteredValues = filterByValues(this.items, values); | ||
this.items = [].concat(values, _toConsumableArray(filteredValues)); | ||
value: function syncPrepend(input) { | ||
var refs = convertToRefs(input); | ||
var filteredRefs = removeDuplicateRefs(this.refs, refs); | ||
this.refs = [].concat(_toConsumableArray(refs), _toConsumableArray(filteredRefs)); | ||
return this; | ||
@@ -786,9 +844,6 @@ } | ||
key: "syncAppend", | ||
value: function syncAppend() { | ||
for (var _len4 = arguments.length, values = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { | ||
values[_key4] = arguments[_key4]; | ||
} | ||
var filteredValues = filterByValues(this.items, values); | ||
this.items = [].concat(_toConsumableArray(filteredValues), values); | ||
value: function syncAppend(input) { | ||
var refs = convertToRefs(input); | ||
var filteredRefs = removeDuplicateRefs(this.refs, refs); | ||
this.refs = [].concat(_toConsumableArray(filteredRefs), _toConsumableArray(refs)); | ||
return this; | ||
@@ -798,26 +853,36 @@ } | ||
key: "detach", | ||
value: function detach() { | ||
for (var _len5 = arguments.length, values = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { | ||
values[_key5] = arguments[_key5]; | ||
} | ||
this.items = filterByValues(this.items, values); | ||
value: function detach(input) { | ||
var refs = convertToRefs(input); | ||
this.refs = removeDuplicateRefs(refs, this.refs); | ||
return this; | ||
} | ||
}, { | ||
key: "toArray", | ||
value: function toArray() { | ||
return this.items; | ||
key: "toNative", | ||
value: function toNative() { | ||
return this.refs; | ||
} | ||
}], [{ | ||
key: "fromNative", | ||
value: function fromNative(refs) { | ||
var instance = new ManyLink(); | ||
instance.refs = refs; | ||
return instance; | ||
} | ||
}]); | ||
return ReferenceMap; | ||
return ManyLink; | ||
}(); | ||
function ref(type, id) { | ||
return _defineProperty({}, REF_KEY, [type, id]); | ||
var _ref; | ||
return _ref = {}, _defineProperty(_ref, TYPENAME, [type]), _defineProperty(_ref, ID, id), _ref; | ||
} | ||
var intersect = function intersect(left, right) { | ||
var condition = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {}; | ||
var intersect = function intersect() { | ||
var left = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
var right = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var condition = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () { | ||
return true; | ||
}; | ||
return Object.keys(right).some(function (key) { | ||
@@ -828,3 +893,5 @@ return left[key] !== undefined && condition(key); | ||
var merge = function merge(left, right) { | ||
var merge = function merge() { | ||
var left = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
var right = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var condition = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function (v) { | ||
@@ -837,3 +904,3 @@ return v; | ||
Object.values(right).forEach(function (_ref) { | ||
Object.entries(right).forEach(function (_ref) { | ||
var _ref2 = _slicedToArray(_ref, 2), | ||
@@ -848,22 +915,14 @@ key = _ref2[0], | ||
var mergeValue = function mergeValue(left, right) { | ||
if (!right) { | ||
var mergeValue = function mergeValue(key, left, right) { | ||
// Value is not defined on right side, so keep left side. | ||
if (right === undefined) { | ||
return left; | ||
} | ||
if (Array.isArray(left)) { | ||
return left.map(function (v, k) { | ||
return mergeValue(v, right[k]); | ||
}); | ||
if (left !== undefined && _typeof(left) !== _typeof(right)) { | ||
// eslint-disable-next-line no-console | ||
console.warn("Key ".concat(key, " had value \"").concat(left, "\" and was updated with value of different type \"").concat(right, "\".")); | ||
} | ||
if ((typeof value === "undefined" ? "undefined" : _typeof(value)) !== 'object' || left[REF_KEY]) { | ||
return right; | ||
} | ||
var result = {}; | ||
Object.keys(left).forEach(function (key) { | ||
result[key] = mergeValue(left[key], right[key]); | ||
}); | ||
return result; | ||
return right; | ||
}; | ||
@@ -903,3 +962,3 @@ /* eslint-disable arrow-body-style */ | ||
entities = data.entities; | ||
return intersect(_this.roots, roots), intersect(_this.entities, entities, function (type) { | ||
return intersect(_this.roots, roots) || intersect(_this.entities, entities, function (type) { | ||
return intersect(_this.entities[type], entities[type], function (id) { | ||
@@ -923,3 +982,3 @@ return intersect(_this.entities[type][id], entities[type][id]); | ||
Object.keys(right).forEach(function (key) { | ||
result[key] = mergeValue(left[key], right[key]); | ||
result[key] = mergeValue(key, left[key], right[key]); | ||
}); | ||
@@ -1066,6 +1125,6 @@ return result; | ||
var getKey = function getKey(field, variables) { | ||
var getKey = function getKey(field, variables, ignoreArgs) { | ||
var name = field.name.value; | ||
if (field.arguments.length === 0) { | ||
if (field.arguments.length === 0 || ignoreArgs) { | ||
return name; | ||
@@ -1082,2 +1141,3 @@ } | ||
var handleSelectionSet = function handleSelectionSet(selectionSet, value, context) { | ||
var ignoreArgs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; | ||
var cache = context.cache, | ||
@@ -1091,3 +1151,3 @@ handleFragment = context.handleFragment; | ||
if (selection.kind === 'Field') { | ||
var key = getKey(selection, options.variables); // eslint-disable-next-line no-use-before-define | ||
var key = getKey(selection, options.variables, ignoreArgs); // eslint-disable-next-line no-use-before-define | ||
@@ -1183,3 +1243,3 @@ result[selection.name.value] = buildNode(selection.selectionSet, value[key], context); | ||
try { | ||
return handleSelectionSet(queryAst.selectionSet, cachedRoots, context); | ||
return handleSelectionSet(queryAst.selectionSet, cachedRoots, context, queryAst.operation === 'mutation'); | ||
} catch (err) { | ||
@@ -1233,3 +1293,3 @@ if (err.name !== 'ValueError') { | ||
data.add({ | ||
entities: _defineProperty({}, TYPENAME, _defineProperty({}, ID, result)) | ||
entities: _defineProperty({}, type, _defineProperty({}, id, result)) | ||
}); | ||
@@ -1273,8 +1333,11 @@ return _defineProperty({}, REF_KEY, [type, id]); | ||
_this.dirty = true; | ||
var updatedData = _this.data.merge(data); | ||
var update = { | ||
optimistic: optimistic, | ||
data: data, | ||
cache: _this.data.merge(data) | ||
cache: updatedData | ||
}; | ||
_this.data = data; | ||
_this.data = updatedData; | ||
_this.updates = [].concat(_toConsumableArray(_this.updates), [update]); | ||
@@ -1401,4 +1464,2 @@ }); | ||
var ProxyResource = function ProxyResource() { | ||
var _this = this; | ||
_classCallCheck(this, ProxyResource); | ||
@@ -1409,3 +1470,3 @@ | ||
_defineProperty(this, "read", function () { | ||
throw _this.promise; | ||
throw new LoadingError(); | ||
}); | ||
@@ -1418,3 +1479,3 @@ | ||
var QueryRequest = function QueryRequest(store, _ast) { | ||
var QueryRequest = function QueryRequest(client, _ast) { | ||
var _this = this; | ||
@@ -1426,3 +1487,3 @@ | ||
_defineProperty(this, "store", void 0); | ||
_defineProperty(this, "client", void 0); | ||
@@ -1460,8 +1521,8 @@ _defineProperty(this, "ast", void 0); | ||
_defineProperty(this, "invalidate", function () { | ||
_this.aborted = true; // Delete resource from store | ||
_this.aborted = true; // Delete resource from client | ||
_this.store.queries.delete(_this.options.name); | ||
_this.client.queries.delete(_this.options.name); | ||
}); | ||
this.store = store; | ||
this.client = client; | ||
this.ast = _ast; | ||
@@ -1475,3 +1536,3 @@ this.options = options; | ||
var data = new DataSet(res.data); // Update store data | ||
var data = new DataSet(res.data); // Update client data | ||
@@ -1481,13 +1542,13 @@ var updateData = new DataSet({ | ||
}); | ||
store.queries.forEach(function (q) { | ||
client.queries.forEach(function (q) { | ||
q.addUpdate(updateData); | ||
}); // Add result to store | ||
}); // Add result to client | ||
_this.cache = new QueryCache(_this, data); | ||
store.queries.set(_this.options.name, _this.cache); // Commit update | ||
client.queries.set(_this.options.name, _this.cache); // Commit update | ||
store.refresh(); | ||
client.refresh(); | ||
}; | ||
var cache = store.cache; | ||
var cache = client.cache; | ||
var cachedResponse = cache[this.options.name]; // Set response from cache or start a new request. | ||
@@ -1504,19 +1565,24 @@ | ||
// Do not start a request on server if SSR is disabled. | ||
this.resource = !isServer || store.ssr ? new Resource(function () { | ||
return createRequest(store.request, _ast, options.variables); | ||
}) : new ProxyResource(); | ||
this.loading = true; // Handle fulfilled and rejected promise | ||
if (isServer && !client.ssr) { | ||
this.resource = new ProxyResource(); | ||
} else { | ||
this.resource = new Resource(function () { | ||
return createRequest(client.request, _ast, options.variables); | ||
}); // Handle fulfilled and rejected promise | ||
this.resource.promise.then(function (res) { | ||
_this.loading = false; // Store response on server side for hydration. | ||
this.resource.promise.then(function (res) { | ||
_this.loading = false; // Store response on server side for hydration. | ||
if (isServer) { | ||
cache[_this.options.name] = res; | ||
} | ||
if (isServer) { | ||
cache[_this.options.name] = res; | ||
} | ||
handleResponse(res); | ||
}, function () { | ||
_this.loading = false; | ||
_this.aborted = true; | ||
}); | ||
handleResponse(res); | ||
}, function () { | ||
_this.loading = false; | ||
_this.aborted = true; | ||
}); | ||
} | ||
this.loading = true; | ||
} | ||
@@ -1529,14 +1595,76 @@ }; | ||
var castValue = function castValue(value) { | ||
if (value instanceof ReferenceMap) { | ||
return value.toArray(); | ||
var ValueCaster = /*#__PURE__*/function () { | ||
function ValueCaster() { | ||
_classCallCheck(this, ValueCaster); | ||
} | ||
if (isDate(value)) { | ||
return value.toISOString(); | ||
} | ||
_createClass(ValueCaster, null, [{ | ||
key: "fromNative", | ||
value: function fromNative(value) { | ||
if (Array.isArray(value)) { | ||
if (value.some(function (v) { | ||
return _typeof(v) === 'object' && REF_KEY in v; | ||
})) { | ||
return ManyLink.fromNative(value); | ||
} | ||
return value; | ||
}; | ||
return value.map(function (v) { | ||
return ValueCaster.fromNative(v); | ||
}); | ||
} | ||
if (_typeof(value) === 'object') { | ||
if (REF_KEY in value) { | ||
return Link.fromNative(value); | ||
} | ||
var result = {}; | ||
Object.entries(value).forEach(function (_ref) { | ||
var _ref2 = _slicedToArray(_ref, 2), | ||
k = _ref2[0], | ||
v = _ref2[1]; | ||
result[k] = ValueCaster.fromNative(v); | ||
}); | ||
return result; | ||
} | ||
return value; | ||
} | ||
}, { | ||
key: "toNative", | ||
value: function toNative(value) { | ||
if (value instanceof Link || value instanceof ManyLink) { | ||
return value.toNative(); | ||
} | ||
if (isDate(value)) { | ||
return value.toISOString(); | ||
} | ||
if (Array.isArray(value)) { | ||
return value.map(function (v) { | ||
return ValueCaster.toNative(v); | ||
}); | ||
} | ||
if (_typeof(value) === 'object') { | ||
var result = {}; | ||
Object.entries(value).forEach(function (_ref3) { | ||
var _ref4 = _slicedToArray(_ref3, 2), | ||
k = _ref4[0], | ||
v = _ref4[1]; | ||
result[k] = ValueCaster.toNative(v); | ||
}); | ||
return result; | ||
} | ||
return value; | ||
} | ||
}]); | ||
return ValueCaster; | ||
}(); | ||
var Record = /*#__PURE__*/function () { | ||
@@ -1567,3 +1695,3 @@ function Record() { | ||
var value = Array.isArray(this.original[key]) ? new ReferenceMap(this.original[key]) : this.original[key]; | ||
var value = ValueCaster.fromNative(this.original[key]); | ||
nextValue = resolve(value); | ||
@@ -1574,3 +1702,3 @@ } else { | ||
this.values[key] = castValue(nextValue); | ||
this.values[key] = ValueCaster.toNative(nextValue); | ||
} | ||
@@ -1591,5 +1719,5 @@ }, { | ||
var get = function get(store, type, id) { | ||
var get = function get(client, type, id) { | ||
var value = null; | ||
store.queries.forEach(function (query) { | ||
client.queries.forEach(function (query) { | ||
var entity = query.data.get(type, id); | ||
@@ -1610,5 +1738,5 @@ | ||
var getRoots = function getRoots(store) { | ||
var getRoots = function getRoots(client) { | ||
var value = null; | ||
store.queries.forEach(function (query) { | ||
client.queries.forEach(function (query) { | ||
var roots = query.data.getRoots(); | ||
@@ -1620,3 +1748,3 @@ value = _objectSpread2(_objectSpread2({}, value), roots); | ||
function applyUpdater(store, updater, data) { | ||
function applyUpdater(client, updater, data, cache) { | ||
if (!updater) { | ||
@@ -1637,3 +1765,3 @@ return data; | ||
var record = new Record(function () { | ||
return _objectSpread2(_objectSpread2({}, get(store, type, id)), result.get(type, id)); | ||
return _objectSpread2(_objectSpread2({}, get(client, type, id)), result.get(type, id)); | ||
}); | ||
@@ -1647,3 +1775,3 @@ resolve(record); | ||
var record = new Record(function () { | ||
return getRoots(store); | ||
return getRoots(client); | ||
}); | ||
@@ -1656,7 +1784,23 @@ resolve(record); | ||
}; | ||
updater(writeStore); | ||
updater(writeStore, cache.selectorSet.getQuery()); | ||
return result; | ||
} | ||
var MutationRequest = function MutationRequest(store, mutation) { | ||
var MutationCache = function MutationCache(request, data) { | ||
_classCallCheck(this, MutationCache); | ||
_defineProperty(this, "request", void 0); | ||
_defineProperty(this, "data", void 0); | ||
_defineProperty(this, "selectorSet", void 0); | ||
this.request = request; | ||
this.data = data; | ||
this.selectorSet = buildSelectorSet(this); | ||
}; | ||
var MutationRequest = function MutationRequest(client, ast) { | ||
var _this = this; | ||
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
@@ -1666,3 +1810,3 @@ | ||
_defineProperty(this, "mutation", void 0); | ||
_defineProperty(this, "ast", void 0); | ||
@@ -1673,20 +1817,26 @@ _defineProperty(this, "options", void 0); | ||
this.mutation = mutation; | ||
_defineProperty(this, "cache", void 0); | ||
this.ast = ast; | ||
this.options = options; | ||
var optimisticData = applyUpdater(store, options.optimisticUpdater, new DataSet()); | ||
store.queries.forEach(function (query) { | ||
var optimisticData = applyUpdater(client, options.optimisticUpdater, new DataSet()); | ||
client.queries.forEach(function (query) { | ||
query.addUpdate(optimisticData, true); | ||
}); | ||
store.refresh(); | ||
client.refresh(); | ||
this.resource = new Resource(function () { | ||
return createRequest(store.request, mutation, options.variables); | ||
return createRequest(client.request, ast, options.variables); | ||
}); // Handle fulfilled and rejected promise | ||
this.resource.promise.then(function (res) { | ||
var data = applyUpdater(store, options.updater, new DataSet({ | ||
entities: res.entities | ||
})); // Set result in store | ||
var data = new DataSet(res.data); // Create cache | ||
_this.cache = new MutationCache(_this, data); | ||
var updatedData = applyUpdater(client, options.updater, new DataSet({ | ||
entities: res.data.entities | ||
}), // Do not add roots to store. | ||
_this.cache); // Set result in client | ||
if (optimisticData) { | ||
store.queries.forEach(function (query) { | ||
client.queries.forEach(function (query) { | ||
query.removeUpdate(optimisticData); | ||
@@ -1696,6 +1846,6 @@ }); | ||
store.queries.forEach(function (query) { | ||
query.addUpdate(data); | ||
client.queries.forEach(function (query) { | ||
query.addUpdate(updatedData); | ||
}); | ||
store.refresh(); | ||
client.refresh(); | ||
}, function (err) { | ||
@@ -1705,10 +1855,10 @@ if (err.message) { | ||
console.error("Mutation Error: ".concat(err.message)); | ||
} // Reset optimistic update in store | ||
} // Reset optimistic update in client | ||
if (optimisticData) { | ||
store.queries.forEach(function (query) { | ||
client.queries.forEach(function (query) { | ||
query.removeUpdate(optimisticData); | ||
}); | ||
store.refresh(); | ||
client.refresh(); | ||
} | ||
@@ -1735,2 +1885,4 @@ }); | ||
_defineProperty(this, "marker", {}); | ||
_defineProperty(this, "preload", function (query) { | ||
@@ -1754,3 +1906,3 @@ var _query$definitions$fi; | ||
_this.selectorSetsByRequest.delete(name); | ||
_this.selectorSetsByRequest.delete(request); | ||
@@ -1876,2 +2028,6 @@ request.invalidate(); | ||
_defineProperty(this, "getSnapshot", function () { | ||
return _this.marker; | ||
}); | ||
_defineProperty(this, "refresh", function () { | ||
@@ -1892,5 +2048,3 @@ _this.requests.forEach(function (request) { | ||
if (shouldUpdate) { | ||
_this.listeners.forEach(function (listener) { | ||
listener(); | ||
}); | ||
_this.update(); | ||
} else { | ||
@@ -1904,9 +2058,23 @@ _this.children.forEach(function (child) { | ||
_defineProperty(this, "reset", function () { | ||
var root = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; | ||
_this.requests = new Map(); | ||
_this.selectorSetsByRequest = new Map(); | ||
if (root) { | ||
_this.update(); | ||
} | ||
_this.children.forEach(function (child) { | ||
child.reset(); | ||
child.reset(false); | ||
}); | ||
}); | ||
_defineProperty(this, "update", function () { | ||
_this.marker = {}; | ||
_this.listeners.forEach(function (listener) { | ||
listener(); | ||
}); | ||
}); | ||
_defineProperty(this, "destroy", function () { | ||
@@ -1975,4 +2143,2 @@ // Remove network from parent store network children. | ||
_this.queries = new Map(); | ||
_this.rootStore.refresh(); | ||
}); | ||
@@ -2008,4 +2174,5 @@ | ||
var store = client.rootStore; | ||
React.useSyncExternalStore(store.subscribe, function () {}, function () {} // TODO: Check this! | ||
); | ||
React.useSyncExternalStore(store.subscribe, store.getSnapshot, function () { | ||
return null; | ||
}); | ||
return /*#__PURE__*/React__default['default'].createElement(TransporterContext.Provider, { | ||
@@ -2022,22 +2189,44 @@ value: { | ||
var REJECTED = 'rejected'; | ||
function useMutation(mutation, options) { | ||
var getLatestInstance = function getLatestInstance(_ref) { | ||
var instances = _ref.current; | ||
if (instances.length === 0) { | ||
return null; | ||
} | ||
return instances[instances.length - 1]; | ||
}; | ||
function useDispatcher() { | ||
var context = React.useContext(TransporterContext); | ||
if (!context) { | ||
throw new Error('"useMutation" hook is used outside of TransporterContext.'); | ||
throw new Error('Dispatcher hook is used outside of TransporterContext.'); | ||
} | ||
var instance; | ||
var instances = React.useRef([]); | ||
return { | ||
dispatch: function dispatch(ast, options) { | ||
var _ast$definitions$find; | ||
var dispatch = function dispatch(dispatchOptions) { | ||
if (instance) { | ||
throw new Error('Mutation was dispatched before.'); | ||
} | ||
var operation = (_ast$definitions$find = ast.definitions.find(function (def) { | ||
return def.kind === 'OperationDefinition'; | ||
})) === null || _ast$definitions$find === void 0 ? void 0 : _ast$definitions$find.operation; | ||
instance = context.store.mutate(mutation, _objectSpread2(_objectSpread2({}, options), dispatchOptions)); | ||
return instance; | ||
}; | ||
if (operation !== 'query' && operation !== 'mutation') { | ||
throw new Error('No operation found. Must be either "query" or "mutation".'); | ||
} | ||
var state = { | ||
var instance = operation === 'query' ? context.client.query(ast, options) : context.client.mutate(ast, options); | ||
instances.current.push(instance); // Return cached selector set. | ||
return instance.resource.promise.then(function () { | ||
return instance.cache.selectorSet.getQuery(); | ||
}); | ||
}, | ||
get ok() { | ||
var instance = getLatestInstance(instances); | ||
if (!instance || instance.status === PENDING) { | ||
@@ -2051,2 +2240,4 @@ return null; | ||
get loading() { | ||
var instance = getLatestInstance(instances); | ||
if (!instance) { | ||
@@ -2060,2 +2251,4 @@ return false; | ||
get executed() { | ||
var instance = getLatestInstance(instances); | ||
if (!instance) { | ||
@@ -2066,15 +2259,43 @@ return false; | ||
return instance.status === FULFILLED || instance.status === REJECTED; | ||
} | ||
/* get errors() { | ||
// TODO | ||
}, | ||
get networkError() { | ||
// TODO | ||
}, */ | ||
get error() { | ||
var instance = getLatestInstance(instances); | ||
if (!instance || instance.status !== REJECTED) { | ||
return null; | ||
} | ||
return instance.response; | ||
} | ||
}; | ||
return [dispatch, state]; | ||
} | ||
function useMutation(mutation, options) { | ||
var _useDispatcher = useDispatcher(), | ||
_useDispatcher2 = _slicedToArray(_useDispatcher, 2), | ||
_dispatch = _useDispatcher2[0], | ||
state = _useDispatcher2[1]; | ||
return _objectSpread2(_objectSpread2({}, state), {}, { | ||
dispatch: function dispatch(dispatchOptions) { | ||
return _dispatch(mutation, _objectSpread2(_objectSpread2({}, options), dispatchOptions)); | ||
} | ||
}); | ||
} | ||
function useQuery(query, options) { | ||
var _useDispatcher = useDispatcher(), | ||
_useDispatcher2 = _slicedToArray(_useDispatcher, 2), | ||
_dispatch = _useDispatcher2[0], | ||
state = _useDispatcher2[1]; | ||
return _objectSpread2(_objectSpread2({}, state), {}, { | ||
dispatch: function dispatch(dispatchOptions) { | ||
return _dispatch(query, _objectSpread2(_objectSpread2({}, options), dispatchOptions)); | ||
} | ||
}); | ||
} | ||
function useReset() { | ||
@@ -2087,9 +2308,10 @@ var context = React.useContext(TransporterContext); | ||
var store = context.store; | ||
var client = context.client; | ||
return function () { | ||
store.reset(); | ||
client.reset(); | ||
}; | ||
} | ||
exports.ReferenceMap = ReferenceMap; | ||
exports.Link = Link; | ||
exports.ManyLink = ManyLink; | ||
exports.Resource = Resource; | ||
@@ -2102,3 +2324,5 @@ exports.Transporter = Transporter; | ||
exports.ref = ref; | ||
exports.useDispatcher = useDispatcher; | ||
exports.useMutation = useMutation; | ||
exports.useQuery = useQuery; | ||
exports.useReset = useReset; |
@@ -1,2 +0,2 @@ | ||
import React, { useRef, useContext, createElement, cloneElement, useSyncExternalStore } from 'react'; | ||
import React, { useRef, useContext, useSyncExternalStore, createElement, cloneElement } from 'react'; | ||
import { Platform } from 'react-native'; | ||
@@ -412,2 +412,20 @@ import { valueFromASTUntyped } from 'graphql/utilities/valueFromASTUntyped'; | ||
var LoadingError = /*#__PURE__*/function (_Error) { | ||
_inherits(LoadingError, _Error); | ||
var _super = _createSuper(LoadingError); | ||
function LoadingError() { | ||
var _this; | ||
_classCallCheck(this, LoadingError); | ||
_this = _super.call(this, 'Loading proxy resource.'); | ||
_this.name = 'LoadingError'; | ||
return _this; | ||
} | ||
return LoadingError; | ||
}( /*#__PURE__*/_wrapNativeSuper(Error)); | ||
/* eslint-disable react/prop-types */ | ||
@@ -430,2 +448,6 @@ | ||
useSyncExternalStore(store.subscribe, store.getSnapshot, function () { | ||
return null; | ||
}); | ||
try { | ||
@@ -466,2 +488,6 @@ var _Resource$all = Resource.all([function () { | ||
throw error; | ||
} | ||
if (error instanceof LoadingError) { | ||
return options.loading; | ||
} // If SSR is enabled and an error occured after loading an async | ||
@@ -690,3 +716,3 @@ // resource, we render the loading component, so that the resource will | ||
if (!config.component) { | ||
throw new Error("You must define a container \"component\"."); | ||
throw new Error('React Transporter Node: You must define a node component.'); | ||
} | ||
@@ -698,2 +724,8 @@ | ||
var isWrappedInContainer = !!store.parentStore.parentStore; | ||
if (!isWrappedInContainer) { | ||
throw new Error('React Transporter Node: A node must be wrapped in a container.'); | ||
} | ||
var getValues = options.data || function () { | ||
@@ -711,16 +743,53 @@ return null; | ||
var _this = undefined; | ||
var Link = /*#__PURE__*/function () { | ||
function Link() { | ||
var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; | ||
var filterByValues = function filterByValues(items, values) { | ||
var result = values.filter(function (value) { | ||
if (!value[REF_KEY]) { | ||
return _this.items.includes(value); | ||
_classCallCheck(this, Link); | ||
_defineProperty(this, "ref", void 0); | ||
if (value === null) { | ||
this.ref = null; | ||
} else { | ||
this.ref = _defineProperty({}, REF_KEY, [value[TYPENAME], value[ID]]); | ||
} | ||
} | ||
return !items.some(function (_ref) { | ||
var _ref2 = _slicedToArray(_ref, 2), | ||
type = _ref2[0], | ||
id = _ref2[1]; | ||
_createClass(Link, [{ | ||
key: "toNative", | ||
value: function toNative() { | ||
return this.ref; | ||
} | ||
}], [{ | ||
key: "fromNative", | ||
value: function fromNative(ref) { | ||
var instance = new Link(); | ||
instance.ref = ref; | ||
return instance; | ||
} | ||
}]); | ||
return type === value[0] && id === value[1]; | ||
return Link; | ||
}(); | ||
var convertToRefs = function convertToRefs(input) { | ||
var values = Array.isArray(input) ? input : [input]; | ||
return values.map(function (value) { | ||
return _defineProperty({}, REF_KEY, [value[TYPENAME], value[ID]]); | ||
}); | ||
}; | ||
var removeDuplicateRefs = function removeDuplicateRefs(currentRefs, refs) { | ||
var result = refs.filter(function (ref) { | ||
var _ref$REF_KEY = _slicedToArray(ref[REF_KEY], 2), | ||
refType = _ref$REF_KEY[0], | ||
refId = _ref$REF_KEY[1]; | ||
return !currentRefs.some(function (_ref2) { | ||
var _ref2$REF_KEY = _slicedToArray(_ref2[REF_KEY], 2), | ||
type = _ref2$REF_KEY[0], | ||
id = _ref2$REF_KEY[1]; | ||
return type === refType && id === refId; | ||
}); | ||
@@ -731,21 +800,17 @@ }); | ||
var ReferenceMap = /*#__PURE__*/function () { | ||
function ReferenceMap() { | ||
var items = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; | ||
var ManyLink = /*#__PURE__*/function () { | ||
function ManyLink() { | ||
var input = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; | ||
_classCallCheck(this, ReferenceMap); | ||
_classCallCheck(this, ManyLink); | ||
_defineProperty(this, "items", void 0); | ||
_defineProperty(this, "refs", void 0); | ||
this.items = items; | ||
this.refs = convertToRefs(input); | ||
} | ||
_createClass(ReferenceMap, [{ | ||
_createClass(ManyLink, [{ | ||
key: "prepend", | ||
value: function prepend() { | ||
for (var _len = arguments.length, values = new Array(_len), _key = 0; _key < _len; _key++) { | ||
values[_key] = arguments[_key]; | ||
} | ||
this.items = [].concat(values, _toConsumableArray(this.items)); | ||
value: function prepend(input) { | ||
this.refs = [].concat(_toConsumableArray(convertToRefs(input)), _toConsumableArray(this.refs)); | ||
return this; | ||
@@ -755,8 +820,4 @@ } | ||
key: "append", | ||
value: function append() { | ||
for (var _len2 = arguments.length, values = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { | ||
values[_key2] = arguments[_key2]; | ||
} | ||
this.items = [].concat(_toConsumableArray(this.items), values); | ||
value: function append(input) { | ||
this.refs = [].concat(_toConsumableArray(this.refs), _toConsumableArray(convertToRefs(input))); | ||
return this; | ||
@@ -766,9 +827,6 @@ } | ||
key: "syncPrepend", | ||
value: function syncPrepend() { | ||
for (var _len3 = arguments.length, values = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { | ||
values[_key3] = arguments[_key3]; | ||
} | ||
var filteredValues = filterByValues(this.items, values); | ||
this.items = [].concat(values, _toConsumableArray(filteredValues)); | ||
value: function syncPrepend(input) { | ||
var refs = convertToRefs(input); | ||
var filteredRefs = removeDuplicateRefs(this.refs, refs); | ||
this.refs = [].concat(_toConsumableArray(refs), _toConsumableArray(filteredRefs)); | ||
return this; | ||
@@ -778,9 +836,6 @@ } | ||
key: "syncAppend", | ||
value: function syncAppend() { | ||
for (var _len4 = arguments.length, values = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { | ||
values[_key4] = arguments[_key4]; | ||
} | ||
var filteredValues = filterByValues(this.items, values); | ||
this.items = [].concat(_toConsumableArray(filteredValues), values); | ||
value: function syncAppend(input) { | ||
var refs = convertToRefs(input); | ||
var filteredRefs = removeDuplicateRefs(this.refs, refs); | ||
this.refs = [].concat(_toConsumableArray(filteredRefs), _toConsumableArray(refs)); | ||
return this; | ||
@@ -790,26 +845,36 @@ } | ||
key: "detach", | ||
value: function detach() { | ||
for (var _len5 = arguments.length, values = new Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { | ||
values[_key5] = arguments[_key5]; | ||
} | ||
this.items = filterByValues(this.items, values); | ||
value: function detach(input) { | ||
var refs = convertToRefs(input); | ||
this.refs = removeDuplicateRefs(refs, this.refs); | ||
return this; | ||
} | ||
}, { | ||
key: "toArray", | ||
value: function toArray() { | ||
return this.items; | ||
key: "toNative", | ||
value: function toNative() { | ||
return this.refs; | ||
} | ||
}], [{ | ||
key: "fromNative", | ||
value: function fromNative(refs) { | ||
var instance = new ManyLink(); | ||
instance.refs = refs; | ||
return instance; | ||
} | ||
}]); | ||
return ReferenceMap; | ||
return ManyLink; | ||
}(); | ||
function ref(type, id) { | ||
return _defineProperty({}, REF_KEY, [type, id]); | ||
var _ref; | ||
return _ref = {}, _defineProperty(_ref, TYPENAME, [type]), _defineProperty(_ref, ID, id), _ref; | ||
} | ||
var intersect = function intersect(left, right) { | ||
var condition = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {}; | ||
var intersect = function intersect() { | ||
var left = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
var right = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var condition = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () { | ||
return true; | ||
}; | ||
return Object.keys(right).some(function (key) { | ||
@@ -820,3 +885,5 @@ return left[key] !== undefined && condition(key); | ||
var merge = function merge(left, right) { | ||
var merge = function merge() { | ||
var left = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; | ||
var right = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; | ||
var condition = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function (v) { | ||
@@ -829,3 +896,3 @@ return v; | ||
Object.values(right).forEach(function (_ref) { | ||
Object.entries(right).forEach(function (_ref) { | ||
var _ref2 = _slicedToArray(_ref, 2), | ||
@@ -840,22 +907,14 @@ key = _ref2[0], | ||
var mergeValue = function mergeValue(left, right) { | ||
if (!right) { | ||
var mergeValue = function mergeValue(key, left, right) { | ||
// Value is not defined on right side, so keep left side. | ||
if (right === undefined) { | ||
return left; | ||
} | ||
if (Array.isArray(left)) { | ||
return left.map(function (v, k) { | ||
return mergeValue(v, right[k]); | ||
}); | ||
if (left !== undefined && _typeof(left) !== _typeof(right)) { | ||
// eslint-disable-next-line no-console | ||
console.warn("Key ".concat(key, " had value \"").concat(left, "\" and was updated with value of different type \"").concat(right, "\".")); | ||
} | ||
if ((typeof value === "undefined" ? "undefined" : _typeof(value)) !== 'object' || left[REF_KEY]) { | ||
return right; | ||
} | ||
var result = {}; | ||
Object.keys(left).forEach(function (key) { | ||
result[key] = mergeValue(left[key], right[key]); | ||
}); | ||
return result; | ||
return right; | ||
}; | ||
@@ -895,3 +954,3 @@ /* eslint-disable arrow-body-style */ | ||
entities = data.entities; | ||
return intersect(_this.roots, roots), intersect(_this.entities, entities, function (type) { | ||
return intersect(_this.roots, roots) || intersect(_this.entities, entities, function (type) { | ||
return intersect(_this.entities[type], entities[type], function (id) { | ||
@@ -915,3 +974,3 @@ return intersect(_this.entities[type][id], entities[type][id]); | ||
Object.keys(right).forEach(function (key) { | ||
result[key] = mergeValue(left[key], right[key]); | ||
result[key] = mergeValue(key, left[key], right[key]); | ||
}); | ||
@@ -1058,6 +1117,6 @@ return result; | ||
var getKey = function getKey(field, variables) { | ||
var getKey = function getKey(field, variables, ignoreArgs) { | ||
var name = field.name.value; | ||
if (field.arguments.length === 0) { | ||
if (field.arguments.length === 0 || ignoreArgs) { | ||
return name; | ||
@@ -1074,2 +1133,3 @@ } | ||
var handleSelectionSet = function handleSelectionSet(selectionSet, value, context) { | ||
var ignoreArgs = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; | ||
var cache = context.cache, | ||
@@ -1083,3 +1143,3 @@ handleFragment = context.handleFragment; | ||
if (selection.kind === 'Field') { | ||
var key = getKey(selection, options.variables); // eslint-disable-next-line no-use-before-define | ||
var key = getKey(selection, options.variables, ignoreArgs); // eslint-disable-next-line no-use-before-define | ||
@@ -1175,3 +1235,3 @@ result[selection.name.value] = buildNode(selection.selectionSet, value[key], context); | ||
try { | ||
return handleSelectionSet(queryAst.selectionSet, cachedRoots, context); | ||
return handleSelectionSet(queryAst.selectionSet, cachedRoots, context, queryAst.operation === 'mutation'); | ||
} catch (err) { | ||
@@ -1225,3 +1285,3 @@ if (err.name !== 'ValueError') { | ||
data.add({ | ||
entities: _defineProperty({}, TYPENAME, _defineProperty({}, ID, result)) | ||
entities: _defineProperty({}, type, _defineProperty({}, id, result)) | ||
}); | ||
@@ -1265,8 +1325,11 @@ return _defineProperty({}, REF_KEY, [type, id]); | ||
_this.dirty = true; | ||
var updatedData = _this.data.merge(data); | ||
var update = { | ||
optimistic: optimistic, | ||
data: data, | ||
cache: _this.data.merge(data) | ||
cache: updatedData | ||
}; | ||
_this.data = data; | ||
_this.data = updatedData; | ||
_this.updates = [].concat(_toConsumableArray(_this.updates), [update]); | ||
@@ -1393,4 +1456,2 @@ }); | ||
var ProxyResource = function ProxyResource() { | ||
var _this = this; | ||
_classCallCheck(this, ProxyResource); | ||
@@ -1401,3 +1462,3 @@ | ||
_defineProperty(this, "read", function () { | ||
throw _this.promise; | ||
throw new LoadingError(); | ||
}); | ||
@@ -1410,3 +1471,3 @@ | ||
var QueryRequest = function QueryRequest(store, _ast) { | ||
var QueryRequest = function QueryRequest(client, _ast) { | ||
var _this = this; | ||
@@ -1418,3 +1479,3 @@ | ||
_defineProperty(this, "store", void 0); | ||
_defineProperty(this, "client", void 0); | ||
@@ -1452,8 +1513,8 @@ _defineProperty(this, "ast", void 0); | ||
_defineProperty(this, "invalidate", function () { | ||
_this.aborted = true; // Delete resource from store | ||
_this.aborted = true; // Delete resource from client | ||
_this.store.queries.delete(_this.options.name); | ||
_this.client.queries.delete(_this.options.name); | ||
}); | ||
this.store = store; | ||
this.client = client; | ||
this.ast = _ast; | ||
@@ -1467,3 +1528,3 @@ this.options = options; | ||
var data = new DataSet(res.data); // Update store data | ||
var data = new DataSet(res.data); // Update client data | ||
@@ -1473,13 +1534,13 @@ var updateData = new DataSet({ | ||
}); | ||
store.queries.forEach(function (q) { | ||
client.queries.forEach(function (q) { | ||
q.addUpdate(updateData); | ||
}); // Add result to store | ||
}); // Add result to client | ||
_this.cache = new QueryCache(_this, data); | ||
store.queries.set(_this.options.name, _this.cache); // Commit update | ||
client.queries.set(_this.options.name, _this.cache); // Commit update | ||
store.refresh(); | ||
client.refresh(); | ||
}; | ||
var cache = store.cache; | ||
var cache = client.cache; | ||
var cachedResponse = cache[this.options.name]; // Set response from cache or start a new request. | ||
@@ -1496,19 +1557,24 @@ | ||
// Do not start a request on server if SSR is disabled. | ||
this.resource = !isServer || store.ssr ? new Resource(function () { | ||
return createRequest(store.request, _ast, options.variables); | ||
}) : new ProxyResource(); | ||
this.loading = true; // Handle fulfilled and rejected promise | ||
if (isServer && !client.ssr) { | ||
this.resource = new ProxyResource(); | ||
} else { | ||
this.resource = new Resource(function () { | ||
return createRequest(client.request, _ast, options.variables); | ||
}); // Handle fulfilled and rejected promise | ||
this.resource.promise.then(function (res) { | ||
_this.loading = false; // Store response on server side for hydration. | ||
this.resource.promise.then(function (res) { | ||
_this.loading = false; // Store response on server side for hydration. | ||
if (isServer) { | ||
cache[_this.options.name] = res; | ||
} | ||
if (isServer) { | ||
cache[_this.options.name] = res; | ||
} | ||
handleResponse(res); | ||
}, function () { | ||
_this.loading = false; | ||
_this.aborted = true; | ||
}); | ||
handleResponse(res); | ||
}, function () { | ||
_this.loading = false; | ||
_this.aborted = true; | ||
}); | ||
} | ||
this.loading = true; | ||
} | ||
@@ -1521,14 +1587,76 @@ }; | ||
var castValue = function castValue(value) { | ||
if (value instanceof ReferenceMap) { | ||
return value.toArray(); | ||
var ValueCaster = /*#__PURE__*/function () { | ||
function ValueCaster() { | ||
_classCallCheck(this, ValueCaster); | ||
} | ||
if (isDate(value)) { | ||
return value.toISOString(); | ||
} | ||
_createClass(ValueCaster, null, [{ | ||
key: "fromNative", | ||
value: function fromNative(value) { | ||
if (Array.isArray(value)) { | ||
if (value.some(function (v) { | ||
return _typeof(v) === 'object' && REF_KEY in v; | ||
})) { | ||
return ManyLink.fromNative(value); | ||
} | ||
return value; | ||
}; | ||
return value.map(function (v) { | ||
return ValueCaster.fromNative(v); | ||
}); | ||
} | ||
if (_typeof(value) === 'object') { | ||
if (REF_KEY in value) { | ||
return Link.fromNative(value); | ||
} | ||
var result = {}; | ||
Object.entries(value).forEach(function (_ref) { | ||
var _ref2 = _slicedToArray(_ref, 2), | ||
k = _ref2[0], | ||
v = _ref2[1]; | ||
result[k] = ValueCaster.fromNative(v); | ||
}); | ||
return result; | ||
} | ||
return value; | ||
} | ||
}, { | ||
key: "toNative", | ||
value: function toNative(value) { | ||
if (value instanceof Link || value instanceof ManyLink) { | ||
return value.toNative(); | ||
} | ||
if (isDate(value)) { | ||
return value.toISOString(); | ||
} | ||
if (Array.isArray(value)) { | ||
return value.map(function (v) { | ||
return ValueCaster.toNative(v); | ||
}); | ||
} | ||
if (_typeof(value) === 'object') { | ||
var result = {}; | ||
Object.entries(value).forEach(function (_ref3) { | ||
var _ref4 = _slicedToArray(_ref3, 2), | ||
k = _ref4[0], | ||
v = _ref4[1]; | ||
result[k] = ValueCaster.toNative(v); | ||
}); | ||
return result; | ||
} | ||
return value; | ||
} | ||
}]); | ||
return ValueCaster; | ||
}(); | ||
var Record = /*#__PURE__*/function () { | ||
@@ -1559,3 +1687,3 @@ function Record() { | ||
var value = Array.isArray(this.original[key]) ? new ReferenceMap(this.original[key]) : this.original[key]; | ||
var value = ValueCaster.fromNative(this.original[key]); | ||
nextValue = resolve(value); | ||
@@ -1566,3 +1694,3 @@ } else { | ||
this.values[key] = castValue(nextValue); | ||
this.values[key] = ValueCaster.toNative(nextValue); | ||
} | ||
@@ -1583,5 +1711,5 @@ }, { | ||
var get = function get(store, type, id) { | ||
var get = function get(client, type, id) { | ||
var value = null; | ||
store.queries.forEach(function (query) { | ||
client.queries.forEach(function (query) { | ||
var entity = query.data.get(type, id); | ||
@@ -1602,5 +1730,5 @@ | ||
var getRoots = function getRoots(store) { | ||
var getRoots = function getRoots(client) { | ||
var value = null; | ||
store.queries.forEach(function (query) { | ||
client.queries.forEach(function (query) { | ||
var roots = query.data.getRoots(); | ||
@@ -1612,3 +1740,3 @@ value = _objectSpread2(_objectSpread2({}, value), roots); | ||
function applyUpdater(store, updater, data) { | ||
function applyUpdater(client, updater, data, cache) { | ||
if (!updater) { | ||
@@ -1629,3 +1757,3 @@ return data; | ||
var record = new Record(function () { | ||
return _objectSpread2(_objectSpread2({}, get(store, type, id)), result.get(type, id)); | ||
return _objectSpread2(_objectSpread2({}, get(client, type, id)), result.get(type, id)); | ||
}); | ||
@@ -1639,3 +1767,3 @@ resolve(record); | ||
var record = new Record(function () { | ||
return getRoots(store); | ||
return getRoots(client); | ||
}); | ||
@@ -1648,7 +1776,23 @@ resolve(record); | ||
}; | ||
updater(writeStore); | ||
updater(writeStore, cache.selectorSet.getQuery()); | ||
return result; | ||
} | ||
var MutationRequest = function MutationRequest(store, mutation) { | ||
var MutationCache = function MutationCache(request, data) { | ||
_classCallCheck(this, MutationCache); | ||
_defineProperty(this, "request", void 0); | ||
_defineProperty(this, "data", void 0); | ||
_defineProperty(this, "selectorSet", void 0); | ||
this.request = request; | ||
this.data = data; | ||
this.selectorSet = buildSelectorSet(this); | ||
}; | ||
var MutationRequest = function MutationRequest(client, ast) { | ||
var _this = this; | ||
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; | ||
@@ -1658,3 +1802,3 @@ | ||
_defineProperty(this, "mutation", void 0); | ||
_defineProperty(this, "ast", void 0); | ||
@@ -1665,20 +1809,26 @@ _defineProperty(this, "options", void 0); | ||
this.mutation = mutation; | ||
_defineProperty(this, "cache", void 0); | ||
this.ast = ast; | ||
this.options = options; | ||
var optimisticData = applyUpdater(store, options.optimisticUpdater, new DataSet()); | ||
store.queries.forEach(function (query) { | ||
var optimisticData = applyUpdater(client, options.optimisticUpdater, new DataSet()); | ||
client.queries.forEach(function (query) { | ||
query.addUpdate(optimisticData, true); | ||
}); | ||
store.refresh(); | ||
client.refresh(); | ||
this.resource = new Resource(function () { | ||
return createRequest(store.request, mutation, options.variables); | ||
return createRequest(client.request, ast, options.variables); | ||
}); // Handle fulfilled and rejected promise | ||
this.resource.promise.then(function (res) { | ||
var data = applyUpdater(store, options.updater, new DataSet({ | ||
entities: res.entities | ||
})); // Set result in store | ||
var data = new DataSet(res.data); // Create cache | ||
_this.cache = new MutationCache(_this, data); | ||
var updatedData = applyUpdater(client, options.updater, new DataSet({ | ||
entities: res.data.entities | ||
}), // Do not add roots to store. | ||
_this.cache); // Set result in client | ||
if (optimisticData) { | ||
store.queries.forEach(function (query) { | ||
client.queries.forEach(function (query) { | ||
query.removeUpdate(optimisticData); | ||
@@ -1688,6 +1838,6 @@ }); | ||
store.queries.forEach(function (query) { | ||
query.addUpdate(data); | ||
client.queries.forEach(function (query) { | ||
query.addUpdate(updatedData); | ||
}); | ||
store.refresh(); | ||
client.refresh(); | ||
}, function (err) { | ||
@@ -1697,10 +1847,10 @@ if (err.message) { | ||
console.error("Mutation Error: ".concat(err.message)); | ||
} // Reset optimistic update in store | ||
} // Reset optimistic update in client | ||
if (optimisticData) { | ||
store.queries.forEach(function (query) { | ||
client.queries.forEach(function (query) { | ||
query.removeUpdate(optimisticData); | ||
}); | ||
store.refresh(); | ||
client.refresh(); | ||
} | ||
@@ -1727,2 +1877,4 @@ }); | ||
_defineProperty(this, "marker", {}); | ||
_defineProperty(this, "preload", function (query) { | ||
@@ -1746,3 +1898,3 @@ var _query$definitions$fi; | ||
_this.selectorSetsByRequest.delete(name); | ||
_this.selectorSetsByRequest.delete(request); | ||
@@ -1868,2 +2020,6 @@ request.invalidate(); | ||
_defineProperty(this, "getSnapshot", function () { | ||
return _this.marker; | ||
}); | ||
_defineProperty(this, "refresh", function () { | ||
@@ -1884,5 +2040,3 @@ _this.requests.forEach(function (request) { | ||
if (shouldUpdate) { | ||
_this.listeners.forEach(function (listener) { | ||
listener(); | ||
}); | ||
_this.update(); | ||
} else { | ||
@@ -1896,9 +2050,23 @@ _this.children.forEach(function (child) { | ||
_defineProperty(this, "reset", function () { | ||
var root = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; | ||
_this.requests = new Map(); | ||
_this.selectorSetsByRequest = new Map(); | ||
if (root) { | ||
_this.update(); | ||
} | ||
_this.children.forEach(function (child) { | ||
child.reset(); | ||
child.reset(false); | ||
}); | ||
}); | ||
_defineProperty(this, "update", function () { | ||
_this.marker = {}; | ||
_this.listeners.forEach(function (listener) { | ||
listener(); | ||
}); | ||
}); | ||
_defineProperty(this, "destroy", function () { | ||
@@ -1967,4 +2135,2 @@ // Remove network from parent store network children. | ||
_this.queries = new Map(); | ||
_this.rootStore.refresh(); | ||
}); | ||
@@ -2000,4 +2166,5 @@ | ||
var store = client.rootStore; | ||
useSyncExternalStore(store.subscribe, function () {}, function () {} // TODO: Check this! | ||
); | ||
useSyncExternalStore(store.subscribe, store.getSnapshot, function () { | ||
return null; | ||
}); | ||
return /*#__PURE__*/React.createElement(TransporterContext.Provider, { | ||
@@ -2014,22 +2181,44 @@ value: { | ||
var REJECTED = 'rejected'; | ||
function useMutation(mutation, options) { | ||
var getLatestInstance = function getLatestInstance(_ref) { | ||
var instances = _ref.current; | ||
if (instances.length === 0) { | ||
return null; | ||
} | ||
return instances[instances.length - 1]; | ||
}; | ||
function useDispatcher() { | ||
var context = useContext(TransporterContext); | ||
if (!context) { | ||
throw new Error('"useMutation" hook is used outside of TransporterContext.'); | ||
throw new Error('Dispatcher hook is used outside of TransporterContext.'); | ||
} | ||
var instance; | ||
var instances = useRef([]); | ||
return { | ||
dispatch: function dispatch(ast, options) { | ||
var _ast$definitions$find; | ||
var dispatch = function dispatch(dispatchOptions) { | ||
if (instance) { | ||
throw new Error('Mutation was dispatched before.'); | ||
} | ||
var operation = (_ast$definitions$find = ast.definitions.find(function (def) { | ||
return def.kind === 'OperationDefinition'; | ||
})) === null || _ast$definitions$find === void 0 ? void 0 : _ast$definitions$find.operation; | ||
instance = context.store.mutate(mutation, _objectSpread2(_objectSpread2({}, options), dispatchOptions)); | ||
return instance; | ||
}; | ||
if (operation !== 'query' && operation !== 'mutation') { | ||
throw new Error('No operation found. Must be either "query" or "mutation".'); | ||
} | ||
var state = { | ||
var instance = operation === 'query' ? context.client.query(ast, options) : context.client.mutate(ast, options); | ||
instances.current.push(instance); // Return cached selector set. | ||
return instance.resource.promise.then(function () { | ||
return instance.cache.selectorSet.getQuery(); | ||
}); | ||
}, | ||
get ok() { | ||
var instance = getLatestInstance(instances); | ||
if (!instance || instance.status === PENDING) { | ||
@@ -2043,2 +2232,4 @@ return null; | ||
get loading() { | ||
var instance = getLatestInstance(instances); | ||
if (!instance) { | ||
@@ -2052,2 +2243,4 @@ return false; | ||
get executed() { | ||
var instance = getLatestInstance(instances); | ||
if (!instance) { | ||
@@ -2058,15 +2251,43 @@ return false; | ||
return instance.status === FULFILLED || instance.status === REJECTED; | ||
} | ||
/* get errors() { | ||
// TODO | ||
}, | ||
get networkError() { | ||
// TODO | ||
}, */ | ||
get error() { | ||
var instance = getLatestInstance(instances); | ||
if (!instance || instance.status !== REJECTED) { | ||
return null; | ||
} | ||
return instance.response; | ||
} | ||
}; | ||
return [dispatch, state]; | ||
} | ||
function useMutation(mutation, options) { | ||
var _useDispatcher = useDispatcher(), | ||
_useDispatcher2 = _slicedToArray(_useDispatcher, 2), | ||
_dispatch = _useDispatcher2[0], | ||
state = _useDispatcher2[1]; | ||
return _objectSpread2(_objectSpread2({}, state), {}, { | ||
dispatch: function dispatch(dispatchOptions) { | ||
return _dispatch(mutation, _objectSpread2(_objectSpread2({}, options), dispatchOptions)); | ||
} | ||
}); | ||
} | ||
function useQuery(query, options) { | ||
var _useDispatcher = useDispatcher(), | ||
_useDispatcher2 = _slicedToArray(_useDispatcher, 2), | ||
_dispatch = _useDispatcher2[0], | ||
state = _useDispatcher2[1]; | ||
return _objectSpread2(_objectSpread2({}, state), {}, { | ||
dispatch: function dispatch(dispatchOptions) { | ||
return _dispatch(query, _objectSpread2(_objectSpread2({}, options), dispatchOptions)); | ||
} | ||
}); | ||
} | ||
function useReset() { | ||
@@ -2079,8 +2300,8 @@ var context = useContext(TransporterContext); | ||
var store = context.store; | ||
var client = context.client; | ||
return function () { | ||
store.reset(); | ||
client.reset(); | ||
}; | ||
} | ||
export { ReferenceMap, Resource, Transporter, TransporterError, TransporterProvider, createContainer, createNode, ref, useMutation, useReset }; | ||
export { Link, ManyLink, Resource, Transporter, TransporterError, TransporterProvider, createContainer, createNode, ref, useDispatcher, useMutation, useQuery, useReset }; |
@@ -1,1 +0,1 @@ | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("react"),require("react-native"),require("graphql/utilities/valueFromASTUntyped")):"function"==typeof define&&define.amd?define(["exports","react","react-native","graphql/utilities/valueFromASTUntyped"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self)["react-transporter"]={},t.React,t.reactNative,t.valueFromASTUntyped)}(this,(function(t,e,r,n){"use strict";function o(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var i=o(e);function u(t){return(u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function a(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}function c(t,e,r){return e&&s(t.prototype,e),r&&s(t,r),t}function f(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function l(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,n)}return r}function h(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?l(Object(r),!0).forEach((function(e){f(t,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):l(Object(r)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))}))}return t}function d(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&p(t,e)}function v(t){return(v=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function p(t,e){return(p=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function y(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function m(t,e,r){return(m=y()?Reflect.construct:function(t,e,r){var n=[null];n.push.apply(n,e);var o=new(Function.bind.apply(t,n));return r&&p(o,r.prototype),o}).apply(null,arguments)}function g(t){var e="function"==typeof Map?new Map:void 0;return(g=function(t){if(null===t||(r=t,-1===Function.toString.call(r).indexOf("[native code]")))return t;var r;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,n)}function n(){return m(t,arguments,v(this).constructor)}return n.prototype=Object.create(t.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),p(n,t)})(t)}function w(t,e){if(null==t)return{};var r,n,o=function(t,e){if(null==t)return{};var r,n,o={},i=Object.keys(t);for(n=0;n<i.length;n++)r=i[n],e.indexOf(r)>=0||(o[r]=t[r]);return o}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n<i.length;n++)r=i[n],e.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}function b(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function S(t,e){return!e||"object"!=typeof e&&"function"!=typeof e?b(t):e}function E(t){var e=y();return function(){var r,n=v(t);if(e){var o=v(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return S(this,r)}}function q(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(t)))return;var r=[],n=!0,o=!1,i=void 0;try{for(var u,a=t[Symbol.iterator]();!(n=(u=a.next()).done)&&(r.push(u.value),!e||r.length!==e);n=!0);}catch(t){o=!0,i=t}finally{try{n||null==a.return||a.return()}finally{if(o)throw i}}return r}(t,e)||j(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function O(t){return function(t){if(Array.isArray(t))return k(t)}(t)||function(t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t))return Array.from(t)}(t)||j(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function j(t,e){if(t){if("string"==typeof t)return k(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?k(t,e):void 0}}function k(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}var R=i.default.createContext(),A="undefined"==typeof window,_=!r.Platform||"web"===r.Platform.OS,P="pending",x="fulfilled",F="rejected",C="__typename",T="id",U="__ref",M=function t(e){var r=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};a(this,t),f(this,"promise",void 0),f(this,"status",P),f(this,"response",void 0),f(this,"read",(function(){switch(r.status){case P:throw r.promise;case F:throw r.response;default:return r.response}}));var o=n.proxy,i=void 0!==o&&o;i?this.promise=new Promise((function(t,e){e(new Error("Proxied resource."))})):(this.promise=e(),this.promise.then((function(t){r.status=x,r.response=t}),(function(t){r.status=F,r.response=t})))};function N(t){var r=t.component,n=t.options,o=t.values,i=n.data||function(){return null},u=e.useRef(!1),a=e.useContext(R),s=a.client,c=a.store;try{var f=q(M.all([function(){return i(c,o)},function(){return r()}]),2),l=f[0],h=f[1];return n.waitForAll&&c.waitForAll(),e.createElement(h,l)}catch(t){if(!A)throw t;if(t instanceof Promise){if(!s.ssr)return n.loading;throw u.current||(u.current=!0),t}if(s.ssr&&u.current)return n.loading;if(n.throwOnError)throw t;return n.error&&e.cloneElement(n.error,{error:t})}}M.all=function(t){var e=[],r=t.map((function(t){try{return t()}catch(t){if(t instanceof Promise)return e.push(t);throw t}}));if(e.length>0)throw Promise.all(e);return r};var Q=function t(e){var r=this;a(this,t),f(this,"status",x),f(this,"response",void 0),f(this,"read",(function(){return r.response})),this.response=e},B=function(t){return t.__esModule?t.default:t.default||t};function D(t){if(t.payload&&t.payload._result){var e=t.payload._result;return"function"==typeof e?new M((function(){return e()})):A||!_?new M((function(){return t.load().then((function(){return t}))})):function(t){var e=t.resolve();return"undefined"!=typeof __webpack_modules__&&!!__webpack_modules__[e]}(e)?new Q(B(e.requireSync())):new M((function(){return e.requireAsync().then((function(t){return B(t)}))}))}return t.bundle?new M((function(){return t.bundle().then((function(t){return B(t)}))})):new Q(t)}var I=void 0,J=function(t,e){return e.filter((function(e){return e.__ref?!t.some((function(t){var r=q(t,2),n=r[0],o=r[1];return n===e[0]&&o===e[1]})):I.items.includes(e)}))},H=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];a(this,t),f(this,"items",void 0),this.items=e}return c(t,[{key:"prepend",value:function(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return this.items=[].concat(e,O(this.items)),this}},{key:"append",value:function(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return this.items=[].concat(O(this.items),e),this}},{key:"syncPrepend",value:function(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];var n=J(this.items,e);return this.items=[].concat(e,O(n)),this}},{key:"syncAppend",value:function(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];var n=J(this.items,e);return this.items=[].concat(O(n),e),this}},{key:"detach",value:function(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];return this.items=J(this.items,e),this}},{key:"toArray",value:function(){return this.items}}]),t}();var G=function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){};return Object.keys(e).some((function(e){return void 0!==t[e]&&r(e)}))},L=function(t,e){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(t){return t};if(!r)return h(h({},t),e);var n=h({},t);return Object.values(e).forEach((function(e){var o=q(e,2),i=o[0],u=o[1];n[i]=void 0===t[i]?u:r(i)})),n},V=function t(e,r){if(!r)return e;if(Array.isArray(e))return e.map((function(e,n){return t(e,r[n])}));if("object"!==("undefined"==typeof value?"undefined":u(value))||e.__ref)return r;var n={};return Object.keys(e).forEach((function(o){n[o]=t(e[o],r[o])})),n},W=function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};a(this,t),f(this,"roots",void 0),f(this,"entities",void 0),f(this,"get",(function(t,r){var n,o,i=null===(n=e.entities[t])||void 0===n?void 0:n[r];return i?h((f(o={},C,t),f(o,T,r),o),i):null})),f(this,"getRoots",(function(){return e.roots})),f(this,"intersectWith",(function(t){var r=t.roots,n=t.entities;return G(e.roots,r),G(e.entities,n,(function(t){return G(e.entities[t],n[t],(function(r){return G(e.entities[t][r],n[t][r])}))}))})),f(this,"add",(function(t){var r=t.roots,n=t.entities;e.roots=L(e.roots,r),e.entities=L(e.entities,n,(function(t){return L(e.entities[t],n[t],(function(r){var o=e.entities[t][r],i=n[t][r],u=h({},o);return Object.keys(i).forEach((function(t){u[t]=V(o[t],i[t])})),u}))}))})),f(this,"merge",(function(r){var n=new t({roots:e.roots,entities:e.entities});return n.add(r),n})),f(this,"extract",(function(){return{roots:e.roots,entities:e.entities}}));var n=r.roots,o=void 0===n?{}:n,i=r.entities,u=void 0===i?{}:i;this.roots=o,this.entities=u},Y=function(t,e){var r=q(e,2),n=r[0],o=r[1];return"".concat(t,".").concat(n,".").concat(o)},$=function t(){var e=this;a(this,t),f(this,"query",null),f(this,"fragments",{}),f(this,"getQuery",(function(){return e.query})),f(this,"setQuery",(function(t){e.query=t})),f(this,"getFragment",(function(t,r){var n=Y(t,r);return e.fragments[n]})),f(this,"setFragment",(function(t,r,n){var o=Y(t,r);e.fragments[o]=n})),f(this,"update",(function(t){var r=!1;return e.query&&e.query!==t.query&&(e.query=t.query,r=!0),Object.keys(e.fragments).forEach((function(n){e.fragments[n]!==t.fragments[n]&&(e.fragments[n]=t.fragments[n],r=!0)})),r}))},z=function(t){return null===t?null:"object"===u(t)?K(t):JSON.stringify(t)},K=function(t){var e=Object.keys(t);e.sort();var r=e.map((function(e){var r=z(t[e]);return null===r?r:'"'.concat(e,'":').concat(r)})).filter((function(t){return null!==t}));return 0===r.length?null:"{".concat(r.join(","),"}")};function X(t,e){var r=K(e);return"".concat(t).concat(r?"(".concat(r,")"):"")}var Z=function(t){d(r,t);var e=E(r);function r(){var t;return a(this,r),(t=e.call(this,"Undefined value.")).name="ValueError",t}return r}(g(Error)),tt=function t(e,r,o){var i=o.cache,u=o.handleFragment,a=i.request,s=a.ast,c=a.options,f={};return e.selections.forEach((function(e){if("Field"===e.kind){var i=function(t,e){var r=t.name.value;if(0===t.arguments.length)return r;var o={};return t.arguments.forEach((function(t){o[t.name.value]=n.valueFromASTUntyped(t.value,e)})),X(r,o)}(e,c.variables);f[e.name.value]=et(e.selectionSet,r[i],o)}if("InlineFragment"===e.kind&&console.log("TODO: inline fragment",e),"FragmentSpread"===e.kind){var a=s.definitions.find((function(t){return"FragmentDefinition"===t.kind&&t.name.value===e.name.value}));try{var l=t(a.selectionSet,r,o);Object.assign(f,u(a.name.value,r[C],r.id,l))}catch(t){if("ValueError"!==t.name)throw t;if(a.typeCondition.name.value===r[C])throw new Error('Fragment "'.concat(a.name.value,'" has an undefined value and has been skipped.'))}}})),f},et=function(t,e,r){return void 0===t?e:Array.isArray(e)?e.map((function(e){return rt(t,e,r)})):rt(t,e,r)},rt=function(t,e,r){if(void 0===e)throw new Z;if(null===e)return null;var n=e.__ref;if(!n)return tt(t,e,r);var o=r.cache,i=r.handleEntity,u=q(n,2),a=u[0],s=u[1],c=o.data.get(a,s);return i(a,s,tt(t,c,r))};function nt(t,e,r){var n=t.request.ast.definitions.find((function(t){return"OperationDefinition"===t.kind})),o=t.data.getRoots(),i={cache:t,handleFragment:e,handleEntity:r};try{return tt(n.selectionSet,o,i)}catch(t){throw"ValueError"!==t.name?t:new Error('Query "'.concat(n.name.value,'" has an undefined value and has been skipped.'))}}var ot=function(t,e){return JSON.stringify(t)===JSON.stringify(e)};function it(t){var e,r=new $,n=nt(t,(function(e,n,o,i){var u,a,s=[n,o],c=null===(u=t.selectorSet)||void 0===u?void 0:u.getFragment(e,s);return r.setFragment(e,s,h((f(a={},C,n),f(a,T,o),a),ot(i,c)?c:i)),{}}),(function(t,e,r){var n;return h((f(n={},C,t),f(n,T,e),n),r)})),o=null===(e=t.selectorSet)||void 0===e?void 0:e.getQuery();return r.setQuery(ot(n,o)?o:n),r}var ut=function t(e,r){var n=this;a(this,t),f(this,"request",void 0),f(this,"original",void 0),f(this,"updates",[]),f(this,"dirty",!1),f(this,"data",void 0),f(this,"selectorSet",void 0),f(this,"addUpdate",(function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(n.data.intersectWith(t)){n.dirty=!0;var r={optimistic:e,data:t,cache:n.data.merge(t)};n.data=t,n.updates=[].concat(O(n.updates),[r])}})),f(this,"removeUpdate",(function(t){var e=!1,r=[];n.updates.forEach((function(o){if(o.data===t)n.dirty=!0,e=!0;else if(e){var i=r.length,u=i>0?r[i-1].cache:n.original;r.push(h(h({},o),{},{cache:u.merge(t)}))}else r.push(o)})),n.updates=r})),f(this,"commit",(function(){var t,e,r;n.dirty&&(n.selectorSet=it(n),n.updates.some((function(t){return t.optimistic}))||(n.original=(t=n,e=new W,r=nt(t,(function(t,e,r,n){return n}),(function(t,r,n){return e.add({entities:f({},C,f({},T,n))}),f({},U,[t,r])})),e.add({roots:r}),e),n.updates=[]),n.dirty=!1)})),this.request=e,this.original=r,this.data=r,this.selectorSet=it(this)},at=function(t){d(r,t);var e=E(r);function r(t,n){var o,i=n.type,u=w(n,["type"]);return a(this,r),f(b(o=e.call(this,t,u)),"type",void 0),o.name="TransporterError",o.type=i,o}return r}(g(Error));function st(t,e,r){return new Promise((function(n,o){var i;t(e.loc.source.body,r).then((function(t){return(i=t).json()})).then((function(t){if(!i.ok)throw new at("Request failed (HttpError - ".concat(i.status,")"),{type:"HttpError",cause:t});t.errors&&(t.errors.forEach((function(t){console.error("GraphQLError: ".concat(t.message))})),o(new at("Request failed (GraphQLError)",{type:"GraphQLError",cause:t.errors}))),n(t)})).catch((function(t){i&&i.ok?o(new at("".concat(t.message," (JsonError)"),{type:"JsonError",cause:t})):o(new at("Request failed (HttpError - ".concat(i?i.status:"Unknown",")"),{type:"HttpError",cause:t}))}))}))}var ct=function t(){var e=this;a(this,t),f(this,"promise",void 0),f(this,"read",(function(){throw e.promise})),this.promise=new Promise((function(){}))},ft=function t(e,r){var n=this,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};a(this,t),f(this,"store",void 0),f(this,"ast",void 0),f(this,"options",void 0),f(this,"resource",void 0),f(this,"selectors",[]),f(this,"loading",!1),f(this,"aborted",!1),f(this,"cache",void 0),f(this,"read",(function(){n.resource.read()})),f(this,"isEqual",(function(t,e){return n.ast===t&&JSON.stringify(n.options.variables)===JSON.stringify(e)})),f(this,"sync",(function(){n.loading||n.aborted||n.cache.commit()})),f(this,"invalidate",(function(){n.aborted=!0,n.store.queries.delete(n.options.name)})),this.store=e,this.ast=r,this.options=o;var i=function(t){if(!n.aborted){var r=new W(t.data),o=new W({entities:r.entities});e.queries.forEach((function(t){t.addUpdate(o)})),n.cache=new ut(n,r),e.queries.set(n.options.name,n.cache),e.refresh()}},u=e.cache,s=u[this.options.name];s?(this.resource=new Q(s),i({data:s}),delete u[this.options.name]):(this.resource=!A||e.ssr?new M((function(){return st(e.request,r,o.variables)})):new ct,this.loading=!0,this.resource.promise.then((function(t){n.loading=!1,A&&(u[n.options.name]=t),i(t)}),(function(){n.loading=!1,n.aborted=!0})))},lt=function(t){return t instanceof H?t.toArray():(e=t,"[object Date]"===Object.prototype.toString.call(e)?t.toISOString():t);var e},ht=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};a(this,t),f(this,"original",void 0),f(this,"values",{}),this.original=e}return c(t,[{key:"set",value:function(t,e){var r,n=Array.isArray(t)?X.apply(void 0,O(t)):t;"function"==typeof e?("function"==typeof this.original&&(this.original=this.original()||{}),r=e(Array.isArray(this.original[n])?new H(this.original[n]):this.original[n])):r=e;this.values[n]=lt(r)}},{key:"fill",value:function(t){var e=this;Object.keys(t).forEach((function(r){e.set(r,t[r])}))}}]),t}();function dt(t,e,r){if(!e)return r;var n=r;return e({insert:function(t,e,r){var o=new ht;r(o),n.add({entities:f({},t,f({},e,o.values))})},update:function(e,r,o){var i=new ht((function(){return h(h({},function(t,e,r){var n=null;return t.queries.forEach((function(t){var o=t.data.get(e,r);if(o){if(t.updates.some((function(t){return t.optimistic&&t.data.get(e,r)})))throw new Error("Cannot perform update on optimistically updated entity. [".concat(e,".").concat(r,"]"));n=h(h({},n),o)}})),n}(t,e,r)),n.get(e,r))}));o(i),n.add({entities:f({},e,f({},r,i.values))})},updateRoots:function(e){var r=new ht((function(){return function(t){var e=null;return t.queries.forEach((function(t){var r=t.data.getRoots();e=h(h({},e),r)})),e}(t)}));e(r),n.add({roots:r.values})}}),n}var vt=function t(e,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};a(this,t),f(this,"mutation",void 0),f(this,"options",void 0),f(this,"resource",void 0),this.mutation=r,this.options=n;var o=dt(e,n.optimisticUpdater,new W);e.queries.forEach((function(t){t.addUpdate(o,!0)})),e.refresh(),this.resource=new M((function(){return st(e.request,r,n.variables)})),this.resource.promise.then((function(t){var r=dt(e,n.updater,new W({entities:t.entities}));o&&e.queries.forEach((function(t){t.removeUpdate(o)})),e.queries.forEach((function(t){t.addUpdate(r)})),e.refresh()}),(function(t){t.message&&console.error("Mutation Error: ".concat(t.message)),o&&(e.queries.forEach((function(t){t.removeUpdate(o)})),e.refresh())}))},pt=function t(e,r){var n=this;a(this,t),f(this,"parentStore",void 0),f(this,"executeQuery",void 0),f(this,"children",[]),f(this,"requests",void 0),f(this,"selectorSetsByRequest",void 0),f(this,"listeners",[]),f(this,"preload",(function(t){var e,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=r.name||(null===(e=t.definitions.find((function(t){return"OperationDefinition"===t.kind})))||void 0===e?void 0:e.name.value);if(!o)throw new Error("No query name found.");var i=n.requests.get(o);return i&&!i.isEqual(t,r.variables)&&(n.requests.delete(o),n.selectorSetsByRequest.delete(o),i.invalidate(),i=null),i||(i=n.executeQuery(t,h(h({},r),{},{name:o})),n.requests.set(o,i)),o})),f(this,"load",(function(t,e){var r=n.preload(t,e);return n.select(r)})),f(this,"getRequest",(function(t){var e=n.requests.get(t);if(!e){if(!n.parentStore)throw new Error('Query "'.concat(t,'" was not found.'));e=n.parentStore.getRequest(t)}return e})),f(this,"select",(function(t){var e=n.getRequest(t);e.read();var r=e.cache.selectorSet.getQuery();return n.selectorSetsByRequest.has(e)||n.selectorSetsByRequest.set(e,new $),n.selectorSetsByRequest.get(e).setQuery(r),r})),f(this,"waitForAll",(function(){n.requests.forEach((function(t){t.read()})),n.parentStore&&n.parentStore.waitForAll()})),f(this,"getFragmentRequest",(function(t,e){var r=Array.from(n.requests.values()).find((function(r){var n=r.cache;return null==n?void 0:n.selectorSet.getFragment(t,e)}));if(!r){if(!n.parentStore){var o=JSON.stringify(e);throw new Error('Fragment "'.concat(t,'" (entry: [').concat(o,"]) was not found."))}r=n.parentStore.getFragmentRequest(t,e)}return r})),f(this,"selectFragment",(function(t,e){var r=n.getFragmentRequest(t,e);r.read();var o=r.cache.selectorSet.getFragment(t,e);return n.selectorSetsByRequest.has(r)||n.selectorSetsByRequest.set(r,new $),n.selectorSetsByRequest.get(r).setFragment(t,e,o),o})),f(this,"addChild",(function(t){n.children=[].concat(O(n.children),[t])})),f(this,"removeChild",(function(t){n.children=n.children.filter((function(e){return e!==t}))})),f(this,"subscribe",(function(t){return n.listeners=[].concat(O(n.listeners),[t]),function(){n.listeners=n.listeners.filter((function(e){return e!==t}))}})),f(this,"refresh",(function(){n.requests.forEach((function(t){t.sync()}));var t=!1;n.selectorSetsByRequest.forEach((function(e,r){e.update(r.cache.selectorSet)&&(t=!0)})),t?n.listeners.forEach((function(t){t()})):n.children.forEach((function(t){t.refresh()}))})),f(this,"reset",(function(){n.requests=new Map,n.children.forEach((function(t){t.reset()}))})),f(this,"destroy",(function(){n.parentStore.removeChild(n),n.requests.forEach((function(t){t.invalidate()}))})),this.parentStore=e,this.executeQuery=r,this.requests=new Map,this.selectorSetsByRequest=new Map,e&&e.addChild(this)};var yt="pending",mt="fulfilled";t.ReferenceMap=H,t.Resource=M,t.Transporter=function t(e){var r=this,n=e.request,o=e.cache,i=void 0===o?{}:o,u=e.ssr,s=void 0!==u&&u;a(this,t),f(this,"request",void 0),f(this,"rootStore",void 0),f(this,"cache",void 0),f(this,"ssr",void 0),f(this,"queries",void 0),f(this,"query",(function(t,e){return new ft(r,t,e)})),f(this,"createStore",(function(t){return new pt(t,r.query)})),f(this,"mutate",(function(t,e){return new vt(r,t,e)})),f(this,"refresh",(function(){r.rootStore.refresh()})),f(this,"reset",(function(){r.rootStore.reset(),r.queries=new Map,r.rootStore.refresh()})),f(this,"extract",(function(){var t={};return r.queries.forEach((function(e,r){t[r]=e.data.extract()})),t})),this.request=n,this.rootStore=this.createStore(null),this.cache=i,this.ssr=s,this.queries=new Map},t.TransporterError=at,t.TransporterProvider=function(t){var r=t.children,n=t.client;if(!n)throw new Error("TransporterProvider: You must provide a Transporter instance.");var o=n.rootStore;return e.useSyncExternalStore(o.subscribe,(function(){}),(function(){})),i.default.createElement(R.Provider,{value:{client:n,store:o}},r)},t.createContainer=function(t){var r,n=t.component,o=w(t,["component"]);if(!n)throw new Error('You must define a container "component".');var u=function(){r||(r=D(n,o.renderer));var t=r.read();return o.renderer?o.renderer(t):t},s=function(t){d(n,t);var r=E(n);function n(t){var e;return a(this,n),f(b(e=r.call(this,t)),"store",void 0),e.state={error:null},e}return c(n,[{key:"componentDidCatch",value:function(t,e){console.error(t,e)}},{key:"componentWillUnmount",value:function(){this.store.destroy()}},{key:"renderContainer",value:function(){var t=this.context.client,r=this.state.error;if(r)return o.error&&e.cloneElement(o.error,{error:r});var n=i.default.createElement(N,{component:u,options:o,values:this.props});return A&&!t.ssr?n:i.default.createElement(i.default.Suspense,{fallback:o.loading},n)}},{key:"render",value:function(){var t=this.context,e=t.client,r=t.store;return this.store||(this.store=e.createStore(r)),i.default.createElement(R.Provider,{value:{client:e,store:this.store}},this.renderContainer())}}]),n}(i.default.Component);o.throwOnError||(s.getDerivedStateFromError=function(t){return{error:t}}),s.contextType=R;var l=n.displayName||n.name;return s.displayName=l?"Container(".concat(l,")"):"Container",s},t.createNode=function(t){var r=t.component,n=w(t,["component"]);if(!t.component)throw new Error('You must define a container "component".');function o(t){var o=e.useContext(R).store,i=n.data||function(){return null};return e.createElement(r,i(o,t))}var i=r.displayName||r.name;return o.displayName=i?"ContainerNode(".concat(i,")"):"ContainerNode",o},t.ref=function(t,e){return f({},U,[t,e])},t.useMutation=function(t,r){var n,o=e.useContext(R);if(!o)throw new Error('"useMutation" hook is used outside of TransporterContext.');return[function(e){if(n)throw new Error("Mutation was dispatched before.");return n=o.store.mutate(t,h(h({},r),e))},{get ok(){return n&&n.status!==yt?n.status===mt:null},get loading(){return!!n&&n.status===yt},get executed(){return!!n&&(n.status===mt||"rejected"===n.status)}}]},t.useReset=function(){var t=e.useContext(R);if(!t)throw new Error('"useReset" hook is used outside of TransporterContext.');var r=t.store;return function(){r.reset()}},Object.defineProperty(t,"__esModule",{value:!0})})); | ||
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports,require("react"),require("react-native"),require("graphql/utilities/valueFromASTUntyped")):"function"==typeof define&&define.amd?define(["exports","react","react-native","graphql/utilities/valueFromASTUntyped"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self)["react-transporter"]={},t.React,t.reactNative,t.valueFromASTUntyped)}(this,(function(t,e,r,n){"use strict";function o(t){return t&&"object"==typeof t&&"default"in t?t:{default:t}}var i=o(e);function u(t){return(u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function a(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function s(t,e){for(var r=0;r<e.length;r++){var n=e[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}function c(t,e,r){return e&&s(t.prototype,e),r&&s(t,r),t}function f(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function l(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter((function(e){return Object.getOwnPropertyDescriptor(t,e).enumerable}))),r.push.apply(r,n)}return r}function h(t){for(var e=1;e<arguments.length;e++){var r=null!=arguments[e]?arguments[e]:{};e%2?l(Object(r),!0).forEach((function(e){f(t,e,r[e])})):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):l(Object(r)).forEach((function(e){Object.defineProperty(t,e,Object.getOwnPropertyDescriptor(r,e))}))}return t}function d(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&p(t,e)}function v(t){return(v=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function p(t,e){return(p=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function y(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}function m(t,e,r){return(m=y()?Reflect.construct:function(t,e,r){var n=[null];n.push.apply(n,e);var o=new(Function.bind.apply(t,n));return r&&p(o,r.prototype),o}).apply(null,arguments)}function g(t){var e="function"==typeof Map?new Map:void 0;return(g=function(t){if(null===t||(r=t,-1===Function.toString.call(r).indexOf("[native code]")))return t;var r;if("function"!=typeof t)throw new TypeError("Super expression must either be null or a function");if(void 0!==e){if(e.has(t))return e.get(t);e.set(t,n)}function n(){return m(t,arguments,v(this).constructor)}return n.prototype=Object.create(t.prototype,{constructor:{value:n,enumerable:!1,writable:!0,configurable:!0}}),p(n,t)})(t)}function w(t,e){if(null==t)return{};var r,n,o=function(t,e){if(null==t)return{};var r,n,o={},i=Object.keys(t);for(n=0;n<i.length;n++)r=i[n],e.indexOf(r)>=0||(o[r]=t[r]);return o}(t,e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(t);for(n=0;n<i.length;n++)r=i[n],e.indexOf(r)>=0||Object.prototype.propertyIsEnumerable.call(t,r)&&(o[r]=t[r])}return o}function b(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function S(t,e){return!e||"object"!=typeof e&&"function"!=typeof e?b(t):e}function E(t){var e=y();return function(){var r,n=v(t);if(e){var o=v(this).constructor;r=Reflect.construct(n,arguments,o)}else r=n.apply(this,arguments);return S(this,r)}}function q(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){if("undefined"==typeof Symbol||!(Symbol.iterator in Object(t)))return;var r=[],n=!0,o=!1,i=void 0;try{for(var u,a=t[Symbol.iterator]();!(n=(u=a.next()).done)&&(r.push(u.value),!e||r.length!==e);n=!0);}catch(t){o=!0,i=t}finally{try{n||null==a.return||a.return()}finally{if(o)throw i}}return r}(t,e)||j(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function O(t){return function(t){if(Array.isArray(t))return k(t)}(t)||function(t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t))return Array.from(t)}(t)||j(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function j(t,e){if(t){if("string"==typeof t)return k(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);return"Object"===r&&t.constructor&&(r=t.constructor.name),"Map"===r||"Set"===r?Array.from(t):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?k(t,e):void 0}}function k(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r<e;r++)n[r]=t[r];return n}var R=i.default.createContext(),_="undefined"==typeof window,N=!r.Platform||"web"===r.Platform.OS,x="pending",P="fulfilled",A="rejected",F="__typename",C="id",T="__ref",Q=function t(e){var r=this,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};a(this,t),f(this,"promise",void 0),f(this,"status",x),f(this,"response",void 0),f(this,"read",(function(){switch(r.status){case x:throw r.promise;case A:throw r.response;default:return r.response}}));var o=n.proxy,i=void 0!==o&&o;i?this.promise=new Promise((function(t,e){e(new Error("Proxied resource."))})):(this.promise=e(),this.promise.then((function(t){r.status=P,r.response=t}),(function(t){r.status=A,r.response=t})))};Q.all=function(t){var e=[],r=t.map((function(t){try{return t()}catch(t){if(t instanceof Promise)return e.push(t);throw t}}));if(e.length>0)throw Promise.all(e);return r};var U=function(t){d(r,t);var e=E(r);function r(){var t;return a(this,r),(t=e.call(this,"Loading proxy resource.")).name="LoadingError",t}return r}(g(Error));function M(t){var r=t.component,n=t.options,o=t.values,i=n.data||function(){return null},u=e.useRef(!1),a=e.useContext(R),s=a.client,c=a.store;e.useSyncExternalStore(c.subscribe,c.getSnapshot,(function(){return null}));try{var f=q(Q.all([function(){return i(c,o)},function(){return r()}]),2),l=f[0],h=f[1];return n.waitForAll&&c.waitForAll(),e.createElement(h,l)}catch(t){if(!_)throw t;if(t instanceof Promise){if(!s.ssr)return n.loading;throw u.current||(u.current=!0),t}if(t instanceof U)return n.loading;if(s.ssr&&u.current)return n.loading;if(n.throwOnError)throw t;return n.error&&e.cloneElement(n.error,{error:t})}}var D=function t(e){var r=this;a(this,t),f(this,"status",P),f(this,"response",void 0),f(this,"read",(function(){return r.response})),this.response=e},B=function(t){return t.__esModule?t.default:t.default||t};function I(t){if(t.payload&&t.payload._result){var e=t.payload._result;return"function"==typeof e?new Q((function(){return e()})):_||!N?new Q((function(){return t.load().then((function(){return t}))})):function(t){var e=t.resolve();return"undefined"!=typeof __webpack_modules__&&!!__webpack_modules__[e]}(e)?new D(B(e.requireSync())):new Q((function(){return e.requireAsync().then((function(t){return B(t)}))}))}return t.bundle?new Q((function(){return t.bundle().then((function(t){return B(t)}))})):new D(t)}var J=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:null;a(this,t),f(this,"ref",void 0),this.ref=null===e?null:f({},T,[e[F],e.id])}return c(t,[{key:"toNative",value:function(){return this.ref}}],[{key:"fromNative",value:function(e){var r=new t;return r.ref=e,r}}]),t}(),L=function(t){return(Array.isArray(t)?t:[t]).map((function(t){return f({},T,[t[F],t.id])}))},H=function(t,e){return e.filter((function(e){var r=q(e.__ref,2),n=r[0],o=r[1];return!t.some((function(t){var e=q(t.__ref,2),r=e[0],i=e[1];return r===n&&i===o}))}))},G=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];a(this,t),f(this,"refs",void 0),this.refs=L(e)}return c(t,[{key:"prepend",value:function(t){return this.refs=[].concat(O(L(t)),O(this.refs)),this}},{key:"append",value:function(t){return this.refs=[].concat(O(this.refs),O(L(t))),this}},{key:"syncPrepend",value:function(t){var e=L(t),r=H(this.refs,e);return this.refs=[].concat(O(e),O(r)),this}},{key:"syncAppend",value:function(t){var e=L(t),r=H(this.refs,e);return this.refs=[].concat(O(r),O(e)),this}},{key:"detach",value:function(t){var e=L(t);return this.refs=H(e,this.refs),this}},{key:"toNative",value:function(){return this.refs}}],[{key:"fromNative",value:function(e){var r=new t;return r.refs=e,r}}]),t}();var V=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(){return!0};return Object.keys(e).some((function(e){return void 0!==t[e]&&r(e)}))},W=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},e=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:function(t){return t};if(!r)return h(h({},t),e);var n=h({},t);return Object.entries(e).forEach((function(e){var o=q(e,2),i=o[0],u=o[1];n[i]=void 0===t[i]?u:r(i)})),n},Y=function(t,e,r){return void 0===r?e:(void 0!==e&&u(e)!==u(r)&&console.warn("Key ".concat(t,' had value "').concat(e,'" and was updated with value of different type "').concat(r,'".')),r)},K=function t(){var e=this,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};a(this,t),f(this,"roots",void 0),f(this,"entities",void 0),f(this,"get",(function(t,r){var n,o,i=null===(n=e.entities[t])||void 0===n?void 0:n[r];return i?h((f(o={},F,t),f(o,C,r),o),i):null})),f(this,"getRoots",(function(){return e.roots})),f(this,"intersectWith",(function(t){var r=t.roots,n=t.entities;return V(e.roots,r)||V(e.entities,n,(function(t){return V(e.entities[t],n[t],(function(r){return V(e.entities[t][r],n[t][r])}))}))})),f(this,"add",(function(t){var r=t.roots,n=t.entities;e.roots=W(e.roots,r),e.entities=W(e.entities,n,(function(t){return W(e.entities[t],n[t],(function(r){var o=e.entities[t][r],i=n[t][r],u=h({},o);return Object.keys(i).forEach((function(t){u[t]=Y(t,o[t],i[t])})),u}))}))})),f(this,"merge",(function(r){var n=new t({roots:e.roots,entities:e.entities});return n.add(r),n})),f(this,"extract",(function(){return{roots:e.roots,entities:e.entities}}));var n=r.roots,o=void 0===n?{}:n,i=r.entities,u=void 0===i?{}:i;this.roots=o,this.entities=u},$=function(t,e){var r=q(e,2),n=r[0],o=r[1];return"".concat(t,".").concat(n,".").concat(o)},z=function t(){var e=this;a(this,t),f(this,"query",null),f(this,"fragments",{}),f(this,"getQuery",(function(){return e.query})),f(this,"setQuery",(function(t){e.query=t})),f(this,"getFragment",(function(t,r){var n=$(t,r);return e.fragments[n]})),f(this,"setFragment",(function(t,r,n){var o=$(t,r);e.fragments[o]=n})),f(this,"update",(function(t){var r=!1;return e.query&&e.query!==t.query&&(e.query=t.query,r=!0),Object.keys(e.fragments).forEach((function(n){e.fragments[n]!==t.fragments[n]&&(e.fragments[n]=t.fragments[n],r=!0)})),r}))},X=function(t){return null===t?null:"object"===u(t)?Z(t):JSON.stringify(t)},Z=function(t){var e=Object.keys(t);e.sort();var r=e.map((function(e){var r=X(t[e]);return null===r?r:'"'.concat(e,'":').concat(r)})).filter((function(t){return null!==t}));return 0===r.length?null:"{".concat(r.join(","),"}")};function tt(t,e){var r=Z(e);return"".concat(t).concat(r?"(".concat(r,")"):"")}var et=function(t){d(r,t);var e=E(r);function r(){var t;return a(this,r),(t=e.call(this,"Undefined value.")).name="ValueError",t}return r}(g(Error)),rt=function(t,e,r){var o=t.name.value;if(0===t.arguments.length||r)return o;var i={};return t.arguments.forEach((function(t){i[t.name.value]=n.valueFromASTUntyped(t.value,e)})),tt(o,i)},nt=function t(e,r,n){var o=arguments.length>3&&void 0!==arguments[3]&&arguments[3],i=n.cache,u=n.handleFragment,a=i.request,s=a.ast,c=a.options,f={};return e.selections.forEach((function(e){if("Field"===e.kind){var i=rt(e,c.variables,o);f[e.name.value]=ot(e.selectionSet,r[i],n)}if("InlineFragment"===e.kind&&console.log("TODO: inline fragment",e),"FragmentSpread"===e.kind){var a=s.definitions.find((function(t){return"FragmentDefinition"===t.kind&&t.name.value===e.name.value}));try{var l=t(a.selectionSet,r,n);Object.assign(f,u(a.name.value,r[F],r.id,l))}catch(t){if("ValueError"!==t.name)throw t;if(a.typeCondition.name.value===r[F])throw new Error('Fragment "'.concat(a.name.value,'" has an undefined value and has been skipped.'))}}})),f},ot=function(t,e,r){return void 0===t?e:Array.isArray(e)?e.map((function(e){return it(t,e,r)})):it(t,e,r)},it=function(t,e,r){if(void 0===e)throw new et;if(null===e)return null;var n=e.__ref;if(!n)return nt(t,e,r);var o=r.cache,i=r.handleEntity,u=q(n,2),a=u[0],s=u[1],c=o.data.get(a,s);return i(a,s,nt(t,c,r))};function ut(t,e,r){var n=t.request.ast.definitions.find((function(t){return"OperationDefinition"===t.kind})),o=t.data.getRoots(),i={cache:t,handleFragment:e,handleEntity:r};try{return nt(n.selectionSet,o,i,"mutation"===n.operation)}catch(t){throw"ValueError"!==t.name?t:new Error('Query "'.concat(n.name.value,'" has an undefined value and has been skipped.'))}}var at=function(t,e){return JSON.stringify(t)===JSON.stringify(e)};function st(t){var e,r=new z,n=ut(t,(function(e,n,o,i){var u,a,s=[n,o],c=null===(u=t.selectorSet)||void 0===u?void 0:u.getFragment(e,s);return r.setFragment(e,s,h((f(a={},F,n),f(a,C,o),a),at(i,c)?c:i)),{}}),(function(t,e,r){var n;return h((f(n={},F,t),f(n,C,e),n),r)})),o=null===(e=t.selectorSet)||void 0===e?void 0:e.getQuery();return r.setQuery(at(n,o)?o:n),r}var ct=function t(e,r){var n=this;a(this,t),f(this,"request",void 0),f(this,"original",void 0),f(this,"updates",[]),f(this,"dirty",!1),f(this,"data",void 0),f(this,"selectorSet",void 0),f(this,"addUpdate",(function(t){var e=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(n.data.intersectWith(t)){n.dirty=!0;var r=n.data.merge(t),o={optimistic:e,data:t,cache:r};n.data=r,n.updates=[].concat(O(n.updates),[o])}})),f(this,"removeUpdate",(function(t){var e=!1,r=[];n.updates.forEach((function(o){if(o.data===t)n.dirty=!0,e=!0;else if(e){var i=r.length,u=i>0?r[i-1].cache:n.original;r.push(h(h({},o),{},{cache:u.merge(t)}))}else r.push(o)})),n.updates=r})),f(this,"commit",(function(){var t,e,r;n.dirty&&(n.selectorSet=st(n),n.updates.some((function(t){return t.optimistic}))||(n.original=(t=n,e=new K,r=ut(t,(function(t,e,r,n){return n}),(function(t,r,n){return e.add({entities:f({},t,f({},r,n))}),f({},T,[t,r])})),e.add({roots:r}),e),n.updates=[]),n.dirty=!1)})),this.request=e,this.original=r,this.data=r,this.selectorSet=st(this)},ft=function(t){d(r,t);var e=E(r);function r(t,n){var o,i=n.type,u=w(n,["type"]);return a(this,r),f(b(o=e.call(this,t,u)),"type",void 0),o.name="TransporterError",o.type=i,o}return r}(g(Error));function lt(t,e,r){return new Promise((function(n,o){var i;t(e.loc.source.body,r).then((function(t){return(i=t).json()})).then((function(t){if(!i.ok)throw new ft("Request failed (HttpError - ".concat(i.status,")"),{type:"HttpError",cause:t});t.errors&&(t.errors.forEach((function(t){console.error("GraphQLError: ".concat(t.message))})),o(new ft("Request failed (GraphQLError)",{type:"GraphQLError",cause:t.errors}))),n(t)})).catch((function(t){i&&i.ok?o(new ft("".concat(t.message," (JsonError)"),{type:"JsonError",cause:t})):o(new ft("Request failed (HttpError - ".concat(i?i.status:"Unknown",")"),{type:"HttpError",cause:t}))}))}))}var ht=function t(){a(this,t),f(this,"promise",void 0),f(this,"read",(function(){throw new U})),this.promise=new Promise((function(){}))},dt=function t(e,r){var n=this,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};a(this,t),f(this,"client",void 0),f(this,"ast",void 0),f(this,"options",void 0),f(this,"resource",void 0),f(this,"selectors",[]),f(this,"loading",!1),f(this,"aborted",!1),f(this,"cache",void 0),f(this,"read",(function(){n.resource.read()})),f(this,"isEqual",(function(t,e){return n.ast===t&&JSON.stringify(n.options.variables)===JSON.stringify(e)})),f(this,"sync",(function(){n.loading||n.aborted||n.cache.commit()})),f(this,"invalidate",(function(){n.aborted=!0,n.client.queries.delete(n.options.name)})),this.client=e,this.ast=r,this.options=o;var i=function(t){if(!n.aborted){var r=new K(t.data),o=new K({entities:r.entities});e.queries.forEach((function(t){t.addUpdate(o)})),n.cache=new ct(n,r),e.queries.set(n.options.name,n.cache),e.refresh()}},u=e.cache,s=u[this.options.name];s?(this.resource=new D(s),i({data:s}),delete u[this.options.name]):(_&&!e.ssr?this.resource=new ht:(this.resource=new Q((function(){return lt(e.request,r,o.variables)})),this.resource.promise.then((function(t){n.loading=!1,_&&(u[n.options.name]=t),i(t)}),(function(){n.loading=!1,n.aborted=!0}))),this.loading=!0)},vt=function(){function t(){a(this,t)}return c(t,null,[{key:"fromNative",value:function(e){if(Array.isArray(e))return e.some((function(t){return"object"===u(t)&&T in t}))?G.fromNative(e):e.map((function(e){return t.fromNative(e)}));if("object"===u(e)){if(T in e)return J.fromNative(e);var r={};return Object.entries(e).forEach((function(e){var n=q(e,2),o=n[0],i=n[1];r[o]=t.fromNative(i)})),r}return e}},{key:"toNative",value:function(e){if(e instanceof J||e instanceof G)return e.toNative();if(r=e,"[object Date]"===Object.prototype.toString.call(r))return e.toISOString();var r;if(Array.isArray(e))return e.map((function(e){return t.toNative(e)}));if("object"===u(e)){var n={};return Object.entries(e).forEach((function(e){var r=q(e,2),o=r[0],i=r[1];n[o]=t.toNative(i)})),n}return e}}]),t}(),pt=function(){function t(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};a(this,t),f(this,"original",void 0),f(this,"values",{}),this.original=e}return c(t,[{key:"set",value:function(t,e){var r,n=Array.isArray(t)?tt.apply(void 0,O(t)):t;"function"==typeof e?("function"==typeof this.original&&(this.original=this.original()||{}),r=e(vt.fromNative(this.original[n]))):r=e;this.values[n]=vt.toNative(r)}},{key:"fill",value:function(t){var e=this;Object.keys(t).forEach((function(r){e.set(r,t[r])}))}}]),t}();function yt(t,e,r,n){if(!e)return r;var o=r;return e({insert:function(t,e,r){var n=new pt;r(n),o.add({entities:f({},t,f({},e,n.values))})},update:function(e,r,n){var i=new pt((function(){return h(h({},function(t,e,r){var n=null;return t.queries.forEach((function(t){var o=t.data.get(e,r);if(o){if(t.updates.some((function(t){return t.optimistic&&t.data.get(e,r)})))throw new Error("Cannot perform update on optimistically updated entity. [".concat(e,".").concat(r,"]"));n=h(h({},n),o)}})),n}(t,e,r)),o.get(e,r))}));n(i),o.add({entities:f({},e,f({},r,i.values))})},updateRoots:function(e){var r=new pt((function(){return function(t){var e=null;return t.queries.forEach((function(t){var r=t.data.getRoots();e=h(h({},e),r)})),e}(t)}));e(r),o.add({roots:r.values})}},n.selectorSet.getQuery()),o}var mt=function t(e,r){a(this,t),f(this,"request",void 0),f(this,"data",void 0),f(this,"selectorSet",void 0),this.request=e,this.data=r,this.selectorSet=st(this)},gt=function t(e,r){var n=this,o=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};a(this,t),f(this,"ast",void 0),f(this,"options",void 0),f(this,"resource",void 0),f(this,"cache",void 0),this.ast=r,this.options=o;var i=yt(e,o.optimisticUpdater,new K);e.queries.forEach((function(t){t.addUpdate(i,!0)})),e.refresh(),this.resource=new Q((function(){return lt(e.request,r,o.variables)})),this.resource.promise.then((function(t){var r=new K(t.data);n.cache=new mt(n,r);var u=yt(e,o.updater,new K({entities:t.data.entities}),n.cache);i&&e.queries.forEach((function(t){t.removeUpdate(i)})),e.queries.forEach((function(t){t.addUpdate(u)})),e.refresh()}),(function(t){t.message&&console.error("Mutation Error: ".concat(t.message)),i&&(e.queries.forEach((function(t){t.removeUpdate(i)})),e.refresh())}))},wt=function t(e,r){var n=this;a(this,t),f(this,"parentStore",void 0),f(this,"executeQuery",void 0),f(this,"children",[]),f(this,"requests",void 0),f(this,"selectorSetsByRequest",void 0),f(this,"listeners",[]),f(this,"marker",{}),f(this,"preload",(function(t){var e,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=r.name||(null===(e=t.definitions.find((function(t){return"OperationDefinition"===t.kind})))||void 0===e?void 0:e.name.value);if(!o)throw new Error("No query name found.");var i=n.requests.get(o);return i&&!i.isEqual(t,r.variables)&&(n.requests.delete(o),n.selectorSetsByRequest.delete(i),i.invalidate(),i=null),i||(i=n.executeQuery(t,h(h({},r),{},{name:o})),n.requests.set(o,i)),o})),f(this,"load",(function(t,e){var r=n.preload(t,e);return n.select(r)})),f(this,"getRequest",(function(t){var e=n.requests.get(t);if(!e){if(!n.parentStore)throw new Error('Query "'.concat(t,'" was not found.'));e=n.parentStore.getRequest(t)}return e})),f(this,"select",(function(t){var e=n.getRequest(t);e.read();var r=e.cache.selectorSet.getQuery();return n.selectorSetsByRequest.has(e)||n.selectorSetsByRequest.set(e,new z),n.selectorSetsByRequest.get(e).setQuery(r),r})),f(this,"waitForAll",(function(){n.requests.forEach((function(t){t.read()})),n.parentStore&&n.parentStore.waitForAll()})),f(this,"getFragmentRequest",(function(t,e){var r=Array.from(n.requests.values()).find((function(r){var n=r.cache;return null==n?void 0:n.selectorSet.getFragment(t,e)}));if(!r){if(!n.parentStore){var o=JSON.stringify(e);throw new Error('Fragment "'.concat(t,'" (entry: [').concat(o,"]) was not found."))}r=n.parentStore.getFragmentRequest(t,e)}return r})),f(this,"selectFragment",(function(t,e){var r=n.getFragmentRequest(t,e);r.read();var o=r.cache.selectorSet.getFragment(t,e);return n.selectorSetsByRequest.has(r)||n.selectorSetsByRequest.set(r,new z),n.selectorSetsByRequest.get(r).setFragment(t,e,o),o})),f(this,"addChild",(function(t){n.children=[].concat(O(n.children),[t])})),f(this,"removeChild",(function(t){n.children=n.children.filter((function(e){return e!==t}))})),f(this,"subscribe",(function(t){return n.listeners=[].concat(O(n.listeners),[t]),function(){n.listeners=n.listeners.filter((function(e){return e!==t}))}})),f(this,"getSnapshot",(function(){return n.marker})),f(this,"refresh",(function(){n.requests.forEach((function(t){t.sync()}));var t=!1;n.selectorSetsByRequest.forEach((function(e,r){e.update(r.cache.selectorSet)&&(t=!0)})),t?n.update():n.children.forEach((function(t){t.refresh()}))})),f(this,"reset",(function(){var t=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];n.requests=new Map,n.selectorSetsByRequest=new Map,t&&n.update(),n.children.forEach((function(t){t.reset(!1)}))})),f(this,"update",(function(){n.marker={},n.listeners.forEach((function(t){t()}))})),f(this,"destroy",(function(){n.parentStore.removeChild(n),n.requests.forEach((function(t){t.invalidate()}))})),this.parentStore=e,this.executeQuery=r,this.requests=new Map,this.selectorSetsByRequest=new Map,e&&e.addChild(this)};var bt="pending",St="fulfilled",Et="rejected",qt=function(t){var e=t.current;return 0===e.length?null:e[e.length-1]};function Ot(){var t=e.useContext(R);if(!t)throw new Error("Dispatcher hook is used outside of TransporterContext.");var r=e.useRef([]);return{dispatch:function(e,n){var o,i=null===(o=e.definitions.find((function(t){return"OperationDefinition"===t.kind})))||void 0===o?void 0:o.operation;if("query"!==i&&"mutation"!==i)throw new Error('No operation found. Must be either "query" or "mutation".');var u="query"===i?t.client.query(e,n):t.client.mutate(e,n);return r.current.push(u),u.resource.promise.then((function(){return u.cache.selectorSet.getQuery()}))},get ok(){var t=qt(r);return t&&t.status!==bt?t.status===St:null},get loading(){var t=qt(r);return!!t&&t.status===bt},get executed(){var t=qt(r);return!!t&&(t.status===St||t.status===Et)},get error(){var t=qt(r);return t&&t.status===Et?t.response:null}}}t.Link=J,t.ManyLink=G,t.Resource=Q,t.Transporter=function t(e){var r=this,n=e.request,o=e.cache,i=void 0===o?{}:o,u=e.ssr,s=void 0!==u&&u;a(this,t),f(this,"request",void 0),f(this,"rootStore",void 0),f(this,"cache",void 0),f(this,"ssr",void 0),f(this,"queries",void 0),f(this,"query",(function(t,e){return new dt(r,t,e)})),f(this,"createStore",(function(t){return new wt(t,r.query)})),f(this,"mutate",(function(t,e){return new gt(r,t,e)})),f(this,"refresh",(function(){r.rootStore.refresh()})),f(this,"reset",(function(){r.rootStore.reset(),r.queries=new Map})),f(this,"extract",(function(){var t={};return r.queries.forEach((function(e,r){t[r]=e.data.extract()})),t})),this.request=n,this.rootStore=this.createStore(null),this.cache=i,this.ssr=s,this.queries=new Map},t.TransporterError=ft,t.TransporterProvider=function(t){var r=t.children,n=t.client;if(!n)throw new Error("TransporterProvider: You must provide a Transporter instance.");var o=n.rootStore;return e.useSyncExternalStore(o.subscribe,o.getSnapshot,(function(){return null})),i.default.createElement(R.Provider,{value:{client:n,store:o}},r)},t.createContainer=function(t){var r,n=t.component,o=w(t,["component"]);if(!n)throw new Error('You must define a container "component".');var u=function(){r||(r=I(n,o.renderer));var t=r.read();return o.renderer?o.renderer(t):t},s=function(t){d(n,t);var r=E(n);function n(t){var e;return a(this,n),f(b(e=r.call(this,t)),"store",void 0),e.state={error:null},e}return c(n,[{key:"componentDidCatch",value:function(t,e){console.error(t,e)}},{key:"componentWillUnmount",value:function(){this.store.destroy()}},{key:"renderContainer",value:function(){var t=this.context.client,r=this.state.error;if(r)return o.error&&e.cloneElement(o.error,{error:r});var n=i.default.createElement(M,{component:u,options:o,values:this.props});return _&&!t.ssr?n:i.default.createElement(i.default.Suspense,{fallback:o.loading},n)}},{key:"render",value:function(){var t=this.context,e=t.client,r=t.store;return this.store||(this.store=e.createStore(r)),i.default.createElement(R.Provider,{value:{client:e,store:this.store}},this.renderContainer())}}]),n}(i.default.Component);o.throwOnError||(s.getDerivedStateFromError=function(t){return{error:t}}),s.contextType=R;var l=n.displayName||n.name;return s.displayName=l?"Container(".concat(l,")"):"Container",s},t.createNode=function(t){var r=t.component,n=w(t,["component"]);if(!t.component)throw new Error("React Transporter Node: You must define a node component.");function o(t){var o=e.useContext(R).store;if(!!!o.parentStore.parentStore)throw new Error("React Transporter Node: A node must be wrapped in a container.");var i=n.data||function(){return null};return e.createElement(r,i(o,t))}var i=r.displayName||r.name;return o.displayName=i?"ContainerNode(".concat(i,")"):"ContainerNode",o},t.ref=function(t,e){var r;return f(r={},F,[t]),f(r,C,e),r},t.useDispatcher=Ot,t.useMutation=function(t,e){var r=q(Ot(),2),n=r[0];return h(h({},r[1]),{},{dispatch:function(r){return n(t,h(h({},e),r))}})},t.useQuery=function(t,e){var r=q(Ot(),2),n=r[0];return h(h({},r[1]),{},{dispatch:function(r){return n(t,h(h({},e),r))}})},t.useReset=function(){var t=e.useContext(R);if(!t)throw new Error('"useReset" hook is used outside of TransporterContext.');var r=t.client;return function(){r.reset()}},Object.defineProperty(t,"__esModule",{value:!0})})); |
{ | ||
"name": "react-transporter", | ||
"version": "1.0.0-alpha.2", | ||
"version": "1.0.0-alpha.3", | ||
"description": "React.js GraphQL client", | ||
@@ -5,0 +5,0 @@ "author": "Markus Wetzel <markuswetzel@gmx.net>", |
Sorry, the diff of this file is too big to display
216975
5362