| 1 | // src/query/core/apiState.ts
|
|---|
| 2 | var QueryStatus = /* @__PURE__ */ ((QueryStatus7) => {
|
|---|
| 3 | QueryStatus7["uninitialized"] = "uninitialized";
|
|---|
| 4 | QueryStatus7["pending"] = "pending";
|
|---|
| 5 | QueryStatus7["fulfilled"] = "fulfilled";
|
|---|
| 6 | QueryStatus7["rejected"] = "rejected";
|
|---|
| 7 | return QueryStatus7;
|
|---|
| 8 | })(QueryStatus || {});
|
|---|
| 9 | var STATUS_UNINITIALIZED = "uninitialized" /* uninitialized */;
|
|---|
| 10 | var STATUS_PENDING = "pending" /* pending */;
|
|---|
| 11 | var STATUS_FULFILLED = "fulfilled" /* fulfilled */;
|
|---|
| 12 | var STATUS_REJECTED = "rejected" /* rejected */;
|
|---|
| 13 | function getRequestStatusFlags(status) {
|
|---|
| 14 | return {
|
|---|
| 15 | status,
|
|---|
| 16 | isUninitialized: status === STATUS_UNINITIALIZED,
|
|---|
| 17 | isLoading: status === STATUS_PENDING,
|
|---|
| 18 | isSuccess: status === STATUS_FULFILLED,
|
|---|
| 19 | isError: status === STATUS_REJECTED
|
|---|
| 20 | };
|
|---|
| 21 | }
|
|---|
| 22 |
|
|---|
| 23 | // src/query/core/rtkImports.ts
|
|---|
| 24 | import { createAction, createSlice, createSelector, createAsyncThunk, combineReducers, createNextState, isAnyOf, isAllOf, isAction, isPending, isRejected, isFulfilled, isRejectedWithValue, isAsyncThunkAction, prepareAutoBatched, SHOULD_AUTOBATCH, isPlainObject, nanoid } from "@reduxjs/toolkit";
|
|---|
| 25 |
|
|---|
| 26 | // src/query/utils/copyWithStructuralSharing.ts
|
|---|
| 27 | var isPlainObject2 = isPlainObject;
|
|---|
| 28 | function copyWithStructuralSharing(oldObj, newObj) {
|
|---|
| 29 | if (oldObj === newObj || !(isPlainObject2(oldObj) && isPlainObject2(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {
|
|---|
| 30 | return newObj;
|
|---|
| 31 | }
|
|---|
| 32 | const newKeys = Object.keys(newObj);
|
|---|
| 33 | const oldKeys = Object.keys(oldObj);
|
|---|
| 34 | let isSameObject = newKeys.length === oldKeys.length;
|
|---|
| 35 | const mergeObj = Array.isArray(newObj) ? [] : {};
|
|---|
| 36 | for (const key of newKeys) {
|
|---|
| 37 | mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);
|
|---|
| 38 | if (isSameObject) isSameObject = oldObj[key] === mergeObj[key];
|
|---|
| 39 | }
|
|---|
| 40 | return isSameObject ? oldObj : mergeObj;
|
|---|
| 41 | }
|
|---|
| 42 |
|
|---|
| 43 | // src/query/utils/filterMap.ts
|
|---|
| 44 | function filterMap(array, predicate, mapper) {
|
|---|
| 45 | return array.reduce((acc, item, i) => {
|
|---|
| 46 | if (predicate(item, i)) {
|
|---|
| 47 | acc.push(mapper(item, i));
|
|---|
| 48 | }
|
|---|
| 49 | return acc;
|
|---|
| 50 | }, []).flat();
|
|---|
| 51 | }
|
|---|
| 52 |
|
|---|
| 53 | // src/query/utils/isAbsoluteUrl.ts
|
|---|
| 54 | function isAbsoluteUrl(url) {
|
|---|
| 55 | return new RegExp(`(^|:)//`).test(url);
|
|---|
| 56 | }
|
|---|
| 57 |
|
|---|
| 58 | // src/query/utils/isDocumentVisible.ts
|
|---|
| 59 | function isDocumentVisible() {
|
|---|
| 60 | if (typeof document === "undefined") {
|
|---|
| 61 | return true;
|
|---|
| 62 | }
|
|---|
| 63 | return document.visibilityState !== "hidden";
|
|---|
| 64 | }
|
|---|
| 65 |
|
|---|
| 66 | // src/query/utils/isNotNullish.ts
|
|---|
| 67 | function isNotNullish(v) {
|
|---|
| 68 | return v != null;
|
|---|
| 69 | }
|
|---|
| 70 | function filterNullishValues(map) {
|
|---|
| 71 | return [...map?.values() ?? []].filter(isNotNullish);
|
|---|
| 72 | }
|
|---|
| 73 |
|
|---|
| 74 | // src/query/utils/isOnline.ts
|
|---|
| 75 | function isOnline() {
|
|---|
| 76 | return typeof navigator === "undefined" ? true : navigator.onLine === void 0 ? true : navigator.onLine;
|
|---|
| 77 | }
|
|---|
| 78 |
|
|---|
| 79 | // src/query/utils/joinUrls.ts
|
|---|
| 80 | var withoutTrailingSlash = (url) => url.replace(/\/$/, "");
|
|---|
| 81 | var withoutLeadingSlash = (url) => url.replace(/^\//, "");
|
|---|
| 82 | function joinUrls(base, url) {
|
|---|
| 83 | if (!base) {
|
|---|
| 84 | return url;
|
|---|
| 85 | }
|
|---|
| 86 | if (!url) {
|
|---|
| 87 | return base;
|
|---|
| 88 | }
|
|---|
| 89 | if (isAbsoluteUrl(url)) {
|
|---|
| 90 | return url;
|
|---|
| 91 | }
|
|---|
| 92 | const delimiter = base.endsWith("/") || !url.startsWith("?") ? "/" : "";
|
|---|
| 93 | base = withoutTrailingSlash(base);
|
|---|
| 94 | url = withoutLeadingSlash(url);
|
|---|
| 95 | return `${base}${delimiter}${url}`;
|
|---|
| 96 | }
|
|---|
| 97 |
|
|---|
| 98 | // src/query/utils/getOrInsert.ts
|
|---|
| 99 | function getOrInsertComputed(map, key, compute) {
|
|---|
| 100 | if (map.has(key)) return map.get(key);
|
|---|
| 101 | return map.set(key, compute(key)).get(key);
|
|---|
| 102 | }
|
|---|
| 103 | var createNewMap = () => /* @__PURE__ */ new Map();
|
|---|
| 104 |
|
|---|
| 105 | // src/query/utils/signals.ts
|
|---|
| 106 | var timeoutSignal = (milliseconds) => {
|
|---|
| 107 | const abortController = new AbortController();
|
|---|
| 108 | setTimeout(() => {
|
|---|
| 109 | const message = "signal timed out";
|
|---|
| 110 | const name = "TimeoutError";
|
|---|
| 111 | abortController.abort(
|
|---|
| 112 | // some environments (React Native, Node) don't have DOMException
|
|---|
| 113 | typeof DOMException !== "undefined" ? new DOMException(message, name) : Object.assign(new Error(message), {
|
|---|
| 114 | name
|
|---|
| 115 | })
|
|---|
| 116 | );
|
|---|
| 117 | }, milliseconds);
|
|---|
| 118 | return abortController.signal;
|
|---|
| 119 | };
|
|---|
| 120 | var anySignal = (...signals) => {
|
|---|
| 121 | for (const signal of signals) if (signal.aborted) return AbortSignal.abort(signal.reason);
|
|---|
| 122 | const abortController = new AbortController();
|
|---|
| 123 | for (const signal of signals) {
|
|---|
| 124 | signal.addEventListener("abort", () => abortController.abort(signal.reason), {
|
|---|
| 125 | signal: abortController.signal,
|
|---|
| 126 | once: true
|
|---|
| 127 | });
|
|---|
| 128 | }
|
|---|
| 129 | return abortController.signal;
|
|---|
| 130 | };
|
|---|
| 131 |
|
|---|
| 132 | // src/query/fetchBaseQuery.ts
|
|---|
| 133 | var defaultFetchFn = (...args) => fetch(...args);
|
|---|
| 134 | var defaultValidateStatus = (response) => response.status >= 200 && response.status <= 299;
|
|---|
| 135 | var defaultIsJsonContentType = (headers) => (
|
|---|
| 136 | /*applicat*/
|
|---|
| 137 | /ion\/(vnd\.api\+)?json/.test(headers.get("content-type") || "")
|
|---|
| 138 | );
|
|---|
| 139 | function stripUndefined(obj) {
|
|---|
| 140 | if (!isPlainObject(obj)) {
|
|---|
| 141 | return obj;
|
|---|
| 142 | }
|
|---|
| 143 | const copy = {
|
|---|
| 144 | ...obj
|
|---|
| 145 | };
|
|---|
| 146 | for (const [k, v] of Object.entries(copy)) {
|
|---|
| 147 | if (v === void 0) delete copy[k];
|
|---|
| 148 | }
|
|---|
| 149 | return copy;
|
|---|
| 150 | }
|
|---|
| 151 | var isJsonifiable = (body) => typeof body === "object" && (isPlainObject(body) || Array.isArray(body) || typeof body.toJSON === "function");
|
|---|
| 152 | function fetchBaseQuery({
|
|---|
| 153 | baseUrl,
|
|---|
| 154 | prepareHeaders = (x) => x,
|
|---|
| 155 | fetchFn = defaultFetchFn,
|
|---|
| 156 | paramsSerializer,
|
|---|
| 157 | isJsonContentType = defaultIsJsonContentType,
|
|---|
| 158 | jsonContentType = "application/json",
|
|---|
| 159 | jsonReplacer,
|
|---|
| 160 | timeout: defaultTimeout,
|
|---|
| 161 | responseHandler: globalResponseHandler,
|
|---|
| 162 | validateStatus: globalValidateStatus,
|
|---|
| 163 | ...baseFetchOptions
|
|---|
| 164 | } = {}) {
|
|---|
| 165 | if (typeof fetch === "undefined" && fetchFn === defaultFetchFn) {
|
|---|
| 166 | console.warn("Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.");
|
|---|
| 167 | }
|
|---|
| 168 | return async (arg, api, extraOptions) => {
|
|---|
| 169 | const {
|
|---|
| 170 | getState,
|
|---|
| 171 | extra,
|
|---|
| 172 | endpoint,
|
|---|
| 173 | forced,
|
|---|
| 174 | type
|
|---|
| 175 | } = api;
|
|---|
| 176 | let meta;
|
|---|
| 177 | let {
|
|---|
| 178 | url,
|
|---|
| 179 | headers = new Headers(baseFetchOptions.headers),
|
|---|
| 180 | params = void 0,
|
|---|
| 181 | responseHandler = globalResponseHandler ?? "json",
|
|---|
| 182 | validateStatus = globalValidateStatus ?? defaultValidateStatus,
|
|---|
| 183 | timeout = defaultTimeout,
|
|---|
| 184 | ...rest
|
|---|
| 185 | } = typeof arg == "string" ? {
|
|---|
| 186 | url: arg
|
|---|
| 187 | } : arg;
|
|---|
| 188 | let config = {
|
|---|
| 189 | ...baseFetchOptions,
|
|---|
| 190 | signal: timeout ? anySignal(api.signal, timeoutSignal(timeout)) : api.signal,
|
|---|
| 191 | ...rest
|
|---|
| 192 | };
|
|---|
| 193 | headers = new Headers(stripUndefined(headers));
|
|---|
| 194 | config.headers = await prepareHeaders(headers, {
|
|---|
| 195 | getState,
|
|---|
| 196 | arg,
|
|---|
| 197 | extra,
|
|---|
| 198 | endpoint,
|
|---|
| 199 | forced,
|
|---|
| 200 | type,
|
|---|
| 201 | extraOptions
|
|---|
| 202 | }) || headers;
|
|---|
| 203 | const bodyIsJsonifiable = isJsonifiable(config.body);
|
|---|
| 204 | if (config.body != null && !bodyIsJsonifiable && typeof config.body !== "string") {
|
|---|
| 205 | config.headers.delete("content-type");
|
|---|
| 206 | }
|
|---|
| 207 | if (!config.headers.has("content-type") && bodyIsJsonifiable) {
|
|---|
| 208 | config.headers.set("content-type", jsonContentType);
|
|---|
| 209 | }
|
|---|
| 210 | if (bodyIsJsonifiable && isJsonContentType(config.headers)) {
|
|---|
| 211 | config.body = JSON.stringify(config.body, jsonReplacer);
|
|---|
| 212 | }
|
|---|
| 213 | if (!config.headers.has("accept")) {
|
|---|
| 214 | if (responseHandler === "json") {
|
|---|
| 215 | config.headers.set("accept", "application/json");
|
|---|
| 216 | } else if (responseHandler === "text") {
|
|---|
| 217 | config.headers.set("accept", "text/plain, text/html, */*");
|
|---|
| 218 | }
|
|---|
| 219 | }
|
|---|
| 220 | if (params) {
|
|---|
| 221 | const divider = ~url.indexOf("?") ? "&" : "?";
|
|---|
| 222 | const query = paramsSerializer ? paramsSerializer(params) : new URLSearchParams(stripUndefined(params));
|
|---|
| 223 | url += divider + query;
|
|---|
| 224 | }
|
|---|
| 225 | url = joinUrls(baseUrl, url);
|
|---|
| 226 | const request = new Request(url, config);
|
|---|
| 227 | const requestClone = new Request(url, config);
|
|---|
| 228 | meta = {
|
|---|
| 229 | request: requestClone
|
|---|
| 230 | };
|
|---|
| 231 | let response;
|
|---|
| 232 | try {
|
|---|
| 233 | response = await fetchFn(request);
|
|---|
| 234 | } catch (e) {
|
|---|
| 235 | return {
|
|---|
| 236 | error: {
|
|---|
| 237 | status: (e instanceof Error || typeof DOMException !== "undefined" && e instanceof DOMException) && e.name === "TimeoutError" ? "TIMEOUT_ERROR" : "FETCH_ERROR",
|
|---|
| 238 | error: String(e)
|
|---|
| 239 | },
|
|---|
| 240 | meta
|
|---|
| 241 | };
|
|---|
| 242 | }
|
|---|
| 243 | const responseClone = response.clone();
|
|---|
| 244 | meta.response = responseClone;
|
|---|
| 245 | let resultData;
|
|---|
| 246 | let responseText = "";
|
|---|
| 247 | try {
|
|---|
| 248 | let handleResponseError;
|
|---|
| 249 | await Promise.all([
|
|---|
| 250 | handleResponse(response, responseHandler).then((r) => resultData = r, (e) => handleResponseError = e),
|
|---|
| 251 | // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182
|
|---|
| 252 | // we *have* to "use up" both streams at the same time or they will stop running in node-fetch scenarios
|
|---|
| 253 | responseClone.text().then((r) => responseText = r, () => {
|
|---|
| 254 | })
|
|---|
| 255 | ]);
|
|---|
| 256 | if (handleResponseError) throw handleResponseError;
|
|---|
| 257 | } catch (e) {
|
|---|
| 258 | return {
|
|---|
| 259 | error: {
|
|---|
| 260 | status: "PARSING_ERROR",
|
|---|
| 261 | originalStatus: response.status,
|
|---|
| 262 | data: responseText,
|
|---|
| 263 | error: String(e)
|
|---|
| 264 | },
|
|---|
| 265 | meta
|
|---|
| 266 | };
|
|---|
| 267 | }
|
|---|
| 268 | return validateStatus(response, resultData) ? {
|
|---|
| 269 | data: resultData,
|
|---|
| 270 | meta
|
|---|
| 271 | } : {
|
|---|
| 272 | error: {
|
|---|
| 273 | status: response.status,
|
|---|
| 274 | data: resultData
|
|---|
| 275 | },
|
|---|
| 276 | meta
|
|---|
| 277 | };
|
|---|
| 278 | };
|
|---|
| 279 | async function handleResponse(response, responseHandler) {
|
|---|
| 280 | if (typeof responseHandler === "function") {
|
|---|
| 281 | return responseHandler(response);
|
|---|
| 282 | }
|
|---|
| 283 | if (responseHandler === "content-type") {
|
|---|
| 284 | responseHandler = isJsonContentType(response.headers) ? "json" : "text";
|
|---|
| 285 | }
|
|---|
| 286 | if (responseHandler === "json") {
|
|---|
| 287 | const text = await response.text();
|
|---|
| 288 | return text.length ? JSON.parse(text) : null;
|
|---|
| 289 | }
|
|---|
| 290 | return response.text();
|
|---|
| 291 | }
|
|---|
| 292 | }
|
|---|
| 293 |
|
|---|
| 294 | // src/query/HandledError.ts
|
|---|
| 295 | var HandledError = class {
|
|---|
| 296 | constructor(value, meta = void 0) {
|
|---|
| 297 | this.value = value;
|
|---|
| 298 | this.meta = meta;
|
|---|
| 299 | }
|
|---|
| 300 | };
|
|---|
| 301 |
|
|---|
| 302 | // src/query/retry.ts
|
|---|
| 303 | async function defaultBackoff(attempt = 0, maxRetries = 5, signal) {
|
|---|
| 304 | const attempts = Math.min(attempt, maxRetries);
|
|---|
| 305 | const timeout = ~~((Math.random() + 0.4) * (300 << attempts));
|
|---|
| 306 | await new Promise((resolve, reject) => {
|
|---|
| 307 | const timeoutId = setTimeout(() => resolve(), timeout);
|
|---|
| 308 | if (signal) {
|
|---|
| 309 | const abortHandler = () => {
|
|---|
| 310 | clearTimeout(timeoutId);
|
|---|
| 311 | reject(new Error("Aborted"));
|
|---|
| 312 | };
|
|---|
| 313 | if (signal.aborted) {
|
|---|
| 314 | clearTimeout(timeoutId);
|
|---|
| 315 | reject(new Error("Aborted"));
|
|---|
| 316 | } else {
|
|---|
| 317 | signal.addEventListener("abort", abortHandler, {
|
|---|
| 318 | once: true
|
|---|
| 319 | });
|
|---|
| 320 | }
|
|---|
| 321 | }
|
|---|
| 322 | });
|
|---|
| 323 | }
|
|---|
| 324 | function fail(error, meta) {
|
|---|
| 325 | throw Object.assign(new HandledError({
|
|---|
| 326 | error,
|
|---|
| 327 | meta
|
|---|
| 328 | }), {
|
|---|
| 329 | throwImmediately: true
|
|---|
| 330 | });
|
|---|
| 331 | }
|
|---|
| 332 | function failIfAborted(signal) {
|
|---|
| 333 | if (signal.aborted) {
|
|---|
| 334 | fail({
|
|---|
| 335 | status: "CUSTOM_ERROR",
|
|---|
| 336 | error: "Aborted"
|
|---|
| 337 | });
|
|---|
| 338 | }
|
|---|
| 339 | }
|
|---|
| 340 | var EMPTY_OPTIONS = {};
|
|---|
| 341 | var retryWithBackoff = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {
|
|---|
| 342 | const possibleMaxRetries = [5, (defaultOptions || EMPTY_OPTIONS).maxRetries, (extraOptions || EMPTY_OPTIONS).maxRetries].filter((x) => x !== void 0);
|
|---|
| 343 | const [maxRetries] = possibleMaxRetries.slice(-1);
|
|---|
| 344 | const defaultRetryCondition = (_, __, {
|
|---|
| 345 | attempt
|
|---|
| 346 | }) => attempt <= maxRetries;
|
|---|
| 347 | const options = {
|
|---|
| 348 | maxRetries,
|
|---|
| 349 | backoff: defaultBackoff,
|
|---|
| 350 | retryCondition: defaultRetryCondition,
|
|---|
| 351 | ...defaultOptions,
|
|---|
| 352 | ...extraOptions
|
|---|
| 353 | };
|
|---|
| 354 | let retry2 = 0;
|
|---|
| 355 | while (true) {
|
|---|
| 356 | failIfAborted(api.signal);
|
|---|
| 357 | try {
|
|---|
| 358 | const result = await baseQuery(args, api, extraOptions);
|
|---|
| 359 | if (result.error) {
|
|---|
| 360 | throw new HandledError(result);
|
|---|
| 361 | }
|
|---|
| 362 | return result;
|
|---|
| 363 | } catch (e) {
|
|---|
| 364 | retry2++;
|
|---|
| 365 | if (e.throwImmediately) {
|
|---|
| 366 | if (e instanceof HandledError) {
|
|---|
| 367 | return e.value;
|
|---|
| 368 | }
|
|---|
| 369 | throw e;
|
|---|
| 370 | }
|
|---|
| 371 | if (e instanceof HandledError) {
|
|---|
| 372 | if (!options.retryCondition(e.value.error, args, {
|
|---|
| 373 | attempt: retry2,
|
|---|
| 374 | baseQueryApi: api,
|
|---|
| 375 | extraOptions
|
|---|
| 376 | })) {
|
|---|
| 377 | return e.value;
|
|---|
| 378 | }
|
|---|
| 379 | } else {
|
|---|
| 380 | if (retry2 > options.maxRetries) {
|
|---|
| 381 | return {
|
|---|
| 382 | error: e
|
|---|
| 383 | };
|
|---|
| 384 | }
|
|---|
| 385 | }
|
|---|
| 386 | failIfAborted(api.signal);
|
|---|
| 387 | try {
|
|---|
| 388 | await options.backoff(retry2, options.maxRetries, api.signal);
|
|---|
| 389 | } catch (backoffError) {
|
|---|
| 390 | failIfAborted(api.signal);
|
|---|
| 391 | throw backoffError;
|
|---|
| 392 | }
|
|---|
| 393 | }
|
|---|
| 394 | }
|
|---|
| 395 | };
|
|---|
| 396 | var retry = /* @__PURE__ */ Object.assign(retryWithBackoff, {
|
|---|
| 397 | fail
|
|---|
| 398 | });
|
|---|
| 399 |
|
|---|
| 400 | // src/query/core/setupListeners.ts
|
|---|
| 401 | var INTERNAL_PREFIX = "__rtkq/";
|
|---|
| 402 | var ONLINE = "online";
|
|---|
| 403 | var OFFLINE = "offline";
|
|---|
| 404 | var FOCUS = "focus";
|
|---|
| 405 | var FOCUSED = "focused";
|
|---|
| 406 | var VISIBILITYCHANGE = "visibilitychange";
|
|---|
| 407 | var onFocus = /* @__PURE__ */ createAction(`${INTERNAL_PREFIX}${FOCUSED}`);
|
|---|
| 408 | var onFocusLost = /* @__PURE__ */ createAction(`${INTERNAL_PREFIX}un${FOCUSED}`);
|
|---|
| 409 | var onOnline = /* @__PURE__ */ createAction(`${INTERNAL_PREFIX}${ONLINE}`);
|
|---|
| 410 | var onOffline = /* @__PURE__ */ createAction(`${INTERNAL_PREFIX}${OFFLINE}`);
|
|---|
| 411 | var actions = {
|
|---|
| 412 | onFocus,
|
|---|
| 413 | onFocusLost,
|
|---|
| 414 | onOnline,
|
|---|
| 415 | onOffline
|
|---|
| 416 | };
|
|---|
| 417 | var initialized = false;
|
|---|
| 418 | function setupListeners(dispatch, customHandler) {
|
|---|
| 419 | function defaultHandler() {
|
|---|
| 420 | const [handleFocus, handleFocusLost, handleOnline, handleOffline] = [onFocus, onFocusLost, onOnline, onOffline].map((action) => () => dispatch(action()));
|
|---|
| 421 | const handleVisibilityChange = () => {
|
|---|
| 422 | if (window.document.visibilityState === "visible") {
|
|---|
| 423 | handleFocus();
|
|---|
| 424 | } else {
|
|---|
| 425 | handleFocusLost();
|
|---|
| 426 | }
|
|---|
| 427 | };
|
|---|
| 428 | let unsubscribe = () => {
|
|---|
| 429 | initialized = false;
|
|---|
| 430 | };
|
|---|
| 431 | if (!initialized) {
|
|---|
| 432 | if (typeof window !== "undefined" && window.addEventListener) {
|
|---|
| 433 | let updateListeners2 = function(add) {
|
|---|
| 434 | Object.entries(handlers).forEach(([event, handler]) => {
|
|---|
| 435 | if (add) {
|
|---|
| 436 | window.addEventListener(event, handler, false);
|
|---|
| 437 | } else {
|
|---|
| 438 | window.removeEventListener(event, handler);
|
|---|
| 439 | }
|
|---|
| 440 | });
|
|---|
| 441 | };
|
|---|
| 442 | var updateListeners = updateListeners2;
|
|---|
| 443 | const handlers = {
|
|---|
| 444 | [FOCUS]: handleFocus,
|
|---|
| 445 | [VISIBILITYCHANGE]: handleVisibilityChange,
|
|---|
| 446 | [ONLINE]: handleOnline,
|
|---|
| 447 | [OFFLINE]: handleOffline
|
|---|
| 448 | };
|
|---|
| 449 | updateListeners2(true);
|
|---|
| 450 | initialized = true;
|
|---|
| 451 | unsubscribe = () => {
|
|---|
| 452 | updateListeners2(false);
|
|---|
| 453 | initialized = false;
|
|---|
| 454 | };
|
|---|
| 455 | }
|
|---|
| 456 | }
|
|---|
| 457 | return unsubscribe;
|
|---|
| 458 | }
|
|---|
| 459 | return customHandler ? customHandler(dispatch, actions) : defaultHandler();
|
|---|
| 460 | }
|
|---|
| 461 |
|
|---|
| 462 | // src/query/endpointDefinitions.ts
|
|---|
| 463 | var ENDPOINT_QUERY = "query" /* query */;
|
|---|
| 464 | var ENDPOINT_MUTATION = "mutation" /* mutation */;
|
|---|
| 465 | var ENDPOINT_INFINITEQUERY = "infinitequery" /* infinitequery */;
|
|---|
| 466 | function isQueryDefinition(e) {
|
|---|
| 467 | return e.type === ENDPOINT_QUERY;
|
|---|
| 468 | }
|
|---|
| 469 | function isMutationDefinition(e) {
|
|---|
| 470 | return e.type === ENDPOINT_MUTATION;
|
|---|
| 471 | }
|
|---|
| 472 | function isInfiniteQueryDefinition(e) {
|
|---|
| 473 | return e.type === ENDPOINT_INFINITEQUERY;
|
|---|
| 474 | }
|
|---|
| 475 | function isAnyQueryDefinition(e) {
|
|---|
| 476 | return isQueryDefinition(e) || isInfiniteQueryDefinition(e);
|
|---|
| 477 | }
|
|---|
| 478 | function calculateProvidedBy(description, result, error, queryArg, meta, assertTagTypes) {
|
|---|
| 479 | const finalDescription = isFunction(description) ? description(result, error, queryArg, meta) : description;
|
|---|
| 480 | if (finalDescription) {
|
|---|
| 481 | return filterMap(finalDescription, isNotNullish, (tag) => assertTagTypes(expandTagDescription(tag)));
|
|---|
| 482 | }
|
|---|
| 483 | return [];
|
|---|
| 484 | }
|
|---|
| 485 | function isFunction(t) {
|
|---|
| 486 | return typeof t === "function";
|
|---|
| 487 | }
|
|---|
| 488 | function expandTagDescription(description) {
|
|---|
| 489 | return typeof description === "string" ? {
|
|---|
| 490 | type: description
|
|---|
| 491 | } : description;
|
|---|
| 492 | }
|
|---|
| 493 |
|
|---|
| 494 | // src/query/utils/immerImports.ts
|
|---|
| 495 | import { current, isDraft, applyPatches, original, isDraftable, produceWithPatches, enablePatches } from "immer";
|
|---|
| 496 |
|
|---|
| 497 | // src/query/core/buildInitiate.ts
|
|---|
| 498 | import { formatProdErrorMessage as _formatProdErrorMessage } from "@reduxjs/toolkit";
|
|---|
| 499 |
|
|---|
| 500 | // src/tsHelpers.ts
|
|---|
| 501 | function asSafePromise(promise, fallback) {
|
|---|
| 502 | return promise.catch(fallback);
|
|---|
| 503 | }
|
|---|
| 504 |
|
|---|
| 505 | // src/query/apiTypes.ts
|
|---|
| 506 | var getEndpointDefinition = (context, endpointName) => context.endpointDefinitions[endpointName];
|
|---|
| 507 |
|
|---|
| 508 | // src/query/core/buildInitiate.ts
|
|---|
| 509 | var forceQueryFnSymbol = Symbol("forceQueryFn");
|
|---|
| 510 | var isUpsertQuery = (arg) => typeof arg[forceQueryFnSymbol] === "function";
|
|---|
| 511 | function buildInitiate({
|
|---|
| 512 | serializeQueryArgs,
|
|---|
| 513 | queryThunk,
|
|---|
| 514 | infiniteQueryThunk,
|
|---|
| 515 | mutationThunk,
|
|---|
| 516 | api,
|
|---|
| 517 | context,
|
|---|
| 518 | getInternalState
|
|---|
| 519 | }) {
|
|---|
| 520 | const getRunningQueries = (dispatch) => getInternalState(dispatch)?.runningQueries;
|
|---|
| 521 | const getRunningMutations = (dispatch) => getInternalState(dispatch)?.runningMutations;
|
|---|
| 522 | const {
|
|---|
| 523 | unsubscribeQueryResult,
|
|---|
| 524 | removeMutationResult,
|
|---|
| 525 | updateSubscriptionOptions
|
|---|
| 526 | } = api.internalActions;
|
|---|
| 527 | return {
|
|---|
| 528 | buildInitiateQuery,
|
|---|
| 529 | buildInitiateInfiniteQuery,
|
|---|
| 530 | buildInitiateMutation,
|
|---|
| 531 | getRunningQueryThunk,
|
|---|
| 532 | getRunningMutationThunk,
|
|---|
| 533 | getRunningQueriesThunk,
|
|---|
| 534 | getRunningMutationsThunk
|
|---|
| 535 | };
|
|---|
| 536 | function getRunningQueryThunk(endpointName, queryArgs) {
|
|---|
| 537 | return (dispatch) => {
|
|---|
| 538 | const endpointDefinition = getEndpointDefinition(context, endpointName);
|
|---|
| 539 | const queryCacheKey = serializeQueryArgs({
|
|---|
| 540 | queryArgs,
|
|---|
| 541 | endpointDefinition,
|
|---|
| 542 | endpointName
|
|---|
| 543 | });
|
|---|
| 544 | return getRunningQueries(dispatch)?.get(queryCacheKey);
|
|---|
| 545 | };
|
|---|
| 546 | }
|
|---|
| 547 | function getRunningMutationThunk(_endpointName, fixedCacheKeyOrRequestId) {
|
|---|
| 548 | return (dispatch) => {
|
|---|
| 549 | return getRunningMutations(dispatch)?.get(fixedCacheKeyOrRequestId);
|
|---|
| 550 | };
|
|---|
| 551 | }
|
|---|
| 552 | function getRunningQueriesThunk() {
|
|---|
| 553 | return (dispatch) => filterNullishValues(getRunningQueries(dispatch));
|
|---|
| 554 | }
|
|---|
| 555 | function getRunningMutationsThunk() {
|
|---|
| 556 | return (dispatch) => filterNullishValues(getRunningMutations(dispatch));
|
|---|
| 557 | }
|
|---|
| 558 | function middlewareWarning(dispatch) {
|
|---|
| 559 | if (process.env.NODE_ENV !== "production") {
|
|---|
| 560 | if (middlewareWarning.triggered) return;
|
|---|
| 561 | const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());
|
|---|
| 562 | middlewareWarning.triggered = true;
|
|---|
| 563 | if (typeof returnedValue !== "object" || typeof returnedValue?.type === "string") {
|
|---|
| 564 | throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage(34) : `Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
|
|---|
| 565 | You must add the middleware for RTK-Query to function correctly!`);
|
|---|
| 566 | }
|
|---|
| 567 | }
|
|---|
| 568 | }
|
|---|
| 569 | function buildInitiateAnyQuery(endpointName, endpointDefinition) {
|
|---|
| 570 | const queryAction = (arg, {
|
|---|
| 571 | subscribe = true,
|
|---|
| 572 | forceRefetch,
|
|---|
| 573 | subscriptionOptions,
|
|---|
| 574 | [forceQueryFnSymbol]: forceQueryFn,
|
|---|
| 575 | ...rest
|
|---|
| 576 | } = {}) => (dispatch, getState) => {
|
|---|
| 577 | const queryCacheKey = serializeQueryArgs({
|
|---|
| 578 | queryArgs: arg,
|
|---|
| 579 | endpointDefinition,
|
|---|
| 580 | endpointName
|
|---|
| 581 | });
|
|---|
| 582 | let thunk;
|
|---|
| 583 | const commonThunkArgs = {
|
|---|
| 584 | ...rest,
|
|---|
| 585 | type: ENDPOINT_QUERY,
|
|---|
| 586 | subscribe,
|
|---|
| 587 | forceRefetch,
|
|---|
| 588 | subscriptionOptions,
|
|---|
| 589 | endpointName,
|
|---|
| 590 | originalArgs: arg,
|
|---|
| 591 | queryCacheKey,
|
|---|
| 592 | [forceQueryFnSymbol]: forceQueryFn
|
|---|
| 593 | };
|
|---|
| 594 | if (isQueryDefinition(endpointDefinition)) {
|
|---|
| 595 | thunk = queryThunk(commonThunkArgs);
|
|---|
| 596 | } else {
|
|---|
| 597 | const {
|
|---|
| 598 | direction,
|
|---|
| 599 | initialPageParam,
|
|---|
| 600 | refetchCachedPages
|
|---|
| 601 | } = rest;
|
|---|
| 602 | thunk = infiniteQueryThunk({
|
|---|
| 603 | ...commonThunkArgs,
|
|---|
| 604 | // Supply these even if undefined. This helps with a field existence
|
|---|
| 605 | // check over in `buildSlice.ts`
|
|---|
| 606 | direction,
|
|---|
| 607 | initialPageParam,
|
|---|
| 608 | refetchCachedPages
|
|---|
| 609 | });
|
|---|
| 610 | }
|
|---|
| 611 | const selector = api.endpoints[endpointName].select(arg);
|
|---|
| 612 | const thunkResult = dispatch(thunk);
|
|---|
| 613 | const stateAfter = selector(getState());
|
|---|
| 614 | middlewareWarning(dispatch);
|
|---|
| 615 | const {
|
|---|
| 616 | requestId,
|
|---|
| 617 | abort
|
|---|
| 618 | } = thunkResult;
|
|---|
| 619 | const skippedSynchronously = stateAfter.requestId !== requestId;
|
|---|
| 620 | const runningQuery = getRunningQueries(dispatch)?.get(queryCacheKey);
|
|---|
| 621 | const selectFromState = () => selector(getState());
|
|---|
| 622 | const statePromise = Object.assign(forceQueryFn ? (
|
|---|
| 623 | // a query has been forced (upsertQueryData)
|
|---|
| 624 | // -> we want to resolve it once data has been written with the data that will be written
|
|---|
| 625 | thunkResult.then(selectFromState)
|
|---|
| 626 | ) : skippedSynchronously && !runningQuery ? (
|
|---|
| 627 | // a query has been skipped due to a condition and we do not have any currently running query
|
|---|
| 628 | // -> we want to resolve it immediately with the current data
|
|---|
| 629 | Promise.resolve(stateAfter)
|
|---|
| 630 | ) : (
|
|---|
| 631 | // query just started or one is already in flight
|
|---|
| 632 | // -> wait for the running query, then resolve with data from after that
|
|---|
| 633 | Promise.all([runningQuery, thunkResult]).then(selectFromState)
|
|---|
| 634 | ), {
|
|---|
| 635 | arg,
|
|---|
| 636 | requestId,
|
|---|
| 637 | subscriptionOptions,
|
|---|
| 638 | queryCacheKey,
|
|---|
| 639 | abort,
|
|---|
| 640 | async unwrap() {
|
|---|
| 641 | const result = await statePromise;
|
|---|
| 642 | if (result.isError) {
|
|---|
| 643 | throw result.error;
|
|---|
| 644 | }
|
|---|
| 645 | return result.data;
|
|---|
| 646 | },
|
|---|
| 647 | refetch: (options) => dispatch(queryAction(arg, {
|
|---|
| 648 | subscribe: false,
|
|---|
| 649 | forceRefetch: true,
|
|---|
| 650 | ...options
|
|---|
| 651 | })),
|
|---|
| 652 | unsubscribe() {
|
|---|
| 653 | if (subscribe) dispatch(unsubscribeQueryResult({
|
|---|
| 654 | queryCacheKey,
|
|---|
| 655 | requestId
|
|---|
| 656 | }));
|
|---|
| 657 | },
|
|---|
| 658 | updateSubscriptionOptions(options) {
|
|---|
| 659 | statePromise.subscriptionOptions = options;
|
|---|
| 660 | dispatch(updateSubscriptionOptions({
|
|---|
| 661 | endpointName,
|
|---|
| 662 | requestId,
|
|---|
| 663 | queryCacheKey,
|
|---|
| 664 | options
|
|---|
| 665 | }));
|
|---|
| 666 | }
|
|---|
| 667 | });
|
|---|
| 668 | if (!runningQuery && !skippedSynchronously && !forceQueryFn) {
|
|---|
| 669 | const runningQueries = getRunningQueries(dispatch);
|
|---|
| 670 | runningQueries.set(queryCacheKey, statePromise);
|
|---|
| 671 | statePromise.then(() => {
|
|---|
| 672 | runningQueries.delete(queryCacheKey);
|
|---|
| 673 | });
|
|---|
| 674 | }
|
|---|
| 675 | return statePromise;
|
|---|
| 676 | };
|
|---|
| 677 | return queryAction;
|
|---|
| 678 | }
|
|---|
| 679 | function buildInitiateQuery(endpointName, endpointDefinition) {
|
|---|
| 680 | const queryAction = buildInitiateAnyQuery(endpointName, endpointDefinition);
|
|---|
| 681 | return queryAction;
|
|---|
| 682 | }
|
|---|
| 683 | function buildInitiateInfiniteQuery(endpointName, endpointDefinition) {
|
|---|
| 684 | const infiniteQueryAction = buildInitiateAnyQuery(endpointName, endpointDefinition);
|
|---|
| 685 | return infiniteQueryAction;
|
|---|
| 686 | }
|
|---|
| 687 | function buildInitiateMutation(endpointName) {
|
|---|
| 688 | return (arg, {
|
|---|
| 689 | track = true,
|
|---|
| 690 | fixedCacheKey
|
|---|
| 691 | } = {}) => (dispatch, getState) => {
|
|---|
| 692 | const thunk = mutationThunk({
|
|---|
| 693 | type: "mutation",
|
|---|
| 694 | endpointName,
|
|---|
| 695 | originalArgs: arg,
|
|---|
| 696 | track,
|
|---|
| 697 | fixedCacheKey
|
|---|
| 698 | });
|
|---|
| 699 | const thunkResult = dispatch(thunk);
|
|---|
| 700 | middlewareWarning(dispatch);
|
|---|
| 701 | const {
|
|---|
| 702 | requestId,
|
|---|
| 703 | abort,
|
|---|
| 704 | unwrap
|
|---|
| 705 | } = thunkResult;
|
|---|
| 706 | const returnValuePromise = asSafePromise(thunkResult.unwrap().then((data) => ({
|
|---|
| 707 | data
|
|---|
| 708 | })), (error) => ({
|
|---|
| 709 | error
|
|---|
| 710 | }));
|
|---|
| 711 | const reset = () => {
|
|---|
| 712 | dispatch(removeMutationResult({
|
|---|
| 713 | requestId,
|
|---|
| 714 | fixedCacheKey
|
|---|
| 715 | }));
|
|---|
| 716 | };
|
|---|
| 717 | const ret = Object.assign(returnValuePromise, {
|
|---|
| 718 | arg: thunkResult.arg,
|
|---|
| 719 | requestId,
|
|---|
| 720 | abort,
|
|---|
| 721 | unwrap,
|
|---|
| 722 | reset
|
|---|
| 723 | });
|
|---|
| 724 | const runningMutations = getRunningMutations(dispatch);
|
|---|
| 725 | runningMutations.set(requestId, ret);
|
|---|
| 726 | ret.then(() => {
|
|---|
| 727 | runningMutations.delete(requestId);
|
|---|
| 728 | });
|
|---|
| 729 | if (fixedCacheKey) {
|
|---|
| 730 | runningMutations.set(fixedCacheKey, ret);
|
|---|
| 731 | ret.then(() => {
|
|---|
| 732 | if (runningMutations.get(fixedCacheKey) === ret) {
|
|---|
| 733 | runningMutations.delete(fixedCacheKey);
|
|---|
| 734 | }
|
|---|
| 735 | });
|
|---|
| 736 | }
|
|---|
| 737 | return ret;
|
|---|
| 738 | };
|
|---|
| 739 | }
|
|---|
| 740 | }
|
|---|
| 741 |
|
|---|
| 742 | // src/query/standardSchema.ts
|
|---|
| 743 | import { SchemaError } from "@standard-schema/utils";
|
|---|
| 744 | var NamedSchemaError = class extends SchemaError {
|
|---|
| 745 | constructor(issues, value, schemaName, _bqMeta) {
|
|---|
| 746 | super(issues);
|
|---|
| 747 | this.value = value;
|
|---|
| 748 | this.schemaName = schemaName;
|
|---|
| 749 | this._bqMeta = _bqMeta;
|
|---|
| 750 | }
|
|---|
| 751 | };
|
|---|
| 752 | var shouldSkip = (skipSchemaValidation, schemaName) => Array.isArray(skipSchemaValidation) ? skipSchemaValidation.includes(schemaName) : !!skipSchemaValidation;
|
|---|
| 753 | async function parseWithSchema(schema, data, schemaName, bqMeta) {
|
|---|
| 754 | const result = await schema["~standard"].validate(data);
|
|---|
| 755 | if (result.issues) {
|
|---|
| 756 | throw new NamedSchemaError(result.issues, data, schemaName, bqMeta);
|
|---|
| 757 | }
|
|---|
| 758 | return result.value;
|
|---|
| 759 | }
|
|---|
| 760 |
|
|---|
| 761 | // src/query/core/buildThunks.ts
|
|---|
| 762 | function defaultTransformResponse(baseQueryReturnValue) {
|
|---|
| 763 | return baseQueryReturnValue;
|
|---|
| 764 | }
|
|---|
| 765 | var addShouldAutoBatch = (arg = {}) => {
|
|---|
| 766 | return {
|
|---|
| 767 | ...arg,
|
|---|
| 768 | [SHOULD_AUTOBATCH]: true
|
|---|
| 769 | };
|
|---|
| 770 | };
|
|---|
| 771 | function buildThunks({
|
|---|
| 772 | reducerPath,
|
|---|
| 773 | baseQuery,
|
|---|
| 774 | context: {
|
|---|
| 775 | endpointDefinitions
|
|---|
| 776 | },
|
|---|
| 777 | serializeQueryArgs,
|
|---|
| 778 | api,
|
|---|
| 779 | assertTagType,
|
|---|
| 780 | selectors,
|
|---|
| 781 | onSchemaFailure,
|
|---|
| 782 | catchSchemaFailure: globalCatchSchemaFailure,
|
|---|
| 783 | skipSchemaValidation: globalSkipSchemaValidation
|
|---|
| 784 | }) {
|
|---|
| 785 | const patchQueryData = (endpointName, arg, patches, updateProvided) => (dispatch, getState) => {
|
|---|
| 786 | const endpointDefinition = endpointDefinitions[endpointName];
|
|---|
| 787 | const queryCacheKey = serializeQueryArgs({
|
|---|
| 788 | queryArgs: arg,
|
|---|
| 789 | endpointDefinition,
|
|---|
| 790 | endpointName
|
|---|
| 791 | });
|
|---|
| 792 | dispatch(api.internalActions.queryResultPatched({
|
|---|
| 793 | queryCacheKey,
|
|---|
| 794 | patches
|
|---|
| 795 | }));
|
|---|
| 796 | if (!updateProvided) {
|
|---|
| 797 | return;
|
|---|
| 798 | }
|
|---|
| 799 | const newValue = api.endpoints[endpointName].select(arg)(
|
|---|
| 800 | // Work around TS 4.1 mismatch
|
|---|
| 801 | getState()
|
|---|
| 802 | );
|
|---|
| 803 | const providedTags = calculateProvidedBy(endpointDefinition.providesTags, newValue.data, void 0, arg, {}, assertTagType);
|
|---|
| 804 | dispatch(api.internalActions.updateProvidedBy([{
|
|---|
| 805 | queryCacheKey,
|
|---|
| 806 | providedTags
|
|---|
| 807 | }]));
|
|---|
| 808 | };
|
|---|
| 809 | function addToStart(items, item, max = 0) {
|
|---|
| 810 | const newItems = [item, ...items];
|
|---|
| 811 | return max && newItems.length > max ? newItems.slice(0, -1) : newItems;
|
|---|
| 812 | }
|
|---|
| 813 | function addToEnd(items, item, max = 0) {
|
|---|
| 814 | const newItems = [...items, item];
|
|---|
| 815 | return max && newItems.length > max ? newItems.slice(1) : newItems;
|
|---|
| 816 | }
|
|---|
| 817 | const updateQueryData = (endpointName, arg, updateRecipe, updateProvided = true) => (dispatch, getState) => {
|
|---|
| 818 | const endpointDefinition = api.endpoints[endpointName];
|
|---|
| 819 | const currentState = endpointDefinition.select(arg)(
|
|---|
| 820 | // Work around TS 4.1 mismatch
|
|---|
| 821 | getState()
|
|---|
| 822 | );
|
|---|
| 823 | const ret = {
|
|---|
| 824 | patches: [],
|
|---|
| 825 | inversePatches: [],
|
|---|
| 826 | undo: () => dispatch(api.util.patchQueryData(endpointName, arg, ret.inversePatches, updateProvided))
|
|---|
| 827 | };
|
|---|
| 828 | if (currentState.status === STATUS_UNINITIALIZED) {
|
|---|
| 829 | return ret;
|
|---|
| 830 | }
|
|---|
| 831 | let newValue;
|
|---|
| 832 | if ("data" in currentState) {
|
|---|
| 833 | if (isDraftable(currentState.data)) {
|
|---|
| 834 | const [value, patches, inversePatches] = produceWithPatches(currentState.data, updateRecipe);
|
|---|
| 835 | ret.patches.push(...patches);
|
|---|
| 836 | ret.inversePatches.push(...inversePatches);
|
|---|
| 837 | newValue = value;
|
|---|
| 838 | } else {
|
|---|
| 839 | newValue = updateRecipe(currentState.data);
|
|---|
| 840 | ret.patches.push({
|
|---|
| 841 | op: "replace",
|
|---|
| 842 | path: [],
|
|---|
| 843 | value: newValue
|
|---|
| 844 | });
|
|---|
| 845 | ret.inversePatches.push({
|
|---|
| 846 | op: "replace",
|
|---|
| 847 | path: [],
|
|---|
| 848 | value: currentState.data
|
|---|
| 849 | });
|
|---|
| 850 | }
|
|---|
| 851 | }
|
|---|
| 852 | if (ret.patches.length === 0) {
|
|---|
| 853 | return ret;
|
|---|
| 854 | }
|
|---|
| 855 | dispatch(api.util.patchQueryData(endpointName, arg, ret.patches, updateProvided));
|
|---|
| 856 | return ret;
|
|---|
| 857 | };
|
|---|
| 858 | const upsertQueryData = (endpointName, arg, value) => (dispatch) => {
|
|---|
| 859 | const res = dispatch(api.endpoints[endpointName].initiate(arg, {
|
|---|
| 860 | subscribe: false,
|
|---|
| 861 | forceRefetch: true,
|
|---|
| 862 | [forceQueryFnSymbol]: () => ({
|
|---|
| 863 | data: value
|
|---|
| 864 | })
|
|---|
| 865 | }));
|
|---|
| 866 | return res;
|
|---|
| 867 | };
|
|---|
| 868 | const getTransformCallbackForEndpoint = (endpointDefinition, transformFieldName) => {
|
|---|
| 869 | return endpointDefinition.query && endpointDefinition[transformFieldName] ? endpointDefinition[transformFieldName] : defaultTransformResponse;
|
|---|
| 870 | };
|
|---|
| 871 | const executeEndpoint = async (arg, {
|
|---|
| 872 | signal,
|
|---|
| 873 | abort,
|
|---|
| 874 | rejectWithValue,
|
|---|
| 875 | fulfillWithValue,
|
|---|
| 876 | dispatch,
|
|---|
| 877 | getState,
|
|---|
| 878 | extra
|
|---|
| 879 | }) => {
|
|---|
| 880 | const endpointDefinition = endpointDefinitions[arg.endpointName];
|
|---|
| 881 | const {
|
|---|
| 882 | metaSchema,
|
|---|
| 883 | skipSchemaValidation = globalSkipSchemaValidation
|
|---|
| 884 | } = endpointDefinition;
|
|---|
| 885 | const isQuery = arg.type === ENDPOINT_QUERY;
|
|---|
| 886 | try {
|
|---|
| 887 | let transformResponse = defaultTransformResponse;
|
|---|
| 888 | const baseQueryApi = {
|
|---|
| 889 | signal,
|
|---|
| 890 | abort,
|
|---|
| 891 | dispatch,
|
|---|
| 892 | getState,
|
|---|
| 893 | extra,
|
|---|
| 894 | endpoint: arg.endpointName,
|
|---|
| 895 | type: arg.type,
|
|---|
| 896 | forced: isQuery ? isForcedQuery(arg, getState()) : void 0,
|
|---|
| 897 | queryCacheKey: isQuery ? arg.queryCacheKey : void 0
|
|---|
| 898 | };
|
|---|
| 899 | const forceQueryFn = isQuery ? arg[forceQueryFnSymbol] : void 0;
|
|---|
| 900 | let finalQueryReturnValue;
|
|---|
| 901 | const fetchPage = async (data, param, maxPages, previous) => {
|
|---|
| 902 | if (param == null && data.pages.length) {
|
|---|
| 903 | return Promise.resolve({
|
|---|
| 904 | data
|
|---|
| 905 | });
|
|---|
| 906 | }
|
|---|
| 907 | const finalQueryArg = {
|
|---|
| 908 | queryArg: arg.originalArgs,
|
|---|
| 909 | pageParam: param
|
|---|
| 910 | };
|
|---|
| 911 | const pageResponse = await executeRequest(finalQueryArg);
|
|---|
| 912 | const addTo = previous ? addToStart : addToEnd;
|
|---|
| 913 | return {
|
|---|
| 914 | data: {
|
|---|
| 915 | pages: addTo(data.pages, pageResponse.data, maxPages),
|
|---|
| 916 | pageParams: addTo(data.pageParams, param, maxPages)
|
|---|
| 917 | },
|
|---|
| 918 | meta: pageResponse.meta
|
|---|
| 919 | };
|
|---|
| 920 | };
|
|---|
| 921 | async function executeRequest(finalQueryArg) {
|
|---|
| 922 | let result;
|
|---|
| 923 | const {
|
|---|
| 924 | extraOptions,
|
|---|
| 925 | argSchema,
|
|---|
| 926 | rawResponseSchema,
|
|---|
| 927 | responseSchema
|
|---|
| 928 | } = endpointDefinition;
|
|---|
| 929 | if (argSchema && !shouldSkip(skipSchemaValidation, "arg")) {
|
|---|
| 930 | finalQueryArg = await parseWithSchema(
|
|---|
| 931 | argSchema,
|
|---|
| 932 | finalQueryArg,
|
|---|
| 933 | "argSchema",
|
|---|
| 934 | {}
|
|---|
| 935 | // we don't have a meta yet, so we can't pass it
|
|---|
| 936 | );
|
|---|
| 937 | }
|
|---|
| 938 | if (forceQueryFn) {
|
|---|
| 939 | result = forceQueryFn();
|
|---|
| 940 | } else if (endpointDefinition.query) {
|
|---|
| 941 | transformResponse = getTransformCallbackForEndpoint(endpointDefinition, "transformResponse");
|
|---|
| 942 | result = await baseQuery(endpointDefinition.query(finalQueryArg), baseQueryApi, extraOptions);
|
|---|
| 943 | } else {
|
|---|
| 944 | result = await endpointDefinition.queryFn(finalQueryArg, baseQueryApi, extraOptions, (arg2) => baseQuery(arg2, baseQueryApi, extraOptions));
|
|---|
| 945 | }
|
|---|
| 946 | if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
|
|---|
| 947 | const what = endpointDefinition.query ? "`baseQuery`" : "`queryFn`";
|
|---|
| 948 | let err;
|
|---|
| 949 | if (!result) {
|
|---|
| 950 | err = `${what} did not return anything.`;
|
|---|
| 951 | } else if (typeof result !== "object") {
|
|---|
| 952 | err = `${what} did not return an object.`;
|
|---|
| 953 | } else if (result.error && result.data) {
|
|---|
| 954 | err = `${what} returned an object containing both \`error\` and \`result\`.`;
|
|---|
| 955 | } else if (result.error === void 0 && result.data === void 0) {
|
|---|
| 956 | err = `${what} returned an object containing neither a valid \`error\` and \`result\`. At least one of them should not be \`undefined\``;
|
|---|
| 957 | } else {
|
|---|
| 958 | for (const key of Object.keys(result)) {
|
|---|
| 959 | if (key !== "error" && key !== "data" && key !== "meta") {
|
|---|
| 960 | err = `The object returned by ${what} has the unknown property ${key}.`;
|
|---|
| 961 | break;
|
|---|
| 962 | }
|
|---|
| 963 | }
|
|---|
| 964 | }
|
|---|
| 965 | if (err) {
|
|---|
| 966 | console.error(`Error encountered handling the endpoint ${arg.endpointName}.
|
|---|
| 967 | ${err}
|
|---|
| 968 | It needs to return an object with either the shape \`{ data: <value> }\` or \`{ error: <value> }\` that may contain an optional \`meta\` property.
|
|---|
| 969 | Object returned was:`, result);
|
|---|
| 970 | }
|
|---|
| 971 | }
|
|---|
| 972 | if (result.error) throw new HandledError(result.error, result.meta);
|
|---|
| 973 | let {
|
|---|
| 974 | data
|
|---|
| 975 | } = result;
|
|---|
| 976 | if (rawResponseSchema && !shouldSkip(skipSchemaValidation, "rawResponse")) {
|
|---|
| 977 | data = await parseWithSchema(rawResponseSchema, result.data, "rawResponseSchema", result.meta);
|
|---|
| 978 | }
|
|---|
| 979 | let transformedResponse = await transformResponse(data, result.meta, finalQueryArg);
|
|---|
| 980 | if (responseSchema && !shouldSkip(skipSchemaValidation, "response")) {
|
|---|
| 981 | transformedResponse = await parseWithSchema(responseSchema, transformedResponse, "responseSchema", result.meta);
|
|---|
| 982 | }
|
|---|
| 983 | return {
|
|---|
| 984 | ...result,
|
|---|
| 985 | data: transformedResponse
|
|---|
| 986 | };
|
|---|
| 987 | }
|
|---|
| 988 | if (isQuery && "infiniteQueryOptions" in endpointDefinition) {
|
|---|
| 989 | const {
|
|---|
| 990 | infiniteQueryOptions
|
|---|
| 991 | } = endpointDefinition;
|
|---|
| 992 | const {
|
|---|
| 993 | maxPages = Infinity
|
|---|
| 994 | } = infiniteQueryOptions;
|
|---|
| 995 | const refetchCachedPages = arg.refetchCachedPages ?? infiniteQueryOptions.refetchCachedPages ?? true;
|
|---|
| 996 | let result;
|
|---|
| 997 | const blankData = {
|
|---|
| 998 | pages: [],
|
|---|
| 999 | pageParams: []
|
|---|
| 1000 | };
|
|---|
| 1001 | const cachedData = selectors.selectQueryEntry(getState(), arg.queryCacheKey)?.data;
|
|---|
| 1002 | const isForcedQueryNeedingRefetch = (
|
|---|
| 1003 | // arg.forceRefetch
|
|---|
| 1004 | isForcedQuery(arg, getState()) && !arg.direction
|
|---|
| 1005 | );
|
|---|
| 1006 | const existingData = isForcedQueryNeedingRefetch || !cachedData ? blankData : cachedData;
|
|---|
| 1007 | if ("direction" in arg && arg.direction && existingData.pages.length) {
|
|---|
| 1008 | const previous = arg.direction === "backward";
|
|---|
| 1009 | const pageParamFn = previous ? getPreviousPageParam : getNextPageParam;
|
|---|
| 1010 | const param = pageParamFn(infiniteQueryOptions, existingData, arg.originalArgs);
|
|---|
| 1011 | result = await fetchPage(existingData, param, maxPages, previous);
|
|---|
| 1012 | } else {
|
|---|
| 1013 | const {
|
|---|
| 1014 | initialPageParam = infiniteQueryOptions.initialPageParam
|
|---|
| 1015 | } = arg;
|
|---|
| 1016 | const cachedPageParams = cachedData?.pageParams ?? [];
|
|---|
| 1017 | const firstPageParam = cachedPageParams[0] ?? initialPageParam;
|
|---|
| 1018 | const totalPages = cachedPageParams.length;
|
|---|
| 1019 | result = await fetchPage(existingData, firstPageParam, maxPages);
|
|---|
| 1020 | if (forceQueryFn) {
|
|---|
| 1021 | result = {
|
|---|
| 1022 | data: result.data.pages[0]
|
|---|
| 1023 | };
|
|---|
| 1024 | }
|
|---|
| 1025 | if (refetchCachedPages) {
|
|---|
| 1026 | for (let i = 1; i < totalPages; i++) {
|
|---|
| 1027 | const param = getNextPageParam(infiniteQueryOptions, result.data, arg.originalArgs);
|
|---|
| 1028 | result = await fetchPage(result.data, param, maxPages);
|
|---|
| 1029 | }
|
|---|
| 1030 | }
|
|---|
| 1031 | }
|
|---|
| 1032 | finalQueryReturnValue = result;
|
|---|
| 1033 | } else {
|
|---|
| 1034 | finalQueryReturnValue = await executeRequest(arg.originalArgs);
|
|---|
| 1035 | }
|
|---|
| 1036 | if (metaSchema && !shouldSkip(skipSchemaValidation, "meta") && finalQueryReturnValue.meta) {
|
|---|
| 1037 | finalQueryReturnValue.meta = await parseWithSchema(metaSchema, finalQueryReturnValue.meta, "metaSchema", finalQueryReturnValue.meta);
|
|---|
| 1038 | }
|
|---|
| 1039 | return fulfillWithValue(finalQueryReturnValue.data, addShouldAutoBatch({
|
|---|
| 1040 | fulfilledTimeStamp: Date.now(),
|
|---|
| 1041 | baseQueryMeta: finalQueryReturnValue.meta
|
|---|
| 1042 | }));
|
|---|
| 1043 | } catch (error) {
|
|---|
| 1044 | let caughtError = error;
|
|---|
| 1045 | if (caughtError instanceof HandledError) {
|
|---|
| 1046 | let transformErrorResponse = getTransformCallbackForEndpoint(endpointDefinition, "transformErrorResponse");
|
|---|
| 1047 | const {
|
|---|
| 1048 | rawErrorResponseSchema,
|
|---|
| 1049 | errorResponseSchema
|
|---|
| 1050 | } = endpointDefinition;
|
|---|
| 1051 | let {
|
|---|
| 1052 | value,
|
|---|
| 1053 | meta
|
|---|
| 1054 | } = caughtError;
|
|---|
| 1055 | try {
|
|---|
| 1056 | if (rawErrorResponseSchema && !shouldSkip(skipSchemaValidation, "rawErrorResponse")) {
|
|---|
| 1057 | value = await parseWithSchema(rawErrorResponseSchema, value, "rawErrorResponseSchema", meta);
|
|---|
| 1058 | }
|
|---|
| 1059 | if (metaSchema && !shouldSkip(skipSchemaValidation, "meta")) {
|
|---|
| 1060 | meta = await parseWithSchema(metaSchema, meta, "metaSchema", meta);
|
|---|
| 1061 | }
|
|---|
| 1062 | let transformedErrorResponse = await transformErrorResponse(value, meta, arg.originalArgs);
|
|---|
| 1063 | if (errorResponseSchema && !shouldSkip(skipSchemaValidation, "errorResponse")) {
|
|---|
| 1064 | transformedErrorResponse = await parseWithSchema(errorResponseSchema, transformedErrorResponse, "errorResponseSchema", meta);
|
|---|
| 1065 | }
|
|---|
| 1066 | return rejectWithValue(transformedErrorResponse, addShouldAutoBatch({
|
|---|
| 1067 | baseQueryMeta: meta
|
|---|
| 1068 | }));
|
|---|
| 1069 | } catch (e) {
|
|---|
| 1070 | caughtError = e;
|
|---|
| 1071 | }
|
|---|
| 1072 | }
|
|---|
| 1073 | try {
|
|---|
| 1074 | if (caughtError instanceof NamedSchemaError) {
|
|---|
| 1075 | const info = {
|
|---|
| 1076 | endpoint: arg.endpointName,
|
|---|
| 1077 | arg: arg.originalArgs,
|
|---|
| 1078 | type: arg.type,
|
|---|
| 1079 | queryCacheKey: isQuery ? arg.queryCacheKey : void 0
|
|---|
| 1080 | };
|
|---|
| 1081 | endpointDefinition.onSchemaFailure?.(caughtError, info);
|
|---|
| 1082 | onSchemaFailure?.(caughtError, info);
|
|---|
| 1083 | const {
|
|---|
| 1084 | catchSchemaFailure = globalCatchSchemaFailure
|
|---|
| 1085 | } = endpointDefinition;
|
|---|
| 1086 | if (catchSchemaFailure) {
|
|---|
| 1087 | return rejectWithValue(catchSchemaFailure(caughtError, info), addShouldAutoBatch({
|
|---|
| 1088 | baseQueryMeta: caughtError._bqMeta
|
|---|
| 1089 | }));
|
|---|
| 1090 | }
|
|---|
| 1091 | }
|
|---|
| 1092 | } catch (e) {
|
|---|
| 1093 | caughtError = e;
|
|---|
| 1094 | }
|
|---|
| 1095 | if (typeof process !== "undefined" && process.env.NODE_ENV !== "production") {
|
|---|
| 1096 | console.error(`An unhandled error occurred processing a request for the endpoint "${arg.endpointName}".
|
|---|
| 1097 | In the case of an unhandled error, no tags will be "provided" or "invalidated".`, caughtError);
|
|---|
| 1098 | } else {
|
|---|
| 1099 | console.error(caughtError);
|
|---|
| 1100 | }
|
|---|
| 1101 | throw caughtError;
|
|---|
| 1102 | }
|
|---|
| 1103 | };
|
|---|
| 1104 | function isForcedQuery(arg, state) {
|
|---|
| 1105 | const requestState = selectors.selectQueryEntry(state, arg.queryCacheKey);
|
|---|
| 1106 | const baseFetchOnMountOrArgChange = selectors.selectConfig(state).refetchOnMountOrArgChange;
|
|---|
| 1107 | const fulfilledVal = requestState?.fulfilledTimeStamp;
|
|---|
| 1108 | const refetchVal = arg.forceRefetch ?? (arg.subscribe && baseFetchOnMountOrArgChange);
|
|---|
| 1109 | if (refetchVal) {
|
|---|
| 1110 | return refetchVal === true || (Number(/* @__PURE__ */ new Date()) - Number(fulfilledVal)) / 1e3 >= refetchVal;
|
|---|
| 1111 | }
|
|---|
| 1112 | return false;
|
|---|
| 1113 | }
|
|---|
| 1114 | const createQueryThunk = () => {
|
|---|
| 1115 | const generatedQueryThunk = createAsyncThunk(`${reducerPath}/executeQuery`, executeEndpoint, {
|
|---|
| 1116 | getPendingMeta({
|
|---|
| 1117 | arg
|
|---|
| 1118 | }) {
|
|---|
| 1119 | const endpointDefinition = endpointDefinitions[arg.endpointName];
|
|---|
| 1120 | return addShouldAutoBatch({
|
|---|
| 1121 | startedTimeStamp: Date.now(),
|
|---|
| 1122 | ...isInfiniteQueryDefinition(endpointDefinition) ? {
|
|---|
| 1123 | direction: arg.direction
|
|---|
| 1124 | } : {}
|
|---|
| 1125 | });
|
|---|
| 1126 | },
|
|---|
| 1127 | condition(queryThunkArg, {
|
|---|
| 1128 | getState
|
|---|
| 1129 | }) {
|
|---|
| 1130 | const state = getState();
|
|---|
| 1131 | const requestState = selectors.selectQueryEntry(state, queryThunkArg.queryCacheKey);
|
|---|
| 1132 | const fulfilledVal = requestState?.fulfilledTimeStamp;
|
|---|
| 1133 | const currentArg = queryThunkArg.originalArgs;
|
|---|
| 1134 | const previousArg = requestState?.originalArgs;
|
|---|
| 1135 | const endpointDefinition = endpointDefinitions[queryThunkArg.endpointName];
|
|---|
| 1136 | const direction = queryThunkArg.direction;
|
|---|
| 1137 | if (isUpsertQuery(queryThunkArg)) {
|
|---|
| 1138 | return true;
|
|---|
| 1139 | }
|
|---|
| 1140 | if (requestState?.status === "pending") {
|
|---|
| 1141 | return false;
|
|---|
| 1142 | }
|
|---|
| 1143 | if (isForcedQuery(queryThunkArg, state)) {
|
|---|
| 1144 | return true;
|
|---|
| 1145 | }
|
|---|
| 1146 | if (isQueryDefinition(endpointDefinition) && endpointDefinition?.forceRefetch?.({
|
|---|
| 1147 | currentArg,
|
|---|
| 1148 | previousArg,
|
|---|
| 1149 | endpointState: requestState,
|
|---|
| 1150 | state
|
|---|
| 1151 | })) {
|
|---|
| 1152 | return true;
|
|---|
| 1153 | }
|
|---|
| 1154 | if (fulfilledVal && !direction) {
|
|---|
| 1155 | return false;
|
|---|
| 1156 | }
|
|---|
| 1157 | return true;
|
|---|
| 1158 | },
|
|---|
| 1159 | dispatchConditionRejection: true
|
|---|
| 1160 | });
|
|---|
| 1161 | return generatedQueryThunk;
|
|---|
| 1162 | };
|
|---|
| 1163 | const queryThunk = createQueryThunk();
|
|---|
| 1164 | const infiniteQueryThunk = createQueryThunk();
|
|---|
| 1165 | const mutationThunk = createAsyncThunk(`${reducerPath}/executeMutation`, executeEndpoint, {
|
|---|
| 1166 | getPendingMeta() {
|
|---|
| 1167 | return addShouldAutoBatch({
|
|---|
| 1168 | startedTimeStamp: Date.now()
|
|---|
| 1169 | });
|
|---|
| 1170 | }
|
|---|
| 1171 | });
|
|---|
| 1172 | const hasTheForce = (options) => "force" in options;
|
|---|
| 1173 | const hasMaxAge = (options) => "ifOlderThan" in options;
|
|---|
| 1174 | const prefetch = (endpointName, arg, options = {}) => (dispatch, getState) => {
|
|---|
| 1175 | const force = hasTheForce(options) && options.force;
|
|---|
| 1176 | const maxAge = hasMaxAge(options) && options.ifOlderThan;
|
|---|
| 1177 | const queryAction = (force2 = true) => {
|
|---|
| 1178 | const options2 = {
|
|---|
| 1179 | forceRefetch: force2,
|
|---|
| 1180 | subscribe: false
|
|---|
| 1181 | };
|
|---|
| 1182 | return api.endpoints[endpointName].initiate(arg, options2);
|
|---|
| 1183 | };
|
|---|
| 1184 | const latestStateValue = api.endpoints[endpointName].select(arg)(getState());
|
|---|
| 1185 | if (force) {
|
|---|
| 1186 | dispatch(queryAction());
|
|---|
| 1187 | } else if (maxAge) {
|
|---|
| 1188 | const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp;
|
|---|
| 1189 | if (!lastFulfilledTs) {
|
|---|
| 1190 | dispatch(queryAction());
|
|---|
| 1191 | return;
|
|---|
| 1192 | }
|
|---|
| 1193 | const shouldRetrigger = (Number(/* @__PURE__ */ new Date()) - Number(new Date(lastFulfilledTs))) / 1e3 >= maxAge;
|
|---|
| 1194 | if (shouldRetrigger) {
|
|---|
| 1195 | dispatch(queryAction());
|
|---|
| 1196 | }
|
|---|
| 1197 | } else {
|
|---|
| 1198 | dispatch(queryAction(false));
|
|---|
| 1199 | }
|
|---|
| 1200 | };
|
|---|
| 1201 | function matchesEndpoint(endpointName) {
|
|---|
| 1202 | return (action) => action?.meta?.arg?.endpointName === endpointName;
|
|---|
| 1203 | }
|
|---|
| 1204 | function buildMatchThunkActions(thunk, endpointName) {
|
|---|
| 1205 | return {
|
|---|
| 1206 | matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),
|
|---|
| 1207 | matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpointName)),
|
|---|
| 1208 | matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName))
|
|---|
| 1209 | };
|
|---|
| 1210 | }
|
|---|
| 1211 | return {
|
|---|
| 1212 | queryThunk,
|
|---|
| 1213 | mutationThunk,
|
|---|
| 1214 | infiniteQueryThunk,
|
|---|
| 1215 | prefetch,
|
|---|
| 1216 | updateQueryData,
|
|---|
| 1217 | upsertQueryData,
|
|---|
| 1218 | patchQueryData,
|
|---|
| 1219 | buildMatchThunkActions
|
|---|
| 1220 | };
|
|---|
| 1221 | }
|
|---|
| 1222 | function getNextPageParam(options, {
|
|---|
| 1223 | pages,
|
|---|
| 1224 | pageParams
|
|---|
| 1225 | }, queryArg) {
|
|---|
| 1226 | const lastIndex = pages.length - 1;
|
|---|
| 1227 | return options.getNextPageParam(pages[lastIndex], pages, pageParams[lastIndex], pageParams, queryArg);
|
|---|
| 1228 | }
|
|---|
| 1229 | function getPreviousPageParam(options, {
|
|---|
| 1230 | pages,
|
|---|
| 1231 | pageParams
|
|---|
| 1232 | }, queryArg) {
|
|---|
| 1233 | return options.getPreviousPageParam?.(pages[0], pages, pageParams[0], pageParams, queryArg);
|
|---|
| 1234 | }
|
|---|
| 1235 | function calculateProvidedByThunk(action, type, endpointDefinitions, assertTagType) {
|
|---|
| 1236 | return calculateProvidedBy(endpointDefinitions[action.meta.arg.endpointName][type], isFulfilled(action) ? action.payload : void 0, isRejectedWithValue(action) ? action.payload : void 0, action.meta.arg.originalArgs, "baseQueryMeta" in action.meta ? action.meta.baseQueryMeta : void 0, assertTagType);
|
|---|
| 1237 | }
|
|---|
| 1238 |
|
|---|
| 1239 | // src/query/utils/getCurrent.ts
|
|---|
| 1240 | function getCurrent(value) {
|
|---|
| 1241 | return isDraft(value) ? current(value) : value;
|
|---|
| 1242 | }
|
|---|
| 1243 |
|
|---|
| 1244 | // src/query/core/buildSlice.ts
|
|---|
| 1245 | function updateQuerySubstateIfExists(state, queryCacheKey, update) {
|
|---|
| 1246 | const substate = state[queryCacheKey];
|
|---|
| 1247 | if (substate) {
|
|---|
| 1248 | update(substate);
|
|---|
| 1249 | }
|
|---|
| 1250 | }
|
|---|
| 1251 | function getMutationCacheKey(id) {
|
|---|
| 1252 | return ("arg" in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId;
|
|---|
| 1253 | }
|
|---|
| 1254 | function updateMutationSubstateIfExists(state, id, update) {
|
|---|
| 1255 | const substate = state[getMutationCacheKey(id)];
|
|---|
| 1256 | if (substate) {
|
|---|
| 1257 | update(substate);
|
|---|
| 1258 | }
|
|---|
| 1259 | }
|
|---|
| 1260 | var initialState = {};
|
|---|
| 1261 | function buildSlice({
|
|---|
| 1262 | reducerPath,
|
|---|
| 1263 | queryThunk,
|
|---|
| 1264 | mutationThunk,
|
|---|
| 1265 | serializeQueryArgs,
|
|---|
| 1266 | context: {
|
|---|
| 1267 | endpointDefinitions: definitions,
|
|---|
| 1268 | apiUid,
|
|---|
| 1269 | extractRehydrationInfo,
|
|---|
| 1270 | hasRehydrationInfo
|
|---|
| 1271 | },
|
|---|
| 1272 | assertTagType,
|
|---|
| 1273 | config
|
|---|
| 1274 | }) {
|
|---|
| 1275 | const resetApiState = createAction(`${reducerPath}/resetApiState`);
|
|---|
| 1276 | function writePendingCacheEntry(draft, arg, upserting, meta) {
|
|---|
| 1277 | draft[arg.queryCacheKey] ??= {
|
|---|
| 1278 | status: STATUS_UNINITIALIZED,
|
|---|
| 1279 | endpointName: arg.endpointName
|
|---|
| 1280 | };
|
|---|
| 1281 | updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
|
|---|
| 1282 | substate.status = STATUS_PENDING;
|
|---|
| 1283 | substate.requestId = upserting && substate.requestId ? (
|
|---|
| 1284 | // for `upsertQuery` **updates**, keep the current `requestId`
|
|---|
| 1285 | substate.requestId
|
|---|
| 1286 | ) : (
|
|---|
| 1287 | // for normal queries or `upsertQuery` **inserts** always update the `requestId`
|
|---|
| 1288 | meta.requestId
|
|---|
| 1289 | );
|
|---|
| 1290 | if (arg.originalArgs !== void 0) {
|
|---|
| 1291 | substate.originalArgs = arg.originalArgs;
|
|---|
| 1292 | }
|
|---|
| 1293 | substate.startedTimeStamp = meta.startedTimeStamp;
|
|---|
| 1294 | const endpointDefinition = definitions[meta.arg.endpointName];
|
|---|
| 1295 | if (isInfiniteQueryDefinition(endpointDefinition) && "direction" in arg) {
|
|---|
| 1296 | ;
|
|---|
| 1297 | substate.direction = arg.direction;
|
|---|
| 1298 | }
|
|---|
| 1299 | });
|
|---|
| 1300 | }
|
|---|
| 1301 | function writeFulfilledCacheEntry(draft, meta, payload, upserting) {
|
|---|
| 1302 | updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, (substate) => {
|
|---|
| 1303 | if (substate.requestId !== meta.requestId && !upserting) return;
|
|---|
| 1304 | const {
|
|---|
| 1305 | merge
|
|---|
| 1306 | } = definitions[meta.arg.endpointName];
|
|---|
| 1307 | substate.status = STATUS_FULFILLED;
|
|---|
| 1308 | if (merge) {
|
|---|
| 1309 | if (substate.data !== void 0) {
|
|---|
| 1310 | const {
|
|---|
| 1311 | fulfilledTimeStamp,
|
|---|
| 1312 | arg,
|
|---|
| 1313 | baseQueryMeta,
|
|---|
| 1314 | requestId
|
|---|
| 1315 | } = meta;
|
|---|
| 1316 | let newData = createNextState(substate.data, (draftSubstateData) => {
|
|---|
| 1317 | return merge(draftSubstateData, payload, {
|
|---|
| 1318 | arg: arg.originalArgs,
|
|---|
| 1319 | baseQueryMeta,
|
|---|
| 1320 | fulfilledTimeStamp,
|
|---|
| 1321 | requestId
|
|---|
| 1322 | });
|
|---|
| 1323 | });
|
|---|
| 1324 | substate.data = newData;
|
|---|
| 1325 | } else {
|
|---|
| 1326 | substate.data = payload;
|
|---|
| 1327 | }
|
|---|
| 1328 | } else {
|
|---|
| 1329 | substate.data = definitions[meta.arg.endpointName].structuralSharing ?? true ? copyWithStructuralSharing(isDraft(substate.data) ? original(substate.data) : substate.data, payload) : payload;
|
|---|
| 1330 | }
|
|---|
| 1331 | delete substate.error;
|
|---|
| 1332 | substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
|
|---|
| 1333 | });
|
|---|
| 1334 | }
|
|---|
| 1335 | const querySlice = createSlice({
|
|---|
| 1336 | name: `${reducerPath}/queries`,
|
|---|
| 1337 | initialState,
|
|---|
| 1338 | reducers: {
|
|---|
| 1339 | removeQueryResult: {
|
|---|
| 1340 | reducer(draft, {
|
|---|
| 1341 | payload: {
|
|---|
| 1342 | queryCacheKey
|
|---|
| 1343 | }
|
|---|
| 1344 | }) {
|
|---|
| 1345 | delete draft[queryCacheKey];
|
|---|
| 1346 | },
|
|---|
| 1347 | prepare: prepareAutoBatched()
|
|---|
| 1348 | },
|
|---|
| 1349 | cacheEntriesUpserted: {
|
|---|
| 1350 | reducer(draft, action) {
|
|---|
| 1351 | for (const entry of action.payload) {
|
|---|
| 1352 | const {
|
|---|
| 1353 | queryDescription: arg,
|
|---|
| 1354 | value
|
|---|
| 1355 | } = entry;
|
|---|
| 1356 | writePendingCacheEntry(draft, arg, true, {
|
|---|
| 1357 | arg,
|
|---|
| 1358 | requestId: action.meta.requestId,
|
|---|
| 1359 | startedTimeStamp: action.meta.timestamp
|
|---|
| 1360 | });
|
|---|
| 1361 | writeFulfilledCacheEntry(
|
|---|
| 1362 | draft,
|
|---|
| 1363 | {
|
|---|
| 1364 | arg,
|
|---|
| 1365 | requestId: action.meta.requestId,
|
|---|
| 1366 | fulfilledTimeStamp: action.meta.timestamp,
|
|---|
| 1367 | baseQueryMeta: {}
|
|---|
| 1368 | },
|
|---|
| 1369 | value,
|
|---|
| 1370 | // We know we're upserting here
|
|---|
| 1371 | true
|
|---|
| 1372 | );
|
|---|
| 1373 | }
|
|---|
| 1374 | },
|
|---|
| 1375 | prepare: (payload) => {
|
|---|
| 1376 | const queryDescriptions = payload.map((entry) => {
|
|---|
| 1377 | const {
|
|---|
| 1378 | endpointName,
|
|---|
| 1379 | arg,
|
|---|
| 1380 | value
|
|---|
| 1381 | } = entry;
|
|---|
| 1382 | const endpointDefinition = definitions[endpointName];
|
|---|
| 1383 | const queryDescription = {
|
|---|
| 1384 | type: ENDPOINT_QUERY,
|
|---|
| 1385 | endpointName,
|
|---|
| 1386 | originalArgs: entry.arg,
|
|---|
| 1387 | queryCacheKey: serializeQueryArgs({
|
|---|
| 1388 | queryArgs: arg,
|
|---|
| 1389 | endpointDefinition,
|
|---|
| 1390 | endpointName
|
|---|
| 1391 | })
|
|---|
| 1392 | };
|
|---|
| 1393 | return {
|
|---|
| 1394 | queryDescription,
|
|---|
| 1395 | value
|
|---|
| 1396 | };
|
|---|
| 1397 | });
|
|---|
| 1398 | const result = {
|
|---|
| 1399 | payload: queryDescriptions,
|
|---|
| 1400 | meta: {
|
|---|
| 1401 | [SHOULD_AUTOBATCH]: true,
|
|---|
| 1402 | requestId: nanoid(),
|
|---|
| 1403 | timestamp: Date.now()
|
|---|
| 1404 | }
|
|---|
| 1405 | };
|
|---|
| 1406 | return result;
|
|---|
| 1407 | }
|
|---|
| 1408 | },
|
|---|
| 1409 | queryResultPatched: {
|
|---|
| 1410 | reducer(draft, {
|
|---|
| 1411 | payload: {
|
|---|
| 1412 | queryCacheKey,
|
|---|
| 1413 | patches
|
|---|
| 1414 | }
|
|---|
| 1415 | }) {
|
|---|
| 1416 | updateQuerySubstateIfExists(draft, queryCacheKey, (substate) => {
|
|---|
| 1417 | substate.data = applyPatches(substate.data, patches.concat());
|
|---|
| 1418 | });
|
|---|
| 1419 | },
|
|---|
| 1420 | prepare: prepareAutoBatched()
|
|---|
| 1421 | }
|
|---|
| 1422 | },
|
|---|
| 1423 | extraReducers(builder) {
|
|---|
| 1424 | builder.addCase(queryThunk.pending, (draft, {
|
|---|
| 1425 | meta,
|
|---|
| 1426 | meta: {
|
|---|
| 1427 | arg
|
|---|
| 1428 | }
|
|---|
| 1429 | }) => {
|
|---|
| 1430 | const upserting = isUpsertQuery(arg);
|
|---|
| 1431 | writePendingCacheEntry(draft, arg, upserting, meta);
|
|---|
| 1432 | }).addCase(queryThunk.fulfilled, (draft, {
|
|---|
| 1433 | meta,
|
|---|
| 1434 | payload
|
|---|
| 1435 | }) => {
|
|---|
| 1436 | const upserting = isUpsertQuery(meta.arg);
|
|---|
| 1437 | writeFulfilledCacheEntry(draft, meta, payload, upserting);
|
|---|
| 1438 | }).addCase(queryThunk.rejected, (draft, {
|
|---|
| 1439 | meta: {
|
|---|
| 1440 | condition,
|
|---|
| 1441 | arg,
|
|---|
| 1442 | requestId
|
|---|
| 1443 | },
|
|---|
| 1444 | error,
|
|---|
| 1445 | payload
|
|---|
| 1446 | }) => {
|
|---|
| 1447 | updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
|
|---|
| 1448 | if (condition) {
|
|---|
| 1449 | } else {
|
|---|
| 1450 | if (substate.requestId !== requestId) return;
|
|---|
| 1451 | substate.status = STATUS_REJECTED;
|
|---|
| 1452 | substate.error = payload ?? error;
|
|---|
| 1453 | }
|
|---|
| 1454 | });
|
|---|
| 1455 | }).addMatcher(hasRehydrationInfo, (draft, action) => {
|
|---|
| 1456 | const {
|
|---|
| 1457 | queries
|
|---|
| 1458 | } = extractRehydrationInfo(action);
|
|---|
| 1459 | for (const [key, entry] of Object.entries(queries)) {
|
|---|
| 1460 | if (
|
|---|
| 1461 | // do not rehydrate entries that were currently in flight.
|
|---|
| 1462 | entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED
|
|---|
| 1463 | ) {
|
|---|
| 1464 | draft[key] = entry;
|
|---|
| 1465 | }
|
|---|
| 1466 | }
|
|---|
| 1467 | });
|
|---|
| 1468 | }
|
|---|
| 1469 | });
|
|---|
| 1470 | const mutationSlice = createSlice({
|
|---|
| 1471 | name: `${reducerPath}/mutations`,
|
|---|
| 1472 | initialState,
|
|---|
| 1473 | reducers: {
|
|---|
| 1474 | removeMutationResult: {
|
|---|
| 1475 | reducer(draft, {
|
|---|
| 1476 | payload
|
|---|
| 1477 | }) {
|
|---|
| 1478 | const cacheKey = getMutationCacheKey(payload);
|
|---|
| 1479 | if (cacheKey in draft) {
|
|---|
| 1480 | delete draft[cacheKey];
|
|---|
| 1481 | }
|
|---|
| 1482 | },
|
|---|
| 1483 | prepare: prepareAutoBatched()
|
|---|
| 1484 | }
|
|---|
| 1485 | },
|
|---|
| 1486 | extraReducers(builder) {
|
|---|
| 1487 | builder.addCase(mutationThunk.pending, (draft, {
|
|---|
| 1488 | meta,
|
|---|
| 1489 | meta: {
|
|---|
| 1490 | requestId,
|
|---|
| 1491 | arg,
|
|---|
| 1492 | startedTimeStamp
|
|---|
| 1493 | }
|
|---|
| 1494 | }) => {
|
|---|
| 1495 | if (!arg.track) return;
|
|---|
| 1496 | draft[getMutationCacheKey(meta)] = {
|
|---|
| 1497 | requestId,
|
|---|
| 1498 | status: STATUS_PENDING,
|
|---|
| 1499 | endpointName: arg.endpointName,
|
|---|
| 1500 | startedTimeStamp
|
|---|
| 1501 | };
|
|---|
| 1502 | }).addCase(mutationThunk.fulfilled, (draft, {
|
|---|
| 1503 | payload,
|
|---|
| 1504 | meta
|
|---|
| 1505 | }) => {
|
|---|
| 1506 | if (!meta.arg.track) return;
|
|---|
| 1507 | updateMutationSubstateIfExists(draft, meta, (substate) => {
|
|---|
| 1508 | if (substate.requestId !== meta.requestId) return;
|
|---|
| 1509 | substate.status = STATUS_FULFILLED;
|
|---|
| 1510 | substate.data = payload;
|
|---|
| 1511 | substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
|
|---|
| 1512 | });
|
|---|
| 1513 | }).addCase(mutationThunk.rejected, (draft, {
|
|---|
| 1514 | payload,
|
|---|
| 1515 | error,
|
|---|
| 1516 | meta
|
|---|
| 1517 | }) => {
|
|---|
| 1518 | if (!meta.arg.track) return;
|
|---|
| 1519 | updateMutationSubstateIfExists(draft, meta, (substate) => {
|
|---|
| 1520 | if (substate.requestId !== meta.requestId) return;
|
|---|
| 1521 | substate.status = STATUS_REJECTED;
|
|---|
| 1522 | substate.error = payload ?? error;
|
|---|
| 1523 | });
|
|---|
| 1524 | }).addMatcher(hasRehydrationInfo, (draft, action) => {
|
|---|
| 1525 | const {
|
|---|
| 1526 | mutations
|
|---|
| 1527 | } = extractRehydrationInfo(action);
|
|---|
| 1528 | for (const [key, entry] of Object.entries(mutations)) {
|
|---|
| 1529 | if (
|
|---|
| 1530 | // do not rehydrate entries that were currently in flight.
|
|---|
| 1531 | (entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED) && // only rehydrate endpoints that were persisted using a `fixedCacheKey`
|
|---|
| 1532 | key !== entry?.requestId
|
|---|
| 1533 | ) {
|
|---|
| 1534 | draft[key] = entry;
|
|---|
| 1535 | }
|
|---|
| 1536 | }
|
|---|
| 1537 | });
|
|---|
| 1538 | }
|
|---|
| 1539 | });
|
|---|
| 1540 | const initialInvalidationState = {
|
|---|
| 1541 | tags: {},
|
|---|
| 1542 | keys: {}
|
|---|
| 1543 | };
|
|---|
| 1544 | const invalidationSlice = createSlice({
|
|---|
| 1545 | name: `${reducerPath}/invalidation`,
|
|---|
| 1546 | initialState: initialInvalidationState,
|
|---|
| 1547 | reducers: {
|
|---|
| 1548 | updateProvidedBy: {
|
|---|
| 1549 | reducer(draft, action) {
|
|---|
| 1550 | for (const {
|
|---|
| 1551 | queryCacheKey,
|
|---|
| 1552 | providedTags
|
|---|
| 1553 | } of action.payload) {
|
|---|
| 1554 | removeCacheKeyFromTags(draft, queryCacheKey);
|
|---|
| 1555 | for (const {
|
|---|
| 1556 | type,
|
|---|
| 1557 | id
|
|---|
| 1558 | } of providedTags) {
|
|---|
| 1559 | const subscribedQueries = (draft.tags[type] ??= {})[id || "__internal_without_id"] ??= [];
|
|---|
| 1560 | const alreadySubscribed = subscribedQueries.includes(queryCacheKey);
|
|---|
| 1561 | if (!alreadySubscribed) {
|
|---|
| 1562 | subscribedQueries.push(queryCacheKey);
|
|---|
| 1563 | }
|
|---|
| 1564 | }
|
|---|
| 1565 | draft.keys[queryCacheKey] = providedTags;
|
|---|
| 1566 | }
|
|---|
| 1567 | },
|
|---|
| 1568 | prepare: prepareAutoBatched()
|
|---|
| 1569 | }
|
|---|
| 1570 | },
|
|---|
| 1571 | extraReducers(builder) {
|
|---|
| 1572 | builder.addCase(querySlice.actions.removeQueryResult, (draft, {
|
|---|
| 1573 | payload: {
|
|---|
| 1574 | queryCacheKey
|
|---|
| 1575 | }
|
|---|
| 1576 | }) => {
|
|---|
| 1577 | removeCacheKeyFromTags(draft, queryCacheKey);
|
|---|
| 1578 | }).addMatcher(hasRehydrationInfo, (draft, action) => {
|
|---|
| 1579 | const {
|
|---|
| 1580 | provided
|
|---|
| 1581 | } = extractRehydrationInfo(action);
|
|---|
| 1582 | for (const [type, incomingTags] of Object.entries(provided.tags ?? {})) {
|
|---|
| 1583 | for (const [id, cacheKeys] of Object.entries(incomingTags)) {
|
|---|
| 1584 | const subscribedQueries = (draft.tags[type] ??= {})[id || "__internal_without_id"] ??= [];
|
|---|
| 1585 | for (const queryCacheKey of cacheKeys) {
|
|---|
| 1586 | const alreadySubscribed = subscribedQueries.includes(queryCacheKey);
|
|---|
| 1587 | if (!alreadySubscribed) {
|
|---|
| 1588 | subscribedQueries.push(queryCacheKey);
|
|---|
| 1589 | }
|
|---|
| 1590 | draft.keys[queryCacheKey] = provided.keys[queryCacheKey];
|
|---|
| 1591 | }
|
|---|
| 1592 | }
|
|---|
| 1593 | }
|
|---|
| 1594 | }).addMatcher(isAnyOf(isFulfilled(queryThunk), isRejectedWithValue(queryThunk)), (draft, action) => {
|
|---|
| 1595 | writeProvidedTagsForQueries(draft, [action]);
|
|---|
| 1596 | }).addMatcher(querySlice.actions.cacheEntriesUpserted.match, (draft, action) => {
|
|---|
| 1597 | const mockActions = action.payload.map(({
|
|---|
| 1598 | queryDescription,
|
|---|
| 1599 | value
|
|---|
| 1600 | }) => {
|
|---|
| 1601 | return {
|
|---|
| 1602 | type: "UNKNOWN",
|
|---|
| 1603 | payload: value,
|
|---|
| 1604 | meta: {
|
|---|
| 1605 | requestStatus: "fulfilled",
|
|---|
| 1606 | requestId: "UNKNOWN",
|
|---|
| 1607 | arg: queryDescription
|
|---|
| 1608 | }
|
|---|
| 1609 | };
|
|---|
| 1610 | });
|
|---|
| 1611 | writeProvidedTagsForQueries(draft, mockActions);
|
|---|
| 1612 | });
|
|---|
| 1613 | }
|
|---|
| 1614 | });
|
|---|
| 1615 | function removeCacheKeyFromTags(draft, queryCacheKey) {
|
|---|
| 1616 | const existingTags = getCurrent(draft.keys[queryCacheKey] ?? []);
|
|---|
| 1617 | for (const tag of existingTags) {
|
|---|
| 1618 | const tagType = tag.type;
|
|---|
| 1619 | const tagId = tag.id ?? "__internal_without_id";
|
|---|
| 1620 | const tagSubscriptions = draft.tags[tagType]?.[tagId];
|
|---|
| 1621 | if (tagSubscriptions) {
|
|---|
| 1622 | draft.tags[tagType][tagId] = getCurrent(tagSubscriptions).filter((qc) => qc !== queryCacheKey);
|
|---|
| 1623 | }
|
|---|
| 1624 | }
|
|---|
| 1625 | delete draft.keys[queryCacheKey];
|
|---|
| 1626 | }
|
|---|
| 1627 | function writeProvidedTagsForQueries(draft, actions3) {
|
|---|
| 1628 | const providedByEntries = actions3.map((action) => {
|
|---|
| 1629 | const providedTags = calculateProvidedByThunk(action, "providesTags", definitions, assertTagType);
|
|---|
| 1630 | const {
|
|---|
| 1631 | queryCacheKey
|
|---|
| 1632 | } = action.meta.arg;
|
|---|
| 1633 | return {
|
|---|
| 1634 | queryCacheKey,
|
|---|
| 1635 | providedTags
|
|---|
| 1636 | };
|
|---|
| 1637 | });
|
|---|
| 1638 | invalidationSlice.caseReducers.updateProvidedBy(draft, invalidationSlice.actions.updateProvidedBy(providedByEntries));
|
|---|
| 1639 | }
|
|---|
| 1640 | const subscriptionSlice = createSlice({
|
|---|
| 1641 | name: `${reducerPath}/subscriptions`,
|
|---|
| 1642 | initialState,
|
|---|
| 1643 | reducers: {
|
|---|
| 1644 | updateSubscriptionOptions(d, a) {
|
|---|
| 1645 | },
|
|---|
| 1646 | unsubscribeQueryResult(d, a) {
|
|---|
| 1647 | },
|
|---|
| 1648 | internal_getRTKQSubscriptions() {
|
|---|
| 1649 | }
|
|---|
| 1650 | }
|
|---|
| 1651 | });
|
|---|
| 1652 | const internalSubscriptionsSlice = createSlice({
|
|---|
| 1653 | name: `${reducerPath}/internalSubscriptions`,
|
|---|
| 1654 | initialState,
|
|---|
| 1655 | reducers: {
|
|---|
| 1656 | subscriptionsUpdated: {
|
|---|
| 1657 | reducer(state, action) {
|
|---|
| 1658 | return applyPatches(state, action.payload);
|
|---|
| 1659 | },
|
|---|
| 1660 | prepare: prepareAutoBatched()
|
|---|
| 1661 | }
|
|---|
| 1662 | }
|
|---|
| 1663 | });
|
|---|
| 1664 | const configSlice = createSlice({
|
|---|
| 1665 | name: `${reducerPath}/config`,
|
|---|
| 1666 | initialState: {
|
|---|
| 1667 | online: isOnline(),
|
|---|
| 1668 | focused: isDocumentVisible(),
|
|---|
| 1669 | middlewareRegistered: false,
|
|---|
| 1670 | ...config
|
|---|
| 1671 | },
|
|---|
| 1672 | reducers: {
|
|---|
| 1673 | middlewareRegistered(state, {
|
|---|
| 1674 | payload
|
|---|
| 1675 | }) {
|
|---|
| 1676 | state.middlewareRegistered = state.middlewareRegistered === "conflict" || apiUid !== payload ? "conflict" : true;
|
|---|
| 1677 | }
|
|---|
| 1678 | },
|
|---|
| 1679 | extraReducers: (builder) => {
|
|---|
| 1680 | builder.addCase(onOnline, (state) => {
|
|---|
| 1681 | state.online = true;
|
|---|
| 1682 | }).addCase(onOffline, (state) => {
|
|---|
| 1683 | state.online = false;
|
|---|
| 1684 | }).addCase(onFocus, (state) => {
|
|---|
| 1685 | state.focused = true;
|
|---|
| 1686 | }).addCase(onFocusLost, (state) => {
|
|---|
| 1687 | state.focused = false;
|
|---|
| 1688 | }).addMatcher(hasRehydrationInfo, (draft) => ({
|
|---|
| 1689 | ...draft
|
|---|
| 1690 | }));
|
|---|
| 1691 | }
|
|---|
| 1692 | });
|
|---|
| 1693 | const combinedReducer = combineReducers({
|
|---|
| 1694 | queries: querySlice.reducer,
|
|---|
| 1695 | mutations: mutationSlice.reducer,
|
|---|
| 1696 | provided: invalidationSlice.reducer,
|
|---|
| 1697 | subscriptions: internalSubscriptionsSlice.reducer,
|
|---|
| 1698 | config: configSlice.reducer
|
|---|
| 1699 | });
|
|---|
| 1700 | const reducer = (state, action) => combinedReducer(resetApiState.match(action) ? void 0 : state, action);
|
|---|
| 1701 | const actions2 = {
|
|---|
| 1702 | ...configSlice.actions,
|
|---|
| 1703 | ...querySlice.actions,
|
|---|
| 1704 | ...subscriptionSlice.actions,
|
|---|
| 1705 | ...internalSubscriptionsSlice.actions,
|
|---|
| 1706 | ...mutationSlice.actions,
|
|---|
| 1707 | ...invalidationSlice.actions,
|
|---|
| 1708 | resetApiState
|
|---|
| 1709 | };
|
|---|
| 1710 | return {
|
|---|
| 1711 | reducer,
|
|---|
| 1712 | actions: actions2
|
|---|
| 1713 | };
|
|---|
| 1714 | }
|
|---|
| 1715 |
|
|---|
| 1716 | // src/query/core/buildSelectors.ts
|
|---|
| 1717 | var skipToken = /* @__PURE__ */ Symbol.for("RTKQ/skipToken");
|
|---|
| 1718 | var initialSubState = {
|
|---|
| 1719 | status: STATUS_UNINITIALIZED
|
|---|
| 1720 | };
|
|---|
| 1721 | var defaultQuerySubState = /* @__PURE__ */ createNextState(initialSubState, () => {
|
|---|
| 1722 | });
|
|---|
| 1723 | var defaultMutationSubState = /* @__PURE__ */ createNextState(initialSubState, () => {
|
|---|
| 1724 | });
|
|---|
| 1725 | function buildSelectors({
|
|---|
| 1726 | serializeQueryArgs,
|
|---|
| 1727 | reducerPath,
|
|---|
| 1728 | createSelector: createSelector2
|
|---|
| 1729 | }) {
|
|---|
| 1730 | const selectSkippedQuery = (state) => defaultQuerySubState;
|
|---|
| 1731 | const selectSkippedMutation = (state) => defaultMutationSubState;
|
|---|
| 1732 | return {
|
|---|
| 1733 | buildQuerySelector,
|
|---|
| 1734 | buildInfiniteQuerySelector,
|
|---|
| 1735 | buildMutationSelector,
|
|---|
| 1736 | selectInvalidatedBy,
|
|---|
| 1737 | selectCachedArgsForQuery,
|
|---|
| 1738 | selectApiState,
|
|---|
| 1739 | selectQueries,
|
|---|
| 1740 | selectMutations,
|
|---|
| 1741 | selectQueryEntry,
|
|---|
| 1742 | selectConfig
|
|---|
| 1743 | };
|
|---|
| 1744 | function withRequestFlags(substate) {
|
|---|
| 1745 | return {
|
|---|
| 1746 | ...substate,
|
|---|
| 1747 | ...getRequestStatusFlags(substate.status)
|
|---|
| 1748 | };
|
|---|
| 1749 | }
|
|---|
| 1750 | function selectApiState(rootState) {
|
|---|
| 1751 | const state = rootState[reducerPath];
|
|---|
| 1752 | if (process.env.NODE_ENV !== "production") {
|
|---|
| 1753 | if (!state) {
|
|---|
| 1754 | if (selectApiState.triggered) return state;
|
|---|
| 1755 | selectApiState.triggered = true;
|
|---|
| 1756 | console.error(`Error: No data found at \`state.${reducerPath}\`. Did you forget to add the reducer to the store?`);
|
|---|
| 1757 | }
|
|---|
| 1758 | }
|
|---|
| 1759 | return state;
|
|---|
| 1760 | }
|
|---|
| 1761 | function selectQueries(rootState) {
|
|---|
| 1762 | return selectApiState(rootState)?.queries;
|
|---|
| 1763 | }
|
|---|
| 1764 | function selectQueryEntry(rootState, cacheKey) {
|
|---|
| 1765 | return selectQueries(rootState)?.[cacheKey];
|
|---|
| 1766 | }
|
|---|
| 1767 | function selectMutations(rootState) {
|
|---|
| 1768 | return selectApiState(rootState)?.mutations;
|
|---|
| 1769 | }
|
|---|
| 1770 | function selectConfig(rootState) {
|
|---|
| 1771 | return selectApiState(rootState)?.config;
|
|---|
| 1772 | }
|
|---|
| 1773 | function buildAnyQuerySelector(endpointName, endpointDefinition, combiner) {
|
|---|
| 1774 | return (queryArgs) => {
|
|---|
| 1775 | if (queryArgs === skipToken) {
|
|---|
| 1776 | return createSelector2(selectSkippedQuery, combiner);
|
|---|
| 1777 | }
|
|---|
| 1778 | const serializedArgs = serializeQueryArgs({
|
|---|
| 1779 | queryArgs,
|
|---|
| 1780 | endpointDefinition,
|
|---|
| 1781 | endpointName
|
|---|
| 1782 | });
|
|---|
| 1783 | const selectQuerySubstate = (state) => selectQueryEntry(state, serializedArgs) ?? defaultQuerySubState;
|
|---|
| 1784 | return createSelector2(selectQuerySubstate, combiner);
|
|---|
| 1785 | };
|
|---|
| 1786 | }
|
|---|
| 1787 | function buildQuerySelector(endpointName, endpointDefinition) {
|
|---|
| 1788 | return buildAnyQuerySelector(endpointName, endpointDefinition, withRequestFlags);
|
|---|
| 1789 | }
|
|---|
| 1790 | function buildInfiniteQuerySelector(endpointName, endpointDefinition) {
|
|---|
| 1791 | const {
|
|---|
| 1792 | infiniteQueryOptions
|
|---|
| 1793 | } = endpointDefinition;
|
|---|
| 1794 | function withInfiniteQueryResultFlags(substate) {
|
|---|
| 1795 | const stateWithRequestFlags = {
|
|---|
| 1796 | ...substate,
|
|---|
| 1797 | ...getRequestStatusFlags(substate.status)
|
|---|
| 1798 | };
|
|---|
| 1799 | const {
|
|---|
| 1800 | isLoading,
|
|---|
| 1801 | isError,
|
|---|
| 1802 | direction
|
|---|
| 1803 | } = stateWithRequestFlags;
|
|---|
| 1804 | const isForward = direction === "forward";
|
|---|
| 1805 | const isBackward = direction === "backward";
|
|---|
| 1806 | return {
|
|---|
| 1807 | ...stateWithRequestFlags,
|
|---|
| 1808 | hasNextPage: getHasNextPage(infiniteQueryOptions, stateWithRequestFlags.data, stateWithRequestFlags.originalArgs),
|
|---|
| 1809 | hasPreviousPage: getHasPreviousPage(infiniteQueryOptions, stateWithRequestFlags.data, stateWithRequestFlags.originalArgs),
|
|---|
| 1810 | isFetchingNextPage: isLoading && isForward,
|
|---|
| 1811 | isFetchingPreviousPage: isLoading && isBackward,
|
|---|
| 1812 | isFetchNextPageError: isError && isForward,
|
|---|
| 1813 | isFetchPreviousPageError: isError && isBackward
|
|---|
| 1814 | };
|
|---|
| 1815 | }
|
|---|
| 1816 | return buildAnyQuerySelector(endpointName, endpointDefinition, withInfiniteQueryResultFlags);
|
|---|
| 1817 | }
|
|---|
| 1818 | function buildMutationSelector() {
|
|---|
| 1819 | return (id) => {
|
|---|
| 1820 | let mutationId;
|
|---|
| 1821 | if (typeof id === "object") {
|
|---|
| 1822 | mutationId = getMutationCacheKey(id) ?? skipToken;
|
|---|
| 1823 | } else {
|
|---|
| 1824 | mutationId = id;
|
|---|
| 1825 | }
|
|---|
| 1826 | const selectMutationSubstate = (state) => selectApiState(state)?.mutations?.[mutationId] ?? defaultMutationSubState;
|
|---|
| 1827 | const finalSelectMutationSubstate = mutationId === skipToken ? selectSkippedMutation : selectMutationSubstate;
|
|---|
| 1828 | return createSelector2(finalSelectMutationSubstate, withRequestFlags);
|
|---|
| 1829 | };
|
|---|
| 1830 | }
|
|---|
| 1831 | function selectInvalidatedBy(state, tags) {
|
|---|
| 1832 | const apiState = state[reducerPath];
|
|---|
| 1833 | const toInvalidate = /* @__PURE__ */ new Set();
|
|---|
| 1834 | const finalTags = filterMap(tags, isNotNullish, expandTagDescription);
|
|---|
| 1835 | for (const tag of finalTags) {
|
|---|
| 1836 | const provided = apiState.provided.tags[tag.type];
|
|---|
| 1837 | if (!provided) {
|
|---|
| 1838 | continue;
|
|---|
| 1839 | }
|
|---|
| 1840 | let invalidateSubscriptions = (tag.id !== void 0 ? (
|
|---|
| 1841 | // id given: invalidate all queries that provide this type & id
|
|---|
| 1842 | provided[tag.id]
|
|---|
| 1843 | ) : (
|
|---|
| 1844 | // no id: invalidate all queries that provide this type
|
|---|
| 1845 | Object.values(provided).flat()
|
|---|
| 1846 | )) ?? [];
|
|---|
| 1847 | for (const invalidate of invalidateSubscriptions) {
|
|---|
| 1848 | toInvalidate.add(invalidate);
|
|---|
| 1849 | }
|
|---|
| 1850 | }
|
|---|
| 1851 | return Array.from(toInvalidate.values()).flatMap((queryCacheKey) => {
|
|---|
| 1852 | const querySubState = apiState.queries[queryCacheKey];
|
|---|
| 1853 | return querySubState ? {
|
|---|
| 1854 | queryCacheKey,
|
|---|
| 1855 | endpointName: querySubState.endpointName,
|
|---|
| 1856 | originalArgs: querySubState.originalArgs
|
|---|
| 1857 | } : [];
|
|---|
| 1858 | });
|
|---|
| 1859 | }
|
|---|
| 1860 | function selectCachedArgsForQuery(state, queryName) {
|
|---|
| 1861 | return filterMap(Object.values(selectQueries(state)), (entry) => entry?.endpointName === queryName && entry.status !== STATUS_UNINITIALIZED, (entry) => entry.originalArgs);
|
|---|
| 1862 | }
|
|---|
| 1863 | function getHasNextPage(options, data, queryArg) {
|
|---|
| 1864 | if (!data) return false;
|
|---|
| 1865 | return getNextPageParam(options, data, queryArg) != null;
|
|---|
| 1866 | }
|
|---|
| 1867 | function getHasPreviousPage(options, data, queryArg) {
|
|---|
| 1868 | if (!data || !options.getPreviousPageParam) return false;
|
|---|
| 1869 | return getPreviousPageParam(options, data, queryArg) != null;
|
|---|
| 1870 | }
|
|---|
| 1871 | }
|
|---|
| 1872 |
|
|---|
| 1873 | // src/query/createApi.ts
|
|---|
| 1874 | import { formatProdErrorMessage as _formatProdErrorMessage2, formatProdErrorMessage as _formatProdErrorMessage22, formatProdErrorMessage as _formatProdErrorMessage3 } from "@reduxjs/toolkit";
|
|---|
| 1875 |
|
|---|
| 1876 | // src/query/defaultSerializeQueryArgs.ts
|
|---|
| 1877 | var cache = WeakMap ? /* @__PURE__ */ new WeakMap() : void 0;
|
|---|
| 1878 | var defaultSerializeQueryArgs = ({
|
|---|
| 1879 | endpointName,
|
|---|
| 1880 | queryArgs
|
|---|
| 1881 | }) => {
|
|---|
| 1882 | let serialized = "";
|
|---|
| 1883 | const cached = cache?.get(queryArgs);
|
|---|
| 1884 | if (typeof cached === "string") {
|
|---|
| 1885 | serialized = cached;
|
|---|
| 1886 | } else {
|
|---|
| 1887 | const stringified = JSON.stringify(queryArgs, (key, value) => {
|
|---|
| 1888 | value = typeof value === "bigint" ? {
|
|---|
| 1889 | $bigint: value.toString()
|
|---|
| 1890 | } : value;
|
|---|
| 1891 | value = isPlainObject(value) ? Object.keys(value).sort().reduce((acc, key2) => {
|
|---|
| 1892 | acc[key2] = value[key2];
|
|---|
| 1893 | return acc;
|
|---|
| 1894 | }, {}) : value;
|
|---|
| 1895 | return value;
|
|---|
| 1896 | });
|
|---|
| 1897 | if (isPlainObject(queryArgs)) {
|
|---|
| 1898 | cache?.set(queryArgs, stringified);
|
|---|
| 1899 | }
|
|---|
| 1900 | serialized = stringified;
|
|---|
| 1901 | }
|
|---|
| 1902 | return `${endpointName}(${serialized})`;
|
|---|
| 1903 | };
|
|---|
| 1904 |
|
|---|
| 1905 | // src/query/createApi.ts
|
|---|
| 1906 | import { weakMapMemoize } from "reselect";
|
|---|
| 1907 | function buildCreateApi(...modules) {
|
|---|
| 1908 | return function baseCreateApi(options) {
|
|---|
| 1909 | const extractRehydrationInfo = weakMapMemoize((action) => options.extractRehydrationInfo?.(action, {
|
|---|
| 1910 | reducerPath: options.reducerPath ?? "api"
|
|---|
| 1911 | }));
|
|---|
| 1912 | const optionsWithDefaults = {
|
|---|
| 1913 | reducerPath: "api",
|
|---|
| 1914 | keepUnusedDataFor: 60,
|
|---|
| 1915 | refetchOnMountOrArgChange: false,
|
|---|
| 1916 | refetchOnFocus: false,
|
|---|
| 1917 | refetchOnReconnect: false,
|
|---|
| 1918 | invalidationBehavior: "delayed",
|
|---|
| 1919 | ...options,
|
|---|
| 1920 | extractRehydrationInfo,
|
|---|
| 1921 | serializeQueryArgs(queryArgsApi) {
|
|---|
| 1922 | let finalSerializeQueryArgs = defaultSerializeQueryArgs;
|
|---|
| 1923 | if ("serializeQueryArgs" in queryArgsApi.endpointDefinition) {
|
|---|
| 1924 | const endpointSQA = queryArgsApi.endpointDefinition.serializeQueryArgs;
|
|---|
| 1925 | finalSerializeQueryArgs = (queryArgsApi2) => {
|
|---|
| 1926 | const initialResult = endpointSQA(queryArgsApi2);
|
|---|
| 1927 | if (typeof initialResult === "string") {
|
|---|
| 1928 | return initialResult;
|
|---|
| 1929 | } else {
|
|---|
| 1930 | return defaultSerializeQueryArgs({
|
|---|
| 1931 | ...queryArgsApi2,
|
|---|
| 1932 | queryArgs: initialResult
|
|---|
| 1933 | });
|
|---|
| 1934 | }
|
|---|
| 1935 | };
|
|---|
| 1936 | } else if (options.serializeQueryArgs) {
|
|---|
| 1937 | finalSerializeQueryArgs = options.serializeQueryArgs;
|
|---|
| 1938 | }
|
|---|
| 1939 | return finalSerializeQueryArgs(queryArgsApi);
|
|---|
| 1940 | },
|
|---|
| 1941 | tagTypes: [...options.tagTypes || []]
|
|---|
| 1942 | };
|
|---|
| 1943 | const context = {
|
|---|
| 1944 | endpointDefinitions: {},
|
|---|
| 1945 | batch(fn) {
|
|---|
| 1946 | fn();
|
|---|
| 1947 | },
|
|---|
| 1948 | apiUid: nanoid(),
|
|---|
| 1949 | extractRehydrationInfo,
|
|---|
| 1950 | hasRehydrationInfo: weakMapMemoize((action) => extractRehydrationInfo(action) != null)
|
|---|
| 1951 | };
|
|---|
| 1952 | const api = {
|
|---|
| 1953 | injectEndpoints,
|
|---|
| 1954 | enhanceEndpoints({
|
|---|
| 1955 | addTagTypes,
|
|---|
| 1956 | endpoints
|
|---|
| 1957 | }) {
|
|---|
| 1958 | if (addTagTypes) {
|
|---|
| 1959 | for (const eT of addTagTypes) {
|
|---|
| 1960 | if (!optionsWithDefaults.tagTypes.includes(eT)) {
|
|---|
| 1961 | ;
|
|---|
| 1962 | optionsWithDefaults.tagTypes.push(eT);
|
|---|
| 1963 | }
|
|---|
| 1964 | }
|
|---|
| 1965 | }
|
|---|
| 1966 | if (endpoints) {
|
|---|
| 1967 | for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {
|
|---|
| 1968 | if (typeof partialDefinition === "function") {
|
|---|
| 1969 | partialDefinition(getEndpointDefinition(context, endpointName));
|
|---|
| 1970 | } else {
|
|---|
| 1971 | Object.assign(getEndpointDefinition(context, endpointName) || {}, partialDefinition);
|
|---|
| 1972 | }
|
|---|
| 1973 | }
|
|---|
| 1974 | }
|
|---|
| 1975 | return api;
|
|---|
| 1976 | }
|
|---|
| 1977 | };
|
|---|
| 1978 | const initializedModules = modules.map((m) => m.init(api, optionsWithDefaults, context));
|
|---|
| 1979 | function injectEndpoints(inject) {
|
|---|
| 1980 | const evaluatedEndpoints = inject.endpoints({
|
|---|
| 1981 | query: (x) => ({
|
|---|
| 1982 | ...x,
|
|---|
| 1983 | type: ENDPOINT_QUERY
|
|---|
| 1984 | }),
|
|---|
| 1985 | mutation: (x) => ({
|
|---|
| 1986 | ...x,
|
|---|
| 1987 | type: ENDPOINT_MUTATION
|
|---|
| 1988 | }),
|
|---|
| 1989 | infiniteQuery: (x) => ({
|
|---|
| 1990 | ...x,
|
|---|
| 1991 | type: ENDPOINT_INFINITEQUERY
|
|---|
| 1992 | })
|
|---|
| 1993 | });
|
|---|
| 1994 | for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {
|
|---|
| 1995 | if (inject.overrideExisting !== true && endpointName in context.endpointDefinitions) {
|
|---|
| 1996 | if (inject.overrideExisting === "throw") {
|
|---|
| 1997 | throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage2(39) : `called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``);
|
|---|
| 1998 | } else if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
|
|---|
| 1999 | console.error(`called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``);
|
|---|
| 2000 | }
|
|---|
| 2001 | continue;
|
|---|
| 2002 | }
|
|---|
| 2003 | if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
|
|---|
| 2004 | if (isInfiniteQueryDefinition(definition)) {
|
|---|
| 2005 | const {
|
|---|
| 2006 | infiniteQueryOptions
|
|---|
| 2007 | } = definition;
|
|---|
| 2008 | const {
|
|---|
| 2009 | maxPages,
|
|---|
| 2010 | getPreviousPageParam: getPreviousPageParam2
|
|---|
| 2011 | } = infiniteQueryOptions;
|
|---|
| 2012 | if (typeof maxPages === "number") {
|
|---|
| 2013 | if (maxPages < 1) {
|
|---|
| 2014 | throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage22(40) : `maxPages for endpoint '${endpointName}' must be a number greater than 0`);
|
|---|
| 2015 | }
|
|---|
| 2016 | if (typeof getPreviousPageParam2 !== "function") {
|
|---|
| 2017 | throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage3(41) : `getPreviousPageParam for endpoint '${endpointName}' must be a function if maxPages is used`);
|
|---|
| 2018 | }
|
|---|
| 2019 | }
|
|---|
| 2020 | }
|
|---|
| 2021 | }
|
|---|
| 2022 | context.endpointDefinitions[endpointName] = definition;
|
|---|
| 2023 | for (const m of initializedModules) {
|
|---|
| 2024 | m.injectEndpoint(endpointName, definition);
|
|---|
| 2025 | }
|
|---|
| 2026 | }
|
|---|
| 2027 | return api;
|
|---|
| 2028 | }
|
|---|
| 2029 | return api.injectEndpoints({
|
|---|
| 2030 | endpoints: options.endpoints
|
|---|
| 2031 | });
|
|---|
| 2032 | };
|
|---|
| 2033 | }
|
|---|
| 2034 |
|
|---|
| 2035 | // src/query/fakeBaseQuery.ts
|
|---|
| 2036 | import { formatProdErrorMessage as _formatProdErrorMessage4 } from "@reduxjs/toolkit";
|
|---|
| 2037 | var _NEVER = /* @__PURE__ */ Symbol();
|
|---|
| 2038 | function fakeBaseQuery() {
|
|---|
| 2039 | return function() {
|
|---|
| 2040 | throw new Error(process.env.NODE_ENV === "production" ? _formatProdErrorMessage4(33) : "When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.");
|
|---|
| 2041 | };
|
|---|
| 2042 | }
|
|---|
| 2043 |
|
|---|
| 2044 | // src/query/tsHelpers.ts
|
|---|
| 2045 | function assertCast(v) {
|
|---|
| 2046 | }
|
|---|
| 2047 | function safeAssign(target, ...args) {
|
|---|
| 2048 | return Object.assign(target, ...args);
|
|---|
| 2049 | }
|
|---|
| 2050 |
|
|---|
| 2051 | // src/query/core/buildMiddleware/batchActions.ts
|
|---|
| 2052 | var buildBatchedActionsHandler = ({
|
|---|
| 2053 | api,
|
|---|
| 2054 | queryThunk,
|
|---|
| 2055 | internalState,
|
|---|
| 2056 | mwApi
|
|---|
| 2057 | }) => {
|
|---|
| 2058 | const subscriptionsPrefix = `${api.reducerPath}/subscriptions`;
|
|---|
| 2059 | let previousSubscriptions = null;
|
|---|
| 2060 | let updateSyncTimer = null;
|
|---|
| 2061 | const {
|
|---|
| 2062 | updateSubscriptionOptions,
|
|---|
| 2063 | unsubscribeQueryResult
|
|---|
| 2064 | } = api.internalActions;
|
|---|
| 2065 | const actuallyMutateSubscriptions = (currentSubscriptions, action) => {
|
|---|
| 2066 | if (updateSubscriptionOptions.match(action)) {
|
|---|
| 2067 | const {
|
|---|
| 2068 | queryCacheKey,
|
|---|
| 2069 | requestId,
|
|---|
| 2070 | options
|
|---|
| 2071 | } = action.payload;
|
|---|
| 2072 | const sub = currentSubscriptions.get(queryCacheKey);
|
|---|
| 2073 | if (sub?.has(requestId)) {
|
|---|
| 2074 | sub.set(requestId, options);
|
|---|
| 2075 | }
|
|---|
| 2076 | return true;
|
|---|
| 2077 | }
|
|---|
| 2078 | if (unsubscribeQueryResult.match(action)) {
|
|---|
| 2079 | const {
|
|---|
| 2080 | queryCacheKey,
|
|---|
| 2081 | requestId
|
|---|
| 2082 | } = action.payload;
|
|---|
| 2083 | const sub = currentSubscriptions.get(queryCacheKey);
|
|---|
| 2084 | if (sub) {
|
|---|
| 2085 | sub.delete(requestId);
|
|---|
| 2086 | }
|
|---|
| 2087 | return true;
|
|---|
| 2088 | }
|
|---|
| 2089 | if (api.internalActions.removeQueryResult.match(action)) {
|
|---|
| 2090 | currentSubscriptions.delete(action.payload.queryCacheKey);
|
|---|
| 2091 | return true;
|
|---|
| 2092 | }
|
|---|
| 2093 | if (queryThunk.pending.match(action)) {
|
|---|
| 2094 | const {
|
|---|
| 2095 | meta: {
|
|---|
| 2096 | arg,
|
|---|
| 2097 | requestId
|
|---|
| 2098 | }
|
|---|
| 2099 | } = action;
|
|---|
| 2100 | const substate = getOrInsertComputed(currentSubscriptions, arg.queryCacheKey, createNewMap);
|
|---|
| 2101 | if (arg.subscribe) {
|
|---|
| 2102 | substate.set(requestId, arg.subscriptionOptions ?? substate.get(requestId) ?? {});
|
|---|
| 2103 | }
|
|---|
| 2104 | return true;
|
|---|
| 2105 | }
|
|---|
| 2106 | let mutated = false;
|
|---|
| 2107 | if (queryThunk.rejected.match(action)) {
|
|---|
| 2108 | const {
|
|---|
| 2109 | meta: {
|
|---|
| 2110 | condition,
|
|---|
| 2111 | arg,
|
|---|
| 2112 | requestId
|
|---|
| 2113 | }
|
|---|
| 2114 | } = action;
|
|---|
| 2115 | if (condition && arg.subscribe) {
|
|---|
| 2116 | const substate = getOrInsertComputed(currentSubscriptions, arg.queryCacheKey, createNewMap);
|
|---|
| 2117 | substate.set(requestId, arg.subscriptionOptions ?? substate.get(requestId) ?? {});
|
|---|
| 2118 | mutated = true;
|
|---|
| 2119 | }
|
|---|
| 2120 | }
|
|---|
| 2121 | return mutated;
|
|---|
| 2122 | };
|
|---|
| 2123 | const getSubscriptions = () => internalState.currentSubscriptions;
|
|---|
| 2124 | const getSubscriptionCount = (queryCacheKey) => {
|
|---|
| 2125 | const subscriptions = getSubscriptions();
|
|---|
| 2126 | const subscriptionsForQueryArg = subscriptions.get(queryCacheKey);
|
|---|
| 2127 | return subscriptionsForQueryArg?.size ?? 0;
|
|---|
| 2128 | };
|
|---|
| 2129 | const isRequestSubscribed = (queryCacheKey, requestId) => {
|
|---|
| 2130 | const subscriptions = getSubscriptions();
|
|---|
| 2131 | return !!subscriptions?.get(queryCacheKey)?.get(requestId);
|
|---|
| 2132 | };
|
|---|
| 2133 | const subscriptionSelectors = {
|
|---|
| 2134 | getSubscriptions,
|
|---|
| 2135 | getSubscriptionCount,
|
|---|
| 2136 | isRequestSubscribed
|
|---|
| 2137 | };
|
|---|
| 2138 | function serializeSubscriptions(currentSubscriptions) {
|
|---|
| 2139 | return JSON.parse(JSON.stringify(Object.fromEntries([...currentSubscriptions].map(([k, v]) => [k, Object.fromEntries(v)]))));
|
|---|
| 2140 | }
|
|---|
| 2141 | return (action, mwApi2) => {
|
|---|
| 2142 | if (!previousSubscriptions) {
|
|---|
| 2143 | previousSubscriptions = serializeSubscriptions(internalState.currentSubscriptions);
|
|---|
| 2144 | }
|
|---|
| 2145 | if (api.util.resetApiState.match(action)) {
|
|---|
| 2146 | previousSubscriptions = {};
|
|---|
| 2147 | internalState.currentSubscriptions.clear();
|
|---|
| 2148 | updateSyncTimer = null;
|
|---|
| 2149 | return [true, false];
|
|---|
| 2150 | }
|
|---|
| 2151 | if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {
|
|---|
| 2152 | return [false, subscriptionSelectors];
|
|---|
| 2153 | }
|
|---|
| 2154 | const didMutate = actuallyMutateSubscriptions(internalState.currentSubscriptions, action);
|
|---|
| 2155 | let actionShouldContinue = true;
|
|---|
| 2156 | if (process.env.NODE_ENV === "test" && typeof action.type === "string" && action.type === `${api.reducerPath}/getPolling`) {
|
|---|
| 2157 | return [false, internalState.currentPolls];
|
|---|
| 2158 | }
|
|---|
| 2159 | if (didMutate) {
|
|---|
| 2160 | if (!updateSyncTimer) {
|
|---|
| 2161 | updateSyncTimer = setTimeout(() => {
|
|---|
| 2162 | const newSubscriptions = serializeSubscriptions(internalState.currentSubscriptions);
|
|---|
| 2163 | const [, patches] = produceWithPatches(previousSubscriptions, () => newSubscriptions);
|
|---|
| 2164 | mwApi2.next(api.internalActions.subscriptionsUpdated(patches));
|
|---|
| 2165 | previousSubscriptions = newSubscriptions;
|
|---|
| 2166 | updateSyncTimer = null;
|
|---|
| 2167 | }, 500);
|
|---|
| 2168 | }
|
|---|
| 2169 | const isSubscriptionSliceAction = typeof action.type == "string" && !!action.type.startsWith(subscriptionsPrefix);
|
|---|
| 2170 | const isAdditionalSubscriptionAction = queryThunk.rejected.match(action) && action.meta.condition && !!action.meta.arg.subscribe;
|
|---|
| 2171 | actionShouldContinue = !isSubscriptionSliceAction && !isAdditionalSubscriptionAction;
|
|---|
| 2172 | }
|
|---|
| 2173 | return [actionShouldContinue, false];
|
|---|
| 2174 | };
|
|---|
| 2175 | };
|
|---|
| 2176 |
|
|---|
| 2177 | // src/query/core/buildMiddleware/cacheCollection.ts
|
|---|
| 2178 | var THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2147483647 / 1e3 - 1;
|
|---|
| 2179 | var buildCacheCollectionHandler = ({
|
|---|
| 2180 | reducerPath,
|
|---|
| 2181 | api,
|
|---|
| 2182 | queryThunk,
|
|---|
| 2183 | context,
|
|---|
| 2184 | internalState,
|
|---|
| 2185 | selectors: {
|
|---|
| 2186 | selectQueryEntry,
|
|---|
| 2187 | selectConfig
|
|---|
| 2188 | },
|
|---|
| 2189 | getRunningQueryThunk,
|
|---|
| 2190 | mwApi
|
|---|
| 2191 | }) => {
|
|---|
| 2192 | const {
|
|---|
| 2193 | removeQueryResult,
|
|---|
| 2194 | unsubscribeQueryResult,
|
|---|
| 2195 | cacheEntriesUpserted
|
|---|
| 2196 | } = api.internalActions;
|
|---|
| 2197 | const canTriggerUnsubscribe = isAnyOf(unsubscribeQueryResult.match, queryThunk.fulfilled, queryThunk.rejected, cacheEntriesUpserted.match);
|
|---|
| 2198 | function anySubscriptionsRemainingForKey(queryCacheKey) {
|
|---|
| 2199 | const subscriptions = internalState.currentSubscriptions.get(queryCacheKey);
|
|---|
| 2200 | if (!subscriptions) {
|
|---|
| 2201 | return false;
|
|---|
| 2202 | }
|
|---|
| 2203 | const hasSubscriptions = subscriptions.size > 0;
|
|---|
| 2204 | return hasSubscriptions;
|
|---|
| 2205 | }
|
|---|
| 2206 | const currentRemovalTimeouts = {};
|
|---|
| 2207 | function abortAllPromises(promiseMap) {
|
|---|
| 2208 | for (const promise of promiseMap.values()) {
|
|---|
| 2209 | promise?.abort?.();
|
|---|
| 2210 | }
|
|---|
| 2211 | }
|
|---|
| 2212 | const handler = (action, mwApi2) => {
|
|---|
| 2213 | const state = mwApi2.getState();
|
|---|
| 2214 | const config = selectConfig(state);
|
|---|
| 2215 | if (canTriggerUnsubscribe(action)) {
|
|---|
| 2216 | let queryCacheKeys;
|
|---|
| 2217 | if (cacheEntriesUpserted.match(action)) {
|
|---|
| 2218 | queryCacheKeys = action.payload.map((entry) => entry.queryDescription.queryCacheKey);
|
|---|
| 2219 | } else {
|
|---|
| 2220 | const {
|
|---|
| 2221 | queryCacheKey
|
|---|
| 2222 | } = unsubscribeQueryResult.match(action) ? action.payload : action.meta.arg;
|
|---|
| 2223 | queryCacheKeys = [queryCacheKey];
|
|---|
| 2224 | }
|
|---|
| 2225 | handleUnsubscribeMany(queryCacheKeys, mwApi2, config);
|
|---|
| 2226 | }
|
|---|
| 2227 | if (api.util.resetApiState.match(action)) {
|
|---|
| 2228 | for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {
|
|---|
| 2229 | if (timeout) clearTimeout(timeout);
|
|---|
| 2230 | delete currentRemovalTimeouts[key];
|
|---|
| 2231 | }
|
|---|
| 2232 | abortAllPromises(internalState.runningQueries);
|
|---|
| 2233 | abortAllPromises(internalState.runningMutations);
|
|---|
| 2234 | }
|
|---|
| 2235 | if (context.hasRehydrationInfo(action)) {
|
|---|
| 2236 | const {
|
|---|
| 2237 | queries
|
|---|
| 2238 | } = context.extractRehydrationInfo(action);
|
|---|
| 2239 | handleUnsubscribeMany(Object.keys(queries), mwApi2, config);
|
|---|
| 2240 | }
|
|---|
| 2241 | };
|
|---|
| 2242 | function handleUnsubscribeMany(cacheKeys, api2, config) {
|
|---|
| 2243 | const state = api2.getState();
|
|---|
| 2244 | for (const queryCacheKey of cacheKeys) {
|
|---|
| 2245 | const entry = selectQueryEntry(state, queryCacheKey);
|
|---|
| 2246 | if (entry?.endpointName) {
|
|---|
| 2247 | handleUnsubscribe(queryCacheKey, entry.endpointName, api2, config);
|
|---|
| 2248 | }
|
|---|
| 2249 | }
|
|---|
| 2250 | }
|
|---|
| 2251 | function handleUnsubscribe(queryCacheKey, endpointName, api2, config) {
|
|---|
| 2252 | const endpointDefinition = getEndpointDefinition(context, endpointName);
|
|---|
| 2253 | const keepUnusedDataFor = endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor;
|
|---|
| 2254 | if (keepUnusedDataFor === Infinity) {
|
|---|
| 2255 | return;
|
|---|
| 2256 | }
|
|---|
| 2257 | const finalKeepUnusedDataFor = Math.max(0, Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS));
|
|---|
| 2258 | if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
|
|---|
| 2259 | const currentTimeout = currentRemovalTimeouts[queryCacheKey];
|
|---|
| 2260 | if (currentTimeout) {
|
|---|
| 2261 | clearTimeout(currentTimeout);
|
|---|
| 2262 | }
|
|---|
| 2263 | currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {
|
|---|
| 2264 | if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
|
|---|
| 2265 | const entry = selectQueryEntry(api2.getState(), queryCacheKey);
|
|---|
| 2266 | if (entry?.endpointName) {
|
|---|
| 2267 | const runningQuery = api2.dispatch(getRunningQueryThunk(entry.endpointName, entry.originalArgs));
|
|---|
| 2268 | runningQuery?.abort();
|
|---|
| 2269 | }
|
|---|
| 2270 | api2.dispatch(removeQueryResult({
|
|---|
| 2271 | queryCacheKey
|
|---|
| 2272 | }));
|
|---|
| 2273 | }
|
|---|
| 2274 | delete currentRemovalTimeouts[queryCacheKey];
|
|---|
| 2275 | }, finalKeepUnusedDataFor * 1e3);
|
|---|
| 2276 | }
|
|---|
| 2277 | }
|
|---|
| 2278 | return handler;
|
|---|
| 2279 | };
|
|---|
| 2280 |
|
|---|
| 2281 | // src/query/core/buildMiddleware/cacheLifecycle.ts
|
|---|
| 2282 | var neverResolvedError = new Error("Promise never resolved before cacheEntryRemoved.");
|
|---|
| 2283 | var buildCacheLifecycleHandler = ({
|
|---|
| 2284 | api,
|
|---|
| 2285 | reducerPath,
|
|---|
| 2286 | context,
|
|---|
| 2287 | queryThunk,
|
|---|
| 2288 | mutationThunk,
|
|---|
| 2289 | internalState,
|
|---|
| 2290 | selectors: {
|
|---|
| 2291 | selectQueryEntry,
|
|---|
| 2292 | selectApiState
|
|---|
| 2293 | }
|
|---|
| 2294 | }) => {
|
|---|
| 2295 | const isQueryThunk = isAsyncThunkAction(queryThunk);
|
|---|
| 2296 | const isMutationThunk = isAsyncThunkAction(mutationThunk);
|
|---|
| 2297 | const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk);
|
|---|
| 2298 | const lifecycleMap = {};
|
|---|
| 2299 | const {
|
|---|
| 2300 | removeQueryResult,
|
|---|
| 2301 | removeMutationResult,
|
|---|
| 2302 | cacheEntriesUpserted
|
|---|
| 2303 | } = api.internalActions;
|
|---|
| 2304 | function resolveLifecycleEntry(cacheKey, data, meta) {
|
|---|
| 2305 | const lifecycle = lifecycleMap[cacheKey];
|
|---|
| 2306 | if (lifecycle?.valueResolved) {
|
|---|
| 2307 | lifecycle.valueResolved({
|
|---|
| 2308 | data,
|
|---|
| 2309 | meta
|
|---|
| 2310 | });
|
|---|
| 2311 | delete lifecycle.valueResolved;
|
|---|
| 2312 | }
|
|---|
| 2313 | }
|
|---|
| 2314 | function removeLifecycleEntry(cacheKey) {
|
|---|
| 2315 | const lifecycle = lifecycleMap[cacheKey];
|
|---|
| 2316 | if (lifecycle) {
|
|---|
| 2317 | delete lifecycleMap[cacheKey];
|
|---|
| 2318 | lifecycle.cacheEntryRemoved();
|
|---|
| 2319 | }
|
|---|
| 2320 | }
|
|---|
| 2321 | function getActionMetaFields(action) {
|
|---|
| 2322 | const {
|
|---|
| 2323 | arg,
|
|---|
| 2324 | requestId
|
|---|
| 2325 | } = action.meta;
|
|---|
| 2326 | const {
|
|---|
| 2327 | endpointName,
|
|---|
| 2328 | originalArgs
|
|---|
| 2329 | } = arg;
|
|---|
| 2330 | return [endpointName, originalArgs, requestId];
|
|---|
| 2331 | }
|
|---|
| 2332 | const handler = (action, mwApi, stateBefore) => {
|
|---|
| 2333 | const cacheKey = getCacheKey(action);
|
|---|
| 2334 | function checkForNewCacheKey(endpointName, cacheKey2, requestId, originalArgs) {
|
|---|
| 2335 | const oldEntry = selectQueryEntry(stateBefore, cacheKey2);
|
|---|
| 2336 | const newEntry = selectQueryEntry(mwApi.getState(), cacheKey2);
|
|---|
| 2337 | if (!oldEntry && newEntry) {
|
|---|
| 2338 | handleNewKey(endpointName, originalArgs, cacheKey2, mwApi, requestId);
|
|---|
| 2339 | }
|
|---|
| 2340 | }
|
|---|
| 2341 | if (queryThunk.pending.match(action)) {
|
|---|
| 2342 | const [endpointName, originalArgs, requestId] = getActionMetaFields(action);
|
|---|
| 2343 | checkForNewCacheKey(endpointName, cacheKey, requestId, originalArgs);
|
|---|
| 2344 | } else if (cacheEntriesUpserted.match(action)) {
|
|---|
| 2345 | for (const {
|
|---|
| 2346 | queryDescription,
|
|---|
| 2347 | value
|
|---|
| 2348 | } of action.payload) {
|
|---|
| 2349 | const {
|
|---|
| 2350 | endpointName,
|
|---|
| 2351 | originalArgs,
|
|---|
| 2352 | queryCacheKey
|
|---|
| 2353 | } = queryDescription;
|
|---|
| 2354 | checkForNewCacheKey(endpointName, queryCacheKey, action.meta.requestId, originalArgs);
|
|---|
| 2355 | resolveLifecycleEntry(queryCacheKey, value, {});
|
|---|
| 2356 | }
|
|---|
| 2357 | } else if (mutationThunk.pending.match(action)) {
|
|---|
| 2358 | const state = mwApi.getState()[reducerPath].mutations[cacheKey];
|
|---|
| 2359 | if (state) {
|
|---|
| 2360 | const [endpointName, originalArgs, requestId] = getActionMetaFields(action);
|
|---|
| 2361 | handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId);
|
|---|
| 2362 | }
|
|---|
| 2363 | } else if (isFulfilledThunk(action)) {
|
|---|
| 2364 | resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta);
|
|---|
| 2365 | } else if (removeQueryResult.match(action) || removeMutationResult.match(action)) {
|
|---|
| 2366 | removeLifecycleEntry(cacheKey);
|
|---|
| 2367 | } else if (api.util.resetApiState.match(action)) {
|
|---|
| 2368 | for (const cacheKey2 of Object.keys(lifecycleMap)) {
|
|---|
| 2369 | removeLifecycleEntry(cacheKey2);
|
|---|
| 2370 | }
|
|---|
| 2371 | }
|
|---|
| 2372 | };
|
|---|
| 2373 | function getCacheKey(action) {
|
|---|
| 2374 | if (isQueryThunk(action)) return action.meta.arg.queryCacheKey;
|
|---|
| 2375 | if (isMutationThunk(action)) {
|
|---|
| 2376 | return action.meta.arg.fixedCacheKey ?? action.meta.requestId;
|
|---|
| 2377 | }
|
|---|
| 2378 | if (removeQueryResult.match(action)) return action.payload.queryCacheKey;
|
|---|
| 2379 | if (removeMutationResult.match(action)) return getMutationCacheKey(action.payload);
|
|---|
| 2380 | return "";
|
|---|
| 2381 | }
|
|---|
| 2382 | function handleNewKey(endpointName, originalArgs, queryCacheKey, mwApi, requestId) {
|
|---|
| 2383 | const endpointDefinition = getEndpointDefinition(context, endpointName);
|
|---|
| 2384 | const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded;
|
|---|
| 2385 | if (!onCacheEntryAdded) return;
|
|---|
| 2386 | const lifecycle = {};
|
|---|
| 2387 | const cacheEntryRemoved = new Promise((resolve) => {
|
|---|
| 2388 | lifecycle.cacheEntryRemoved = resolve;
|
|---|
| 2389 | });
|
|---|
| 2390 | const cacheDataLoaded = Promise.race([new Promise((resolve) => {
|
|---|
| 2391 | lifecycle.valueResolved = resolve;
|
|---|
| 2392 | }), cacheEntryRemoved.then(() => {
|
|---|
| 2393 | throw neverResolvedError;
|
|---|
| 2394 | })]);
|
|---|
| 2395 | cacheDataLoaded.catch(() => {
|
|---|
| 2396 | });
|
|---|
| 2397 | lifecycleMap[queryCacheKey] = lifecycle;
|
|---|
| 2398 | const selector = api.endpoints[endpointName].select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : queryCacheKey);
|
|---|
| 2399 | const extra = mwApi.dispatch((_, __, extra2) => extra2);
|
|---|
| 2400 | const lifecycleApi = {
|
|---|
| 2401 | ...mwApi,
|
|---|
| 2402 | getCacheEntry: () => selector(mwApi.getState()),
|
|---|
| 2403 | requestId,
|
|---|
| 2404 | extra,
|
|---|
| 2405 | updateCachedData: isAnyQueryDefinition(endpointDefinition) ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
|
|---|
| 2406 | cacheDataLoaded,
|
|---|
| 2407 | cacheEntryRemoved
|
|---|
| 2408 | };
|
|---|
| 2409 | const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi);
|
|---|
| 2410 | Promise.resolve(runningHandler).catch((e) => {
|
|---|
| 2411 | if (e === neverResolvedError) return;
|
|---|
| 2412 | throw e;
|
|---|
| 2413 | });
|
|---|
| 2414 | }
|
|---|
| 2415 | return handler;
|
|---|
| 2416 | };
|
|---|
| 2417 |
|
|---|
| 2418 | // src/query/core/buildMiddleware/devMiddleware.ts
|
|---|
| 2419 | var buildDevCheckHandler = ({
|
|---|
| 2420 | api,
|
|---|
| 2421 | context: {
|
|---|
| 2422 | apiUid
|
|---|
| 2423 | },
|
|---|
| 2424 | reducerPath
|
|---|
| 2425 | }) => {
|
|---|
| 2426 | return (action, mwApi) => {
|
|---|
| 2427 | if (api.util.resetApiState.match(action)) {
|
|---|
| 2428 | mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
|
|---|
| 2429 | }
|
|---|
| 2430 | if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
|
|---|
| 2431 | if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && mwApi.getState()[reducerPath]?.config?.middlewareRegistered === "conflict") {
|
|---|
| 2432 | console.warn(`There is a mismatch between slice and middleware for the reducerPath "${reducerPath}".
|
|---|
| 2433 | You can only have one api per reducer path, this will lead to crashes in various situations!${reducerPath === "api" ? `
|
|---|
| 2434 | If you have multiple apis, you *have* to specify the reducerPath option when using createApi!` : ""}`);
|
|---|
| 2435 | }
|
|---|
| 2436 | }
|
|---|
| 2437 | };
|
|---|
| 2438 | };
|
|---|
| 2439 |
|
|---|
| 2440 | // src/query/core/buildMiddleware/invalidationByTags.ts
|
|---|
| 2441 | var buildInvalidationByTagsHandler = ({
|
|---|
| 2442 | reducerPath,
|
|---|
| 2443 | context,
|
|---|
| 2444 | context: {
|
|---|
| 2445 | endpointDefinitions
|
|---|
| 2446 | },
|
|---|
| 2447 | mutationThunk,
|
|---|
| 2448 | queryThunk,
|
|---|
| 2449 | api,
|
|---|
| 2450 | assertTagType,
|
|---|
| 2451 | refetchQuery,
|
|---|
| 2452 | internalState
|
|---|
| 2453 | }) => {
|
|---|
| 2454 | const {
|
|---|
| 2455 | removeQueryResult
|
|---|
| 2456 | } = api.internalActions;
|
|---|
| 2457 | const isThunkActionWithTags = isAnyOf(isFulfilled(mutationThunk), isRejectedWithValue(mutationThunk));
|
|---|
| 2458 | const isQueryEnd = isAnyOf(isFulfilled(queryThunk, mutationThunk), isRejected(queryThunk, mutationThunk));
|
|---|
| 2459 | let pendingTagInvalidations = [];
|
|---|
| 2460 | let pendingRequestCount = 0;
|
|---|
| 2461 | const handler = (action, mwApi) => {
|
|---|
| 2462 | if (queryThunk.pending.match(action) || mutationThunk.pending.match(action)) {
|
|---|
| 2463 | pendingRequestCount++;
|
|---|
| 2464 | }
|
|---|
| 2465 | if (isQueryEnd(action)) {
|
|---|
| 2466 | pendingRequestCount = Math.max(0, pendingRequestCount - 1);
|
|---|
| 2467 | }
|
|---|
| 2468 | if (isThunkActionWithTags(action)) {
|
|---|
| 2469 | invalidateTags(calculateProvidedByThunk(action, "invalidatesTags", endpointDefinitions, assertTagType), mwApi);
|
|---|
| 2470 | } else if (isQueryEnd(action)) {
|
|---|
| 2471 | invalidateTags([], mwApi);
|
|---|
| 2472 | } else if (api.util.invalidateTags.match(action)) {
|
|---|
| 2473 | invalidateTags(calculateProvidedBy(action.payload, void 0, void 0, void 0, void 0, assertTagType), mwApi);
|
|---|
| 2474 | }
|
|---|
| 2475 | };
|
|---|
| 2476 | function hasPendingRequests() {
|
|---|
| 2477 | return pendingRequestCount > 0;
|
|---|
| 2478 | }
|
|---|
| 2479 | function invalidateTags(newTags, mwApi) {
|
|---|
| 2480 | const rootState = mwApi.getState();
|
|---|
| 2481 | const state = rootState[reducerPath];
|
|---|
| 2482 | pendingTagInvalidations.push(...newTags);
|
|---|
| 2483 | if (state.config.invalidationBehavior === "delayed" && hasPendingRequests()) {
|
|---|
| 2484 | return;
|
|---|
| 2485 | }
|
|---|
| 2486 | const tags = pendingTagInvalidations;
|
|---|
| 2487 | pendingTagInvalidations = [];
|
|---|
| 2488 | if (tags.length === 0) return;
|
|---|
| 2489 | const toInvalidate = api.util.selectInvalidatedBy(rootState, tags);
|
|---|
| 2490 | context.batch(() => {
|
|---|
| 2491 | const valuesArray = Array.from(toInvalidate.values());
|
|---|
| 2492 | for (const {
|
|---|
| 2493 | queryCacheKey
|
|---|
| 2494 | } of valuesArray) {
|
|---|
| 2495 | const querySubState = state.queries[queryCacheKey];
|
|---|
| 2496 | const subscriptionSubState = getOrInsertComputed(internalState.currentSubscriptions, queryCacheKey, createNewMap);
|
|---|
| 2497 | if (querySubState) {
|
|---|
| 2498 | if (subscriptionSubState.size === 0) {
|
|---|
| 2499 | mwApi.dispatch(removeQueryResult({
|
|---|
| 2500 | queryCacheKey
|
|---|
| 2501 | }));
|
|---|
| 2502 | } else if (querySubState.status !== STATUS_UNINITIALIZED) {
|
|---|
| 2503 | mwApi.dispatch(refetchQuery(querySubState));
|
|---|
| 2504 | }
|
|---|
| 2505 | }
|
|---|
| 2506 | }
|
|---|
| 2507 | });
|
|---|
| 2508 | }
|
|---|
| 2509 | return handler;
|
|---|
| 2510 | };
|
|---|
| 2511 |
|
|---|
| 2512 | // src/query/core/buildMiddleware/polling.ts
|
|---|
| 2513 | var buildPollingHandler = ({
|
|---|
| 2514 | reducerPath,
|
|---|
| 2515 | queryThunk,
|
|---|
| 2516 | api,
|
|---|
| 2517 | refetchQuery,
|
|---|
| 2518 | internalState
|
|---|
| 2519 | }) => {
|
|---|
| 2520 | const {
|
|---|
| 2521 | currentPolls,
|
|---|
| 2522 | currentSubscriptions
|
|---|
| 2523 | } = internalState;
|
|---|
| 2524 | const pendingPollingUpdates = /* @__PURE__ */ new Set();
|
|---|
| 2525 | let pollingUpdateTimer = null;
|
|---|
| 2526 | const handler = (action, mwApi) => {
|
|---|
| 2527 | if (api.internalActions.updateSubscriptionOptions.match(action) || api.internalActions.unsubscribeQueryResult.match(action)) {
|
|---|
| 2528 | schedulePollingUpdate(action.payload.queryCacheKey, mwApi);
|
|---|
| 2529 | }
|
|---|
| 2530 | if (queryThunk.pending.match(action) || queryThunk.rejected.match(action) && action.meta.condition) {
|
|---|
| 2531 | schedulePollingUpdate(action.meta.arg.queryCacheKey, mwApi);
|
|---|
| 2532 | }
|
|---|
| 2533 | if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action) && !action.meta.condition) {
|
|---|
| 2534 | startNextPoll(action.meta.arg, mwApi);
|
|---|
| 2535 | }
|
|---|
| 2536 | if (api.util.resetApiState.match(action)) {
|
|---|
| 2537 | clearPolls();
|
|---|
| 2538 | if (pollingUpdateTimer) {
|
|---|
| 2539 | clearTimeout(pollingUpdateTimer);
|
|---|
| 2540 | pollingUpdateTimer = null;
|
|---|
| 2541 | }
|
|---|
| 2542 | pendingPollingUpdates.clear();
|
|---|
| 2543 | }
|
|---|
| 2544 | };
|
|---|
| 2545 | function schedulePollingUpdate(queryCacheKey, api2) {
|
|---|
| 2546 | pendingPollingUpdates.add(queryCacheKey);
|
|---|
| 2547 | if (!pollingUpdateTimer) {
|
|---|
| 2548 | pollingUpdateTimer = setTimeout(() => {
|
|---|
| 2549 | for (const key of pendingPollingUpdates) {
|
|---|
| 2550 | updatePollingInterval({
|
|---|
| 2551 | queryCacheKey: key
|
|---|
| 2552 | }, api2);
|
|---|
| 2553 | }
|
|---|
| 2554 | pendingPollingUpdates.clear();
|
|---|
| 2555 | pollingUpdateTimer = null;
|
|---|
| 2556 | }, 0);
|
|---|
| 2557 | }
|
|---|
| 2558 | }
|
|---|
| 2559 | function startNextPoll({
|
|---|
| 2560 | queryCacheKey
|
|---|
| 2561 | }, api2) {
|
|---|
| 2562 | const state = api2.getState()[reducerPath];
|
|---|
| 2563 | const querySubState = state.queries[queryCacheKey];
|
|---|
| 2564 | const subscriptions = currentSubscriptions.get(queryCacheKey);
|
|---|
| 2565 | if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) return;
|
|---|
| 2566 | const {
|
|---|
| 2567 | lowestPollingInterval,
|
|---|
| 2568 | skipPollingIfUnfocused
|
|---|
| 2569 | } = findLowestPollingInterval(subscriptions);
|
|---|
| 2570 | if (!Number.isFinite(lowestPollingInterval)) return;
|
|---|
| 2571 | const currentPoll = currentPolls.get(queryCacheKey);
|
|---|
| 2572 | if (currentPoll?.timeout) {
|
|---|
| 2573 | clearTimeout(currentPoll.timeout);
|
|---|
| 2574 | currentPoll.timeout = void 0;
|
|---|
| 2575 | }
|
|---|
| 2576 | const nextPollTimestamp = Date.now() + lowestPollingInterval;
|
|---|
| 2577 | currentPolls.set(queryCacheKey, {
|
|---|
| 2578 | nextPollTimestamp,
|
|---|
| 2579 | pollingInterval: lowestPollingInterval,
|
|---|
| 2580 | timeout: setTimeout(() => {
|
|---|
| 2581 | if (state.config.focused || !skipPollingIfUnfocused) {
|
|---|
| 2582 | api2.dispatch(refetchQuery(querySubState));
|
|---|
| 2583 | }
|
|---|
| 2584 | startNextPoll({
|
|---|
| 2585 | queryCacheKey
|
|---|
| 2586 | }, api2);
|
|---|
| 2587 | }, lowestPollingInterval)
|
|---|
| 2588 | });
|
|---|
| 2589 | }
|
|---|
| 2590 | function updatePollingInterval({
|
|---|
| 2591 | queryCacheKey
|
|---|
| 2592 | }, api2) {
|
|---|
| 2593 | const state = api2.getState()[reducerPath];
|
|---|
| 2594 | const querySubState = state.queries[queryCacheKey];
|
|---|
| 2595 | const subscriptions = currentSubscriptions.get(queryCacheKey);
|
|---|
| 2596 | if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) {
|
|---|
| 2597 | return;
|
|---|
| 2598 | }
|
|---|
| 2599 | const {
|
|---|
| 2600 | lowestPollingInterval
|
|---|
| 2601 | } = findLowestPollingInterval(subscriptions);
|
|---|
| 2602 | if (process.env.NODE_ENV === "test") {
|
|---|
| 2603 | const updateCounters = currentPolls.pollUpdateCounters ??= {};
|
|---|
| 2604 | updateCounters[queryCacheKey] ??= 0;
|
|---|
| 2605 | updateCounters[queryCacheKey]++;
|
|---|
| 2606 | }
|
|---|
| 2607 | if (!Number.isFinite(lowestPollingInterval)) {
|
|---|
| 2608 | cleanupPollForKey(queryCacheKey);
|
|---|
| 2609 | return;
|
|---|
| 2610 | }
|
|---|
| 2611 | const currentPoll = currentPolls.get(queryCacheKey);
|
|---|
| 2612 | const nextPollTimestamp = Date.now() + lowestPollingInterval;
|
|---|
| 2613 | if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {
|
|---|
| 2614 | startNextPoll({
|
|---|
| 2615 | queryCacheKey
|
|---|
| 2616 | }, api2);
|
|---|
| 2617 | }
|
|---|
| 2618 | }
|
|---|
| 2619 | function cleanupPollForKey(key) {
|
|---|
| 2620 | const existingPoll = currentPolls.get(key);
|
|---|
| 2621 | if (existingPoll?.timeout) {
|
|---|
| 2622 | clearTimeout(existingPoll.timeout);
|
|---|
| 2623 | }
|
|---|
| 2624 | currentPolls.delete(key);
|
|---|
| 2625 | }
|
|---|
| 2626 | function clearPolls() {
|
|---|
| 2627 | for (const key of currentPolls.keys()) {
|
|---|
| 2628 | cleanupPollForKey(key);
|
|---|
| 2629 | }
|
|---|
| 2630 | }
|
|---|
| 2631 | function findLowestPollingInterval(subscribers = /* @__PURE__ */ new Map()) {
|
|---|
| 2632 | let skipPollingIfUnfocused = false;
|
|---|
| 2633 | let lowestPollingInterval = Number.POSITIVE_INFINITY;
|
|---|
| 2634 | for (const entry of subscribers.values()) {
|
|---|
| 2635 | if (!!entry.pollingInterval) {
|
|---|
| 2636 | lowestPollingInterval = Math.min(entry.pollingInterval, lowestPollingInterval);
|
|---|
| 2637 | skipPollingIfUnfocused = entry.skipPollingIfUnfocused || skipPollingIfUnfocused;
|
|---|
| 2638 | }
|
|---|
| 2639 | }
|
|---|
| 2640 | return {
|
|---|
| 2641 | lowestPollingInterval,
|
|---|
| 2642 | skipPollingIfUnfocused
|
|---|
| 2643 | };
|
|---|
| 2644 | }
|
|---|
| 2645 | return handler;
|
|---|
| 2646 | };
|
|---|
| 2647 |
|
|---|
| 2648 | // src/query/core/buildMiddleware/queryLifecycle.ts
|
|---|
| 2649 | var buildQueryLifecycleHandler = ({
|
|---|
| 2650 | api,
|
|---|
| 2651 | context,
|
|---|
| 2652 | queryThunk,
|
|---|
| 2653 | mutationThunk
|
|---|
| 2654 | }) => {
|
|---|
| 2655 | const isPendingThunk = isPending(queryThunk, mutationThunk);
|
|---|
| 2656 | const isRejectedThunk = isRejected(queryThunk, mutationThunk);
|
|---|
| 2657 | const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk);
|
|---|
| 2658 | const lifecycleMap = {};
|
|---|
| 2659 | const handler = (action, mwApi) => {
|
|---|
| 2660 | if (isPendingThunk(action)) {
|
|---|
| 2661 | const {
|
|---|
| 2662 | requestId,
|
|---|
| 2663 | arg: {
|
|---|
| 2664 | endpointName,
|
|---|
| 2665 | originalArgs
|
|---|
| 2666 | }
|
|---|
| 2667 | } = action.meta;
|
|---|
| 2668 | const endpointDefinition = getEndpointDefinition(context, endpointName);
|
|---|
| 2669 | const onQueryStarted = endpointDefinition?.onQueryStarted;
|
|---|
| 2670 | if (onQueryStarted) {
|
|---|
| 2671 | const lifecycle = {};
|
|---|
| 2672 | const queryFulfilled = new Promise((resolve, reject) => {
|
|---|
| 2673 | lifecycle.resolve = resolve;
|
|---|
| 2674 | lifecycle.reject = reject;
|
|---|
| 2675 | });
|
|---|
| 2676 | queryFulfilled.catch(() => {
|
|---|
| 2677 | });
|
|---|
| 2678 | lifecycleMap[requestId] = lifecycle;
|
|---|
| 2679 | const selector = api.endpoints[endpointName].select(isAnyQueryDefinition(endpointDefinition) ? originalArgs : requestId);
|
|---|
| 2680 | const extra = mwApi.dispatch((_, __, extra2) => extra2);
|
|---|
| 2681 | const lifecycleApi = {
|
|---|
| 2682 | ...mwApi,
|
|---|
| 2683 | getCacheEntry: () => selector(mwApi.getState()),
|
|---|
| 2684 | requestId,
|
|---|
| 2685 | extra,
|
|---|
| 2686 | updateCachedData: isAnyQueryDefinition(endpointDefinition) ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
|
|---|
| 2687 | queryFulfilled
|
|---|
| 2688 | };
|
|---|
| 2689 | onQueryStarted(originalArgs, lifecycleApi);
|
|---|
| 2690 | }
|
|---|
| 2691 | } else if (isFullfilledThunk(action)) {
|
|---|
| 2692 | const {
|
|---|
| 2693 | requestId,
|
|---|
| 2694 | baseQueryMeta
|
|---|
| 2695 | } = action.meta;
|
|---|
| 2696 | lifecycleMap[requestId]?.resolve({
|
|---|
| 2697 | data: action.payload,
|
|---|
| 2698 | meta: baseQueryMeta
|
|---|
| 2699 | });
|
|---|
| 2700 | delete lifecycleMap[requestId];
|
|---|
| 2701 | } else if (isRejectedThunk(action)) {
|
|---|
| 2702 | const {
|
|---|
| 2703 | requestId,
|
|---|
| 2704 | rejectedWithValue,
|
|---|
| 2705 | baseQueryMeta
|
|---|
| 2706 | } = action.meta;
|
|---|
| 2707 | lifecycleMap[requestId]?.reject({
|
|---|
| 2708 | error: action.payload ?? action.error,
|
|---|
| 2709 | isUnhandledError: !rejectedWithValue,
|
|---|
| 2710 | meta: baseQueryMeta
|
|---|
| 2711 | });
|
|---|
| 2712 | delete lifecycleMap[requestId];
|
|---|
| 2713 | }
|
|---|
| 2714 | };
|
|---|
| 2715 | return handler;
|
|---|
| 2716 | };
|
|---|
| 2717 |
|
|---|
| 2718 | // src/query/core/buildMiddleware/windowEventHandling.ts
|
|---|
| 2719 | var buildWindowEventHandler = ({
|
|---|
| 2720 | reducerPath,
|
|---|
| 2721 | context,
|
|---|
| 2722 | api,
|
|---|
| 2723 | refetchQuery,
|
|---|
| 2724 | internalState
|
|---|
| 2725 | }) => {
|
|---|
| 2726 | const {
|
|---|
| 2727 | removeQueryResult
|
|---|
| 2728 | } = api.internalActions;
|
|---|
| 2729 | const handler = (action, mwApi) => {
|
|---|
| 2730 | if (onFocus.match(action)) {
|
|---|
| 2731 | refetchValidQueries(mwApi, "refetchOnFocus");
|
|---|
| 2732 | }
|
|---|
| 2733 | if (onOnline.match(action)) {
|
|---|
| 2734 | refetchValidQueries(mwApi, "refetchOnReconnect");
|
|---|
| 2735 | }
|
|---|
| 2736 | };
|
|---|
| 2737 | function refetchValidQueries(api2, type) {
|
|---|
| 2738 | const state = api2.getState()[reducerPath];
|
|---|
| 2739 | const queries = state.queries;
|
|---|
| 2740 | const subscriptions = internalState.currentSubscriptions;
|
|---|
| 2741 | context.batch(() => {
|
|---|
| 2742 | for (const queryCacheKey of subscriptions.keys()) {
|
|---|
| 2743 | const querySubState = queries[queryCacheKey];
|
|---|
| 2744 | const subscriptionSubState = subscriptions.get(queryCacheKey);
|
|---|
| 2745 | if (!subscriptionSubState || !querySubState) continue;
|
|---|
| 2746 | const values = [...subscriptionSubState.values()];
|
|---|
| 2747 | const shouldRefetch = values.some((sub) => sub[type] === true) || values.every((sub) => sub[type] === void 0) && state.config[type];
|
|---|
| 2748 | if (shouldRefetch) {
|
|---|
| 2749 | if (subscriptionSubState.size === 0) {
|
|---|
| 2750 | api2.dispatch(removeQueryResult({
|
|---|
| 2751 | queryCacheKey
|
|---|
| 2752 | }));
|
|---|
| 2753 | } else if (querySubState.status !== STATUS_UNINITIALIZED) {
|
|---|
| 2754 | api2.dispatch(refetchQuery(querySubState));
|
|---|
| 2755 | }
|
|---|
| 2756 | }
|
|---|
| 2757 | }
|
|---|
| 2758 | });
|
|---|
| 2759 | }
|
|---|
| 2760 | return handler;
|
|---|
| 2761 | };
|
|---|
| 2762 |
|
|---|
| 2763 | // src/query/core/buildMiddleware/index.ts
|
|---|
| 2764 | function buildMiddleware(input) {
|
|---|
| 2765 | const {
|
|---|
| 2766 | reducerPath,
|
|---|
| 2767 | queryThunk,
|
|---|
| 2768 | api,
|
|---|
| 2769 | context,
|
|---|
| 2770 | getInternalState
|
|---|
| 2771 | } = input;
|
|---|
| 2772 | const {
|
|---|
| 2773 | apiUid
|
|---|
| 2774 | } = context;
|
|---|
| 2775 | const actions2 = {
|
|---|
| 2776 | invalidateTags: createAction(`${reducerPath}/invalidateTags`)
|
|---|
| 2777 | };
|
|---|
| 2778 | const isThisApiSliceAction = (action) => action.type.startsWith(`${reducerPath}/`);
|
|---|
| 2779 | const handlerBuilders = [buildDevCheckHandler, buildCacheCollectionHandler, buildInvalidationByTagsHandler, buildPollingHandler, buildCacheLifecycleHandler, buildQueryLifecycleHandler];
|
|---|
| 2780 | const middleware = (mwApi) => {
|
|---|
| 2781 | let initialized2 = false;
|
|---|
| 2782 | const internalState = getInternalState(mwApi.dispatch);
|
|---|
| 2783 | const builderArgs = {
|
|---|
| 2784 | ...input,
|
|---|
| 2785 | internalState,
|
|---|
| 2786 | refetchQuery,
|
|---|
| 2787 | isThisApiSliceAction,
|
|---|
| 2788 | mwApi
|
|---|
| 2789 | };
|
|---|
| 2790 | const handlers = handlerBuilders.map((build) => build(builderArgs));
|
|---|
| 2791 | const batchedActionsHandler = buildBatchedActionsHandler(builderArgs);
|
|---|
| 2792 | const windowEventsHandler = buildWindowEventHandler(builderArgs);
|
|---|
| 2793 | return (next) => {
|
|---|
| 2794 | return (action) => {
|
|---|
| 2795 | if (!isAction(action)) {
|
|---|
| 2796 | return next(action);
|
|---|
| 2797 | }
|
|---|
| 2798 | if (!initialized2) {
|
|---|
| 2799 | initialized2 = true;
|
|---|
| 2800 | mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
|
|---|
| 2801 | }
|
|---|
| 2802 | const mwApiWithNext = {
|
|---|
| 2803 | ...mwApi,
|
|---|
| 2804 | next
|
|---|
| 2805 | };
|
|---|
| 2806 | const stateBefore = mwApi.getState();
|
|---|
| 2807 | const [actionShouldContinue, internalProbeResult] = batchedActionsHandler(action, mwApiWithNext, stateBefore);
|
|---|
| 2808 | let res;
|
|---|
| 2809 | if (actionShouldContinue) {
|
|---|
| 2810 | res = next(action);
|
|---|
| 2811 | } else {
|
|---|
| 2812 | res = internalProbeResult;
|
|---|
| 2813 | }
|
|---|
| 2814 | if (!!mwApi.getState()[reducerPath]) {
|
|---|
| 2815 | windowEventsHandler(action, mwApiWithNext, stateBefore);
|
|---|
| 2816 | if (isThisApiSliceAction(action) || context.hasRehydrationInfo(action)) {
|
|---|
| 2817 | for (const handler of handlers) {
|
|---|
| 2818 | handler(action, mwApiWithNext, stateBefore);
|
|---|
| 2819 | }
|
|---|
| 2820 | }
|
|---|
| 2821 | }
|
|---|
| 2822 | return res;
|
|---|
| 2823 | };
|
|---|
| 2824 | };
|
|---|
| 2825 | };
|
|---|
| 2826 | return {
|
|---|
| 2827 | middleware,
|
|---|
| 2828 | actions: actions2
|
|---|
| 2829 | };
|
|---|
| 2830 | function refetchQuery(querySubState) {
|
|---|
| 2831 | return input.api.endpoints[querySubState.endpointName].initiate(querySubState.originalArgs, {
|
|---|
| 2832 | subscribe: false,
|
|---|
| 2833 | forceRefetch: true
|
|---|
| 2834 | });
|
|---|
| 2835 | }
|
|---|
| 2836 | }
|
|---|
| 2837 |
|
|---|
| 2838 | // src/query/core/module.ts
|
|---|
| 2839 | var coreModuleName = /* @__PURE__ */ Symbol();
|
|---|
| 2840 | var coreModule = ({
|
|---|
| 2841 | createSelector: createSelector2 = createSelector
|
|---|
| 2842 | } = {}) => ({
|
|---|
| 2843 | name: coreModuleName,
|
|---|
| 2844 | init(api, {
|
|---|
| 2845 | baseQuery,
|
|---|
| 2846 | tagTypes,
|
|---|
| 2847 | reducerPath,
|
|---|
| 2848 | serializeQueryArgs,
|
|---|
| 2849 | keepUnusedDataFor,
|
|---|
| 2850 | refetchOnMountOrArgChange,
|
|---|
| 2851 | refetchOnFocus,
|
|---|
| 2852 | refetchOnReconnect,
|
|---|
| 2853 | invalidationBehavior,
|
|---|
| 2854 | onSchemaFailure,
|
|---|
| 2855 | catchSchemaFailure,
|
|---|
| 2856 | skipSchemaValidation
|
|---|
| 2857 | }, context) {
|
|---|
| 2858 | enablePatches();
|
|---|
| 2859 | assertCast(serializeQueryArgs);
|
|---|
| 2860 | const assertTagType = (tag) => {
|
|---|
| 2861 | if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
|
|---|
| 2862 | if (!tagTypes.includes(tag.type)) {
|
|---|
| 2863 | console.error(`Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!`);
|
|---|
| 2864 | }
|
|---|
| 2865 | }
|
|---|
| 2866 | return tag;
|
|---|
| 2867 | };
|
|---|
| 2868 | Object.assign(api, {
|
|---|
| 2869 | reducerPath,
|
|---|
| 2870 | endpoints: {},
|
|---|
| 2871 | internalActions: {
|
|---|
| 2872 | onOnline,
|
|---|
| 2873 | onOffline,
|
|---|
| 2874 | onFocus,
|
|---|
| 2875 | onFocusLost
|
|---|
| 2876 | },
|
|---|
| 2877 | util: {}
|
|---|
| 2878 | });
|
|---|
| 2879 | const selectors = buildSelectors({
|
|---|
| 2880 | serializeQueryArgs,
|
|---|
| 2881 | reducerPath,
|
|---|
| 2882 | createSelector: createSelector2
|
|---|
| 2883 | });
|
|---|
| 2884 | const {
|
|---|
| 2885 | selectInvalidatedBy,
|
|---|
| 2886 | selectCachedArgsForQuery,
|
|---|
| 2887 | buildQuerySelector,
|
|---|
| 2888 | buildInfiniteQuerySelector,
|
|---|
| 2889 | buildMutationSelector
|
|---|
| 2890 | } = selectors;
|
|---|
| 2891 | safeAssign(api.util, {
|
|---|
| 2892 | selectInvalidatedBy,
|
|---|
| 2893 | selectCachedArgsForQuery
|
|---|
| 2894 | });
|
|---|
| 2895 | const {
|
|---|
| 2896 | queryThunk,
|
|---|
| 2897 | infiniteQueryThunk,
|
|---|
| 2898 | mutationThunk,
|
|---|
| 2899 | patchQueryData,
|
|---|
| 2900 | updateQueryData,
|
|---|
| 2901 | upsertQueryData,
|
|---|
| 2902 | prefetch,
|
|---|
| 2903 | buildMatchThunkActions
|
|---|
| 2904 | } = buildThunks({
|
|---|
| 2905 | baseQuery,
|
|---|
| 2906 | reducerPath,
|
|---|
| 2907 | context,
|
|---|
| 2908 | api,
|
|---|
| 2909 | serializeQueryArgs,
|
|---|
| 2910 | assertTagType,
|
|---|
| 2911 | selectors,
|
|---|
| 2912 | onSchemaFailure,
|
|---|
| 2913 | catchSchemaFailure,
|
|---|
| 2914 | skipSchemaValidation
|
|---|
| 2915 | });
|
|---|
| 2916 | const {
|
|---|
| 2917 | reducer,
|
|---|
| 2918 | actions: sliceActions
|
|---|
| 2919 | } = buildSlice({
|
|---|
| 2920 | context,
|
|---|
| 2921 | queryThunk,
|
|---|
| 2922 | infiniteQueryThunk,
|
|---|
| 2923 | mutationThunk,
|
|---|
| 2924 | serializeQueryArgs,
|
|---|
| 2925 | reducerPath,
|
|---|
| 2926 | assertTagType,
|
|---|
| 2927 | config: {
|
|---|
| 2928 | refetchOnFocus,
|
|---|
| 2929 | refetchOnReconnect,
|
|---|
| 2930 | refetchOnMountOrArgChange,
|
|---|
| 2931 | keepUnusedDataFor,
|
|---|
| 2932 | reducerPath,
|
|---|
| 2933 | invalidationBehavior
|
|---|
| 2934 | }
|
|---|
| 2935 | });
|
|---|
| 2936 | safeAssign(api.util, {
|
|---|
| 2937 | patchQueryData,
|
|---|
| 2938 | updateQueryData,
|
|---|
| 2939 | upsertQueryData,
|
|---|
| 2940 | prefetch,
|
|---|
| 2941 | resetApiState: sliceActions.resetApiState,
|
|---|
| 2942 | upsertQueryEntries: sliceActions.cacheEntriesUpserted
|
|---|
| 2943 | });
|
|---|
| 2944 | safeAssign(api.internalActions, sliceActions);
|
|---|
| 2945 | const internalStateMap = /* @__PURE__ */ new WeakMap();
|
|---|
| 2946 | const getInternalState = (dispatch) => {
|
|---|
| 2947 | const state = getOrInsertComputed(internalStateMap, dispatch, () => ({
|
|---|
| 2948 | currentSubscriptions: /* @__PURE__ */ new Map(),
|
|---|
| 2949 | currentPolls: /* @__PURE__ */ new Map(),
|
|---|
| 2950 | runningQueries: /* @__PURE__ */ new Map(),
|
|---|
| 2951 | runningMutations: /* @__PURE__ */ new Map()
|
|---|
| 2952 | }));
|
|---|
| 2953 | return state;
|
|---|
| 2954 | };
|
|---|
| 2955 | const {
|
|---|
| 2956 | buildInitiateQuery,
|
|---|
| 2957 | buildInitiateInfiniteQuery,
|
|---|
| 2958 | buildInitiateMutation,
|
|---|
| 2959 | getRunningMutationThunk,
|
|---|
| 2960 | getRunningMutationsThunk,
|
|---|
| 2961 | getRunningQueriesThunk,
|
|---|
| 2962 | getRunningQueryThunk
|
|---|
| 2963 | } = buildInitiate({
|
|---|
| 2964 | queryThunk,
|
|---|
| 2965 | mutationThunk,
|
|---|
| 2966 | infiniteQueryThunk,
|
|---|
| 2967 | api,
|
|---|
| 2968 | serializeQueryArgs,
|
|---|
| 2969 | context,
|
|---|
| 2970 | getInternalState
|
|---|
| 2971 | });
|
|---|
| 2972 | safeAssign(api.util, {
|
|---|
| 2973 | getRunningMutationThunk,
|
|---|
| 2974 | getRunningMutationsThunk,
|
|---|
| 2975 | getRunningQueryThunk,
|
|---|
| 2976 | getRunningQueriesThunk
|
|---|
| 2977 | });
|
|---|
| 2978 | const {
|
|---|
| 2979 | middleware,
|
|---|
| 2980 | actions: middlewareActions
|
|---|
| 2981 | } = buildMiddleware({
|
|---|
| 2982 | reducerPath,
|
|---|
| 2983 | context,
|
|---|
| 2984 | queryThunk,
|
|---|
| 2985 | mutationThunk,
|
|---|
| 2986 | infiniteQueryThunk,
|
|---|
| 2987 | api,
|
|---|
| 2988 | assertTagType,
|
|---|
| 2989 | selectors,
|
|---|
| 2990 | getRunningQueryThunk,
|
|---|
| 2991 | getInternalState
|
|---|
| 2992 | });
|
|---|
| 2993 | safeAssign(api.util, middlewareActions);
|
|---|
| 2994 | safeAssign(api, {
|
|---|
| 2995 | reducer,
|
|---|
| 2996 | middleware
|
|---|
| 2997 | });
|
|---|
| 2998 | return {
|
|---|
| 2999 | name: coreModuleName,
|
|---|
| 3000 | injectEndpoint(endpointName, definition) {
|
|---|
| 3001 | const anyApi = api;
|
|---|
| 3002 | const endpoint = anyApi.endpoints[endpointName] ??= {};
|
|---|
| 3003 | if (isQueryDefinition(definition)) {
|
|---|
| 3004 | safeAssign(endpoint, {
|
|---|
| 3005 | name: endpointName,
|
|---|
| 3006 | select: buildQuerySelector(endpointName, definition),
|
|---|
| 3007 | initiate: buildInitiateQuery(endpointName, definition)
|
|---|
| 3008 | }, buildMatchThunkActions(queryThunk, endpointName));
|
|---|
| 3009 | }
|
|---|
| 3010 | if (isMutationDefinition(definition)) {
|
|---|
| 3011 | safeAssign(endpoint, {
|
|---|
| 3012 | name: endpointName,
|
|---|
| 3013 | select: buildMutationSelector(),
|
|---|
| 3014 | initiate: buildInitiateMutation(endpointName)
|
|---|
| 3015 | }, buildMatchThunkActions(mutationThunk, endpointName));
|
|---|
| 3016 | }
|
|---|
| 3017 | if (isInfiniteQueryDefinition(definition)) {
|
|---|
| 3018 | safeAssign(endpoint, {
|
|---|
| 3019 | name: endpointName,
|
|---|
| 3020 | select: buildInfiniteQuerySelector(endpointName, definition),
|
|---|
| 3021 | initiate: buildInitiateInfiniteQuery(endpointName, definition)
|
|---|
| 3022 | }, buildMatchThunkActions(queryThunk, endpointName));
|
|---|
| 3023 | }
|
|---|
| 3024 | }
|
|---|
| 3025 | };
|
|---|
| 3026 | }
|
|---|
| 3027 | });
|
|---|
| 3028 |
|
|---|
| 3029 | // src/query/core/index.ts
|
|---|
| 3030 | var createApi = /* @__PURE__ */ buildCreateApi(coreModule());
|
|---|
| 3031 | export {
|
|---|
| 3032 | NamedSchemaError,
|
|---|
| 3033 | QueryStatus,
|
|---|
| 3034 | _NEVER,
|
|---|
| 3035 | buildCreateApi,
|
|---|
| 3036 | copyWithStructuralSharing,
|
|---|
| 3037 | coreModule,
|
|---|
| 3038 | coreModuleName,
|
|---|
| 3039 | createApi,
|
|---|
| 3040 | defaultSerializeQueryArgs,
|
|---|
| 3041 | fakeBaseQuery,
|
|---|
| 3042 | fetchBaseQuery,
|
|---|
| 3043 | retry,
|
|---|
| 3044 | setupListeners,
|
|---|
| 3045 | skipToken
|
|---|
| 3046 | };
|
|---|
| 3047 | //# sourceMappingURL=rtk-query.modern.mjs.map |
|---|