@hyper-fetch/core 9.6.2 → 9.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/__tests__/features/optimistic/optimistic.concurrency.spec.ts +278 -0
- package/__tests__/features/optimistic/optimistic.helpers.spec.ts +307 -0
- package/__tests__/features/optimistic/optimistic.matrix.spec.ts +315 -0
- package/__tests__/features/optimistic/optimistic.races.spec.ts +270 -0
- package/__tests__/features/optimistic/optimistic.random.spec.ts +191 -0
- package/__tests__/features/optimistic/optimistic.rollback.spec.ts +1001 -0
- package/__tests__/features/optimistic/optimistic.typescript.spec.ts +196 -0
- package/__tests__/features/request/request.optimistic.spec.ts +12 -1
- package/__tests__/utils/optimistic.utils.ts +124 -0
- package/dist/cache/cache.d.ts.map +1 -1
- package/dist/client/client.d.ts.map +1 -1
- package/dist/dispatcher/dispatcher.d.ts.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +704 -196
- package/dist/index.mjs.map +1 -1
- package/dist/optimistic/index.d.ts +5 -0
- package/dist/optimistic/index.d.ts.map +1 -0
- package/dist/optimistic/optimistic.d.ts +67 -0
- package/dist/optimistic/optimistic.d.ts.map +1 -0
- package/dist/optimistic/optimistic.settlement.d.ts +60 -0
- package/dist/optimistic/optimistic.settlement.d.ts.map +1 -0
- package/dist/optimistic/optimistic.types.d.ts +109 -0
- package/dist/optimistic/optimistic.types.d.ts.map +1 -0
- package/dist/optimistic/optimistic.utils.d.ts +29 -0
- package/dist/optimistic/optimistic.utils.d.ts.map +1 -0
- package/dist/request/request.d.ts +13 -5
- package/dist/request/request.d.ts.map +1 -1
- package/dist/request/request.types.d.ts +40 -1
- package/dist/request/request.types.d.ts.map +1 -1
- package/dist/request/request.utils.d.ts.map +1 -1
- package/package.json +1 -1
- package/src/cache/cache.ts +2 -1
- package/src/client/client.ts +2 -0
- package/src/dispatcher/dispatcher.ts +13 -0
- package/src/index.ts +4 -0
- package/src/optimistic/index.ts +4 -0
- package/src/optimistic/optimistic.settlement.ts +406 -0
- package/src/optimistic/optimistic.ts +162 -0
- package/src/optimistic/optimistic.types.ts +175 -0
- package/src/optimistic/optimistic.utils.ts +112 -0
- package/src/request/request.ts +19 -6
- package/src/request/request.types.ts +41 -1
- package/src/request/request.utils.ts +31 -54
- package/tsconfig.json +2 -0
package/dist/index.mjs
CHANGED
|
@@ -21,143 +21,215 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
21
21
|
enumerable: true
|
|
22
22
|
}) : target, mod));
|
|
23
23
|
//#endregion
|
|
24
|
-
//#region src/
|
|
24
|
+
//#region src/optimistic/optimistic.utils.ts
|
|
25
|
+
var isComparableId = (value) => typeof value === "string" || typeof value === "number";
|
|
25
26
|
/**
|
|
26
|
-
*
|
|
27
|
-
*
|
|
27
|
+
* Tells if the item is selected by the match. Plain values are compared with the `key` field of the item, numbers and
|
|
28
|
+
* strings match each other the same way route params do (`"1"` matches `1`).
|
|
28
29
|
*/
|
|
29
|
-
var
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
/**
|
|
50
|
-
* Callback that will be executed when plugin is mounted
|
|
51
|
-
*/
|
|
52
|
-
onMount = (callback) => {
|
|
53
|
-
this.pluginMethods.onMount = callback;
|
|
54
|
-
return this;
|
|
55
|
-
};
|
|
56
|
-
/**
|
|
57
|
-
* Callback that will be executed when plugin is unmounted
|
|
58
|
-
*/
|
|
59
|
-
onUnmount = (callback) => {
|
|
60
|
-
this.pluginMethods.onUnmount = callback;
|
|
61
|
-
return this;
|
|
62
|
-
};
|
|
63
|
-
/**
|
|
64
|
-
* Callback that will be executed when request is created
|
|
65
|
-
*/
|
|
66
|
-
onRequestCreate = (callback) => {
|
|
67
|
-
this.pluginMethods.onRequestCreate = callback;
|
|
68
|
-
return this;
|
|
69
|
-
};
|
|
70
|
-
/**
|
|
71
|
-
* Callback that will be executed when request gets triggered
|
|
72
|
-
*/
|
|
73
|
-
onRequestTrigger = (callback) => {
|
|
74
|
-
this.pluginMethods.onRequestTrigger = callback;
|
|
75
|
-
return this;
|
|
76
|
-
};
|
|
77
|
-
/**
|
|
78
|
-
* Callback that will be executed when request starts
|
|
79
|
-
*/
|
|
80
|
-
onRequestStart = (callback) => {
|
|
81
|
-
this.pluginMethods.onRequestStart = callback;
|
|
82
|
-
return this;
|
|
30
|
+
var isOptimisticMatch = (item, match, key = "id") => {
|
|
31
|
+
if (typeof match === "function") return !!match(item);
|
|
32
|
+
if (item === null || typeof item !== "object") return false;
|
|
33
|
+
const value = item[key];
|
|
34
|
+
if (Object.is(value, match)) return true;
|
|
35
|
+
return isComparableId(value) && isComparableId(match) && String(value) === String(match);
|
|
36
|
+
};
|
|
37
|
+
var assertList = (list) => {
|
|
38
|
+
if (!Array.isArray(list)) throw new TypeError("Optimistic list helpers need an array, use .list(field) for an array inside an object");
|
|
39
|
+
return list;
|
|
40
|
+
};
|
|
41
|
+
var assertEntry = (data) => {
|
|
42
|
+
if (data === null || typeof data !== "object" || Array.isArray(data)) throw new TypeError("Optimistic increment(field, by) needs an object, use increment(match, field, by) on a list");
|
|
43
|
+
return data;
|
|
44
|
+
};
|
|
45
|
+
var addToField = (item, field, by) => {
|
|
46
|
+
const value = item[field];
|
|
47
|
+
return {
|
|
48
|
+
...item,
|
|
49
|
+
[field]: (typeof value === "number" ? value : 0) + by
|
|
83
50
|
};
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
51
|
+
};
|
|
52
|
+
/**
|
|
53
|
+
* Maps the matching items. The list keeps its reference when nothing matched, so unchanged data produces no write.
|
|
54
|
+
*/
|
|
55
|
+
var mapMatching = (list, { match, key }, map) => {
|
|
56
|
+
const items = assertList(list);
|
|
57
|
+
let changed = false;
|
|
58
|
+
const next = items.map((item) => {
|
|
59
|
+
if (!isOptimisticMatch(item, match, key)) return item;
|
|
60
|
+
changed = true;
|
|
61
|
+
return map(item);
|
|
62
|
+
});
|
|
63
|
+
return changed ? next : items;
|
|
64
|
+
};
|
|
65
|
+
var patchItems = (list, selector, fields) => {
|
|
66
|
+
return mapMatching(list, selector, (item) => ({
|
|
67
|
+
...item,
|
|
68
|
+
...fields
|
|
69
|
+
}));
|
|
70
|
+
};
|
|
71
|
+
var insertItem = (list, item, options) => {
|
|
72
|
+
const items = assertList(list);
|
|
73
|
+
const at = options?.at ?? "end";
|
|
74
|
+
if (at === "start") return [item, ...items];
|
|
75
|
+
if (at === "end") return [...items, item];
|
|
76
|
+
const next = [...items];
|
|
77
|
+
next.splice(at, 0, item);
|
|
78
|
+
return next;
|
|
79
|
+
};
|
|
80
|
+
var removeItems = (list, { match, key }) => {
|
|
81
|
+
const items = assertList(list);
|
|
82
|
+
const next = items.filter((item) => !isOptimisticMatch(item, match, key));
|
|
83
|
+
return next.length === items.length ? items : next;
|
|
84
|
+
};
|
|
85
|
+
var incrementItems = (list, selector, { field, by }) => {
|
|
86
|
+
return mapMatching(list, selector, (item) => addToField(item, field, by));
|
|
87
|
+
};
|
|
88
|
+
var incrementField = (data, field, by) => {
|
|
89
|
+
return addToField(assertEntry(data), field, by);
|
|
90
|
+
};
|
|
91
|
+
/**
|
|
92
|
+
* Runs a list helper on the array held in `field`. A missing list counts as empty, the object keeps its reference when
|
|
93
|
+
* the list did not change.
|
|
94
|
+
*/
|
|
95
|
+
var updateListField = (data, field, update) => {
|
|
96
|
+
const entry = assertEntry(data);
|
|
97
|
+
const list = entry[field] ?? [];
|
|
98
|
+
const next = update(assertList(list));
|
|
99
|
+
return next === list ? entry : {
|
|
100
|
+
...entry,
|
|
101
|
+
[field]: next
|
|
90
102
|
};
|
|
103
|
+
};
|
|
104
|
+
//#endregion
|
|
105
|
+
//#region src/optimistic/optimistic.ts
|
|
106
|
+
/**
|
|
107
|
+
* One change of one target, built with `optimistic(target)`. Core applies it before the mutation is sent, and runs its
|
|
108
|
+
* `.commit()` on success or its `.rollback()` when the mutation fails, is aborted or removed from the queue.
|
|
109
|
+
* Operations are immutable - `.rollback()` and `.commit()` return a new operation, so one can be reused.
|
|
110
|
+
*/
|
|
111
|
+
var OptimisticOperation = class OptimisticOperation {
|
|
112
|
+
/** @internal */
|
|
113
|
+
target;
|
|
114
|
+
/** @internal */
|
|
115
|
+
allVariants;
|
|
116
|
+
/** @internal */
|
|
117
|
+
update;
|
|
118
|
+
/** @internal */
|
|
119
|
+
onRollback = void 0;
|
|
120
|
+
/** @internal */
|
|
121
|
+
onCommit = void 0;
|
|
122
|
+
constructor(options) {
|
|
123
|
+
this.target = options.target;
|
|
124
|
+
this.allVariants = options.allVariants;
|
|
125
|
+
this.update = options.update;
|
|
126
|
+
this.onRollback = options.onRollback;
|
|
127
|
+
this.onCommit = options.onCommit;
|
|
128
|
+
}
|
|
91
129
|
/**
|
|
92
|
-
*
|
|
130
|
+
* Undo of this change, written by hand and run by core when the mutation fails for good, is aborted or removed from
|
|
131
|
+
* the queue. Rollbacks of one mutation run in reverse order of the changes. It receives
|
|
132
|
+
* `{ data, previous, reason, response, request }` and returns the new data; returning nothing leaves the data as it
|
|
133
|
+
* is. Build the result from `data` and use `previous` only to look old values up. Must be synchronous.
|
|
134
|
+
* Without it nothing is undone locally and the target is refetched.
|
|
93
135
|
*/
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
136
|
+
rollback(callback) {
|
|
137
|
+
return new OptimisticOperation({
|
|
138
|
+
target: this.target,
|
|
139
|
+
allVariants: this.allVariants,
|
|
140
|
+
update: this.update,
|
|
141
|
+
onRollback: callback,
|
|
142
|
+
onCommit: this.onCommit
|
|
143
|
+
});
|
|
144
|
+
}
|
|
98
145
|
/**
|
|
99
|
-
*
|
|
146
|
+
* Runs when the mutation succeeds, before the target is refreshed. It receives `{ data, response, request }` and
|
|
147
|
+
* returns the new data, for example to swap a temporary item for the one from the response. Returning nothing leaves
|
|
148
|
+
* the data as it is. Must be synchronous.
|
|
100
149
|
*/
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
return
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
return this;
|
|
119
|
-
};
|
|
120
|
-
/** Called when a new item is added to a dispatcher queue */
|
|
121
|
-
onDispatcherItemAdded = (callback) => {
|
|
122
|
-
this.pluginMethods.onDispatcherItemAdded = callback;
|
|
123
|
-
return this;
|
|
124
|
-
};
|
|
125
|
-
/** Called when an item is removed from a dispatcher queue */
|
|
126
|
-
onDispatcherItemDeleted = (callback) => {
|
|
127
|
-
this.pluginMethods.onDispatcherItemDeleted = callback;
|
|
128
|
-
return this;
|
|
129
|
-
};
|
|
130
|
-
/** Called when a new dispatcher queue is created */
|
|
131
|
-
onDispatcherQueueCreated = (callback) => {
|
|
132
|
-
this.pluginMethods.onDispatcherQueueCreated = callback;
|
|
133
|
-
return this;
|
|
134
|
-
};
|
|
135
|
-
/** Called when an entire dispatcher queue is cleared */
|
|
136
|
-
onDispatcherQueueCleared = (callback) => {
|
|
137
|
-
this.pluginMethods.onDispatcherQueueCleared = callback;
|
|
138
|
-
return this;
|
|
139
|
-
};
|
|
140
|
-
/** Called when a cache entry is created or updated */
|
|
141
|
-
onCacheItemChange = (callback) => {
|
|
142
|
-
this.pluginMethods.onCacheItemChange = callback;
|
|
143
|
-
return this;
|
|
144
|
-
};
|
|
145
|
-
/** Called when a cache entry is deleted */
|
|
146
|
-
onCacheItemDelete = (callback) => {
|
|
147
|
-
this.pluginMethods.onCacheItemDelete = callback;
|
|
148
|
-
return this;
|
|
149
|
-
};
|
|
150
|
-
/** Called when a cache entry is invalidated */
|
|
151
|
-
onCacheItemInvalidate = (callback) => {
|
|
152
|
-
this.pluginMethods.onCacheItemInvalidate = callback;
|
|
153
|
-
return this;
|
|
150
|
+
commit(callback) {
|
|
151
|
+
return new OptimisticOperation({
|
|
152
|
+
target: this.target,
|
|
153
|
+
allVariants: this.allVariants,
|
|
154
|
+
update: this.update,
|
|
155
|
+
onRollback: this.onRollback,
|
|
156
|
+
onCommit: callback
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
var createTarget = (target, allVariants) => {
|
|
161
|
+
const operation = (update) => {
|
|
162
|
+
return new OptimisticOperation({
|
|
163
|
+
target,
|
|
164
|
+
allVariants,
|
|
165
|
+
update
|
|
166
|
+
});
|
|
154
167
|
};
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
168
|
+
const createListHelpers = (onList) => ({
|
|
169
|
+
patch: (match, fields, options) => {
|
|
170
|
+
return operation(onList((list) => patchItems(list, {
|
|
171
|
+
match,
|
|
172
|
+
key: options?.key
|
|
173
|
+
}, fields)));
|
|
174
|
+
},
|
|
175
|
+
insert: (item, options) => {
|
|
176
|
+
return operation(onList((list) => insertItem(list, item, options)));
|
|
177
|
+
},
|
|
178
|
+
remove: (match, options) => {
|
|
179
|
+
return operation(onList((list) => removeItems(list, {
|
|
180
|
+
match,
|
|
181
|
+
key: options?.key
|
|
182
|
+
})));
|
|
183
|
+
},
|
|
184
|
+
increment: (match, field, by, options) => {
|
|
185
|
+
return operation(onList((list) => incrementItems(list, {
|
|
186
|
+
match,
|
|
187
|
+
key: options?.key
|
|
188
|
+
}, {
|
|
189
|
+
field,
|
|
190
|
+
by
|
|
191
|
+
})));
|
|
192
|
+
}
|
|
193
|
+
});
|
|
194
|
+
const listHelpers = createListHelpers((update) => (data) => update(data));
|
|
195
|
+
return {
|
|
196
|
+
...listHelpers,
|
|
197
|
+
set: (updater) => operation(updater),
|
|
198
|
+
increment: (...args) => {
|
|
199
|
+
if (args.length >= 3) {
|
|
200
|
+
const [match, field, by, options] = args;
|
|
201
|
+
return listHelpers.increment(match, field, by, options);
|
|
202
|
+
}
|
|
203
|
+
const [field, by] = args;
|
|
204
|
+
return operation((data) => incrementField(data, field, by));
|
|
205
|
+
},
|
|
206
|
+
list: (field) => {
|
|
207
|
+
return createListHelpers((update) => (data) => updateListField(data, field, update));
|
|
208
|
+
}
|
|
159
209
|
};
|
|
160
210
|
};
|
|
211
|
+
var optimisticFactory = (target) => createTarget(target, false);
|
|
212
|
+
optimisticFactory.all = (target) => createTarget(target, true);
|
|
213
|
+
/**
|
|
214
|
+
* Describes an optimistic change of a cached request. Return the operations from `setOptimistic` or pass them with the
|
|
215
|
+
* `optimistic` send option, core applies them, runs `.commit()` / `.rollback()` when the mutation settles and refreshes
|
|
216
|
+
* the targets once the last pending mutation on them is done.
|
|
217
|
+
*
|
|
218
|
+
* - `optimistic(getTodos)` - the entry of this request (its params and query params)
|
|
219
|
+
* - `optimistic.all(getTodos)` - every cached variant of it, whatever the query params (filters, infinite pages)
|
|
220
|
+
*
|
|
221
|
+
* Helpers: `set(updater)`, `patch(match, fields)`, `insert(item, { at })`, `remove(match)`,
|
|
222
|
+
* `increment(field, by)` / `increment(match, field, by)` and `.list("field")` for an array inside an object.
|
|
223
|
+
*
|
|
224
|
+
* @example
|
|
225
|
+
* optimistic(getTodos)
|
|
226
|
+
* .patch(params.todoId, payload)
|
|
227
|
+
* .rollback(({ data, previous }) => {
|
|
228
|
+
* const before = previous.find((todo) => todo.id === params.todoId);
|
|
229
|
+
* return data.map((todo) => (todo.id === params.todoId && before ? before : todo));
|
|
230
|
+
* });
|
|
231
|
+
*/
|
|
232
|
+
var optimistic = optimisticFactory;
|
|
161
233
|
//#endregion
|
|
162
234
|
//#region src/constants/time.constants.ts
|
|
163
235
|
var Time = /* @__PURE__ */ function(Time) {
|
|
@@ -1461,67 +1533,36 @@ var mapResponseForSend = async (request, response) => {
|
|
|
1461
1533
|
if (mapping instanceof Promise) return await mapping;
|
|
1462
1534
|
return mapping || response;
|
|
1463
1535
|
};
|
|
1464
|
-
/**
|
|
1465
|
-
* Rollback is user code running in the middle of the response handling, its failure can't affect the request
|
|
1466
|
-
*/
|
|
1467
|
-
var rollbackOptimistic = (optimistic, args) => {
|
|
1468
|
-
const logFailure = (error) => {
|
|
1469
|
-
args.request.client.logger.error({
|
|
1470
|
-
title: "Optimistic rollback failed",
|
|
1471
|
-
type: "system",
|
|
1472
|
-
extra: {
|
|
1473
|
-
error,
|
|
1474
|
-
reason: args.reason,
|
|
1475
|
-
request: args.request
|
|
1476
|
-
}
|
|
1477
|
-
});
|
|
1478
|
-
throwOutsideLifecycle(error);
|
|
1479
|
-
};
|
|
1480
|
-
try {
|
|
1481
|
-
Promise.resolve(optimistic.rollback?.(args)).catch(logFailure);
|
|
1482
|
-
} catch (error) {
|
|
1483
|
-
logFailure(error);
|
|
1484
|
-
}
|
|
1485
|
-
};
|
|
1486
|
-
var invalidateOptimistic = (optimistic, request) => {
|
|
1487
|
-
optimistic.invalidate?.forEach((target) => {
|
|
1488
|
-
try {
|
|
1489
|
-
request.client.cache.invalidate(target);
|
|
1490
|
-
} catch (error) {
|
|
1491
|
-
request.client.logger.error({
|
|
1492
|
-
title: "Optimistic invalidation failed",
|
|
1493
|
-
type: "system",
|
|
1494
|
-
extra: {
|
|
1495
|
-
error,
|
|
1496
|
-
target,
|
|
1497
|
-
request
|
|
1498
|
-
}
|
|
1499
|
-
});
|
|
1500
|
-
throwOutsideLifecycle(error);
|
|
1501
|
-
}
|
|
1502
|
-
});
|
|
1503
|
-
};
|
|
1504
1536
|
var sendRequest = async (request, options) => {
|
|
1505
1537
|
const { client } = request;
|
|
1506
1538
|
const { requestManager } = client;
|
|
1507
1539
|
const [dispatcher] = getRequestDispatcher(request, options?.dispatcherType);
|
|
1508
1540
|
let mutationContext;
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1541
|
+
let pendingOptimistic;
|
|
1542
|
+
const optimisticSource = options?.optimistic ?? request.optimistic;
|
|
1543
|
+
if (optimisticSource) {
|
|
1544
|
+
try {
|
|
1545
|
+
const result = Array.isArray(optimisticSource) ? optimisticSource : optimisticSource({
|
|
1546
|
+
request,
|
|
1547
|
+
client: request.client,
|
|
1548
|
+
payload: request.payload,
|
|
1549
|
+
params: request.params,
|
|
1550
|
+
queryParams: request.queryParams,
|
|
1551
|
+
optimistic
|
|
1552
|
+
});
|
|
1553
|
+
mutationContext = getOptimisticResult(result instanceof Promise ? await result : result);
|
|
1554
|
+
} catch (error) {
|
|
1555
|
+
return {
|
|
1556
|
+
data: null,
|
|
1557
|
+
error: /* @__PURE__ */ new Error(`Optimistic callback failed: ${error instanceof Error ? error.message : error}`),
|
|
1558
|
+
status: null,
|
|
1559
|
+
success: false,
|
|
1560
|
+
extra: client.adapter.defaultExtra,
|
|
1561
|
+
requestTimestamp: Date.now(),
|
|
1562
|
+
responseTimestamp: Date.now()
|
|
1563
|
+
};
|
|
1564
|
+
}
|
|
1565
|
+
pendingOptimistic = applyOptimistic(client, mutationContext);
|
|
1525
1566
|
}
|
|
1526
1567
|
return new Promise((resolve) => {
|
|
1527
1568
|
let isResolved = false;
|
|
@@ -1540,19 +1581,25 @@ var sendRequest = async (request, options) => {
|
|
|
1540
1581
|
if (!mappings.has(values)) mappings.set(values, runResponseMapper(request, values.response));
|
|
1541
1582
|
return mappings.get(values);
|
|
1542
1583
|
};
|
|
1543
|
-
const unmountSettlement =
|
|
1544
|
-
const
|
|
1584
|
+
const unmountSettlement = pendingOptimistic ? requestManager.events.onResponseById(requestId, (values) => {
|
|
1585
|
+
const pending = pendingOptimistic;
|
|
1545
1586
|
const willBeResent = getWillBeResent(values);
|
|
1546
1587
|
const settle = (response) => {
|
|
1547
1588
|
if (isSettled || !response.success && willBeResent) return;
|
|
1548
1589
|
isSettled = true;
|
|
1549
|
-
if (values.details.isCanceled)
|
|
1590
|
+
if (values.details.isCanceled) settleOptimistic(pending, {
|
|
1591
|
+
type: "rollback",
|
|
1550
1592
|
reason: "abort",
|
|
1551
1593
|
response,
|
|
1552
1594
|
request
|
|
1553
1595
|
});
|
|
1554
|
-
else if (response.success)
|
|
1555
|
-
|
|
1596
|
+
else if (response.success) settleOptimistic(pending, {
|
|
1597
|
+
type: "success",
|
|
1598
|
+
response,
|
|
1599
|
+
request
|
|
1600
|
+
});
|
|
1601
|
+
else settleOptimistic(pending, {
|
|
1602
|
+
type: "rollback",
|
|
1556
1603
|
reason: "error",
|
|
1557
1604
|
response,
|
|
1558
1605
|
request
|
|
@@ -1633,9 +1680,10 @@ var sendRequest = async (request, options) => {
|
|
|
1633
1680
|
if (!isResolved) {
|
|
1634
1681
|
isResolved = true;
|
|
1635
1682
|
isDelivered = true;
|
|
1636
|
-
if (
|
|
1683
|
+
if (pendingOptimistic && !isSettled) {
|
|
1637
1684
|
isSettled = true;
|
|
1638
|
-
|
|
1685
|
+
settleOptimistic(pendingOptimistic, {
|
|
1686
|
+
type: "rollback",
|
|
1639
1687
|
reason: "removed",
|
|
1640
1688
|
request
|
|
1641
1689
|
});
|
|
@@ -1844,10 +1892,18 @@ var Request = class Request {
|
|
|
1844
1892
|
};
|
|
1845
1893
|
/**
|
|
1846
1894
|
* Configure optimistic update behavior for this request.
|
|
1847
|
-
* The callback runs before the request is sent and receives
|
|
1848
|
-
*
|
|
1849
|
-
*
|
|
1850
|
-
*
|
|
1895
|
+
* The callback runs before the request is sent and receives `{ request, client, payload, params, queryParams,
|
|
1896
|
+
* optimistic }`. A synchronous callback changes the cache within the `send()` call.
|
|
1897
|
+
*
|
|
1898
|
+
* Return an array of changes built with `optimistic()` - core applies them, runs their `.commit()` on success or
|
|
1899
|
+
* `.rollback()` on final failure, abort or queue removal, and refreshes the targets after the last pending mutation
|
|
1900
|
+
* on them. Or return an object with `updates`, `context` (available in lifecycle callbacks as `mutationContext`),
|
|
1901
|
+
* `rollback` (called once on failure, abort or queue removal), `invalidate` (requests invalidated on success),
|
|
1902
|
+
* `rollbackOnError` and `revalidate`.
|
|
1903
|
+
* Everything runs for every way of sending the request, not only inside of framework hooks.
|
|
1904
|
+
*
|
|
1905
|
+
* @example
|
|
1906
|
+
* toggleTodo.setOptimistic(({ params, payload }) => [optimistic(getTodos).patch(params.todoId, payload)]);
|
|
1851
1907
|
*/
|
|
1852
1908
|
setOptimistic = (callback) => {
|
|
1853
1909
|
const cloned = this.clone();
|
|
@@ -2127,7 +2183,7 @@ var Request = class Request {
|
|
|
2127
2183
|
* ```
|
|
2128
2184
|
*/
|
|
2129
2185
|
send = async (options) => {
|
|
2130
|
-
const { dispatcherType: _dispatcherType, cachePolicy = "network-only", ...configuration } = options || {};
|
|
2186
|
+
const { dispatcherType: _dispatcherType, cachePolicy = "network-only", optimistic: _optimistic, ...configuration } = options || {};
|
|
2131
2187
|
const request = this.clone(configuration);
|
|
2132
2188
|
const sendRequestOptions = options === void 0 ? void 0 : {
|
|
2133
2189
|
...options,
|
|
@@ -2152,6 +2208,443 @@ var Request = class Request {
|
|
|
2152
2208
|
};
|
|
2153
2209
|
};
|
|
2154
2210
|
//#endregion
|
|
2211
|
+
//#region src/optimistic/optimistic.settlement.ts
|
|
2212
|
+
var clientStates = /* @__PURE__ */ new WeakMap();
|
|
2213
|
+
var getClientState = (client) => {
|
|
2214
|
+
let state = clientStates.get(client);
|
|
2215
|
+
if (!state) {
|
|
2216
|
+
state = {
|
|
2217
|
+
keys: /* @__PURE__ */ new Map(),
|
|
2218
|
+
staleRequests: /* @__PURE__ */ new Map()
|
|
2219
|
+
};
|
|
2220
|
+
clientStates.set(client, state);
|
|
2221
|
+
}
|
|
2222
|
+
return state;
|
|
2223
|
+
};
|
|
2224
|
+
/**
|
|
2225
|
+
* Failures of user code (helpers, commits, rollbacks, predicates) are logged and thrown outside of the request
|
|
2226
|
+
* lifecycle, like every other user code running in it - the request and the other changes still settle.
|
|
2227
|
+
*/
|
|
2228
|
+
var reportFailure = (client, title, extra) => {
|
|
2229
|
+
client.logger.error({
|
|
2230
|
+
title,
|
|
2231
|
+
type: "system",
|
|
2232
|
+
extra
|
|
2233
|
+
});
|
|
2234
|
+
throwOutsideLifecycle(extra.error);
|
|
2235
|
+
};
|
|
2236
|
+
var readEntry = (client, storageKey) => {
|
|
2237
|
+
return client.cache.get(storageKey);
|
|
2238
|
+
};
|
|
2239
|
+
/**
|
|
2240
|
+
* Writes the data through the regular cache path, so listeners get one event per change. The entry keeps its
|
|
2241
|
+
* timestamps and staleness - an optimistic value doesn't make the entry fresh.
|
|
2242
|
+
*/
|
|
2243
|
+
var writeData = (request, entry, data) => {
|
|
2244
|
+
const entryRequest = request.clone({
|
|
2245
|
+
staleTime: entry.staleTime,
|
|
2246
|
+
cacheTime: entry.cacheTime
|
|
2247
|
+
});
|
|
2248
|
+
request.client.cache.set(entryRequest, {
|
|
2249
|
+
...entry,
|
|
2250
|
+
data
|
|
2251
|
+
});
|
|
2252
|
+
};
|
|
2253
|
+
/**
|
|
2254
|
+
* Cache keys targeted by the operation. `optimistic.all()` matches every entry of the same method and endpoint
|
|
2255
|
+
* whatever the query params; a custom cache key matches itself and the keys derived from it (infinite pages).
|
|
2256
|
+
*/
|
|
2257
|
+
var resolveTargets = (client, operation) => {
|
|
2258
|
+
const { target } = operation;
|
|
2259
|
+
const targets = /* @__PURE__ */ new Map();
|
|
2260
|
+
if (!operation.allVariants) {
|
|
2261
|
+
targets.set(scopeKey(target.cacheKey, target.scope), target);
|
|
2262
|
+
return targets;
|
|
2263
|
+
}
|
|
2264
|
+
const prefix = target.cacheKey === getRequestKey(target) ? `${stringifyKey(target.method)}_${stringifyKey(target.endpoint)}_` : `${target.cacheKey}_`;
|
|
2265
|
+
client.cache.keys().forEach((storageKey) => {
|
|
2266
|
+
const entry = client.cache.storage.get(storageKey);
|
|
2267
|
+
if (!entry || entry.scope !== target.scope) return;
|
|
2268
|
+
if (entry.cacheKey === target.cacheKey) targets.set(storageKey, target);
|
|
2269
|
+
else if (entry.cacheKey.startsWith(prefix)) targets.set(storageKey, target.clone().setCacheKey(entry.cacheKey));
|
|
2270
|
+
});
|
|
2271
|
+
return targets;
|
|
2272
|
+
};
|
|
2273
|
+
/**
|
|
2274
|
+
* Runs `.rollback()` / `.commit()` of an operation and writes what it returned. User code can't break the settlement:
|
|
2275
|
+
* a throw or a promise is reported and the key gets refreshed.
|
|
2276
|
+
*/
|
|
2277
|
+
var runSettleCallback = (pending, { operation, storageKey, request, previous }, outcome) => {
|
|
2278
|
+
const { client } = pending;
|
|
2279
|
+
const entry = readEntry(client, storageKey);
|
|
2280
|
+
const isCommit = outcome.type === "success";
|
|
2281
|
+
const title = isCommit ? "Optimistic commit failed" : "Optimistic rollback failed";
|
|
2282
|
+
const run = (data) => {
|
|
2283
|
+
if (outcome.type === "success") {
|
|
2284
|
+
const response = outcome.response;
|
|
2285
|
+
return operation.onCommit?.({
|
|
2286
|
+
data,
|
|
2287
|
+
response,
|
|
2288
|
+
request: outcome.request
|
|
2289
|
+
});
|
|
2290
|
+
}
|
|
2291
|
+
const { type: _type, ...args } = outcome;
|
|
2292
|
+
return operation.onRollback?.({
|
|
2293
|
+
...args,
|
|
2294
|
+
data,
|
|
2295
|
+
previous
|
|
2296
|
+
});
|
|
2297
|
+
};
|
|
2298
|
+
if (!(isCommit ? operation.onCommit : operation.onRollback) || !entry) return;
|
|
2299
|
+
try {
|
|
2300
|
+
const next = run(entry.data);
|
|
2301
|
+
if (next instanceof Promise) {
|
|
2302
|
+
next.catch((error) => reportFailure(client, title, {
|
|
2303
|
+
error,
|
|
2304
|
+
storageKey
|
|
2305
|
+
}));
|
|
2306
|
+
throw new TypeError("Optimistic rollback and commit must be synchronous, the returned promise was ignored");
|
|
2307
|
+
}
|
|
2308
|
+
if (next !== void 0 && next !== entry.data) writeData(request, entry, next);
|
|
2309
|
+
} catch (error) {
|
|
2310
|
+
reportFailure(client, title, {
|
|
2311
|
+
error,
|
|
2312
|
+
storageKey,
|
|
2313
|
+
request: outcome.request
|
|
2314
|
+
});
|
|
2315
|
+
pending.failed.add(storageKey);
|
|
2316
|
+
}
|
|
2317
|
+
};
|
|
2318
|
+
/** Rollback of the hand-written object form - runs once, its failure can't affect the request */
|
|
2319
|
+
var runObjectRollback = (pending, args) => {
|
|
2320
|
+
const { client, result } = pending;
|
|
2321
|
+
const onFailure = (error) => {
|
|
2322
|
+
reportFailure(client, "Optimistic rollback failed", {
|
|
2323
|
+
error,
|
|
2324
|
+
reason: args.reason,
|
|
2325
|
+
request: args.request
|
|
2326
|
+
});
|
|
2327
|
+
};
|
|
2328
|
+
try {
|
|
2329
|
+
Promise.resolve(result.rollback?.(args)).catch(onFailure);
|
|
2330
|
+
} catch (error) {
|
|
2331
|
+
onFailure(error);
|
|
2332
|
+
}
|
|
2333
|
+
};
|
|
2334
|
+
var runObjectInvalidation = ({ client, result }, request) => {
|
|
2335
|
+
result.invalidate?.forEach((target) => {
|
|
2336
|
+
try {
|
|
2337
|
+
client.cache.invalidate(target);
|
|
2338
|
+
} catch (error) {
|
|
2339
|
+
reportFailure(client, "Optimistic invalidation failed", {
|
|
2340
|
+
error,
|
|
2341
|
+
target,
|
|
2342
|
+
request
|
|
2343
|
+
});
|
|
2344
|
+
}
|
|
2345
|
+
});
|
|
2346
|
+
};
|
|
2347
|
+
/**
|
|
2348
|
+
* `rollbackOnError` decides about final errors only - aborted and removed requests are always reverted.
|
|
2349
|
+
* A predicate that throws is reported and the change is reverted.
|
|
2350
|
+
*/
|
|
2351
|
+
var shouldRollback = (pending, outcome) => {
|
|
2352
|
+
const { rollbackOnError } = pending.result;
|
|
2353
|
+
if (outcome.reason !== "error" || rollbackOnError === void 0 || rollbackOnError === true) return true;
|
|
2354
|
+
if (rollbackOnError === false) return false;
|
|
2355
|
+
try {
|
|
2356
|
+
return !!rollbackOnError({
|
|
2357
|
+
response: outcome.response,
|
|
2358
|
+
request: outcome.request
|
|
2359
|
+
});
|
|
2360
|
+
} catch (error) {
|
|
2361
|
+
reportFailure(pending.client, "Optimistic rollbackOnError failed", {
|
|
2362
|
+
error,
|
|
2363
|
+
request: outcome.request
|
|
2364
|
+
});
|
|
2365
|
+
return true;
|
|
2366
|
+
}
|
|
2367
|
+
};
|
|
2368
|
+
var getRunningRequestsOnKey = (client, storageKey) => {
|
|
2369
|
+
return [...client.fetchDispatcher.getAllRunningRequests(), ...client.submitDispatcher.getAllRunningRequests()].filter(({ request }) => scopeKey(request.cacheKey, request.scope) === storageKey);
|
|
2370
|
+
};
|
|
2371
|
+
var hasStaleRequests = (state, storageKey) => {
|
|
2372
|
+
return [...state.staleRequests.values()].includes(storageKey);
|
|
2373
|
+
};
|
|
2374
|
+
/** Refreshes the key once nothing pending or stale is left on it */
|
|
2375
|
+
var refreshWhenIdle = (client, state, storageKey) => {
|
|
2376
|
+
const keyState = state.keys.get(storageKey);
|
|
2377
|
+
if (!keyState || keyState.pending > 0 || hasStaleRequests(state, storageKey)) return;
|
|
2378
|
+
state.keys.delete(storageKey);
|
|
2379
|
+
if (keyState.refresh) client.cache.invalidate(keyState.request);
|
|
2380
|
+
};
|
|
2381
|
+
var release = (pending, refresh) => {
|
|
2382
|
+
const { client, targets, failed, guarded } = pending;
|
|
2383
|
+
const state = getClientState(client);
|
|
2384
|
+
targets.forEach((request, storageKey) => {
|
|
2385
|
+
const keyState = state.keys.get(storageKey);
|
|
2386
|
+
const shouldRefresh = refresh || failed.has(storageKey);
|
|
2387
|
+
if (!guarded.has(storageKey)) {
|
|
2388
|
+
if (keyState && shouldRefresh) keyState.refresh = true;
|
|
2389
|
+
else if (shouldRefresh) client.cache.invalidate(request);
|
|
2390
|
+
return;
|
|
2391
|
+
}
|
|
2392
|
+
if (!keyState) return;
|
|
2393
|
+
keyState.pending -= 1;
|
|
2394
|
+
keyState.refresh = keyState.refresh || shouldRefresh;
|
|
2395
|
+
keyState.request = request;
|
|
2396
|
+
getRunningRequestsOnKey(client, storageKey).forEach(({ requestId }) => {
|
|
2397
|
+
state.staleRequests.set(requestId, storageKey);
|
|
2398
|
+
});
|
|
2399
|
+
refreshWhenIdle(client, state, storageKey);
|
|
2400
|
+
});
|
|
2401
|
+
};
|
|
2402
|
+
/**
|
|
2403
|
+
* @internal
|
|
2404
|
+
* Normalizes what `setOptimistic` or the `optimistic` send option returned into the object form.
|
|
2405
|
+
*/
|
|
2406
|
+
var getOptimisticResult = (value) => {
|
|
2407
|
+
if (Array.isArray(value)) return { updates: value };
|
|
2408
|
+
return value || {};
|
|
2409
|
+
};
|
|
2410
|
+
/**
|
|
2411
|
+
* @internal
|
|
2412
|
+
* Applies the operations of the mutation and registers its target keys as pending. A failing operation is reported,
|
|
2413
|
+
* the others still apply.
|
|
2414
|
+
*/
|
|
2415
|
+
var applyOptimistic = (client, result) => {
|
|
2416
|
+
const pending = {
|
|
2417
|
+
client,
|
|
2418
|
+
result,
|
|
2419
|
+
applied: [],
|
|
2420
|
+
targets: /* @__PURE__ */ new Map(),
|
|
2421
|
+
guarded: /* @__PURE__ */ new Set(),
|
|
2422
|
+
failed: /* @__PURE__ */ new Set()
|
|
2423
|
+
};
|
|
2424
|
+
const state = getClientState(client);
|
|
2425
|
+
result.updates?.forEach((value) => {
|
|
2426
|
+
try {
|
|
2427
|
+
if (!(value instanceof OptimisticOperation)) throw new TypeError("Optimistic updates accept operations created with optimistic()");
|
|
2428
|
+
const operation = value;
|
|
2429
|
+
resolveTargets(client, operation).forEach((request, storageKey) => {
|
|
2430
|
+
pending.targets.set(storageKey, request);
|
|
2431
|
+
const entry = readEntry(client, storageKey);
|
|
2432
|
+
if (!entry) return;
|
|
2433
|
+
try {
|
|
2434
|
+
const next = operation.update(entry.data);
|
|
2435
|
+
if (next !== entry.data) writeData(request, entry, next);
|
|
2436
|
+
pending.applied.push({
|
|
2437
|
+
operation,
|
|
2438
|
+
storageKey,
|
|
2439
|
+
request,
|
|
2440
|
+
previous: entry.data
|
|
2441
|
+
});
|
|
2442
|
+
pending.guarded.add(storageKey);
|
|
2443
|
+
} catch (error) {
|
|
2444
|
+
reportFailure(client, "Optimistic update failed", {
|
|
2445
|
+
error,
|
|
2446
|
+
storageKey
|
|
2447
|
+
});
|
|
2448
|
+
pending.failed.add(storageKey);
|
|
2449
|
+
}
|
|
2450
|
+
});
|
|
2451
|
+
} catch (error) {
|
|
2452
|
+
reportFailure(client, "Optimistic update failed", {
|
|
2453
|
+
error,
|
|
2454
|
+
operation: value
|
|
2455
|
+
});
|
|
2456
|
+
}
|
|
2457
|
+
});
|
|
2458
|
+
pending.guarded.forEach((storageKey) => {
|
|
2459
|
+
const request = pending.targets.get(storageKey);
|
|
2460
|
+
const keyState = state.keys.get(storageKey) ?? {
|
|
2461
|
+
pending: 0,
|
|
2462
|
+
refresh: false,
|
|
2463
|
+
request
|
|
2464
|
+
};
|
|
2465
|
+
keyState.pending += 1;
|
|
2466
|
+
state.keys.set(storageKey, keyState);
|
|
2467
|
+
});
|
|
2468
|
+
return pending;
|
|
2469
|
+
};
|
|
2470
|
+
/**
|
|
2471
|
+
* @internal
|
|
2472
|
+
* Settles the mutation once. Success runs the commits and invalidations, a final error, abort or queue removal runs the
|
|
2473
|
+
* rollbacks in reverse order of application. The targets get refreshed after the last pending mutation on them.
|
|
2474
|
+
*/
|
|
2475
|
+
var settleOptimistic = (pending, outcome) => {
|
|
2476
|
+
const { result, applied } = pending;
|
|
2477
|
+
const canRefresh = result.revalidate !== false;
|
|
2478
|
+
if (outcome.type === "success") {
|
|
2479
|
+
applied.forEach((operation) => runSettleCallback(pending, operation, outcome));
|
|
2480
|
+
runObjectInvalidation(pending, outcome.request);
|
|
2481
|
+
return release(pending, canRefresh);
|
|
2482
|
+
}
|
|
2483
|
+
const { type: _type, ...args } = outcome;
|
|
2484
|
+
if (!shouldRollback(pending, args)) return release(pending, false);
|
|
2485
|
+
for (let index = applied.length - 1; index >= 0; index -= 1) runSettleCallback(pending, applied[index], outcome);
|
|
2486
|
+
runObjectRollback(pending, args);
|
|
2487
|
+
return release(pending, canRefresh);
|
|
2488
|
+
};
|
|
2489
|
+
/**
|
|
2490
|
+
* @internal
|
|
2491
|
+
* Stale response guard, called where the dispatcher writes a response to the cache. A response is discarded when a
|
|
2492
|
+
* mutation changed its key and is pending, or when the fetch started before the latest such mutation settled - the
|
|
2493
|
+
* refresh after the mutation supplies current data. Keys that had no data when the change was applied are not
|
|
2494
|
+
* guarded, so a first load is never held back. Manual cache writes don't go through this check.
|
|
2495
|
+
*/
|
|
2496
|
+
var isStaleOptimisticResponse = (client, request, requestId) => {
|
|
2497
|
+
const state = clientStates.get(client);
|
|
2498
|
+
if (!state) return false;
|
|
2499
|
+
const storageKey = scopeKey(request.cacheKey, request.scope);
|
|
2500
|
+
const isMarked = state.staleRequests.delete(requestId);
|
|
2501
|
+
const isPending = (state.keys.get(storageKey)?.pending ?? 0) > 0;
|
|
2502
|
+
if (isMarked) refreshWhenIdle(client, state, storageKey);
|
|
2503
|
+
return isMarked || isPending;
|
|
2504
|
+
};
|
|
2505
|
+
/** @internal Drops the pending state of the client, its mutations will never settle after clearing it */
|
|
2506
|
+
var resetOptimisticState = (client) => {
|
|
2507
|
+
clientStates.delete(client);
|
|
2508
|
+
};
|
|
2509
|
+
//#endregion
|
|
2510
|
+
//#region src/plugin/plugin.ts
|
|
2511
|
+
/**
|
|
2512
|
+
* Base class for plugins that hook into the request, cache, dispatcher, and adapter lifecycle.
|
|
2513
|
+
* Extend this to build devtools, logging, analytics, or custom side-effect plugins.
|
|
2514
|
+
*/
|
|
2515
|
+
var Plugin = class {
|
|
2516
|
+
name;
|
|
2517
|
+
data;
|
|
2518
|
+
client = void 0;
|
|
2519
|
+
pluginMethods = {};
|
|
2520
|
+
constructor(config) {
|
|
2521
|
+
this.config = config;
|
|
2522
|
+
this.name = config.name;
|
|
2523
|
+
if (config.data) this.data = config.data;
|
|
2524
|
+
}
|
|
2525
|
+
/** Bind the plugin to a client instance. Called automatically when the plugin is added via `client.addPlugin()`. */
|
|
2526
|
+
initialize = (client) => {
|
|
2527
|
+
this.client = client;
|
|
2528
|
+
return this;
|
|
2529
|
+
};
|
|
2530
|
+
/** Invoke a registered plugin method by name. Used internally by the client to dispatch lifecycle events. */
|
|
2531
|
+
trigger = (method, data) => {
|
|
2532
|
+
const callback = this.pluginMethods[method];
|
|
2533
|
+
if (callback) callback(data);
|
|
2534
|
+
};
|
|
2535
|
+
/**
|
|
2536
|
+
* Callback that will be executed when plugin is mounted
|
|
2537
|
+
*/
|
|
2538
|
+
onMount = (callback) => {
|
|
2539
|
+
this.pluginMethods.onMount = callback;
|
|
2540
|
+
return this;
|
|
2541
|
+
};
|
|
2542
|
+
/**
|
|
2543
|
+
* Callback that will be executed when plugin is unmounted
|
|
2544
|
+
*/
|
|
2545
|
+
onUnmount = (callback) => {
|
|
2546
|
+
this.pluginMethods.onUnmount = callback;
|
|
2547
|
+
return this;
|
|
2548
|
+
};
|
|
2549
|
+
/**
|
|
2550
|
+
* Callback that will be executed when request is created
|
|
2551
|
+
*/
|
|
2552
|
+
onRequestCreate = (callback) => {
|
|
2553
|
+
this.pluginMethods.onRequestCreate = callback;
|
|
2554
|
+
return this;
|
|
2555
|
+
};
|
|
2556
|
+
/**
|
|
2557
|
+
* Callback that will be executed when request gets triggered
|
|
2558
|
+
*/
|
|
2559
|
+
onRequestTrigger = (callback) => {
|
|
2560
|
+
this.pluginMethods.onRequestTrigger = callback;
|
|
2561
|
+
return this;
|
|
2562
|
+
};
|
|
2563
|
+
/**
|
|
2564
|
+
* Callback that will be executed when request starts
|
|
2565
|
+
*/
|
|
2566
|
+
onRequestStart = (callback) => {
|
|
2567
|
+
this.pluginMethods.onRequestStart = callback;
|
|
2568
|
+
return this;
|
|
2569
|
+
};
|
|
2570
|
+
/**
|
|
2571
|
+
* Callback that will be executed when response is successful
|
|
2572
|
+
*/
|
|
2573
|
+
onRequestSuccess = (callback) => {
|
|
2574
|
+
this.pluginMethods.onRequestSuccess = callback;
|
|
2575
|
+
return this;
|
|
2576
|
+
};
|
|
2577
|
+
/**
|
|
2578
|
+
* Callback that will be executed when response is failed
|
|
2579
|
+
*/
|
|
2580
|
+
onRequestError = (callback) => {
|
|
2581
|
+
this.pluginMethods.onRequestError = callback;
|
|
2582
|
+
return this;
|
|
2583
|
+
};
|
|
2584
|
+
/**
|
|
2585
|
+
* Callback that will be executed when response is finished
|
|
2586
|
+
*/
|
|
2587
|
+
onRequestFinished = (callback) => {
|
|
2588
|
+
this.pluginMethods.onRequestFinished = callback;
|
|
2589
|
+
return this;
|
|
2590
|
+
};
|
|
2591
|
+
/** Called when the dispatcher storage is fully cleared */
|
|
2592
|
+
onDispatcherCleared = (callback) => {
|
|
2593
|
+
this.pluginMethods.onDispatcherCleared = callback;
|
|
2594
|
+
return this;
|
|
2595
|
+
};
|
|
2596
|
+
/** Called when a dispatcher queue has no more pending requests */
|
|
2597
|
+
onDispatcherQueueDrained = (callback) => {
|
|
2598
|
+
this.pluginMethods.onDispatcherQueueDrained = callback;
|
|
2599
|
+
return this;
|
|
2600
|
+
};
|
|
2601
|
+
/** Called when a dispatcher queue transitions to running, paused, or stopped */
|
|
2602
|
+
onDispatcherQueueRunning = (callback) => {
|
|
2603
|
+
this.pluginMethods.onDispatcherQueueRunning = callback;
|
|
2604
|
+
return this;
|
|
2605
|
+
};
|
|
2606
|
+
/** Called when a new item is added to a dispatcher queue */
|
|
2607
|
+
onDispatcherItemAdded = (callback) => {
|
|
2608
|
+
this.pluginMethods.onDispatcherItemAdded = callback;
|
|
2609
|
+
return this;
|
|
2610
|
+
};
|
|
2611
|
+
/** Called when an item is removed from a dispatcher queue */
|
|
2612
|
+
onDispatcherItemDeleted = (callback) => {
|
|
2613
|
+
this.pluginMethods.onDispatcherItemDeleted = callback;
|
|
2614
|
+
return this;
|
|
2615
|
+
};
|
|
2616
|
+
/** Called when a new dispatcher queue is created */
|
|
2617
|
+
onDispatcherQueueCreated = (callback) => {
|
|
2618
|
+
this.pluginMethods.onDispatcherQueueCreated = callback;
|
|
2619
|
+
return this;
|
|
2620
|
+
};
|
|
2621
|
+
/** Called when an entire dispatcher queue is cleared */
|
|
2622
|
+
onDispatcherQueueCleared = (callback) => {
|
|
2623
|
+
this.pluginMethods.onDispatcherQueueCleared = callback;
|
|
2624
|
+
return this;
|
|
2625
|
+
};
|
|
2626
|
+
/** Called when a cache entry is created or updated */
|
|
2627
|
+
onCacheItemChange = (callback) => {
|
|
2628
|
+
this.pluginMethods.onCacheItemChange = callback;
|
|
2629
|
+
return this;
|
|
2630
|
+
};
|
|
2631
|
+
/** Called when a cache entry is deleted */
|
|
2632
|
+
onCacheItemDelete = (callback) => {
|
|
2633
|
+
this.pluginMethods.onCacheItemDelete = callback;
|
|
2634
|
+
return this;
|
|
2635
|
+
};
|
|
2636
|
+
/** Called when a cache entry is invalidated */
|
|
2637
|
+
onCacheItemInvalidate = (callback) => {
|
|
2638
|
+
this.pluginMethods.onCacheItemInvalidate = callback;
|
|
2639
|
+
return this;
|
|
2640
|
+
};
|
|
2641
|
+
/** Called when the adapter fetcher is about to execute a request */
|
|
2642
|
+
onAdapterFetch = (callback) => {
|
|
2643
|
+
this.pluginMethods.onAdapterFetch = callback;
|
|
2644
|
+
return this;
|
|
2645
|
+
};
|
|
2646
|
+
};
|
|
2647
|
+
//#endregion
|
|
2155
2648
|
//#region src/cache/cache.ts
|
|
2156
2649
|
/** Timers can't wait longer than 2^31-1 ms (~24.8 days) - a longer delay overflows and fires immediately */
|
|
2157
2650
|
var MAX_TIMER_DELAY = 2147483647;
|
|
@@ -3308,7 +3801,12 @@ var Dispatcher = class {
|
|
|
3308
3801
|
isOffline
|
|
3309
3802
|
}));
|
|
3310
3803
|
const storageKey = scopeKey(request.cacheKey, scope);
|
|
3311
|
-
|
|
3804
|
+
const isOutdated = (this.cachedOrder.get(storageKey) ?? 0) > sentOrder;
|
|
3805
|
+
let isStaleOptimistic = false;
|
|
3806
|
+
notify(() => {
|
|
3807
|
+
isStaleOptimistic = isStaleOptimisticResponse(this.client, request, requestId);
|
|
3808
|
+
});
|
|
3809
|
+
if (isOutdated) this.logger.debug({
|
|
3312
3810
|
title: "Response of a request sent before the cached one, skipping the cache",
|
|
3313
3811
|
type: "system",
|
|
3314
3812
|
extra: {
|
|
@@ -3317,6 +3815,15 @@ var Dispatcher = class {
|
|
|
3317
3815
|
response
|
|
3318
3816
|
}
|
|
3319
3817
|
});
|
|
3818
|
+
else if (isStaleOptimistic) this.logger.debug({
|
|
3819
|
+
title: "Response started before a pending optimistic change settled, skipping the cache",
|
|
3820
|
+
type: "system",
|
|
3821
|
+
extra: {
|
|
3822
|
+
requestId,
|
|
3823
|
+
request,
|
|
3824
|
+
response
|
|
3825
|
+
}
|
|
3826
|
+
});
|
|
3320
3827
|
else {
|
|
3321
3828
|
if (response.success) this.cachedOrder.set(storageKey, sentOrder);
|
|
3322
3829
|
notify(() => cache.set(request, {
|
|
@@ -4669,6 +5176,7 @@ var Client = class {
|
|
|
4669
5176
|
});
|
|
4670
5177
|
this.requestManager.abortAll();
|
|
4671
5178
|
this.requestManager.abortControllers.clear();
|
|
5179
|
+
resetOptimisticState(this);
|
|
4672
5180
|
this.fetchDispatcher.clear();
|
|
4673
5181
|
this.submitDispatcher.clear();
|
|
4674
5182
|
this.cache.clear();
|
|
@@ -5166,6 +5674,6 @@ var fetchInfinite = async (request, options) => {
|
|
|
5166
5674
|
return result;
|
|
5167
5675
|
};
|
|
5168
5676
|
//#endregion
|
|
5169
|
-
export { AbortError, Adapter, AppEvents, AppManager, Cache, Client, DeletedError, Dispatcher, DispatcherMode, EventEmitter, HttpAdapter, HttpMethods, LoggerManager, Plugin, Request, RequestManager, RequestProcessingError, SAFE_HTTP_METHODS, Time, TimeoutError, UnexpectedError, appManagerInitialOptions, canRetryRequest, createClient, createConfiguration, createRequestHooks, createSdk, defaultMapper, defaultTimeout, fetchInfinite, getAbortByAbortKey, getAbortByIdKey, getAbortKey, getAdapter, getAdapterBindings, getAdapterHeaders, getAdapterOnError, getAdapterPayload, getAppManagerEvents, getCacheByKey, getCacheData, getCacheEvents, getCacheKey, getCachedPages, getDeleteByKey, getDeleteKey, getDispatcherChangeByKey, getDispatcherChangeKey, getDispatcherDrainedByKey, getDispatcherDrainedKey, getDispatcherEvents, getDispatcherRunningByKey, getDispatcherRunningKey, getDispatcherStatusByKey, getDispatcherStatusKey, getDownloadProgressByIdKey, getDownloadProgressByQueryKey, getDownloadProgressKey, getErrorMessage, getHasNextPage, getHasPreviousPage, getInitialPageParam, getInvalidateByKey, getInvalidateKey, getIsEqualTimestamp, getLoadingByCacheKey, getLoadingByIdKey, getLoadingByQueryKey, getLoadingKey, getNextPageParam, getPageItems, getPageRequest, getPageTotal, getPaginationMode, getPreviousPageParam, getProgressData, getProgressValue, getRemoveByIdKey, getRemoveByQueryKey, getRemoveKey, getRequestDeduplicatedByCacheKey, getRequestDeduplicatedByIdKey, getRequestDeduplicatedByQueryKey, getRequestDeduplicatedKey, getRequestDispatcher, getRequestEta, getRequestKey, getRequestManagerEvents, getRequestStarByQueryKey, getRequestStartByIdKey, getRequestStartKey, getRequestType, getResponseByCacheKey, getResponseByIdKey, getResponseHeaders, getResponseKey, getResponseStartByIdKey, getResponseStartByQueryKey, getResponseStartKey, getSimpleKey, getTime, getUniqueRequestId, getUploadProgressByIdKey, getUploadProgressByQueryKey, getUploadProgressKey, handleResponse, hasDocument, hasWindow, interceptRequest, interceptResponse, isNavigatorOnline, isPlainObject, logLevelOrder, logger, loggerColors, loggerStyles, mapResponseForSend, mocker, onDocumentEvent, onWindowEvent, parseErrorResponse, parseResponse, replaceEqualDeep, resolveClientMode, runResponseMapper, runUserCode, scopeKey, sendRequest, stringifyDefaultOptions, stringifyKey, stringifyQueryParams, stringifyValue, throwOutsideLifecycle, xhrExtra };
|
|
5677
|
+
export { AbortError, Adapter, AppEvents, AppManager, Cache, Client, DeletedError, Dispatcher, DispatcherMode, EventEmitter, HttpAdapter, HttpMethods, LoggerManager, OptimisticOperation, Plugin, Request, RequestManager, RequestProcessingError, SAFE_HTTP_METHODS, Time, TimeoutError, UnexpectedError, appManagerInitialOptions, applyOptimistic, canRetryRequest, createClient, createConfiguration, createRequestHooks, createSdk, defaultMapper, defaultTimeout, fetchInfinite, getAbortByAbortKey, getAbortByIdKey, getAbortKey, getAdapter, getAdapterBindings, getAdapterHeaders, getAdapterOnError, getAdapterPayload, getAppManagerEvents, getCacheByKey, getCacheData, getCacheEvents, getCacheKey, getCachedPages, getDeleteByKey, getDeleteKey, getDispatcherChangeByKey, getDispatcherChangeKey, getDispatcherDrainedByKey, getDispatcherDrainedKey, getDispatcherEvents, getDispatcherRunningByKey, getDispatcherRunningKey, getDispatcherStatusByKey, getDispatcherStatusKey, getDownloadProgressByIdKey, getDownloadProgressByQueryKey, getDownloadProgressKey, getErrorMessage, getHasNextPage, getHasPreviousPage, getInitialPageParam, getInvalidateByKey, getInvalidateKey, getIsEqualTimestamp, getLoadingByCacheKey, getLoadingByIdKey, getLoadingByQueryKey, getLoadingKey, getNextPageParam, getOptimisticResult, getPageItems, getPageRequest, getPageTotal, getPaginationMode, getPreviousPageParam, getProgressData, getProgressValue, getRemoveByIdKey, getRemoveByQueryKey, getRemoveKey, getRequestDeduplicatedByCacheKey, getRequestDeduplicatedByIdKey, getRequestDeduplicatedByQueryKey, getRequestDeduplicatedKey, getRequestDispatcher, getRequestEta, getRequestKey, getRequestManagerEvents, getRequestStarByQueryKey, getRequestStartByIdKey, getRequestStartKey, getRequestType, getResponseByCacheKey, getResponseByIdKey, getResponseHeaders, getResponseKey, getResponseStartByIdKey, getResponseStartByQueryKey, getResponseStartKey, getSimpleKey, getTime, getUniqueRequestId, getUploadProgressByIdKey, getUploadProgressByQueryKey, getUploadProgressKey, handleResponse, hasDocument, hasWindow, incrementField, incrementItems, insertItem, interceptRequest, interceptResponse, isNavigatorOnline, isOptimisticMatch, isPlainObject, isStaleOptimisticResponse, logLevelOrder, logger, loggerColors, loggerStyles, mapResponseForSend, mocker, onDocumentEvent, onWindowEvent, optimistic, parseErrorResponse, parseResponse, patchItems, removeItems, replaceEqualDeep, resetOptimisticState, resolveClientMode, runResponseMapper, runUserCode, scopeKey, sendRequest, settleOptimistic, stringifyDefaultOptions, stringifyKey, stringifyQueryParams, stringifyValue, throwOutsideLifecycle, updateListField, xhrExtra };
|
|
5170
5678
|
|
|
5171
5679
|
//# sourceMappingURL=index.mjs.map
|