@choksheak/react-utils 0.4.7 → 0.4.8
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/NoSSR.cjs +5 -2
- package/{NoSSR.mjs → NoSSR.js} +4 -1
- package/NoSSR.min.cjs +14 -1
- package/NoSSR.min.cjs.map +1 -1
- package/NoSSR.min.js +15 -0
- package/{NoSSR.min.mjs.map → NoSSR.min.js.map} +1 -1
- package/chunk-4YV72T4D.min.js +105 -0
- package/{storage.min.mjs.map → chunk-4YV72T4D.min.js.map} +1 -1
- package/chunk-5PDGU37E.cjs +104 -0
- package/{storage.mjs → chunk-7CPBZFDV.js} +5 -3
- package/{stringify.mjs → chunk-7XC6EVMX.js} +2 -0
- package/chunk-AXDXFCZV.min.js +35 -0
- package/{stringify.min.mjs.map → chunk-AXDXFCZV.min.js.map} +1 -1
- package/chunk-C6X4GPZ4.min.cjs +596 -0
- package/chunk-C6X4GPZ4.min.cjs.map +1 -0
- package/{sharedState.mjs → chunk-CIDQGOPA.js} +23 -8
- package/chunk-CYTO5EZE.cjs +34 -0
- package/chunk-HFIQE4XZ.cjs +595 -0
- package/chunk-IS3BZTWE.cjs +35 -0
- package/chunk-JYZY2SHD.min.js +596 -0
- package/chunk-JYZY2SHD.min.js.map +1 -0
- package/chunk-K2L3OVGY.min.cjs +18 -0
- package/chunk-K2L3OVGY.min.cjs.map +1 -0
- package/chunk-KGDXU6Q2.min.cjs +222 -0
- package/chunk-KGDXU6Q2.min.cjs.map +1 -0
- package/chunk-MNWSPF5J.min.js +18 -0
- package/{useDeepMemo.min.mjs.map → chunk-MNWSPF5J.min.js.map} +1 -1
- package/chunk-P2E73RBM.min.cjs +35 -0
- package/chunk-P2E73RBM.min.cjs.map +1 -0
- package/chunk-PCGGKBOL.min.js +222 -0
- package/chunk-PCGGKBOL.min.js.map +1 -0
- package/chunk-PHITDXZT.min.js +36 -0
- package/chunk-PHITDXZT.min.js.map +1 -0
- package/{sharedQuery.mjs → chunk-RFKUMDNU.js} +17 -6
- package/chunk-RRQBFF4W.min.cjs +105 -0
- package/chunk-RRQBFF4W.min.cjs.map +1 -0
- package/chunk-TST6JKQ5.min.cjs +36 -0
- package/chunk-TST6JKQ5.min.cjs.map +1 -0
- package/chunk-U67V476Y.js +35 -0
- package/chunk-UNDIVFP5.cjs +221 -0
- package/chunk-WXLUEDBO.cjs +17 -0
- package/{useDeepMemo.mjs → chunk-YTXGK6BR.js} +2 -0
- package/dist-4BDJ7HYS.min.js +546 -0
- package/dist-4BDJ7HYS.min.js.map +1 -0
- package/dist-HKOCAKHU.min.cjs +546 -0
- package/dist-HKOCAKHU.min.cjs.map +1 -0
- package/dist-RQU6CWRG.js +545 -0
- package/dist-UKP7SPWZ.cjs +545 -0
- package/index.cjs +43 -5
- package/index.d.cts +2 -2
- package/index.d.ts +2 -2
- package/index.js +43 -0
- package/index.min.cjs +43 -1
- package/index.min.cjs.map +1 -1
- package/index.min.js +44 -0
- package/index.min.js.map +1 -0
- package/magic-string.es-2AQNCEBL.min.js +1309 -0
- package/magic-string.es-2AQNCEBL.min.js.map +1 -0
- package/magic-string.es-HC5PDAU3.cjs +1308 -0
- package/magic-string.es-KDMUXKGI.js +1308 -0
- package/magic-string.es-XJ27RPMN.min.cjs +1309 -0
- package/magic-string.es-XJ27RPMN.min.cjs.map +1 -0
- package/package.json +48 -8
- package/sharedQuery.cjs +8 -575
- package/sharedQuery.d.cts +7 -92
- package/sharedQuery.d.ts +7 -92
- package/sharedQuery.js +17 -0
- package/sharedQuery.min.cjs +17 -1
- package/sharedQuery.min.cjs.map +1 -1
- package/sharedQuery.min.js +18 -0
- package/sharedQuery.min.js.map +1 -0
- package/sharedState.cjs +11 -199
- package/sharedState.d.cts +12 -57
- package/sharedState.d.ts +12 -57
- package/sharedState.js +18 -0
- package/sharedState.min.cjs +18 -1
- package/sharedState.min.cjs.map +1 -1
- package/sharedState.min.js +19 -0
- package/sharedState.min.js.map +1 -0
- package/storage.cjs +7 -98
- package/storage.js +11 -0
- package/storage.min.cjs +11 -1
- package/storage.min.cjs.map +1 -1
- package/storage.min.js +12 -0
- package/storage.min.js.map +1 -0
- package/stringify.cjs +5 -30
- package/stringify.js +7 -0
- package/stringify.min.cjs +7 -1
- package/stringify.min.cjs.map +1 -1
- package/stringify.min.js +8 -0
- package/stringify.min.js.map +1 -0
- package/useDeepMemo.cjs +5 -13
- package/useDeepMemo.js +7 -0
- package/useDeepMemo.min.cjs +7 -1
- package/useDeepMemo.min.cjs.map +1 -1
- package/useDeepMemo.min.js +8 -0
- package/useDeepMemo.min.js.map +1 -0
- package/NoSSR.min.mjs +0 -2
- package/index.min.mjs +0 -2
- package/index.min.mjs.map +0 -1
- package/index.mjs +0 -5
- package/sharedQuery.min.mjs +0 -2
- package/sharedQuery.min.mjs.map +0 -1
- package/sharedState.min.mjs +0 -2
- package/sharedState.min.mjs.map +0 -1
- package/storage.min.mjs +0 -2
- package/stringify.min.mjs +0 -2
- package/useDeepMemo.min.mjs +0 -2
|
@@ -0,0 +1,595 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
var _chunkUNDIVFP5cjs = require('./chunk-UNDIVFP5.cjs');
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
var _chunkCYTO5EZEcjs = require('./chunk-CYTO5EZE.cjs');
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
var _chunkWXLUEDBOcjs = require('./chunk-WXLUEDBO.cjs');
|
|
11
|
+
|
|
12
|
+
// src/sharedQuery.ts
|
|
13
|
+
var _http = require('@choksheak/ts-utils/http');
|
|
14
|
+
var _nonNil = require('@choksheak/ts-utils/nonNil');
|
|
15
|
+
var _objectsizeof = require('object-sizeof'); var _objectsizeof2 = _interopRequireDefault(_objectsizeof);
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
var _react = require('react');
|
|
23
|
+
var _xxhashjs = require('xxhashjs'); var _xxhashjs2 = _interopRequireDefault(_xxhashjs);
|
|
24
|
+
var SharedQueryConfig = {
|
|
25
|
+
/** Refetch on every page load. */
|
|
26
|
+
staleMs: 0,
|
|
27
|
+
/** Keep in cache for a long time. */
|
|
28
|
+
expiryMs: 30 * 864e5,
|
|
29
|
+
/** Always refetch automatically if the data is stale. */
|
|
30
|
+
refetchOnStale: true,
|
|
31
|
+
/** No default persistence configured. */
|
|
32
|
+
persistTo: void 0,
|
|
33
|
+
/** 100 is not too large, but please tweak accordingly. */
|
|
34
|
+
maxSize: 100,
|
|
35
|
+
/** 100kb limit before discarding old records. */
|
|
36
|
+
maxBytes: 1e5,
|
|
37
|
+
/** Default to log to console. */
|
|
38
|
+
log: (...args) => console.log("[sharedQuery]", ...args)
|
|
39
|
+
};
|
|
40
|
+
function configureSharedQuery(config) {
|
|
41
|
+
Object.assign(SharedQueryConfig, config);
|
|
42
|
+
}
|
|
43
|
+
var moduleQueryRegistry = /* @__PURE__ */ new Map();
|
|
44
|
+
function getOrCreateQueryRegistry() {
|
|
45
|
+
if (typeof window !== "undefined") {
|
|
46
|
+
const g = window.globalThis;
|
|
47
|
+
return g.reactUtilsQueryRegistry ??= /* @__PURE__ */ new Map();
|
|
48
|
+
}
|
|
49
|
+
return moduleQueryRegistry;
|
|
50
|
+
}
|
|
51
|
+
function sharedQuery1(options) {
|
|
52
|
+
const registry = getOrCreateQueryRegistry();
|
|
53
|
+
const key = options.queryName || options.url;
|
|
54
|
+
const existing = registry.get(key);
|
|
55
|
+
if (existing) {
|
|
56
|
+
return existing;
|
|
57
|
+
}
|
|
58
|
+
const obj = sharedQuery2(options);
|
|
59
|
+
registry.set(key, obj);
|
|
60
|
+
return obj;
|
|
61
|
+
}
|
|
62
|
+
function sharedQuery2(options) {
|
|
63
|
+
const url = options.url || "";
|
|
64
|
+
const queryName = options.queryName || url;
|
|
65
|
+
if (!queryName) {
|
|
66
|
+
throw new Error(`Either queryName or url must be specified.`);
|
|
67
|
+
}
|
|
68
|
+
const inflightQueries = /* @__PURE__ */ new Map();
|
|
69
|
+
const mountedKeys = /* @__PURE__ */ new Map();
|
|
70
|
+
let queryFn;
|
|
71
|
+
if (options.queryFn) {
|
|
72
|
+
queryFn = options.queryFn;
|
|
73
|
+
} else if (url) {
|
|
74
|
+
const fetcher = _http.http.use(_http.retries.call(void 0, ));
|
|
75
|
+
queryFn = async (...args) => {
|
|
76
|
+
let params = "";
|
|
77
|
+
const firstArg = _optionalChain([args, 'optionalAccess', _ => _[0]]);
|
|
78
|
+
if (firstArg) {
|
|
79
|
+
if (typeof firstArg === "string") {
|
|
80
|
+
params = firstArg;
|
|
81
|
+
} else if (typeof firstArg === "object") {
|
|
82
|
+
const entries = [];
|
|
83
|
+
for (const [k, v] of Object.entries(firstArg)) {
|
|
84
|
+
if (v === void 0) continue;
|
|
85
|
+
if (Array.isArray(v)) {
|
|
86
|
+
for (const item of v) {
|
|
87
|
+
if (item === void 0) continue;
|
|
88
|
+
entries.push([k, String(item)]);
|
|
89
|
+
}
|
|
90
|
+
} else {
|
|
91
|
+
entries.push([k, String(v)]);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
params = new URLSearchParams(entries).toString();
|
|
95
|
+
}
|
|
96
|
+
if (params) {
|
|
97
|
+
if (url.includes("?")) {
|
|
98
|
+
params = "&" + params;
|
|
99
|
+
} else {
|
|
100
|
+
params = "?" + params;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const response = await fetcher.get(url + params);
|
|
105
|
+
return await response.json();
|
|
106
|
+
};
|
|
107
|
+
} else {
|
|
108
|
+
throw new Error(`Either queryFn or url must be specified`);
|
|
109
|
+
}
|
|
110
|
+
const refetchFn = options.refetchFn;
|
|
111
|
+
const staleMs = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _2 => _2.staleMs]), () => ( SharedQueryConfig.staleMs));
|
|
112
|
+
const expiryMs = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _3 => _3.expiryMs]), () => ( SharedQueryConfig.expiryMs));
|
|
113
|
+
const refetchOnStale = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _4 => _4.refetchOnStale]), () => ( SharedQueryConfig.refetchOnStale));
|
|
114
|
+
const store = options.store;
|
|
115
|
+
if (store) {
|
|
116
|
+
if ("persistTo" in store && store.isValid) {
|
|
117
|
+
const isValid = store.isValid;
|
|
118
|
+
options = {
|
|
119
|
+
...options,
|
|
120
|
+
store: {
|
|
121
|
+
...store,
|
|
122
|
+
isValid: (u) => {
|
|
123
|
+
if (!u || typeof u !== "object") {
|
|
124
|
+
return false;
|
|
125
|
+
}
|
|
126
|
+
for (const v of Object.values(u)) {
|
|
127
|
+
if (!v || typeof v !== "object" || !("data" in v) || !("dataUpdatedMs" in v) || !("lastUpdatedMs" in v) || typeof v.dataUpdatedMs !== "number" || typeof v.lastUpdatedMs !== "number" || !isValid(v.data)) {
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
} else {
|
|
137
|
+
const persistTo = _nullishCoalesce(options.persistTo, () => ( SharedQueryConfig.persistTo));
|
|
138
|
+
if (persistTo) {
|
|
139
|
+
options = {
|
|
140
|
+
...options,
|
|
141
|
+
store: {
|
|
142
|
+
persistTo,
|
|
143
|
+
key: queryName,
|
|
144
|
+
expiryMs
|
|
145
|
+
}
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
const maxSize = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _5 => _5.maxSize]), () => ( SharedQueryConfig.maxSize));
|
|
150
|
+
const maxBytes = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _6 => _6.maxBytes]), () => ( SharedQueryConfig.maxBytes));
|
|
151
|
+
const keepLastNonEmptyData = Boolean(_optionalChain([options, 'optionalAccess', _7 => _7.keepLastNonEmptyData]));
|
|
152
|
+
const log = _nullishCoalesce(_optionalChain([options, 'optionalAccess', _8 => _8.log]), () => ( SharedQueryConfig.log));
|
|
153
|
+
options.name = queryName;
|
|
154
|
+
const queryState = _chunkUNDIVFP5cjs.sharedState.call(void 0,
|
|
155
|
+
{},
|
|
156
|
+
// defaultValue
|
|
157
|
+
options
|
|
158
|
+
);
|
|
159
|
+
function isStale(dataUpdatedMs) {
|
|
160
|
+
if (staleMs === 0) return true;
|
|
161
|
+
const ageMs = Date.now() - dataUpdatedMs;
|
|
162
|
+
return ageMs > staleMs;
|
|
163
|
+
}
|
|
164
|
+
function isExpired(dataUpdatedMs) {
|
|
165
|
+
if (expiryMs === 0) return false;
|
|
166
|
+
const ageMs = Date.now() - dataUpdatedMs;
|
|
167
|
+
return ageMs > expiryMs;
|
|
168
|
+
}
|
|
169
|
+
function enforceSizeLimit() {
|
|
170
|
+
if (!maxSize && !maxBytes) {
|
|
171
|
+
return;
|
|
172
|
+
}
|
|
173
|
+
const oldState = queryState.getSnapshot();
|
|
174
|
+
const oldSize = Object.keys(oldState).length;
|
|
175
|
+
if (oldSize <= 1) {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const oldByteSize = _objectsizeof2.default.call(void 0, oldState);
|
|
179
|
+
let numToCut = maxSize ? oldSize - maxSize : 0;
|
|
180
|
+
let bytesToCut = maxBytes ? oldByteSize - maxBytes : 0;
|
|
181
|
+
if (numToCut <= 0 && bytesToCut <= 0) {
|
|
182
|
+
log(
|
|
183
|
+
`No need to trim data for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`
|
|
184
|
+
);
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
log(
|
|
188
|
+
`Need to trim ${queryName}: numToCut=${numToCut}, bytesToCut=${bytesToCut}`
|
|
189
|
+
);
|
|
190
|
+
const newState = { ...oldState };
|
|
191
|
+
let needUpdate = false;
|
|
192
|
+
const deleteKeyIfNotMounted = (key, expired) => {
|
|
193
|
+
if (mountedKeys.has(key)) {
|
|
194
|
+
log(`Cannot clean up ${key} as it is mounted`);
|
|
195
|
+
return;
|
|
196
|
+
}
|
|
197
|
+
const byteSize = _objectsizeof2.default.call(void 0, key) + _objectsizeof2.default.call(void 0, newState[key]);
|
|
198
|
+
log(
|
|
199
|
+
`Cleaning up unmounted${expired ? ", expired" : ""} ${key} (byteSize=${byteSize.toLocaleString()})`
|
|
200
|
+
);
|
|
201
|
+
numToCut--;
|
|
202
|
+
bytesToCut -= byteSize;
|
|
203
|
+
delete newState[key];
|
|
204
|
+
needUpdate = true;
|
|
205
|
+
};
|
|
206
|
+
let entriesByTimeAscending = Object.entries(newState).sort(
|
|
207
|
+
(entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs
|
|
208
|
+
);
|
|
209
|
+
for (const [key] of entriesByTimeAscending) {
|
|
210
|
+
if (!isExpired(newState[key].lastUpdatedMs)) {
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
deleteKeyIfNotMounted(key, true);
|
|
214
|
+
}
|
|
215
|
+
if (numToCut > 0 || bytesToCut > 0) {
|
|
216
|
+
if (needUpdate) {
|
|
217
|
+
entriesByTimeAscending = Object.entries(newState).sort(
|
|
218
|
+
(entry1, entry2) => entry1[1].lastUpdatedMs - entry2[1].lastUpdatedMs
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
for (const [key] of entriesByTimeAscending) {
|
|
222
|
+
deleteKeyIfNotMounted(key, false);
|
|
223
|
+
if (numToCut <= 0 && bytesToCut <= 0) {
|
|
224
|
+
break;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
if (!needUpdate) {
|
|
229
|
+
log(
|
|
230
|
+
`No trimmable entries found for ${queryName}: size=${oldSize} (limit=${maxSize}), byteSize=${oldByteSize.toLocaleString()} (limit=${maxBytes.toLocaleString()})`
|
|
231
|
+
);
|
|
232
|
+
return;
|
|
233
|
+
}
|
|
234
|
+
queryState.setValue(newState);
|
|
235
|
+
log(
|
|
236
|
+
`Trimmed data for ${queryName}: size=[${oldSize} -> ${Object.keys(newState).length}] (limit=${maxSize}), byteSize=[${oldByteSize.toLocaleString()} -> ${_objectsizeof2.default.call(void 0, newState).toLocaleString()}] (limit=${maxBytes.toLocaleString()})`
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
function setData(queryKey, data, dataUpdatedMs = Date.now()) {
|
|
240
|
+
const entry = {
|
|
241
|
+
lastUpdatedMs: Date.now(),
|
|
242
|
+
loading: false,
|
|
243
|
+
data,
|
|
244
|
+
dataUpdatedMs
|
|
245
|
+
};
|
|
246
|
+
queryState.setValue((prev) => ({ ...prev, [queryKey]: entry }));
|
|
247
|
+
enforceSizeLimit();
|
|
248
|
+
}
|
|
249
|
+
async function startFetching(queryKey, queryType, args) {
|
|
250
|
+
log(`Start fetching ${queryKey}, queryType=${queryType}`);
|
|
251
|
+
try {
|
|
252
|
+
const data = await (queryType === "refetch" && refetchFn ? refetchFn(...args) : queryFn(...args));
|
|
253
|
+
log(`Successfully fetched ${queryKey}`);
|
|
254
|
+
setData(queryKey, data, Date.now());
|
|
255
|
+
return data;
|
|
256
|
+
} catch (e) {
|
|
257
|
+
log(`Failed to fetch ${queryKey} for queryType=${queryType}: ${e}`);
|
|
258
|
+
throw e;
|
|
259
|
+
} finally {
|
|
260
|
+
inflightQueries.delete(queryKey);
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
function dedupedFetch(queryKey, queryType, ...args) {
|
|
264
|
+
const inflightQuery = inflightQueries.get(queryKey);
|
|
265
|
+
if (inflightQuery) {
|
|
266
|
+
log(
|
|
267
|
+
`Deduplicating inflight fetch for ${queryKey}, queryType=${queryType}`
|
|
268
|
+
);
|
|
269
|
+
return inflightQuery.promise;
|
|
270
|
+
}
|
|
271
|
+
const promise = startFetching(queryKey, queryType, args);
|
|
272
|
+
const abortController = new AbortController();
|
|
273
|
+
inflightQueries.set(queryKey, { promise, abortController });
|
|
274
|
+
return promise;
|
|
275
|
+
}
|
|
276
|
+
const obj = {
|
|
277
|
+
queryName,
|
|
278
|
+
queryFn,
|
|
279
|
+
refetchFn,
|
|
280
|
+
expiryMs,
|
|
281
|
+
staleMs,
|
|
282
|
+
refetchOnStale,
|
|
283
|
+
maxSize,
|
|
284
|
+
maxBytes,
|
|
285
|
+
keepLastNonEmptyData,
|
|
286
|
+
log,
|
|
287
|
+
queryState,
|
|
288
|
+
/** Returns a key to identify requests based on the given args. */
|
|
289
|
+
getQueryKey(args) {
|
|
290
|
+
let s = _chunkCYTO5EZEcjs.stringifyDeterministicForKeys.call(void 0, args);
|
|
291
|
+
if (s.length > 30) {
|
|
292
|
+
s = _xxhashjs2.default.h32(s, 39406).toString(16).slice(2);
|
|
293
|
+
}
|
|
294
|
+
return queryName + ":" + s;
|
|
295
|
+
},
|
|
296
|
+
/**
|
|
297
|
+
* Get the AbortController to abort the inflight query (if any).
|
|
298
|
+
*
|
|
299
|
+
* Note that once you get the controller, you can also get the signal easily
|
|
300
|
+
* using `controller.signal`. So if you need both the controller and the
|
|
301
|
+
* signal, just use this function.
|
|
302
|
+
*/
|
|
303
|
+
getAbortController(args) {
|
|
304
|
+
const queryKey = obj.getQueryKey(args);
|
|
305
|
+
return obj.getAbortControllerByKey(queryKey);
|
|
306
|
+
},
|
|
307
|
+
getAbortControllerByKey(queryKey) {
|
|
308
|
+
return _nullishCoalesce(_optionalChain([inflightQueries, 'access', _9 => _9.get, 'call', _10 => _10(queryKey), 'optionalAccess', _11 => _11.abortController]), () => ( null));
|
|
309
|
+
},
|
|
310
|
+
/**
|
|
311
|
+
* Get the AbortSignal to check for query abortions.
|
|
312
|
+
*
|
|
313
|
+
* Example using fetch:
|
|
314
|
+
* ```
|
|
315
|
+
* const getUserQuery = sharedQuery({
|
|
316
|
+
* queryName: "getUser",
|
|
317
|
+
* queryFn: (userId: string) => {
|
|
318
|
+
* // Get the signal for this current execution.
|
|
319
|
+
* const signal = getUserQuery.getAbortSignal([userId]);
|
|
320
|
+
*
|
|
321
|
+
* // Pass the signal to fetch so that it can be aborted.
|
|
322
|
+
* const response = await fetch(`/users/${userId}`, { signal });
|
|
323
|
+
*
|
|
324
|
+
* // Check for errors.
|
|
325
|
+
* if (!response.ok) {
|
|
326
|
+
* throw new Error(response.statusText);
|
|
327
|
+
* }
|
|
328
|
+
*
|
|
329
|
+
* // Return the data.
|
|
330
|
+
* return await response.json();
|
|
331
|
+
* },
|
|
332
|
+
* });
|
|
333
|
+
* ```
|
|
334
|
+
*
|
|
335
|
+
* Example using `http.ts`:
|
|
336
|
+
* ```
|
|
337
|
+
* const getUserQuery = sharedQuery({
|
|
338
|
+
* queryName: "getUser",
|
|
339
|
+
* queryFn: (userId: string) => {
|
|
340
|
+
* // Get the signal for this current execution.
|
|
341
|
+
* const signal = getUserQuery.getAbortSignal([userId]);
|
|
342
|
+
*
|
|
343
|
+
* // Pass the signal to fetch so that it can be aborted.
|
|
344
|
+
* const response = await http.get(`/users/${userId}`, { signal });
|
|
345
|
+
* return await response.json();
|
|
346
|
+
* },
|
|
347
|
+
* });
|
|
348
|
+
* ```
|
|
349
|
+
*/
|
|
350
|
+
getAbortSignal(args) {
|
|
351
|
+
const queryKey = obj.getQueryKey(args);
|
|
352
|
+
return obj.getAbortSignalByKey(queryKey);
|
|
353
|
+
},
|
|
354
|
+
getAbortSignalByKey(queryKey) {
|
|
355
|
+
return _nullishCoalesce(_optionalChain([obj, 'access', _12 => _12.getAbortControllerByKey, 'call', _13 => _13(queryKey), 'optionalAccess', _14 => _14.signal]), () => ( null));
|
|
356
|
+
},
|
|
357
|
+
/** For cached data, we need to return the correct timestamps as well. */
|
|
358
|
+
async getCachedOrFetch(...args) {
|
|
359
|
+
const startMs = Date.now();
|
|
360
|
+
await queryState.readyPromise;
|
|
361
|
+
const waitedMs = Date.now() - startMs;
|
|
362
|
+
const queryKey = obj.getQueryKey(args);
|
|
363
|
+
const cached = _optionalChain([queryState, 'access', _15 => _15.getSnapshot, 'call', _16 => _16(), 'optionalAccess', _17 => _17[queryKey]]);
|
|
364
|
+
if (waitedMs) {
|
|
365
|
+
log(`${queryKey}: Waited for ${waitedMs}ms before data is ready`);
|
|
366
|
+
}
|
|
367
|
+
if (_optionalChain([cached, 'optionalAccess', _18 => _18.data]) && !isExpired(_nullishCoalesce(cached.dataUpdatedMs, () => ( 0)))) {
|
|
368
|
+
if (!isStale(_nullishCoalesce(cached.dataUpdatedMs, () => ( 0)))) {
|
|
369
|
+
log(`Return fresh data ${queryKey} from cache without fetching`);
|
|
370
|
+
return cached;
|
|
371
|
+
}
|
|
372
|
+
if (refetchOnStale) {
|
|
373
|
+
log(`refetchOnStale for ${queryKey}`);
|
|
374
|
+
void dedupedFetch(queryKey, "query", ...args);
|
|
375
|
+
}
|
|
376
|
+
log(`Returning stale data for ${queryKey}`);
|
|
377
|
+
return cached;
|
|
378
|
+
}
|
|
379
|
+
const data = await dedupedFetch(queryKey, "query", ...args);
|
|
380
|
+
const now = Date.now();
|
|
381
|
+
return {
|
|
382
|
+
// Don't keep old error.
|
|
383
|
+
lastUpdatedMs: now,
|
|
384
|
+
loading: false,
|
|
385
|
+
data,
|
|
386
|
+
dataUpdatedMs: now
|
|
387
|
+
};
|
|
388
|
+
},
|
|
389
|
+
/** Get the entire stored entry for a query key. */
|
|
390
|
+
getQueryValue(queryKey) {
|
|
391
|
+
return _optionalChain([queryState, 'access', _19 => _19.getSnapshot, 'call', _20 => _20(), 'optionalAccess', _21 => _21[queryKey]]);
|
|
392
|
+
},
|
|
393
|
+
/** Get the current stored data for a query key. */
|
|
394
|
+
getData(queryKey) {
|
|
395
|
+
const stateValue = _optionalChain([queryState, 'access', _22 => _22.getSnapshot, 'call', _23 => _23(), 'optionalAccess', _24 => _24[queryKey]]);
|
|
396
|
+
if (_optionalChain([stateValue, 'optionalAccess', _25 => _25.lastUpdatedMs])) {
|
|
397
|
+
if (isExpired(stateValue.lastUpdatedMs)) {
|
|
398
|
+
obj.deleteData(queryKey);
|
|
399
|
+
return void 0;
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
return _optionalChain([stateValue, 'optionalAccess', _26 => _26.data]);
|
|
403
|
+
},
|
|
404
|
+
/** Set the data directly if the user obtained it from somewhere else. */
|
|
405
|
+
setData,
|
|
406
|
+
/**
|
|
407
|
+
* Do a new fetch even when the data is already cached, but don't fetch if
|
|
408
|
+
* another fetch is already inflight.
|
|
409
|
+
*/
|
|
410
|
+
async updateFromSource(...args) {
|
|
411
|
+
const key = obj.getQueryKey(args);
|
|
412
|
+
return await dedupedFetch(key, "query", ...args);
|
|
413
|
+
},
|
|
414
|
+
/**
|
|
415
|
+
* Perform an explicit refetch. If `options.refetchFn` was not specified,
|
|
416
|
+
* then this would be identical to calling `obj.updateFromSource()`.
|
|
417
|
+
*/
|
|
418
|
+
async refetch(...args) {
|
|
419
|
+
const key = obj.getQueryKey(args);
|
|
420
|
+
return await dedupedFetch(key, "refetch", ...args);
|
|
421
|
+
},
|
|
422
|
+
/** Delete the cached data for one set of arguments. */
|
|
423
|
+
deleteData(queryKey) {
|
|
424
|
+
const record = queryState.getSnapshot();
|
|
425
|
+
const clone = { ...record };
|
|
426
|
+
delete clone[queryKey];
|
|
427
|
+
queryState.setValue(clone);
|
|
428
|
+
const inflight = inflightQueries.get(queryKey);
|
|
429
|
+
if (inflight) {
|
|
430
|
+
inflightQueries.delete(queryKey);
|
|
431
|
+
inflight.abortController.abort("Deleted");
|
|
432
|
+
}
|
|
433
|
+
},
|
|
434
|
+
/** Delete all currently cached data & all inflight promises. */
|
|
435
|
+
clear() {
|
|
436
|
+
queryState.delete();
|
|
437
|
+
for (const { abortController } of Array.from(inflightQueries.values())) {
|
|
438
|
+
abortController.abort("Cleared");
|
|
439
|
+
}
|
|
440
|
+
inflightQueries.clear();
|
|
441
|
+
},
|
|
442
|
+
/** Keep track of mounted keys. */
|
|
443
|
+
mount(queryKey) {
|
|
444
|
+
mountedKeys.set(queryKey, (_nullishCoalesce(mountedKeys.get(queryKey), () => ( 0))) + 1);
|
|
445
|
+
},
|
|
446
|
+
/** Clean up mounted keys. */
|
|
447
|
+
unmount(queryKey) {
|
|
448
|
+
const count = mountedKeys.get(queryKey);
|
|
449
|
+
if (count === 1) {
|
|
450
|
+
mountedKeys.delete(queryKey);
|
|
451
|
+
} else {
|
|
452
|
+
mountedKeys.set(queryKey, (_nullishCoalesce(count, () => ( 0))) - 1);
|
|
453
|
+
}
|
|
454
|
+
},
|
|
455
|
+
/**
|
|
456
|
+
* Discard the oldest entries if the size exceeds the limit. The last
|
|
457
|
+
* remaining record cannot be deleted no matter what the limit is.
|
|
458
|
+
*/
|
|
459
|
+
enforceSizeLimit
|
|
460
|
+
};
|
|
461
|
+
return obj;
|
|
462
|
+
}
|
|
463
|
+
function sharedQuery(options) {
|
|
464
|
+
return sharedQuery1(options);
|
|
465
|
+
}
|
|
466
|
+
var DEFAULT_QUERY_STATE_ENTRY = {
|
|
467
|
+
lastUpdatedMs: 0,
|
|
468
|
+
loading: true
|
|
469
|
+
};
|
|
470
|
+
function useSharedQuery(query, ...args) {
|
|
471
|
+
const stableArgs = _chunkWXLUEDBOcjs.useDeepMemo.call(void 0, args);
|
|
472
|
+
const [queryState, setQueryState] = _chunkUNDIVFP5cjs.useSharedState.call(void 0, query.queryState);
|
|
473
|
+
const isMounted = _react.useRef.call(void 0, true);
|
|
474
|
+
const queryKey = _react.useMemo.call(void 0,
|
|
475
|
+
() => query.getQueryKey(stableArgs),
|
|
476
|
+
[query, stableArgs]
|
|
477
|
+
);
|
|
478
|
+
const queryStateValue = _nullishCoalesce(queryState[queryKey], () => ( DEFAULT_QUERY_STATE_ENTRY));
|
|
479
|
+
const setQueryStateValue = _react.useCallback.call(void 0,
|
|
480
|
+
(next) => {
|
|
481
|
+
setQueryState((prev) => {
|
|
482
|
+
const clone = { ...prev };
|
|
483
|
+
clone[queryKey] = typeof next === "function" ? next(_nullishCoalesce(clone[queryKey], () => ( DEFAULT_QUERY_STATE_ENTRY))) : next;
|
|
484
|
+
return clone;
|
|
485
|
+
});
|
|
486
|
+
},
|
|
487
|
+
[queryKey, setQueryState]
|
|
488
|
+
);
|
|
489
|
+
const [lastNonEmptyData, setLastNonEmptyData] = _react.useState.call(void 0, );
|
|
490
|
+
_react.useEffect.call(void 0, () => {
|
|
491
|
+
if (query.keepLastNonEmptyData && queryStateValue.data !== void 0) {
|
|
492
|
+
setLastNonEmptyData(queryStateValue.data);
|
|
493
|
+
}
|
|
494
|
+
}, [query.keepLastNonEmptyData, queryStateValue.data]);
|
|
495
|
+
const executeQuery = _react.useCallback.call(void 0,
|
|
496
|
+
async (isRefetch) => {
|
|
497
|
+
query.log(
|
|
498
|
+
`Begin executing shared query ${queryKey}, isRefetch=${isRefetch}`
|
|
499
|
+
);
|
|
500
|
+
if (!isMounted.current) return;
|
|
501
|
+
setQueryStateValue((prev) => ({
|
|
502
|
+
// Keep old data and error.
|
|
503
|
+
...prev,
|
|
504
|
+
lastUpdatedMs: Date.now(),
|
|
505
|
+
loading: true
|
|
506
|
+
}));
|
|
507
|
+
try {
|
|
508
|
+
let state;
|
|
509
|
+
if (isRefetch) {
|
|
510
|
+
const data = await query.refetch(...stableArgs);
|
|
511
|
+
const now = Date.now();
|
|
512
|
+
state = {
|
|
513
|
+
// Don't keep old error.
|
|
514
|
+
lastUpdatedMs: now,
|
|
515
|
+
loading: false,
|
|
516
|
+
data,
|
|
517
|
+
dataUpdatedMs: now
|
|
518
|
+
};
|
|
519
|
+
} else {
|
|
520
|
+
state = await query.getCachedOrFetch(...stableArgs);
|
|
521
|
+
}
|
|
522
|
+
if (!isMounted.current) return;
|
|
523
|
+
setQueryStateValue({ ...state, loading: false });
|
|
524
|
+
return state.data;
|
|
525
|
+
} catch (e) {
|
|
526
|
+
if (!isMounted.current) return;
|
|
527
|
+
const now = Date.now();
|
|
528
|
+
setQueryStateValue((prev) => ({
|
|
529
|
+
// Keep old data.
|
|
530
|
+
...prev,
|
|
531
|
+
lastUpdatedMs: now,
|
|
532
|
+
loading: false,
|
|
533
|
+
error: e,
|
|
534
|
+
errorUpdatedMs: now
|
|
535
|
+
}));
|
|
536
|
+
}
|
|
537
|
+
},
|
|
538
|
+
[query, queryKey, setQueryStateValue, stableArgs]
|
|
539
|
+
);
|
|
540
|
+
_react.useEffect.call(void 0, () => {
|
|
541
|
+
isMounted.current = true;
|
|
542
|
+
query.mount(queryKey);
|
|
543
|
+
void executeQuery(false);
|
|
544
|
+
return () => {
|
|
545
|
+
isMounted.current = false;
|
|
546
|
+
query.unmount(queryKey);
|
|
547
|
+
};
|
|
548
|
+
}, [executeQuery, query, queryKey]);
|
|
549
|
+
return _react.useMemo.call(void 0, () => {
|
|
550
|
+
return {
|
|
551
|
+
...queryStateValue,
|
|
552
|
+
// Fill with lastNonEmptyData when data is undefined.
|
|
553
|
+
data: queryStateValue.data !== void 0 ? queryStateValue.data : lastNonEmptyData,
|
|
554
|
+
latestData: queryStateValue.data,
|
|
555
|
+
// This works only if the user-given queryFn supports abort. If not,
|
|
556
|
+
// this function doesn't do anything, since we don't have any means to
|
|
557
|
+
// abort the running queryFn.
|
|
558
|
+
abortCurrentQuery: (reason) => {
|
|
559
|
+
const controller = query.getAbortControllerByKey(queryKey);
|
|
560
|
+
_optionalChain([controller, 'optionalAccess', _27 => _27.abort, 'call', _28 => _28(reason)]);
|
|
561
|
+
return Boolean(controller);
|
|
562
|
+
},
|
|
563
|
+
getCachedOrFetch: async () => {
|
|
564
|
+
const data = await query.getCachedOrFetch(...stableArgs);
|
|
565
|
+
return _nonNil.nonNil.call(void 0,
|
|
566
|
+
data.data,
|
|
567
|
+
typeof data.error === "string" ? data.error : JSON.stringify(data.error)
|
|
568
|
+
);
|
|
569
|
+
},
|
|
570
|
+
refetch: () => {
|
|
571
|
+
return executeQuery(true);
|
|
572
|
+
},
|
|
573
|
+
setData: (data, dataUpdatedMs) => {
|
|
574
|
+
query.setData(queryKey, data, dataUpdatedMs);
|
|
575
|
+
},
|
|
576
|
+
deleteData: () => {
|
|
577
|
+
query.deleteData(queryKey);
|
|
578
|
+
}
|
|
579
|
+
};
|
|
580
|
+
}, [
|
|
581
|
+
executeQuery,
|
|
582
|
+
lastNonEmptyData,
|
|
583
|
+
query,
|
|
584
|
+
queryKey,
|
|
585
|
+
queryStateValue,
|
|
586
|
+
stableArgs
|
|
587
|
+
]);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
exports.SharedQueryConfig = SharedQueryConfig; exports.configureSharedQuery = configureSharedQuery; exports.sharedQuery = sharedQuery; exports.useSharedQuery = useSharedQuery;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
8
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
9
|
+
};
|
|
10
|
+
var __export = (target, all) => {
|
|
11
|
+
for (var name in all)
|
|
12
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
13
|
+
};
|
|
14
|
+
var __copyProps = (to, from, except, desc) => {
|
|
15
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
16
|
+
for (let key of __getOwnPropNames(from))
|
|
17
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
18
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
19
|
+
}
|
|
20
|
+
return to;
|
|
21
|
+
};
|
|
22
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
23
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
24
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
25
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
26
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
27
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
28
|
+
mod
|
|
29
|
+
));
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
exports.__commonJS = __commonJS; exports.__export = __export; exports.__toESM = __toESM;
|