1 | var __defProp = Object.defineProperty;
|
2 | var __defProps = Object.defineProperties;
|
3 | var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
4 | var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
5 | var __hasOwnProp = Object.prototype.hasOwnProperty;
|
6 | var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
7 | var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
8 | var __spreadValues = (a, b) => {
|
9 | for (var prop in b || (b = {}))
|
10 | if (__hasOwnProp.call(b, prop))
|
11 | __defNormalProp(a, prop, b[prop]);
|
12 | if (__getOwnPropSymbols)
|
13 | for (var prop of __getOwnPropSymbols(b)) {
|
14 | if (__propIsEnum.call(b, prop))
|
15 | __defNormalProp(a, prop, b[prop]);
|
16 | }
|
17 | return a;
|
18 | };
|
19 | var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
20 | var __objRest = (source, exclude) => {
|
21 | var target = {};
|
22 | for (var prop in source)
|
23 | if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0)
|
24 | target[prop] = source[prop];
|
25 | if (source != null && __getOwnPropSymbols)
|
26 | for (var prop of __getOwnPropSymbols(source)) {
|
27 | if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop))
|
28 | target[prop] = source[prop];
|
29 | }
|
30 | return target;
|
31 | };
|
32 |
|
33 | var QueryStatus;
|
34 | (function (QueryStatus2) {
|
35 | QueryStatus2["uninitialized"] = "uninitialized";
|
36 | QueryStatus2["pending"] = "pending";
|
37 | QueryStatus2["fulfilled"] = "fulfilled";
|
38 | QueryStatus2["rejected"] = "rejected";
|
39 | })(QueryStatus || (QueryStatus = {}));
|
40 | function getRequestStatusFlags(status) {
|
41 | return {
|
42 | status,
|
43 | isUninitialized: status === QueryStatus.uninitialized,
|
44 | isLoading: status === QueryStatus.pending,
|
45 | isSuccess: status === QueryStatus.fulfilled,
|
46 | isError: status === QueryStatus.rejected
|
47 | };
|
48 | }
|
49 |
|
50 | function isAbsoluteUrl(url) {
|
51 | return new RegExp(`(^|:)//`).test(url);
|
52 | }
|
53 |
|
54 | var withoutTrailingSlash = (url) => url.replace(/\/$/, "");
|
55 | var withoutLeadingSlash = (url) => url.replace(/^\//, "");
|
56 | function joinUrls(base, url) {
|
57 | if (!base) {
|
58 | return url;
|
59 | }
|
60 | if (!url) {
|
61 | return base;
|
62 | }
|
63 | if (isAbsoluteUrl(url)) {
|
64 | return url;
|
65 | }
|
66 | base = withoutTrailingSlash(base);
|
67 | url = withoutLeadingSlash(url);
|
68 | return `${base}/${url}`;
|
69 | }
|
70 |
|
71 | var flatten = (arr) => [].concat(...arr);
|
72 |
|
73 | function isOnline() {
|
74 | return typeof navigator === "undefined" ? true : navigator.onLine === void 0 ? true : navigator.onLine;
|
75 | }
|
76 |
|
77 | function isDocumentVisible() {
|
78 | if (typeof document === "undefined") {
|
79 | return true;
|
80 | }
|
81 | return document.visibilityState !== "hidden";
|
82 | }
|
83 |
|
84 | import { isPlainObject as _iPO } from "@reduxjs/toolkit";
|
85 | var isPlainObject = _iPO;
|
86 | function copyWithStructuralSharing(oldObj, newObj) {
|
87 | if (oldObj === newObj || !(isPlainObject(oldObj) && isPlainObject(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {
|
88 | return newObj;
|
89 | }
|
90 | const newKeys = Object.keys(newObj);
|
91 | const oldKeys = Object.keys(oldObj);
|
92 | let isSameObject = newKeys.length === oldKeys.length;
|
93 | const mergeObj = Array.isArray(newObj) ? [] : {};
|
94 | for (const key of newKeys) {
|
95 | mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);
|
96 | if (isSameObject)
|
97 | isSameObject = oldObj[key] === mergeObj[key];
|
98 | }
|
99 | return isSameObject ? oldObj : mergeObj;
|
100 | }
|
101 |
|
102 | import { isPlainObject as isPlainObject2 } from "@reduxjs/toolkit";
|
103 | var defaultFetchFn = (...args) => fetch(...args);
|
104 | var defaultValidateStatus = (response) => response.status >= 200 && response.status <= 299;
|
105 | var isJsonContentType = (headers) => {
|
106 | var _a, _b;
|
107 | return (_b = (_a = headers.get("content-type")) == null ? void 0 : _a.trim()) == null ? void 0 : _b.startsWith("application/json");
|
108 | };
|
109 | var handleResponse = async (response, responseHandler) => {
|
110 | if (typeof responseHandler === "function") {
|
111 | return responseHandler(response);
|
112 | }
|
113 | if (responseHandler === "text") {
|
114 | return response.text();
|
115 | }
|
116 | if (responseHandler === "json") {
|
117 | const text = await response.text();
|
118 | return text.length ? JSON.parse(text) : void 0;
|
119 | }
|
120 | };
|
121 | function stripUndefined(obj) {
|
122 | if (!isPlainObject2(obj)) {
|
123 | return obj;
|
124 | }
|
125 | const copy = __spreadValues({}, obj);
|
126 | for (const [k, v] of Object.entries(copy)) {
|
127 | if (typeof v === "undefined")
|
128 | delete copy[k];
|
129 | }
|
130 | return copy;
|
131 | }
|
132 | function fetchBaseQuery(_a = {}) {
|
133 | var _b = _a, { baseUrl, prepareHeaders = (x) => x, fetchFn = defaultFetchFn } = _b, baseFetchOptions = __objRest(_b, [
|
134 | "baseUrl",
|
135 | "prepareHeaders",
|
136 | "fetchFn"
|
137 | ]);
|
138 | if (typeof fetch === "undefined" && fetchFn === defaultFetchFn) {
|
139 | console.warn("Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.");
|
140 | }
|
141 | return async (arg, { signal, getState }) => {
|
142 | let meta;
|
143 | let _a2 = typeof arg == "string" ? { url: arg } : arg, { url, method = "GET", headers = new Headers({}), body = void 0, params = void 0, responseHandler = "json", validateStatus = defaultValidateStatus } = _a2, rest = __objRest(_a2, [
|
144 | "url",
|
145 | "method",
|
146 | "headers",
|
147 | "body",
|
148 | "params",
|
149 | "responseHandler",
|
150 | "validateStatus"
|
151 | ]);
|
152 | let config = __spreadValues(__spreadProps(__spreadValues({}, baseFetchOptions), {
|
153 | method,
|
154 | signal,
|
155 | body
|
156 | }), rest);
|
157 | config.headers = await prepareHeaders(new Headers(stripUndefined(headers)), { getState });
|
158 | const isJsonifiable = (body2) => typeof body2 === "object" && (isPlainObject2(body2) || Array.isArray(body2) || typeof body2.toJSON === "function");
|
159 | if (!config.headers.has("content-type") && isJsonifiable(body)) {
|
160 | config.headers.set("content-type", "application/json");
|
161 | }
|
162 | if (body && isJsonContentType(config.headers)) {
|
163 | config.body = JSON.stringify(body);
|
164 | }
|
165 | if (params) {
|
166 | const divider = ~url.indexOf("?") ? "&" : "?";
|
167 | const query = new URLSearchParams(stripUndefined(params));
|
168 | url += divider + query;
|
169 | }
|
170 | url = joinUrls(baseUrl, url);
|
171 | const request = new Request(url, config);
|
172 | const requestClone = request.clone();
|
173 | meta = { request: requestClone };
|
174 | let response;
|
175 | try {
|
176 | response = await fetchFn(request);
|
177 | }
|
178 | catch (e) {
|
179 | return { error: { status: "FETCH_ERROR", error: String(e) }, meta };
|
180 | }
|
181 | const responseClone = response.clone();
|
182 | meta.response = responseClone;
|
183 | let resultData;
|
184 | let responseText = "";
|
185 | try {
|
186 | let handleResponseError;
|
187 | await Promise.all([
|
188 | handleResponse(response, responseHandler).then((r) => resultData = r, (e) => handleResponseError = e),
|
189 | responseClone.text().then((r) => responseText = r, () => {
|
190 | })
|
191 | ]);
|
192 | if (handleResponseError)
|
193 | throw handleResponseError;
|
194 | }
|
195 | catch (e) {
|
196 | return {
|
197 | error: {
|
198 | status: "PARSING_ERROR",
|
199 | originalStatus: response.status,
|
200 | data: responseText,
|
201 | error: String(e)
|
202 | },
|
203 | meta
|
204 | };
|
205 | }
|
206 | return validateStatus(response, resultData) ? {
|
207 | data: resultData,
|
208 | meta
|
209 | } : {
|
210 | error: {
|
211 | status: response.status,
|
212 | data: resultData
|
213 | },
|
214 | meta
|
215 | };
|
216 | };
|
217 | }
|
218 |
|
219 | var HandledError = class {
|
220 | constructor(value, meta = void 0) {
|
221 | this.value = value;
|
222 | this.meta = meta;
|
223 | }
|
224 | };
|
225 |
|
226 | async function defaultBackoff(attempt = 0, maxRetries = 5) {
|
227 | const attempts = Math.min(attempt, maxRetries);
|
228 | const timeout = ~~((Math.random() + 0.4) * (300 << attempts));
|
229 | await new Promise((resolve) => setTimeout((res) => resolve(res), timeout));
|
230 | }
|
231 | function fail(e) {
|
232 | throw Object.assign(new HandledError({ error: e }), {
|
233 | throwImmediately: true
|
234 | });
|
235 | }
|
236 | var retryWithBackoff = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {
|
237 | const options = __spreadValues(__spreadValues({
|
238 | maxRetries: 5,
|
239 | backoff: defaultBackoff
|
240 | }, defaultOptions), extraOptions);
|
241 | let retry2 = 0;
|
242 | while (true) {
|
243 | try {
|
244 | const result = await baseQuery(args, api, extraOptions);
|
245 | if (result.error) {
|
246 | throw new HandledError(result);
|
247 | }
|
248 | return result;
|
249 | }
|
250 | catch (e) {
|
251 | retry2++;
|
252 | if (e.throwImmediately || retry2 > options.maxRetries) {
|
253 | if (e instanceof HandledError) {
|
254 | return e.value;
|
255 | }
|
256 | throw e;
|
257 | }
|
258 | await options.backoff(retry2, options.maxRetries);
|
259 | }
|
260 | }
|
261 | };
|
262 | var retry = Object.assign(retryWithBackoff, { fail });
|
263 |
|
264 | import { createAction } from "@reduxjs/toolkit";
|
265 | var onFocus = createAction("__rtkq/focused");
|
266 | var onFocusLost = createAction("__rtkq/unfocused");
|
267 | var onOnline = createAction("__rtkq/online");
|
268 | var onOffline = createAction("__rtkq/offline");
|
269 | var initialized = false;
|
270 | function setupListeners(dispatch, customHandler) {
|
271 | function defaultHandler() {
|
272 | const handleFocus = () => dispatch(onFocus());
|
273 | const handleFocusLost = () => dispatch(onFocusLost());
|
274 | const handleOnline = () => dispatch(onOnline());
|
275 | const handleOffline = () => dispatch(onOffline());
|
276 | const handleVisibilityChange = () => {
|
277 | if (window.document.visibilityState === "visible") {
|
278 | handleFocus();
|
279 | }
|
280 | else {
|
281 | handleFocusLost();
|
282 | }
|
283 | };
|
284 | if (!initialized) {
|
285 | if (typeof window !== "undefined" && window.addEventListener) {
|
286 | window.addEventListener("visibilitychange", handleVisibilityChange, false);
|
287 | window.addEventListener("focus", handleFocus, false);
|
288 | window.addEventListener("online", handleOnline, false);
|
289 | window.addEventListener("offline", handleOffline, false);
|
290 | initialized = true;
|
291 | }
|
292 | }
|
293 | const unsubscribe = () => {
|
294 | window.removeEventListener("focus", handleFocus);
|
295 | window.removeEventListener("visibilitychange", handleVisibilityChange);
|
296 | window.removeEventListener("online", handleOnline);
|
297 | window.removeEventListener("offline", handleOffline);
|
298 | initialized = false;
|
299 | };
|
300 | return unsubscribe;
|
301 | }
|
302 | return customHandler ? customHandler(dispatch, { onFocus, onFocusLost, onOffline, onOnline }) : defaultHandler();
|
303 | }
|
304 |
|
305 | import { createNextState, createSelector } from "@reduxjs/toolkit";
|
306 | var skipToken = Symbol.for("RTKQ/skipToken");
|
307 | var skipSelector = skipToken;
|
308 | var initialSubState = {
|
309 | status: QueryStatus.uninitialized
|
310 | };
|
311 | var defaultQuerySubState = createNextState(initialSubState, () => {
|
312 | });
|
313 | var defaultMutationSubState = createNextState(initialSubState, () => {
|
314 | });
|
315 | function buildSelectors({ serializeQueryArgs, reducerPath }) {
|
316 | return { buildQuerySelector, buildMutationSelector };
|
317 | function withRequestFlags(substate) {
|
318 | return __spreadValues(__spreadValues({}, substate), getRequestStatusFlags(substate.status));
|
319 | }
|
320 | function selectInternalState(rootState) {
|
321 | const state = rootState[reducerPath];
|
322 | if (true) {
|
323 | if (!state) {
|
324 | if (selectInternalState.triggered)
|
325 | return state;
|
326 | selectInternalState.triggered = true;
|
327 | console.error(`Error: No data found at \`state.${reducerPath}\`. Did you forget to add the reducer to the store?`);
|
328 | }
|
329 | }
|
330 | return state;
|
331 | }
|
332 | function buildQuerySelector(endpointName, endpointDefinition) {
|
333 | return (queryArgs) => {
|
334 | const selectQuerySubState = createSelector(selectInternalState, (internalState) => {
|
335 | var _a, _b;
|
336 | return (_b = queryArgs === skipToken ? void 0 : (_a = internalState == null ? void 0 : internalState.queries) == null ? void 0 : _a[serializeQueryArgs({
|
337 | queryArgs,
|
338 | endpointDefinition,
|
339 | endpointName
|
340 | })]) != null ? _b : defaultQuerySubState;
|
341 | });
|
342 | return createSelector(selectQuerySubState, withRequestFlags);
|
343 | };
|
344 | }
|
345 | function buildMutationSelector() {
|
346 | return (mutationId) => {
|
347 | const selectMutationSubstate = createSelector(selectInternalState, (internalState) => {
|
348 | var _a, _b;
|
349 | return (_b = mutationId === skipToken ? void 0 : (_a = internalState == null ? void 0 : internalState.mutations) == null ? void 0 : _a[mutationId]) != null ? _b : defaultMutationSubState;
|
350 | });
|
351 | return createSelector(selectMutationSubstate, withRequestFlags);
|
352 | };
|
353 | }
|
354 | }
|
355 |
|
356 | import { isPlainObject as isPlainObject3 } from "@reduxjs/toolkit";
|
357 | var defaultSerializeQueryArgs = ({ endpointName, queryArgs }) => {
|
358 | return `${endpointName}(${JSON.stringify(queryArgs, (key, value) => isPlainObject3(value) ? Object.keys(value).sort().reduce((acc, key2) => {
|
359 | acc[key2] = value[key2];
|
360 | return acc;
|
361 | }, {}) : value)})`;
|
362 | };
|
363 |
|
364 | var DefinitionType;
|
365 | (function (DefinitionType2) {
|
366 | DefinitionType2["query"] = "query";
|
367 | DefinitionType2["mutation"] = "mutation";
|
368 | })(DefinitionType || (DefinitionType = {}));
|
369 | function isQueryDefinition(e) {
|
370 | return e.type === DefinitionType.query;
|
371 | }
|
372 | function isMutationDefinition(e) {
|
373 | return e.type === DefinitionType.mutation;
|
374 | }
|
375 | function calculateProvidedBy(description, result, error, queryArg, assertTagTypes) {
|
376 | if (isFunction(description)) {
|
377 | return description(result, error, queryArg).map(expandTagDescription).map(assertTagTypes);
|
378 | }
|
379 | if (Array.isArray(description)) {
|
380 | return description.map(expandTagDescription).map(assertTagTypes);
|
381 | }
|
382 | return [];
|
383 | }
|
384 | function isFunction(t) {
|
385 | return typeof t === "function";
|
386 | }
|
387 | function expandTagDescription(description) {
|
388 | return typeof description === "string" ? { type: description } : description;
|
389 | }
|
390 |
|
391 | import { nanoid } from "@reduxjs/toolkit";
|
392 | function buildCreateApi(...modules) {
|
393 | return function baseCreateApi(options) {
|
394 | const optionsWithDefaults = __spreadProps(__spreadValues({
|
395 | reducerPath: "api",
|
396 | serializeQueryArgs: defaultSerializeQueryArgs,
|
397 | keepUnusedDataFor: 60,
|
398 | refetchOnMountOrArgChange: false,
|
399 | refetchOnFocus: false,
|
400 | refetchOnReconnect: false
|
401 | }, options), {
|
402 | tagTypes: [...options.tagTypes || []]
|
403 | });
|
404 | const context = {
|
405 | endpointDefinitions: {},
|
406 | batch(fn) {
|
407 | fn();
|
408 | },
|
409 | apiUid: nanoid()
|
410 | };
|
411 | const api = {
|
412 | injectEndpoints,
|
413 | enhanceEndpoints({ addTagTypes, endpoints }) {
|
414 | if (addTagTypes) {
|
415 | for (const eT of addTagTypes) {
|
416 | if (!optionsWithDefaults.tagTypes.includes(eT)) {
|
417 | optionsWithDefaults.tagTypes.push(eT);
|
418 | }
|
419 | }
|
420 | }
|
421 | if (endpoints) {
|
422 | for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {
|
423 | if (typeof partialDefinition === "function") {
|
424 | partialDefinition(context.endpointDefinitions[endpointName]);
|
425 | }
|
426 | Object.assign(context.endpointDefinitions[endpointName] || {}, partialDefinition);
|
427 | }
|
428 | }
|
429 | return api;
|
430 | }
|
431 | };
|
432 | const initializedModules = modules.map((m) => m.init(api, optionsWithDefaults, context));
|
433 | function injectEndpoints(inject) {
|
434 | const evaluatedEndpoints = inject.endpoints({
|
435 | query: (x) => __spreadProps(__spreadValues({}, x), { type: DefinitionType.query }),
|
436 | mutation: (x) => __spreadProps(__spreadValues({}, x), { type: DefinitionType.mutation })
|
437 | });
|
438 | for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {
|
439 | if (!inject.overrideExisting && endpointName in context.endpointDefinitions) {
|
440 | if (typeof process !== "undefined" && true) {
|
441 | console.error(`called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``);
|
442 | }
|
443 | continue;
|
444 | }
|
445 | context.endpointDefinitions[endpointName] = definition;
|
446 | for (const m of initializedModules) {
|
447 | m.injectEndpoint(endpointName, definition);
|
448 | }
|
449 | }
|
450 | return api;
|
451 | }
|
452 | return api.injectEndpoints({ endpoints: options.endpoints });
|
453 | };
|
454 | }
|
455 |
|
456 | function fakeBaseQuery() {
|
457 | return function () {
|
458 | throw new Error("When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.");
|
459 | };
|
460 | }
|
461 |
|
462 | import { isAllOf, isFulfilled, isPending, isRejected, isRejectedWithValue } from "@reduxjs/toolkit";
|
463 | import { isDraftable, produceWithPatches } from "immer";
|
464 | import { createAsyncThunk } from "@reduxjs/toolkit";
|
465 | function defaultTransformResponse(baseQueryReturnValue) {
|
466 | return baseQueryReturnValue;
|
467 | }
|
468 | function buildThunks({ reducerPath, baseQuery, context: { endpointDefinitions }, serializeQueryArgs, api }) {
|
469 | const patchQueryData = (endpointName, args, patches) => (dispatch) => {
|
470 | const endpointDefinition = endpointDefinitions[endpointName];
|
471 | dispatch(api.internalActions.queryResultPatched({
|
472 | queryCacheKey: serializeQueryArgs({
|
473 | queryArgs: args,
|
474 | endpointDefinition,
|
475 | endpointName
|
476 | }),
|
477 | patches
|
478 | }));
|
479 | };
|
480 | const updateQueryData = (endpointName, args, updateRecipe) => (dispatch, getState) => {
|
481 | const currentState = api.endpoints[endpointName].select(args)(getState());
|
482 | let ret = {
|
483 | patches: [],
|
484 | inversePatches: [],
|
485 | undo: () => dispatch(api.util.patchQueryData(endpointName, args, ret.inversePatches))
|
486 | };
|
487 | if (currentState.status === QueryStatus.uninitialized) {
|
488 | return ret;
|
489 | }
|
490 | if ("data" in currentState) {
|
491 | if (isDraftable(currentState.data)) {
|
492 | const [, patches, inversePatches] = produceWithPatches(currentState.data, updateRecipe);
|
493 | ret.patches.push(...patches);
|
494 | ret.inversePatches.push(...inversePatches);
|
495 | }
|
496 | else {
|
497 | const value = updateRecipe(currentState.data);
|
498 | ret.patches.push({ op: "replace", path: [], value });
|
499 | ret.inversePatches.push({
|
500 | op: "replace",
|
501 | path: [],
|
502 | value: currentState.data
|
503 | });
|
504 | }
|
505 | }
|
506 | dispatch(api.util.patchQueryData(endpointName, args, ret.patches));
|
507 | return ret;
|
508 | };
|
509 | const executeEndpoint = async (arg, { signal, rejectWithValue, fulfillWithValue, dispatch, getState, extra }) => {
|
510 | const endpointDefinition = endpointDefinitions[arg.endpointName];
|
511 | try {
|
512 | let transformResponse = defaultTransformResponse;
|
513 | let result;
|
514 | const baseQueryApi = {
|
515 | signal,
|
516 | dispatch,
|
517 | getState,
|
518 | extra
|
519 | };
|
520 | if (endpointDefinition.query) {
|
521 | result = await baseQuery(endpointDefinition.query(arg.originalArgs), baseQueryApi, endpointDefinition.extraOptions);
|
522 | if (endpointDefinition.transformResponse) {
|
523 | transformResponse = endpointDefinition.transformResponse;
|
524 | }
|
525 | }
|
526 | else {
|
527 | result = await endpointDefinition.queryFn(arg.originalArgs, baseQueryApi, endpointDefinition.extraOptions, (arg2) => baseQuery(arg2, baseQueryApi, endpointDefinition.extraOptions));
|
528 | }
|
529 | if (result.error)
|
530 | throw new HandledError(result.error, result.meta);
|
531 | return fulfillWithValue(await transformResponse(result.data, result.meta), {
|
532 | fulfilledTimeStamp: Date.now(),
|
533 | baseQueryMeta: result.meta
|
534 | });
|
535 | }
|
536 | catch (error) {
|
537 | if (error instanceof HandledError) {
|
538 | return rejectWithValue(error.value, { baseQueryMeta: error.meta });
|
539 | }
|
540 | if (typeof process !== "undefined" && true) {
|
541 | console.error(`An unhandled error occured processing a request for the endpoint "${arg.endpointName}".
|
542 | In the case of an unhandled error, no tags will be "provided" or "invalidated".`, error);
|
543 | }
|
544 | else {
|
545 | console.error(error);
|
546 | }
|
547 | throw error;
|
548 | }
|
549 | };
|
550 | const queryThunk = createAsyncThunk(`${reducerPath}/executeQuery`, executeEndpoint, {
|
551 | getPendingMeta() {
|
552 | return { startedTimeStamp: Date.now() };
|
553 | },
|
554 | condition(arg, { getState }) {
|
555 | var _a, _b;
|
556 | const state = getState()[reducerPath];
|
557 | const requestState = (_a = state == null ? void 0 : state.queries) == null ? void 0 : _a[arg.queryCacheKey];
|
558 | const baseFetchOnMountOrArgChange = state.config.refetchOnMountOrArgChange;
|
559 | const fulfilledVal = requestState == null ? void 0 : requestState.fulfilledTimeStamp;
|
560 | const refetchVal = (_b = arg.forceRefetch) != null ? _b : arg.subscribe && baseFetchOnMountOrArgChange;
|
561 | if ((requestState == null ? void 0 : requestState.status) === "pending")
|
562 | return false;
|
563 | if (fulfilledVal) {
|
564 | if (refetchVal) {
|
565 | return refetchVal === true || (Number(new Date()) - Number(fulfilledVal)) / 1e3 >= refetchVal;
|
566 | }
|
567 | return false;
|
568 | }
|
569 | return true;
|
570 | },
|
571 | dispatchConditionRejection: true
|
572 | });
|
573 | const mutationThunk = createAsyncThunk(`${reducerPath}/executeMutation`, executeEndpoint, {
|
574 | getPendingMeta() {
|
575 | return { startedTimeStamp: Date.now() };
|
576 | }
|
577 | });
|
578 | const hasTheForce = (options) => "force" in options;
|
579 | const hasMaxAge = (options) => "ifOlderThan" in options;
|
580 | const prefetch = (endpointName, arg, options) => (dispatch, getState) => {
|
581 | const force = hasTheForce(options) && options.force;
|
582 | const maxAge = hasMaxAge(options) && options.ifOlderThan;
|
583 | const queryAction = (force2 = true) => api.endpoints[endpointName].initiate(arg, { forceRefetch: force2 });
|
584 | const latestStateValue = api.endpoints[endpointName].select(arg)(getState());
|
585 | if (force) {
|
586 | dispatch(queryAction());
|
587 | }
|
588 | else if (maxAge) {
|
589 | const lastFulfilledTs = latestStateValue == null ? void 0 : latestStateValue.fulfilledTimeStamp;
|
590 | if (!lastFulfilledTs) {
|
591 | dispatch(queryAction());
|
592 | return;
|
593 | }
|
594 | const shouldRetrigger = (Number(new Date()) - Number(new Date(lastFulfilledTs))) / 1e3 >= maxAge;
|
595 | if (shouldRetrigger) {
|
596 | dispatch(queryAction());
|
597 | }
|
598 | }
|
599 | else {
|
600 | dispatch(queryAction(false));
|
601 | }
|
602 | };
|
603 | function matchesEndpoint(endpointName) {
|
604 | return (action) => {
|
605 | var _a, _b;
|
606 | return ((_b = (_a = action == null ? void 0 : action.meta) == null ? void 0 : _a.arg) == null ? void 0 : _b.endpointName) === endpointName;
|
607 | };
|
608 | }
|
609 | function buildMatchThunkActions(thunk, endpointName) {
|
610 | return {
|
611 | matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),
|
612 | matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpointName)),
|
613 | matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName))
|
614 | };
|
615 | }
|
616 | return {
|
617 | queryThunk,
|
618 | mutationThunk,
|
619 | prefetch,
|
620 | updateQueryData,
|
621 | patchQueryData,
|
622 | buildMatchThunkActions
|
623 | };
|
624 | }
|
625 | function calculateProvidedByThunk(action, type, endpointDefinitions, assertTagType) {
|
626 | return calculateProvidedBy(endpointDefinitions[action.meta.arg.endpointName][type], isFulfilled(action) ? action.payload : void 0, isRejectedWithValue(action) ? action.payload : void 0, action.meta.arg.originalArgs, assertTagType);
|
627 | }
|
628 |
|
629 | import { combineReducers, createAction as createAction2, createSlice, isAnyOf, isFulfilled as isFulfilled2, isRejectedWithValue as isRejectedWithValue2 } from "@reduxjs/toolkit";
|
630 | import { applyPatches } from "immer";
|
631 | function updateQuerySubstateIfExists(state, queryCacheKey, update) {
|
632 | const substate = state[queryCacheKey];
|
633 | if (substate) {
|
634 | update(substate);
|
635 | }
|
636 | }
|
637 | function updateMutationSubstateIfExists(state, { requestId }, update) {
|
638 | const substate = state[requestId];
|
639 | if (substate) {
|
640 | update(substate);
|
641 | }
|
642 | }
|
643 | var initialState = {};
|
644 | function buildSlice({ reducerPath, queryThunk, mutationThunk, context: { endpointDefinitions: definitions, apiUid }, assertTagType, config }) {
|
645 | const resetApiState = createAction2(`${reducerPath}/resetApiState`);
|
646 | const querySlice = createSlice({
|
647 | name: `${reducerPath}/queries`,
|
648 | initialState,
|
649 | reducers: {
|
650 | removeQueryResult(draft, { payload: { queryCacheKey } }) {
|
651 | delete draft[queryCacheKey];
|
652 | },
|
653 | queryResultPatched(draft, { payload: { queryCacheKey, patches } }) {
|
654 | updateQuerySubstateIfExists(draft, queryCacheKey, (substate) => {
|
655 | substate.data = applyPatches(substate.data, patches.concat());
|
656 | });
|
657 | }
|
658 | },
|
659 | extraReducers(builder) {
|
660 | builder.addCase(queryThunk.pending, (draft, { meta, meta: { arg } }) => {
|
661 | var _a, _b;
|
662 | if (arg.subscribe) {
|
663 | (_b = draft[_a = arg.queryCacheKey]) != null ? _b : draft[_a] = {
|
664 | status: QueryStatus.uninitialized,
|
665 | endpointName: arg.endpointName
|
666 | };
|
667 | }
|
668 | updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
|
669 | substate.status = QueryStatus.pending;
|
670 | substate.requestId = meta.requestId;
|
671 | substate.originalArgs = arg.originalArgs;
|
672 | substate.startedTimeStamp = meta.startedTimeStamp;
|
673 | });
|
674 | }).addCase(queryThunk.fulfilled, (draft, { meta, payload }) => {
|
675 | updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, (substate) => {
|
676 | if (substate.requestId !== meta.requestId)
|
677 | return;
|
678 | substate.status = QueryStatus.fulfilled;
|
679 | substate.data = copyWithStructuralSharing(substate.data, payload);
|
680 | delete substate.error;
|
681 | substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
|
682 | });
|
683 | }).addCase(queryThunk.rejected, (draft, { meta: { condition, arg, requestId }, error, payload }) => {
|
684 | updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
|
685 | if (condition) {
|
686 | }
|
687 | else {
|
688 | if (substate.requestId !== requestId)
|
689 | return;
|
690 | substate.status = QueryStatus.rejected;
|
691 | substate.error = payload != null ? payload : error;
|
692 | }
|
693 | });
|
694 | });
|
695 | }
|
696 | });
|
697 | const mutationSlice = createSlice({
|
698 | name: `${reducerPath}/mutations`,
|
699 | initialState,
|
700 | reducers: {
|
701 | unsubscribeMutationResult(draft, action) {
|
702 | if (action.payload.requestId in draft) {
|
703 | delete draft[action.payload.requestId];
|
704 | }
|
705 | }
|
706 | },
|
707 | extraReducers(builder) {
|
708 | builder.addCase(mutationThunk.pending, (draft, { meta: { arg, requestId, startedTimeStamp } }) => {
|
709 | if (!arg.track)
|
710 | return;
|
711 | draft[requestId] = {
|
712 | status: QueryStatus.pending,
|
713 | endpointName: arg.endpointName,
|
714 | startedTimeStamp
|
715 | };
|
716 | }).addCase(mutationThunk.fulfilled, (draft, { payload, meta, meta: { requestId } }) => {
|
717 | if (!meta.arg.track)
|
718 | return;
|
719 | updateMutationSubstateIfExists(draft, { requestId }, (substate) => {
|
720 | substate.status = QueryStatus.fulfilled;
|
721 | substate.data = payload;
|
722 | substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
|
723 | });
|
724 | }).addCase(mutationThunk.rejected, (draft, { payload, error, meta: { requestId, arg } }) => {
|
725 | if (!arg.track)
|
726 | return;
|
727 | updateMutationSubstateIfExists(draft, { requestId }, (substate) => {
|
728 | substate.status = QueryStatus.rejected;
|
729 | substate.error = payload != null ? payload : error;
|
730 | });
|
731 | });
|
732 | }
|
733 | });
|
734 | const invalidationSlice = createSlice({
|
735 | name: `${reducerPath}/invalidation`,
|
736 | initialState,
|
737 | reducers: {},
|
738 | extraReducers(builder) {
|
739 | builder.addCase(querySlice.actions.removeQueryResult, (draft, { payload: { queryCacheKey } }) => {
|
740 | for (const tagTypeSubscriptions of Object.values(draft)) {
|
741 | for (const idSubscriptions of Object.values(tagTypeSubscriptions)) {
|
742 | const foundAt = idSubscriptions.indexOf(queryCacheKey);
|
743 | if (foundAt !== -1) {
|
744 | idSubscriptions.splice(foundAt, 1);
|
745 | }
|
746 | }
|
747 | }
|
748 | }).addMatcher(isAnyOf(isFulfilled2(queryThunk), isRejectedWithValue2(queryThunk)), (draft, action) => {
|
749 | var _a, _b, _c, _d;
|
750 | const providedTags = calculateProvidedByThunk(action, "providesTags", definitions, assertTagType);
|
751 | const { queryCacheKey } = action.meta.arg;
|
752 | for (const { type, id } of providedTags) {
|
753 | const subscribedQueries = (_d = (_b = (_a = draft[type]) != null ? _a : draft[type] = {})[_c = id || "__internal_without_id"]) != null ? _d : _b[_c] = [];
|
754 | const alreadySubscribed = subscribedQueries.includes(queryCacheKey);
|
755 | if (!alreadySubscribed) {
|
756 | subscribedQueries.push(queryCacheKey);
|
757 | }
|
758 | }
|
759 | });
|
760 | }
|
761 | });
|
762 | const subscriptionSlice = createSlice({
|
763 | name: `${reducerPath}/subscriptions`,
|
764 | initialState,
|
765 | reducers: {
|
766 | updateSubscriptionOptions(draft, { payload: { queryCacheKey, requestId, options } }) {
|
767 | var _a;
|
768 | if ((_a = draft == null ? void 0 : draft[queryCacheKey]) == null ? void 0 : _a[requestId]) {
|
769 | draft[queryCacheKey][requestId] = options;
|
770 | }
|
771 | },
|
772 | unsubscribeQueryResult(draft, { payload: { queryCacheKey, requestId } }) {
|
773 | if (draft[queryCacheKey]) {
|
774 | delete draft[queryCacheKey][requestId];
|
775 | }
|
776 | }
|
777 | },
|
778 | extraReducers: (builder) => {
|
779 | builder.addCase(querySlice.actions.removeQueryResult, (draft, { payload: { queryCacheKey } }) => {
|
780 | delete draft[queryCacheKey];
|
781 | }).addCase(queryThunk.pending, (draft, { meta: { arg, requestId } }) => {
|
782 | var _a, _b, _c, _d;
|
783 | if (arg.subscribe) {
|
784 | const substate = (_b = draft[_a = arg.queryCacheKey]) != null ? _b : draft[_a] = {};
|
785 | substate[requestId] = (_d = (_c = arg.subscriptionOptions) != null ? _c : substate[requestId]) != null ? _d : {};
|
786 | }
|
787 | }).addCase(queryThunk.rejected, (draft, { meta: { condition, arg, requestId }, error, payload }) => {
|
788 | var _a, _b;
|
789 | const substate = draft[arg.queryCacheKey];
|
790 | if (condition && arg.subscribe && substate) {
|
791 | substate[requestId] = (_b = (_a = arg.subscriptionOptions) != null ? _a : substate[requestId]) != null ? _b : {};
|
792 | }
|
793 | });
|
794 | }
|
795 | });
|
796 | const configSlice = createSlice({
|
797 | name: `${reducerPath}/config`,
|
798 | initialState: __spreadValues({
|
799 | online: isOnline(),
|
800 | focused: isDocumentVisible(),
|
801 | middlewareRegistered: false
|
802 | }, config),
|
803 | reducers: {
|
804 | middlewareRegistered(state, { payload }) {
|
805 | state.middlewareRegistered = state.middlewareRegistered === "conflict" || apiUid !== payload ? "conflict" : true;
|
806 | }
|
807 | },
|
808 | extraReducers: (builder) => {
|
809 | builder.addCase(onOnline, (state) => {
|
810 | state.online = true;
|
811 | }).addCase(onOffline, (state) => {
|
812 | state.online = false;
|
813 | }).addCase(onFocus, (state) => {
|
814 | state.focused = true;
|
815 | }).addCase(onFocusLost, (state) => {
|
816 | state.focused = false;
|
817 | });
|
818 | }
|
819 | });
|
820 | const combinedReducer = combineReducers({
|
821 | queries: querySlice.reducer,
|
822 | mutations: mutationSlice.reducer,
|
823 | provided: invalidationSlice.reducer,
|
824 | subscriptions: subscriptionSlice.reducer,
|
825 | config: configSlice.reducer
|
826 | });
|
827 | const reducer = (state, action) => combinedReducer(resetApiState.match(action) ? void 0 : state, action);
|
828 | const actions = __spreadProps(__spreadValues(__spreadValues(__spreadValues(__spreadValues({}, configSlice.actions), querySlice.actions), subscriptionSlice.actions), mutationSlice.actions), {
|
829 | resetApiState
|
830 | });
|
831 | return { reducer, actions };
|
832 | }
|
833 |
|
834 | import { compose } from "redux";
|
835 | import { createAction as createAction3 } from "@reduxjs/toolkit";
|
836 |
|
837 | var build = ({ reducerPath, api, context }) => {
|
838 | const { removeQueryResult, unsubscribeQueryResult } = api.internalActions;
|
839 | return (mwApi) => {
|
840 | const currentRemovalTimeouts = {};
|
841 | return (next) => (action) => {
|
842 | var _a, _b;
|
843 | const result = next(action);
|
844 | if (unsubscribeQueryResult.match(action)) {
|
845 | const state = mwApi.getState()[reducerPath];
|
846 | const { queryCacheKey } = action.payload;
|
847 | const endpointDefinition = context.endpointDefinitions[(_a = state.queries[queryCacheKey]) == null ? void 0 : _a.endpointName];
|
848 | handleUnsubscribe(queryCacheKey, mwApi, (_b = endpointDefinition == null ? void 0 : endpointDefinition.keepUnusedDataFor) != null ? _b : state.config.keepUnusedDataFor);
|
849 | }
|
850 | if (api.util.resetApiState.match(action)) {
|
851 | for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {
|
852 | if (timeout)
|
853 | clearTimeout(timeout);
|
854 | delete currentRemovalTimeouts[key];
|
855 | }
|
856 | }
|
857 | return result;
|
858 | };
|
859 | function handleUnsubscribe(queryCacheKey, api2, keepUnusedDataFor) {
|
860 | const currentTimeout = currentRemovalTimeouts[queryCacheKey];
|
861 | if (currentTimeout) {
|
862 | clearTimeout(currentTimeout);
|
863 | }
|
864 | currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {
|
865 | const subscriptions = api2.getState()[reducerPath].subscriptions[queryCacheKey];
|
866 | if (!subscriptions || Object.keys(subscriptions).length === 0) {
|
867 | api2.dispatch(removeQueryResult({ queryCacheKey }));
|
868 | }
|
869 | delete currentRemovalTimeouts[queryCacheKey];
|
870 | }, keepUnusedDataFor * 1e3);
|
871 | }
|
872 | };
|
873 | };
|
874 |
|
875 | import { isAnyOf as isAnyOf2, isFulfilled as isFulfilled3, isRejectedWithValue as isRejectedWithValue3 } from "@reduxjs/toolkit";
|
876 | var build2 = ({ reducerPath, context, context: { endpointDefinitions }, mutationThunk, api, assertTagType, refetchQuery }) => {
|
877 | const { removeQueryResult } = api.internalActions;
|
878 | return (mwApi) => (next) => (action) => {
|
879 | const result = next(action);
|
880 | if (isAnyOf2(isFulfilled3(mutationThunk), isRejectedWithValue3(mutationThunk))(action)) {
|
881 | invalidateTags(calculateProvidedByThunk(action, "invalidatesTags", endpointDefinitions, assertTagType), mwApi);
|
882 | }
|
883 | if (api.util.invalidateTags.match(action)) {
|
884 | invalidateTags(calculateProvidedBy(action.payload, void 0, void 0, void 0, assertTagType), mwApi);
|
885 | }
|
886 | return result;
|
887 | };
|
888 | function invalidateTags(tags, api2) {
|
889 | var _a;
|
890 | const state = api2.getState()[reducerPath];
|
891 | const toInvalidate = new Set();
|
892 | for (const tag of tags) {
|
893 | const provided = state.provided[tag.type];
|
894 | if (!provided) {
|
895 | continue;
|
896 | }
|
897 | let invalidateSubscriptions = (_a = tag.id !== void 0 ? provided[tag.id] : flatten(Object.values(provided))) != null ? _a : [];
|
898 | for (const invalidate of invalidateSubscriptions) {
|
899 | toInvalidate.add(invalidate);
|
900 | }
|
901 | }
|
902 | context.batch(() => {
|
903 | const valuesArray = Array.from(toInvalidate.values());
|
904 | for (const queryCacheKey of valuesArray) {
|
905 | const querySubState = state.queries[queryCacheKey];
|
906 | const subscriptionSubState = state.subscriptions[queryCacheKey];
|
907 | if (querySubState && subscriptionSubState) {
|
908 | if (Object.keys(subscriptionSubState).length === 0) {
|
909 | api2.dispatch(removeQueryResult({ queryCacheKey }));
|
910 | }
|
911 | else if (querySubState.status !== QueryStatus.uninitialized) {
|
912 | api2.dispatch(refetchQuery(querySubState, queryCacheKey));
|
913 | }
|
914 | else {
|
915 | }
|
916 | }
|
917 | }
|
918 | });
|
919 | }
|
920 | };
|
921 |
|
922 | var build3 = ({ reducerPath, queryThunk, api, refetchQuery }) => {
|
923 | return (mwApi) => {
|
924 | const currentPolls = {};
|
925 | return (next) => (action) => {
|
926 | const result = next(action);
|
927 | if (api.internalActions.updateSubscriptionOptions.match(action)) {
|
928 | updatePollingInterval(action.payload, mwApi);
|
929 | }
|
930 | if (queryThunk.pending.match(action) || queryThunk.rejected.match(action) && action.meta.condition) {
|
931 | updatePollingInterval(action.meta.arg, mwApi);
|
932 | }
|
933 | if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action) && !action.meta.condition) {
|
934 | startNextPoll(action.meta.arg, mwApi);
|
935 | }
|
936 | if (api.util.resetApiState.match(action)) {
|
937 | clearPolls();
|
938 | }
|
939 | return result;
|
940 | };
|
941 | function startNextPoll({ queryCacheKey }, api2) {
|
942 | const state = api2.getState()[reducerPath];
|
943 | const querySubState = state.queries[queryCacheKey];
|
944 | const subscriptions = state.subscriptions[queryCacheKey];
|
945 | if (!querySubState || querySubState.status === QueryStatus.uninitialized)
|
946 | return;
|
947 | const lowestPollingInterval = findLowestPollingInterval(subscriptions);
|
948 | if (!Number.isFinite(lowestPollingInterval))
|
949 | return;
|
950 | const currentPoll = currentPolls[queryCacheKey];
|
951 | if (currentPoll == null ? void 0 : currentPoll.timeout) {
|
952 | clearTimeout(currentPoll.timeout);
|
953 | currentPoll.timeout = void 0;
|
954 | }
|
955 | const nextPollTimestamp = Date.now() + lowestPollingInterval;
|
956 | const currentInterval = currentPolls[queryCacheKey] = {
|
957 | nextPollTimestamp,
|
958 | pollingInterval: lowestPollingInterval,
|
959 | timeout: setTimeout(() => {
|
960 | currentInterval.timeout = void 0;
|
961 | api2.dispatch(refetchQuery(querySubState, queryCacheKey));
|
962 | }, lowestPollingInterval)
|
963 | };
|
964 | }
|
965 | function updatePollingInterval({ queryCacheKey }, api2) {
|
966 | const state = api2.getState()[reducerPath];
|
967 | const querySubState = state.queries[queryCacheKey];
|
968 | const subscriptions = state.subscriptions[queryCacheKey];
|
969 | if (!querySubState || querySubState.status === QueryStatus.uninitialized) {
|
970 | return;
|
971 | }
|
972 | const lowestPollingInterval = findLowestPollingInterval(subscriptions);
|
973 | const currentPoll = currentPolls[queryCacheKey];
|
974 | if (!Number.isFinite(lowestPollingInterval)) {
|
975 | if (currentPoll == null ? void 0 : currentPoll.timeout) {
|
976 | clearTimeout(currentPoll.timeout);
|
977 | }
|
978 | delete currentPolls[queryCacheKey];
|
979 | return;
|
980 | }
|
981 | const nextPollTimestamp = Date.now() + lowestPollingInterval;
|
982 | if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {
|
983 | startNextPoll({ queryCacheKey }, api2);
|
984 | }
|
985 | }
|
986 | function clearPolls() {
|
987 | for (const [key, poll] of Object.entries(currentPolls)) {
|
988 | if (poll == null ? void 0 : poll.timeout)
|
989 | clearTimeout(poll.timeout);
|
990 | delete currentPolls[key];
|
991 | }
|
992 | }
|
993 | };
|
994 | function findLowestPollingInterval(subscribers = {}) {
|
995 | let lowestPollingInterval = Number.POSITIVE_INFINITY;
|
996 | for (const subscription of Object.values(subscribers)) {
|
997 | if (!!subscription.pollingInterval)
|
998 | lowestPollingInterval = Math.min(subscription.pollingInterval, lowestPollingInterval);
|
999 | }
|
1000 | return lowestPollingInterval;
|
1001 | }
|
1002 | };
|
1003 |
|
1004 | var build4 = ({ reducerPath, context, refetchQuery }) => {
|
1005 | return (mwApi) => (next) => (action) => {
|
1006 | const result = next(action);
|
1007 | if (onFocus.match(action)) {
|
1008 | refetchValidQueries(mwApi, "refetchOnFocus");
|
1009 | }
|
1010 | if (onOnline.match(action)) {
|
1011 | refetchValidQueries(mwApi, "refetchOnReconnect");
|
1012 | }
|
1013 | return result;
|
1014 | };
|
1015 | function refetchValidQueries(api, type) {
|
1016 | const state = api.getState()[reducerPath];
|
1017 | const queries = state.queries;
|
1018 | const subscriptions = state.subscriptions;
|
1019 | context.batch(() => {
|
1020 | for (const queryCacheKey of Object.keys(subscriptions)) {
|
1021 | const querySubState = queries[queryCacheKey];
|
1022 | const subscriptionSubState = subscriptions[queryCacheKey];
|
1023 | if (!subscriptionSubState || !querySubState || querySubState.status === QueryStatus.uninitialized)
|
1024 | return;
|
1025 | const shouldRefetch = Object.values(subscriptionSubState).some((sub) => sub[type] === true) || Object.values(subscriptionSubState).every((sub) => sub[type] === void 0) && state.config[type];
|
1026 | if (shouldRefetch) {
|
1027 | api.dispatch(refetchQuery(querySubState, queryCacheKey));
|
1028 | }
|
1029 | }
|
1030 | });
|
1031 | }
|
1032 | };
|
1033 |
|
1034 | import { isAsyncThunkAction, isFulfilled as isFulfilled4 } from "@reduxjs/toolkit";
|
1035 | var neverResolvedError = new Error("Promise never resolved before cacheEntryRemoved.");
|
1036 | var build5 = ({ api, reducerPath, context, queryThunk, mutationThunk }) => {
|
1037 | const isQueryThunk = isAsyncThunkAction(queryThunk);
|
1038 | const isMutationThunk = isAsyncThunkAction(mutationThunk);
|
1039 | const isFullfilledThunk = isFulfilled4(queryThunk, mutationThunk);
|
1040 | return (mwApi) => {
|
1041 | const lifecycleMap = {};
|
1042 | return (next) => (action) => {
|
1043 | const stateBefore = mwApi.getState();
|
1044 | const result = next(action);
|
1045 | const cacheKey = getCacheKey(action);
|
1046 | if (queryThunk.pending.match(action)) {
|
1047 | const oldState = stateBefore[reducerPath].queries[cacheKey];
|
1048 | const state = mwApi.getState()[reducerPath].queries[cacheKey];
|
1049 | if (!oldState && state) {
|
1050 | handleNewKey(action.meta.arg.endpointName, action.meta.arg.originalArgs, cacheKey, mwApi, action.meta.requestId);
|
1051 | }
|
1052 | }
|
1053 | else if (mutationThunk.pending.match(action)) {
|
1054 | const state = mwApi.getState()[reducerPath].mutations[cacheKey];
|
1055 | if (state) {
|
1056 | handleNewKey(action.meta.arg.endpointName, action.meta.arg.originalArgs, cacheKey, mwApi, action.meta.requestId);
|
1057 | }
|
1058 | }
|
1059 | else if (isFullfilledThunk(action)) {
|
1060 | const lifecycle = lifecycleMap[cacheKey];
|
1061 | if (lifecycle == null ? void 0 : lifecycle.valueResolved) {
|
1062 | lifecycle.valueResolved({
|
1063 | data: action.payload,
|
1064 | meta: action.meta.baseQueryMeta
|
1065 | });
|
1066 | delete lifecycle.valueResolved;
|
1067 | }
|
1068 | }
|
1069 | else if (api.internalActions.removeQueryResult.match(action) || api.internalActions.unsubscribeMutationResult.match(action)) {
|
1070 | const lifecycle = lifecycleMap[cacheKey];
|
1071 | if (lifecycle) {
|
1072 | delete lifecycleMap[cacheKey];
|
1073 | lifecycle.cacheEntryRemoved();
|
1074 | }
|
1075 | }
|
1076 | else if (api.util.resetApiState.match(action)) {
|
1077 | for (const [cacheKey2, lifecycle] of Object.entries(lifecycleMap)) {
|
1078 | delete lifecycleMap[cacheKey2];
|
1079 | lifecycle.cacheEntryRemoved();
|
1080 | }
|
1081 | }
|
1082 | return result;
|
1083 | };
|
1084 | function getCacheKey(action) {
|
1085 | if (isQueryThunk(action))
|
1086 | return action.meta.arg.queryCacheKey;
|
1087 | if (isMutationThunk(action))
|
1088 | return action.meta.requestId;
|
1089 | if (api.internalActions.removeQueryResult.match(action))
|
1090 | return action.payload.queryCacheKey;
|
1091 | if (api.internalActions.unsubscribeMutationResult.match(action))
|
1092 | return action.payload.requestId;
|
1093 | return "";
|
1094 | }
|
1095 | function handleNewKey(endpointName, originalArgs, queryCacheKey, mwApi2, requestId) {
|
1096 | const endpointDefinition = context.endpointDefinitions[endpointName];
|
1097 | const onCacheEntryAdded = endpointDefinition == null ? void 0 : endpointDefinition.onCacheEntryAdded;
|
1098 | if (!onCacheEntryAdded)
|
1099 | return;
|
1100 | let lifecycle = {};
|
1101 | const cacheEntryRemoved = new Promise((resolve) => {
|
1102 | lifecycle.cacheEntryRemoved = resolve;
|
1103 | });
|
1104 | const cacheDataLoaded = Promise.race([
|
1105 | new Promise((resolve) => {
|
1106 | lifecycle.valueResolved = resolve;
|
1107 | }),
|
1108 | cacheEntryRemoved.then(() => {
|
1109 | throw neverResolvedError;
|
1110 | })
|
1111 | ]);
|
1112 | cacheDataLoaded.catch(() => {
|
1113 | });
|
1114 | lifecycleMap[queryCacheKey] = lifecycle;
|
1115 | const selector = api.endpoints[endpointName].select(endpointDefinition.type === DefinitionType.query ? originalArgs : queryCacheKey);
|
1116 | const extra = mwApi2.dispatch((_, __, extra2) => extra2);
|
1117 | const lifecycleApi = __spreadProps(__spreadValues({}, mwApi2), {
|
1118 | getCacheEntry: () => selector(mwApi2.getState()),
|
1119 | requestId,
|
1120 | extra,
|
1121 | updateCachedData: endpointDefinition.type === DefinitionType.query ? (updateRecipe) => mwApi2.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
|
1122 | cacheDataLoaded,
|
1123 | cacheEntryRemoved
|
1124 | });
|
1125 | const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi);
|
1126 | Promise.resolve(runningHandler).catch((e) => {
|
1127 | if (e === neverResolvedError)
|
1128 | return;
|
1129 | throw e;
|
1130 | });
|
1131 | }
|
1132 | };
|
1133 | };
|
1134 |
|
1135 | import { isPending as isPending2, isRejected as isRejected2, isFulfilled as isFulfilled5 } from "@reduxjs/toolkit";
|
1136 | var build6 = ({ api, context, queryThunk, mutationThunk }) => {
|
1137 | const isPendingThunk = isPending2(queryThunk, mutationThunk);
|
1138 | const isRejectedThunk = isRejected2(queryThunk, mutationThunk);
|
1139 | const isFullfilledThunk = isFulfilled5(queryThunk, mutationThunk);
|
1140 | return (mwApi) => {
|
1141 | const lifecycleMap = {};
|
1142 | return (next) => (action) => {
|
1143 | var _a, _b, _c;
|
1144 | const result = next(action);
|
1145 | if (isPendingThunk(action)) {
|
1146 | const { requestId, arg: { endpointName, originalArgs } } = action.meta;
|
1147 | const endpointDefinition = context.endpointDefinitions[endpointName];
|
1148 | const onQueryStarted = endpointDefinition == null ? void 0 : endpointDefinition.onQueryStarted;
|
1149 | if (onQueryStarted) {
|
1150 | const lifecycle = {};
|
1151 | const queryFulfilled = new Promise((resolve, reject) => {
|
1152 | lifecycle.resolve = resolve;
|
1153 | lifecycle.reject = reject;
|
1154 | });
|
1155 | queryFulfilled.catch(() => {
|
1156 | });
|
1157 | lifecycleMap[requestId] = lifecycle;
|
1158 | const selector = api.endpoints[endpointName].select(endpointDefinition.type === DefinitionType.query ? originalArgs : requestId);
|
1159 | const extra = mwApi.dispatch((_, __, extra2) => extra2);
|
1160 | const lifecycleApi = __spreadProps(__spreadValues({}, mwApi), {
|
1161 | getCacheEntry: () => selector(mwApi.getState()),
|
1162 | requestId,
|
1163 | extra,
|
1164 | updateCachedData: endpointDefinition.type === DefinitionType.query ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
|
1165 | queryFulfilled
|
1166 | });
|
1167 | onQueryStarted(originalArgs, lifecycleApi);
|
1168 | }
|
1169 | }
|
1170 | else if (isFullfilledThunk(action)) {
|
1171 | const { requestId, baseQueryMeta } = action.meta;
|
1172 | (_a = lifecycleMap[requestId]) == null ? void 0 : _a.resolve({
|
1173 | data: action.payload,
|
1174 | meta: baseQueryMeta
|
1175 | });
|
1176 | delete lifecycleMap[requestId];
|
1177 | }
|
1178 | else if (isRejectedThunk(action)) {
|
1179 | const { requestId, rejectedWithValue, baseQueryMeta } = action.meta;
|
1180 | (_c = lifecycleMap[requestId]) == null ? void 0 : _c.reject({
|
1181 | error: (_b = action.payload) != null ? _b : action.error,
|
1182 | isUnhandledError: !rejectedWithValue,
|
1183 | meta: baseQueryMeta
|
1184 | });
|
1185 | delete lifecycleMap[requestId];
|
1186 | }
|
1187 | return result;
|
1188 | };
|
1189 | };
|
1190 | };
|
1191 |
|
1192 | var build7 = ({ api, context: { apiUid }, reducerPath }) => {
|
1193 | return (mwApi) => {
|
1194 | let initialized2 = false;
|
1195 | return (next) => (action) => {
|
1196 | var _a, _b;
|
1197 | if (!initialized2) {
|
1198 | initialized2 = true;
|
1199 | mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
|
1200 | }
|
1201 | const result = next(action);
|
1202 | if (api.util.resetApiState.match(action)) {
|
1203 | mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
|
1204 | }
|
1205 | if (typeof process !== "undefined" && true) {
|
1206 | if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && ((_b = (_a = mwApi.getState()[reducerPath]) == null ? void 0 : _a.config) == null ? void 0 : _b.middlewareRegistered) === "conflict") {
|
1207 | console.warn(`There is a mismatch between slice and middleware for the reducerPath "${reducerPath}".
|
1208 | You can only have one api per reducer path, this will lead to crashes in various situations!${reducerPath === "api" ? `
|
1209 | If you have multiple apis, you *have* to specify the reducerPath option when using createApi!` : ""}`);
|
1210 | }
|
1211 | }
|
1212 | return result;
|
1213 | };
|
1214 | };
|
1215 | };
|
1216 |
|
1217 | function buildMiddleware(input) {
|
1218 | const { reducerPath, queryThunk } = input;
|
1219 | const actions = {
|
1220 | invalidateTags: createAction3(`${reducerPath}/invalidateTags`)
|
1221 | };
|
1222 | const middlewares = [
|
1223 | build7,
|
1224 | build,
|
1225 | build2,
|
1226 | build3,
|
1227 | build4,
|
1228 | build5,
|
1229 | build6
|
1230 | ].map((build8) => build8(__spreadProps(__spreadValues({}, input), {
|
1231 | refetchQuery
|
1232 | })));
|
1233 | const middleware = (mwApi) => (next) => {
|
1234 | const applied = compose(...middlewares.map((middleware2) => middleware2(mwApi)))(next);
|
1235 | return (action) => {
|
1236 | if (mwApi.getState()[reducerPath]) {
|
1237 | return applied(action);
|
1238 | }
|
1239 | return next(action);
|
1240 | };
|
1241 | };
|
1242 | return { middleware, actions };
|
1243 | function refetchQuery(querySubState, queryCacheKey, override = {}) {
|
1244 | return queryThunk(__spreadValues({
|
1245 | endpointName: querySubState.endpointName,
|
1246 | originalArgs: querySubState.originalArgs,
|
1247 | subscribe: false,
|
1248 | forceRefetch: true,
|
1249 | queryCacheKey
|
1250 | }, override));
|
1251 | }
|
1252 | }
|
1253 |
|
1254 | function buildInitiate({ serializeQueryArgs, queryThunk, mutationThunk, api }) {
|
1255 | const { unsubscribeQueryResult, unsubscribeMutationResult, updateSubscriptionOptions } = api.internalActions;
|
1256 | return { buildInitiateQuery, buildInitiateMutation };
|
1257 | function middlewareWarning(getState) {
|
1258 | var _a, _b;
|
1259 | if (true) {
|
1260 | if (middlewareWarning.triggered)
|
1261 | return;
|
1262 | const registered = (_b = (_a = getState()[api.reducerPath]) == null ? void 0 : _a.config) == null ? void 0 : _b.middlewareRegistered;
|
1263 | if (registered !== void 0) {
|
1264 | ;
|
1265 | middlewareWarning.triggered = true;
|
1266 | }
|
1267 | if (registered === false) {
|
1268 | console.warn(`Warning: Middleware for RTK-Query API at reducerPath "${api.reducerPath}" has not been added to the store.
|
1269 | Features like automatic cache collection, automatic refetching etc. will not be available.`);
|
1270 | }
|
1271 | }
|
1272 | }
|
1273 | function buildInitiateQuery(endpointName, endpointDefinition) {
|
1274 | const queryAction = (arg, { subscribe = true, forceRefetch, subscriptionOptions } = {}) => (dispatch, getState) => {
|
1275 | const queryCacheKey = serializeQueryArgs({
|
1276 | queryArgs: arg,
|
1277 | endpointDefinition,
|
1278 | endpointName
|
1279 | });
|
1280 | const thunk = queryThunk({
|
1281 | subscribe,
|
1282 | forceRefetch,
|
1283 | subscriptionOptions,
|
1284 | endpointName,
|
1285 | originalArgs: arg,
|
1286 | queryCacheKey
|
1287 | });
|
1288 | const thunkResult = dispatch(thunk);
|
1289 | middlewareWarning(getState);
|
1290 | const { requestId, abort } = thunkResult;
|
1291 | const statePromise = Object.assign(thunkResult.then(() => api.endpoints[endpointName].select(arg)(getState())), {
|
1292 | arg,
|
1293 | requestId,
|
1294 | subscriptionOptions,
|
1295 | abort,
|
1296 | refetch() {
|
1297 | dispatch(queryAction(arg, { subscribe: false, forceRefetch: true }));
|
1298 | },
|
1299 | unsubscribe() {
|
1300 | if (subscribe)
|
1301 | dispatch(unsubscribeQueryResult({
|
1302 | queryCacheKey,
|
1303 | requestId
|
1304 | }));
|
1305 | },
|
1306 | updateSubscriptionOptions(options) {
|
1307 | statePromise.subscriptionOptions = options;
|
1308 | dispatch(updateSubscriptionOptions({
|
1309 | endpointName,
|
1310 | requestId,
|
1311 | queryCacheKey,
|
1312 | options
|
1313 | }));
|
1314 | }
|
1315 | });
|
1316 | return statePromise;
|
1317 | };
|
1318 | return queryAction;
|
1319 | }
|
1320 | function buildInitiateMutation(endpointName, definition) {
|
1321 | return (arg, { track = true } = {}) => (dispatch, getState) => {
|
1322 | const thunk = mutationThunk({
|
1323 | endpointName,
|
1324 | originalArgs: arg,
|
1325 | track
|
1326 | });
|
1327 | const thunkResult = dispatch(thunk);
|
1328 | middlewareWarning(getState);
|
1329 | const { requestId, abort } = thunkResult;
|
1330 | const returnValuePromise = thunkResult.unwrap().then((data) => ({ data })).catch((error) => ({ error }));
|
1331 | return Object.assign(returnValuePromise, {
|
1332 | arg: thunkResult.arg,
|
1333 | requestId,
|
1334 | abort,
|
1335 | unwrap: thunkResult.unwrap,
|
1336 | unsubscribe() {
|
1337 | if (track)
|
1338 | dispatch(unsubscribeMutationResult({ requestId }));
|
1339 | }
|
1340 | });
|
1341 | };
|
1342 | }
|
1343 | }
|
1344 |
|
1345 | function assertCast(v) {
|
1346 | }
|
1347 | function safeAssign(target, ...args) {
|
1348 | Object.assign(target, ...args);
|
1349 | }
|
1350 |
|
1351 | import { enablePatches } from "immer";
|
1352 | var coreModuleName = Symbol();
|
1353 | var coreModule = () => ({
|
1354 | name: coreModuleName,
|
1355 | init(api, { baseQuery, tagTypes, reducerPath, serializeQueryArgs, keepUnusedDataFor, refetchOnMountOrArgChange, refetchOnFocus, refetchOnReconnect }, context) {
|
1356 | enablePatches();
|
1357 | assertCast(serializeQueryArgs);
|
1358 | const assertTagType = (tag) => {
|
1359 | if (typeof process !== "undefined" && true) {
|
1360 | if (!tagTypes.includes(tag.type)) {
|
1361 | console.error(`Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!`);
|
1362 | }
|
1363 | }
|
1364 | return tag;
|
1365 | };
|
1366 | Object.assign(api, {
|
1367 | reducerPath,
|
1368 | endpoints: {},
|
1369 | internalActions: {
|
1370 | onOnline,
|
1371 | onOffline,
|
1372 | onFocus,
|
1373 | onFocusLost
|
1374 | },
|
1375 | util: {}
|
1376 | });
|
1377 | const { queryThunk, mutationThunk, patchQueryData, updateQueryData, prefetch, buildMatchThunkActions } = buildThunks({
|
1378 | baseQuery,
|
1379 | reducerPath,
|
1380 | context,
|
1381 | api,
|
1382 | serializeQueryArgs
|
1383 | });
|
1384 | const { reducer, actions: sliceActions } = buildSlice({
|
1385 | context,
|
1386 | queryThunk,
|
1387 | mutationThunk,
|
1388 | reducerPath,
|
1389 | assertTagType,
|
1390 | config: {
|
1391 | refetchOnFocus,
|
1392 | refetchOnReconnect,
|
1393 | refetchOnMountOrArgChange,
|
1394 | keepUnusedDataFor,
|
1395 | reducerPath
|
1396 | }
|
1397 | });
|
1398 | safeAssign(api.util, {
|
1399 | patchQueryData,
|
1400 | updateQueryData,
|
1401 | prefetch,
|
1402 | resetApiState: sliceActions.resetApiState
|
1403 | });
|
1404 | safeAssign(api.internalActions, sliceActions);
|
1405 | Object.defineProperty(api.util, "updateQueryResult", {
|
1406 | get() {
|
1407 | if (typeof process !== "undefined" && true) {
|
1408 | console.warn("`api.util.updateQueryResult` has been renamed to `api.util.updateQueryData`, please change your code accordingly");
|
1409 | }
|
1410 | return api.util.updateQueryData;
|
1411 | }
|
1412 | });
|
1413 | Object.defineProperty(api.util, "patchQueryResult", {
|
1414 | get() {
|
1415 | if (typeof process !== "undefined" && true) {
|
1416 | console.warn("`api.util.patchQueryResult` has been renamed to `api.util.patchQueryData`, please change your code accordingly");
|
1417 | }
|
1418 | return api.util.patchQueryData;
|
1419 | }
|
1420 | });
|
1421 | const { middleware, actions: middlewareActions } = buildMiddleware({
|
1422 | reducerPath,
|
1423 | context,
|
1424 | queryThunk,
|
1425 | mutationThunk,
|
1426 | api,
|
1427 | assertTagType
|
1428 | });
|
1429 | safeAssign(api.util, middlewareActions);
|
1430 | safeAssign(api, { reducer, middleware });
|
1431 | const { buildQuerySelector, buildMutationSelector } = buildSelectors({
|
1432 | serializeQueryArgs,
|
1433 | reducerPath
|
1434 | });
|
1435 | const { buildInitiateQuery, buildInitiateMutation } = buildInitiate({
|
1436 | queryThunk,
|
1437 | mutationThunk,
|
1438 | api,
|
1439 | serializeQueryArgs
|
1440 | });
|
1441 | return {
|
1442 | name: coreModuleName,
|
1443 | injectEndpoint(endpointName, definition) {
|
1444 | var _a, _b;
|
1445 | const anyApi = api;
|
1446 | (_b = (_a = anyApi.endpoints)[endpointName]) != null ? _b : _a[endpointName] = {};
|
1447 | if (isQueryDefinition(definition)) {
|
1448 | safeAssign(anyApi.endpoints[endpointName], {
|
1449 | select: buildQuerySelector(endpointName, definition),
|
1450 | initiate: buildInitiateQuery(endpointName, definition)
|
1451 | }, buildMatchThunkActions(queryThunk, endpointName));
|
1452 | }
|
1453 | else if (isMutationDefinition(definition)) {
|
1454 | safeAssign(anyApi.endpoints[endpointName], {
|
1455 | select: buildMutationSelector(),
|
1456 | initiate: buildInitiateMutation(endpointName, definition)
|
1457 | }, buildMatchThunkActions(mutationThunk, endpointName));
|
1458 | }
|
1459 | }
|
1460 | };
|
1461 | }
|
1462 | });
|
1463 |
|
1464 | var createApi = buildCreateApi(coreModule());
|
1465 | export { QueryStatus, buildCreateApi, copyWithStructuralSharing, coreModule, createApi, fakeBaseQuery, fetchBaseQuery, retry, setupListeners, skipSelector, skipToken };
|
1466 |
|
\ | No newline at end of file |