@me1a/ui 1.2.10 → 1.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -478,6 +478,9 @@ function getArchtype(thing) {
478
478
  function has(thing, prop) {
479
479
  return getArchtype(thing) === 2 /* Map */ ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);
480
480
  }
481
+ function get(thing, prop) {
482
+ return getArchtype(thing) === 2 /* Map */ ? thing.get(prop) : thing[prop];
483
+ }
481
484
  function set(thing, propOrOldValue, value) {
482
485
  const t = getArchtype(thing);
483
486
  if (t === 2 /* Map */)
@@ -570,6 +573,10 @@ function getPlugin(pluginKey) {
570
573
  }
571
574
  return plugin;
572
575
  }
576
+ function loadPlugin(pluginKey, implementation) {
577
+ if (!plugins[pluginKey])
578
+ plugins[pluginKey] = implementation;
579
+ }
573
580
 
574
581
  // src/core/scope.ts
575
582
  var currentScope;
@@ -1085,15 +1092,250 @@ function currentImpl(value) {
1085
1092
  return copy;
1086
1093
  }
1087
1094
 
1095
+ // src/plugins/patches.ts
1096
+ function enablePatches() {
1097
+ const errorOffset = 16;
1098
+ if (process.env.NODE_ENV !== "production") {
1099
+ errors.push(
1100
+ 'Sets cannot have "replace" patches.',
1101
+ function(op) {
1102
+ return "Unsupported patch operation: " + op;
1103
+ },
1104
+ function(path) {
1105
+ return "Cannot apply patch, path doesn't resolve: " + path;
1106
+ },
1107
+ "Patching reserved attributes like __proto__, prototype and constructor is not allowed"
1108
+ );
1109
+ }
1110
+ const REPLACE = "replace";
1111
+ const ADD = "add";
1112
+ const REMOVE = "remove";
1113
+ function generatePatches_(state, basePath, patches, inversePatches) {
1114
+ switch (state.type_) {
1115
+ case 0 /* Object */:
1116
+ case 2 /* Map */:
1117
+ return generatePatchesFromAssigned(
1118
+ state,
1119
+ basePath,
1120
+ patches,
1121
+ inversePatches
1122
+ );
1123
+ case 1 /* Array */:
1124
+ return generateArrayPatches(state, basePath, patches, inversePatches);
1125
+ case 3 /* Set */:
1126
+ return generateSetPatches(
1127
+ state,
1128
+ basePath,
1129
+ patches,
1130
+ inversePatches
1131
+ );
1132
+ }
1133
+ }
1134
+ function generateArrayPatches(state, basePath, patches, inversePatches) {
1135
+ let { base_, assigned_ } = state;
1136
+ let copy_ = state.copy_;
1137
+ if (copy_.length < base_.length) {
1138
+ [base_, copy_] = [copy_, base_];
1139
+ [patches, inversePatches] = [inversePatches, patches];
1140
+ }
1141
+ for (let i = 0; i < base_.length; i++) {
1142
+ if (assigned_[i] && copy_[i] !== base_[i]) {
1143
+ const path = basePath.concat([i]);
1144
+ patches.push({
1145
+ op: REPLACE,
1146
+ path,
1147
+ // Need to maybe clone it, as it can in fact be the original value
1148
+ // due to the base/copy inversion at the start of this function
1149
+ value: clonePatchValueIfNeeded(copy_[i])
1150
+ });
1151
+ inversePatches.push({
1152
+ op: REPLACE,
1153
+ path,
1154
+ value: clonePatchValueIfNeeded(base_[i])
1155
+ });
1156
+ }
1157
+ }
1158
+ for (let i = base_.length; i < copy_.length; i++) {
1159
+ const path = basePath.concat([i]);
1160
+ patches.push({
1161
+ op: ADD,
1162
+ path,
1163
+ // Need to maybe clone it, as it can in fact be the original value
1164
+ // due to the base/copy inversion at the start of this function
1165
+ value: clonePatchValueIfNeeded(copy_[i])
1166
+ });
1167
+ }
1168
+ for (let i = copy_.length - 1; base_.length <= i; --i) {
1169
+ const path = basePath.concat([i]);
1170
+ inversePatches.push({
1171
+ op: REMOVE,
1172
+ path
1173
+ });
1174
+ }
1175
+ }
1176
+ function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {
1177
+ const { base_, copy_ } = state;
1178
+ each(state.assigned_, (key, assignedValue) => {
1179
+ const origValue = get(base_, key);
1180
+ const value = get(copy_, key);
1181
+ const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD;
1182
+ if (origValue === value && op === REPLACE)
1183
+ return;
1184
+ const path = basePath.concat(key);
1185
+ patches.push(op === REMOVE ? { op, path } : { op, path, value });
1186
+ inversePatches.push(
1187
+ op === ADD ? { op: REMOVE, path } : op === REMOVE ? { op: ADD, path, value: clonePatchValueIfNeeded(origValue) } : { op: REPLACE, path, value: clonePatchValueIfNeeded(origValue) }
1188
+ );
1189
+ });
1190
+ }
1191
+ function generateSetPatches(state, basePath, patches, inversePatches) {
1192
+ let { base_, copy_ } = state;
1193
+ let i = 0;
1194
+ base_.forEach((value) => {
1195
+ if (!copy_.has(value)) {
1196
+ const path = basePath.concat([i]);
1197
+ patches.push({
1198
+ op: REMOVE,
1199
+ path,
1200
+ value
1201
+ });
1202
+ inversePatches.unshift({
1203
+ op: ADD,
1204
+ path,
1205
+ value
1206
+ });
1207
+ }
1208
+ i++;
1209
+ });
1210
+ i = 0;
1211
+ copy_.forEach((value) => {
1212
+ if (!base_.has(value)) {
1213
+ const path = basePath.concat([i]);
1214
+ patches.push({
1215
+ op: ADD,
1216
+ path,
1217
+ value
1218
+ });
1219
+ inversePatches.unshift({
1220
+ op: REMOVE,
1221
+ path,
1222
+ value
1223
+ });
1224
+ }
1225
+ i++;
1226
+ });
1227
+ }
1228
+ function generateReplacementPatches_(baseValue, replacement, patches, inversePatches) {
1229
+ patches.push({
1230
+ op: REPLACE,
1231
+ path: [],
1232
+ value: replacement === NOTHING ? void 0 : replacement
1233
+ });
1234
+ inversePatches.push({
1235
+ op: REPLACE,
1236
+ path: [],
1237
+ value: baseValue
1238
+ });
1239
+ }
1240
+ function applyPatches_(draft, patches) {
1241
+ patches.forEach((patch) => {
1242
+ const { path, op } = patch;
1243
+ let base = draft;
1244
+ for (let i = 0; i < path.length - 1; i++) {
1245
+ const parentType = getArchtype(base);
1246
+ let p = path[i];
1247
+ if (typeof p !== "string" && typeof p !== "number") {
1248
+ p = "" + p;
1249
+ }
1250
+ if ((parentType === 0 /* Object */ || parentType === 1 /* Array */) && (p === "__proto__" || p === "constructor"))
1251
+ die(errorOffset + 3);
1252
+ if (typeof base === "function" && p === "prototype")
1253
+ die(errorOffset + 3);
1254
+ base = get(base, p);
1255
+ if (typeof base !== "object")
1256
+ die(errorOffset + 2, path.join("/"));
1257
+ }
1258
+ const type = getArchtype(base);
1259
+ const value = deepClonePatchValue(patch.value);
1260
+ const key = path[path.length - 1];
1261
+ switch (op) {
1262
+ case REPLACE:
1263
+ switch (type) {
1264
+ case 2 /* Map */:
1265
+ return base.set(key, value);
1266
+ case 3 /* Set */:
1267
+ die(errorOffset);
1268
+ default:
1269
+ return base[key] = value;
1270
+ }
1271
+ case ADD:
1272
+ switch (type) {
1273
+ case 1 /* Array */:
1274
+ return key === "-" ? base.push(value) : base.splice(key, 0, value);
1275
+ case 2 /* Map */:
1276
+ return base.set(key, value);
1277
+ case 3 /* Set */:
1278
+ return base.add(value);
1279
+ default:
1280
+ return base[key] = value;
1281
+ }
1282
+ case REMOVE:
1283
+ switch (type) {
1284
+ case 1 /* Array */:
1285
+ return base.splice(key, 1);
1286
+ case 2 /* Map */:
1287
+ return base.delete(key);
1288
+ case 3 /* Set */:
1289
+ return base.delete(patch.value);
1290
+ default:
1291
+ return delete base[key];
1292
+ }
1293
+ default:
1294
+ die(errorOffset + 1, op);
1295
+ }
1296
+ });
1297
+ return draft;
1298
+ }
1299
+ function deepClonePatchValue(obj) {
1300
+ if (!isDraftable(obj))
1301
+ return obj;
1302
+ if (Array.isArray(obj))
1303
+ return obj.map(deepClonePatchValue);
1304
+ if (isMap(obj))
1305
+ return new Map(
1306
+ Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])
1307
+ );
1308
+ if (isSet(obj))
1309
+ return new Set(Array.from(obj).map(deepClonePatchValue));
1310
+ const cloned = Object.create(getPrototypeOf(obj));
1311
+ for (const key in obj)
1312
+ cloned[key] = deepClonePatchValue(obj[key]);
1313
+ if (has(obj, DRAFTABLE))
1314
+ cloned[DRAFTABLE] = obj[DRAFTABLE];
1315
+ return cloned;
1316
+ }
1317
+ function clonePatchValueIfNeeded(obj) {
1318
+ if (isDraft(obj)) {
1319
+ return deepClonePatchValue(obj);
1320
+ } else
1321
+ return obj;
1322
+ }
1323
+ loadPlugin("Patches", {
1324
+ applyPatches_,
1325
+ generatePatches_,
1326
+ generateReplacementPatches_
1327
+ });
1328
+ }
1329
+
1088
1330
  // src/immer.ts
1089
1331
  var immer = new Immer2();
1090
1332
  var produce = immer.produce;
1091
- immer.produceWithPatches.bind(
1333
+ var produceWithPatches = immer.produceWithPatches.bind(
1092
1334
  immer
1093
1335
  );
1094
1336
  immer.setAutoFreeze.bind(immer);
1095
1337
  immer.setUseStrictShallowCopy.bind(immer);
1096
- immer.applyPatches.bind(immer);
1338
+ var applyPatches = immer.applyPatches.bind(immer);
1097
1339
  immer.createDraft.bind(immer);
1098
1340
  immer.finishDraft.bind(immer);
1099
1341
 
@@ -3717,24 +3959,2463 @@ function formatProdErrorMessage(code) {
3717
3959
  return `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or use the non-minified dev environment for full errors. `;
3718
3960
  }
3719
3961
 
3962
+ // src/query/core/apiState.ts
3963
+ var QueryStatus = /* @__PURE__ */ ((QueryStatus2) => {
3964
+ QueryStatus2["uninitialized"] = "uninitialized";
3965
+ QueryStatus2["pending"] = "pending";
3966
+ QueryStatus2["fulfilled"] = "fulfilled";
3967
+ QueryStatus2["rejected"] = "rejected";
3968
+ return QueryStatus2;
3969
+ })(QueryStatus || {});
3970
+ function getRequestStatusFlags(status) {
3971
+ return {
3972
+ status,
3973
+ isUninitialized: status === "uninitialized" /* uninitialized */,
3974
+ isLoading: status === "pending" /* pending */,
3975
+ isSuccess: status === "fulfilled" /* fulfilled */,
3976
+ isError: status === "rejected" /* rejected */
3977
+ };
3978
+ }
3979
+
3980
+ // src/query/utils/copyWithStructuralSharing.ts
3981
+ var isPlainObject2 = isPlainObject$1;
3982
+ function copyWithStructuralSharing(oldObj, newObj) {
3983
+ if (oldObj === newObj || !(isPlainObject2(oldObj) && isPlainObject2(newObj) || Array.isArray(oldObj) && Array.isArray(newObj))) {
3984
+ return newObj;
3985
+ }
3986
+ const newKeys = Object.keys(newObj);
3987
+ const oldKeys = Object.keys(oldObj);
3988
+ let isSameObject = newKeys.length === oldKeys.length;
3989
+ const mergeObj = Array.isArray(newObj) ? [] : {};
3990
+ for (const key of newKeys) {
3991
+ mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key]);
3992
+ if (isSameObject) isSameObject = oldObj[key] === mergeObj[key];
3993
+ }
3994
+ return isSameObject ? oldObj : mergeObj;
3995
+ }
3996
+
3997
+ // src/query/utils/countObjectKeys.ts
3998
+ function countObjectKeys(obj) {
3999
+ let count = 0;
4000
+ for (const _key in obj) {
4001
+ count++;
4002
+ }
4003
+ return count;
4004
+ }
4005
+
4006
+ // src/query/utils/flatten.ts
4007
+ var flatten = (arr) => [].concat(...arr);
4008
+
4009
+ // src/query/utils/isAbsoluteUrl.ts
4010
+ function isAbsoluteUrl(url) {
4011
+ return new RegExp(`(^|:)//`).test(url);
4012
+ }
4013
+
4014
+ // src/query/utils/isDocumentVisible.ts
4015
+ function isDocumentVisible() {
4016
+ if (typeof document === "undefined") {
4017
+ return true;
4018
+ }
4019
+ return document.visibilityState !== "hidden";
4020
+ }
4021
+
4022
+ // src/query/utils/isNotNullish.ts
4023
+ function isNotNullish(v) {
4024
+ return v != null;
4025
+ }
4026
+
4027
+ // src/query/utils/isOnline.ts
4028
+ function isOnline() {
4029
+ return typeof navigator === "undefined" ? true : navigator.onLine === void 0 ? true : navigator.onLine;
4030
+ }
4031
+
4032
+ // src/query/utils/joinUrls.ts
4033
+ var withoutTrailingSlash = (url) => url.replace(/\/$/, "");
4034
+ var withoutLeadingSlash = (url) => url.replace(/^\//, "");
4035
+ function joinUrls(base, url) {
4036
+ if (!base) {
4037
+ return url;
4038
+ }
4039
+ if (!url) {
4040
+ return base;
4041
+ }
4042
+ if (isAbsoluteUrl(url)) {
4043
+ return url;
4044
+ }
4045
+ const delimiter = base.endsWith("/") || !url.startsWith("?") ? "/" : "";
4046
+ base = withoutTrailingSlash(base);
4047
+ url = withoutLeadingSlash(url);
4048
+ return `${base}${delimiter}${url}`;
4049
+ }
4050
+
4051
+ // src/query/fetchBaseQuery.ts
4052
+ var defaultFetchFn = (...args) => fetch(...args);
4053
+ var defaultValidateStatus = (response) => response.status >= 200 && response.status <= 299;
4054
+ var defaultIsJsonContentType = (headers) => (
4055
+ /*applicat*/
4056
+ /ion\/(vnd\.api\+)?json/.test(headers.get("content-type") || "")
4057
+ );
4058
+ function stripUndefined(obj) {
4059
+ if (!isPlainObject$1(obj)) {
4060
+ return obj;
4061
+ }
4062
+ const copy = {
4063
+ ...obj
4064
+ };
4065
+ for (const [k, v] of Object.entries(copy)) {
4066
+ if (v === void 0) delete copy[k];
4067
+ }
4068
+ return copy;
4069
+ }
4070
+ function fetchBaseQuery({
4071
+ baseUrl,
4072
+ prepareHeaders = (x) => x,
4073
+ fetchFn = defaultFetchFn,
4074
+ paramsSerializer,
4075
+ isJsonContentType = defaultIsJsonContentType,
4076
+ jsonContentType = "application/json",
4077
+ jsonReplacer,
4078
+ timeout: defaultTimeout,
4079
+ responseHandler: globalResponseHandler,
4080
+ validateStatus: globalValidateStatus,
4081
+ ...baseFetchOptions
4082
+ } = {}) {
4083
+ if (typeof fetch === "undefined" && fetchFn === defaultFetchFn) {
4084
+ console.warn("Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.");
4085
+ }
4086
+ return async (arg, api, extraOptions) => {
4087
+ const {
4088
+ getState,
4089
+ extra,
4090
+ endpoint,
4091
+ forced,
4092
+ type
4093
+ } = api;
4094
+ let meta;
4095
+ let {
4096
+ url,
4097
+ headers = new Headers(baseFetchOptions.headers),
4098
+ params = void 0,
4099
+ responseHandler = globalResponseHandler ?? "json",
4100
+ validateStatus = globalValidateStatus ?? defaultValidateStatus,
4101
+ timeout = defaultTimeout,
4102
+ ...rest
4103
+ } = typeof arg == "string" ? {
4104
+ url: arg
4105
+ } : arg;
4106
+ let abortController, signal = api.signal;
4107
+ if (timeout) {
4108
+ abortController = new AbortController();
4109
+ api.signal.addEventListener("abort", abortController.abort);
4110
+ signal = abortController.signal;
4111
+ }
4112
+ let config = {
4113
+ ...baseFetchOptions,
4114
+ signal,
4115
+ ...rest
4116
+ };
4117
+ headers = new Headers(stripUndefined(headers));
4118
+ config.headers = await prepareHeaders(headers, {
4119
+ getState,
4120
+ arg,
4121
+ extra,
4122
+ endpoint,
4123
+ forced,
4124
+ type,
4125
+ extraOptions
4126
+ }) || headers;
4127
+ const isJsonifiable = (body) => typeof body === "object" && (isPlainObject$1(body) || Array.isArray(body) || typeof body.toJSON === "function");
4128
+ if (!config.headers.has("content-type") && isJsonifiable(config.body)) {
4129
+ config.headers.set("content-type", jsonContentType);
4130
+ }
4131
+ if (isJsonifiable(config.body) && isJsonContentType(config.headers)) {
4132
+ config.body = JSON.stringify(config.body, jsonReplacer);
4133
+ }
4134
+ if (params) {
4135
+ const divider = ~url.indexOf("?") ? "&" : "?";
4136
+ const query = paramsSerializer ? paramsSerializer(params) : new URLSearchParams(stripUndefined(params));
4137
+ url += divider + query;
4138
+ }
4139
+ url = joinUrls(baseUrl, url);
4140
+ const request = new Request(url, config);
4141
+ const requestClone = new Request(url, config);
4142
+ meta = {
4143
+ request: requestClone
4144
+ };
4145
+ let response, timedOut = false, timeoutId = abortController && setTimeout(() => {
4146
+ timedOut = true;
4147
+ abortController.abort();
4148
+ }, timeout);
4149
+ try {
4150
+ response = await fetchFn(request);
4151
+ } catch (e) {
4152
+ return {
4153
+ error: {
4154
+ status: timedOut ? "TIMEOUT_ERROR" : "FETCH_ERROR",
4155
+ error: String(e)
4156
+ },
4157
+ meta
4158
+ };
4159
+ } finally {
4160
+ if (timeoutId) clearTimeout(timeoutId);
4161
+ abortController?.signal.removeEventListener("abort", abortController.abort);
4162
+ }
4163
+ const responseClone = response.clone();
4164
+ meta.response = responseClone;
4165
+ let resultData;
4166
+ let responseText = "";
4167
+ try {
4168
+ let handleResponseError;
4169
+ await Promise.all([
4170
+ handleResponse(response, responseHandler).then((r) => resultData = r, (e) => handleResponseError = e),
4171
+ // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182
4172
+ // we *have* to "use up" both streams at the same time or they will stop running in node-fetch scenarios
4173
+ responseClone.text().then((r) => responseText = r, () => {
4174
+ })
4175
+ ]);
4176
+ if (handleResponseError) throw handleResponseError;
4177
+ } catch (e) {
4178
+ return {
4179
+ error: {
4180
+ status: "PARSING_ERROR",
4181
+ originalStatus: response.status,
4182
+ data: responseText,
4183
+ error: String(e)
4184
+ },
4185
+ meta
4186
+ };
4187
+ }
4188
+ return validateStatus(response, resultData) ? {
4189
+ data: resultData,
4190
+ meta
4191
+ } : {
4192
+ error: {
4193
+ status: response.status,
4194
+ data: resultData
4195
+ },
4196
+ meta
4197
+ };
4198
+ };
4199
+ async function handleResponse(response, responseHandler) {
4200
+ if (typeof responseHandler === "function") {
4201
+ return responseHandler(response);
4202
+ }
4203
+ if (responseHandler === "content-type") {
4204
+ responseHandler = isJsonContentType(response.headers) ? "json" : "text";
4205
+ }
4206
+ if (responseHandler === "json") {
4207
+ const text = await response.text();
4208
+ return text.length ? JSON.parse(text) : null;
4209
+ }
4210
+ return response.text();
4211
+ }
4212
+ }
4213
+
4214
+ // src/query/HandledError.ts
4215
+ var HandledError = class {
4216
+ constructor(value, meta = void 0) {
4217
+ this.value = value;
4218
+ this.meta = meta;
4219
+ }
4220
+ };
4221
+
4222
+ // src/query/retry.ts
4223
+ async function defaultBackoff(attempt = 0, maxRetries = 5) {
4224
+ const attempts = Math.min(attempt, maxRetries);
4225
+ const timeout = ~~((Math.random() + 0.4) * (300 << attempts));
4226
+ await new Promise((resolve) => setTimeout((res) => resolve(res), timeout));
4227
+ }
4228
+ function fail(e) {
4229
+ throw Object.assign(new HandledError({
4230
+ error: e
4231
+ }), {
4232
+ throwImmediately: true
4233
+ });
4234
+ }
4235
+ var EMPTY_OPTIONS = {};
4236
+ var retryWithBackoff = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {
4237
+ const possibleMaxRetries = [5, (defaultOptions || EMPTY_OPTIONS).maxRetries, (extraOptions || EMPTY_OPTIONS).maxRetries].filter((x) => x !== void 0);
4238
+ const [maxRetries] = possibleMaxRetries.slice(-1);
4239
+ const defaultRetryCondition = (_, __, {
4240
+ attempt
4241
+ }) => attempt <= maxRetries;
4242
+ const options = {
4243
+ maxRetries,
4244
+ backoff: defaultBackoff,
4245
+ retryCondition: defaultRetryCondition,
4246
+ ...defaultOptions,
4247
+ ...extraOptions
4248
+ };
4249
+ let retry2 = 0;
4250
+ while (true) {
4251
+ try {
4252
+ const result = await baseQuery(args, api, extraOptions);
4253
+ if (result.error) {
4254
+ throw new HandledError(result);
4255
+ }
4256
+ return result;
4257
+ } catch (e) {
4258
+ retry2++;
4259
+ if (e.throwImmediately) {
4260
+ if (e instanceof HandledError) {
4261
+ return e.value;
4262
+ }
4263
+ throw e;
4264
+ }
4265
+ if (e instanceof HandledError && !options.retryCondition(e.value.error, args, {
4266
+ attempt: retry2,
4267
+ baseQueryApi: api,
4268
+ extraOptions
4269
+ })) {
4270
+ return e.value;
4271
+ }
4272
+ await options.backoff(retry2, options.maxRetries);
4273
+ }
4274
+ }
4275
+ };
4276
+ var retry = /* @__PURE__ */ Object.assign(retryWithBackoff, {
4277
+ fail
4278
+ });
4279
+
4280
+ // src/query/core/setupListeners.ts
4281
+ var onFocus = /* @__PURE__ */ createAction("__rtkq/focused");
4282
+ var onFocusLost = /* @__PURE__ */ createAction("__rtkq/unfocused");
4283
+ var onOnline = /* @__PURE__ */ createAction("__rtkq/online");
4284
+ var onOffline = /* @__PURE__ */ createAction("__rtkq/offline");
4285
+ var initialized = false;
4286
+ function setupListeners(dispatch, customHandler) {
4287
+ function defaultHandler() {
4288
+ const handleFocus = () => dispatch(onFocus());
4289
+ const handleFocusLost = () => dispatch(onFocusLost());
4290
+ const handleOnline = () => dispatch(onOnline());
4291
+ const handleOffline = () => dispatch(onOffline());
4292
+ const handleVisibilityChange = () => {
4293
+ if (window.document.visibilityState === "visible") {
4294
+ handleFocus();
4295
+ } else {
4296
+ handleFocusLost();
4297
+ }
4298
+ };
4299
+ if (!initialized) {
4300
+ if (typeof window !== "undefined" && window.addEventListener) {
4301
+ window.addEventListener("visibilitychange", handleVisibilityChange, false);
4302
+ window.addEventListener("focus", handleFocus, false);
4303
+ window.addEventListener("online", handleOnline, false);
4304
+ window.addEventListener("offline", handleOffline, false);
4305
+ initialized = true;
4306
+ }
4307
+ }
4308
+ const unsubscribe = () => {
4309
+ window.removeEventListener("focus", handleFocus);
4310
+ window.removeEventListener("visibilitychange", handleVisibilityChange);
4311
+ window.removeEventListener("online", handleOnline);
4312
+ window.removeEventListener("offline", handleOffline);
4313
+ initialized = false;
4314
+ };
4315
+ return unsubscribe;
4316
+ }
4317
+ return customHandler ? customHandler(dispatch, {
4318
+ onFocus,
4319
+ onFocusLost,
4320
+ onOffline,
4321
+ onOnline
4322
+ }) : defaultHandler();
4323
+ }
4324
+
4325
+ // src/query/endpointDefinitions.ts
4326
+ function isQueryDefinition(e) {
4327
+ return e.type === "query" /* query */;
4328
+ }
4329
+ function isMutationDefinition(e) {
4330
+ return e.type === "mutation" /* mutation */;
4331
+ }
4332
+ function calculateProvidedBy(description, result, error, queryArg, meta, assertTagTypes) {
4333
+ if (isFunction(description)) {
4334
+ return description(result, error, queryArg, meta).map(expandTagDescription).map(assertTagTypes);
4335
+ }
4336
+ if (Array.isArray(description)) {
4337
+ return description.map(expandTagDescription).map(assertTagTypes);
4338
+ }
4339
+ return [];
4340
+ }
4341
+ function isFunction(t) {
4342
+ return typeof t === "function";
4343
+ }
4344
+ function expandTagDescription(description) {
4345
+ return typeof description === "string" ? {
4346
+ type: description
4347
+ } : description;
4348
+ }
4349
+
4350
+ // src/tsHelpers.ts
4351
+ function asSafePromise(promise, fallback) {
4352
+ return promise.catch(fallback);
4353
+ }
4354
+
4355
+ // src/query/core/buildInitiate.ts
4356
+ var forceQueryFnSymbol = Symbol("forceQueryFn");
4357
+ var isUpsertQuery = (arg) => typeof arg[forceQueryFnSymbol] === "function";
4358
+ function buildInitiate({
4359
+ serializeQueryArgs,
4360
+ queryThunk,
4361
+ mutationThunk,
4362
+ api,
4363
+ context
4364
+ }) {
4365
+ const runningQueries = /* @__PURE__ */ new Map();
4366
+ const runningMutations = /* @__PURE__ */ new Map();
4367
+ const {
4368
+ unsubscribeQueryResult,
4369
+ removeMutationResult,
4370
+ updateSubscriptionOptions
4371
+ } = api.internalActions;
4372
+ return {
4373
+ buildInitiateQuery,
4374
+ buildInitiateMutation,
4375
+ getRunningQueryThunk,
4376
+ getRunningMutationThunk,
4377
+ getRunningQueriesThunk,
4378
+ getRunningMutationsThunk
4379
+ };
4380
+ function getRunningQueryThunk(endpointName, queryArgs) {
4381
+ return (dispatch) => {
4382
+ const endpointDefinition = context.endpointDefinitions[endpointName];
4383
+ const queryCacheKey = serializeQueryArgs({
4384
+ queryArgs,
4385
+ endpointDefinition,
4386
+ endpointName
4387
+ });
4388
+ return runningQueries.get(dispatch)?.[queryCacheKey];
4389
+ };
4390
+ }
4391
+ function getRunningMutationThunk(_endpointName, fixedCacheKeyOrRequestId) {
4392
+ return (dispatch) => {
4393
+ return runningMutations.get(dispatch)?.[fixedCacheKeyOrRequestId];
4394
+ };
4395
+ }
4396
+ function getRunningQueriesThunk() {
4397
+ return (dispatch) => Object.values(runningQueries.get(dispatch) || {}).filter(isNotNullish);
4398
+ }
4399
+ function getRunningMutationsThunk() {
4400
+ return (dispatch) => Object.values(runningMutations.get(dispatch) || {}).filter(isNotNullish);
4401
+ }
4402
+ function middlewareWarning(dispatch) {
4403
+ if (process.env.NODE_ENV !== "production") {
4404
+ if (middlewareWarning.triggered) return;
4405
+ const returnedValue = dispatch(api.internalActions.internal_getRTKQSubscriptions());
4406
+ middlewareWarning.triggered = true;
4407
+ if (typeof returnedValue !== "object" || typeof returnedValue?.type === "string") {
4408
+ 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.
4409
+ You must add the middleware for RTK-Query to function correctly!`);
4410
+ }
4411
+ }
4412
+ }
4413
+ function buildInitiateQuery(endpointName, endpointDefinition) {
4414
+ const queryAction = (arg, {
4415
+ subscribe = true,
4416
+ forceRefetch,
4417
+ subscriptionOptions,
4418
+ [forceQueryFnSymbol]: forceQueryFn,
4419
+ ...rest
4420
+ } = {}) => (dispatch, getState) => {
4421
+ const queryCacheKey = serializeQueryArgs({
4422
+ queryArgs: arg,
4423
+ endpointDefinition,
4424
+ endpointName
4425
+ });
4426
+ const thunk = queryThunk({
4427
+ ...rest,
4428
+ type: "query",
4429
+ subscribe,
4430
+ forceRefetch,
4431
+ subscriptionOptions,
4432
+ endpointName,
4433
+ originalArgs: arg,
4434
+ queryCacheKey,
4435
+ [forceQueryFnSymbol]: forceQueryFn
4436
+ });
4437
+ const selector = api.endpoints[endpointName].select(arg);
4438
+ const thunkResult = dispatch(thunk);
4439
+ const stateAfter = selector(getState());
4440
+ middlewareWarning(dispatch);
4441
+ const {
4442
+ requestId,
4443
+ abort
4444
+ } = thunkResult;
4445
+ const skippedSynchronously = stateAfter.requestId !== requestId;
4446
+ const runningQuery = runningQueries.get(dispatch)?.[queryCacheKey];
4447
+ const selectFromState = () => selector(getState());
4448
+ const statePromise = Object.assign(forceQueryFn ? (
4449
+ // a query has been forced (upsertQueryData)
4450
+ // -> we want to resolve it once data has been written with the data that will be written
4451
+ thunkResult.then(selectFromState)
4452
+ ) : skippedSynchronously && !runningQuery ? (
4453
+ // a query has been skipped due to a condition and we do not have any currently running query
4454
+ // -> we want to resolve it immediately with the current data
4455
+ Promise.resolve(stateAfter)
4456
+ ) : (
4457
+ // query just started or one is already in flight
4458
+ // -> wait for the running query, then resolve with data from after that
4459
+ Promise.all([runningQuery, thunkResult]).then(selectFromState)
4460
+ ), {
4461
+ arg,
4462
+ requestId,
4463
+ subscriptionOptions,
4464
+ queryCacheKey,
4465
+ abort,
4466
+ async unwrap() {
4467
+ const result = await statePromise;
4468
+ if (result.isError) {
4469
+ throw result.error;
4470
+ }
4471
+ return result.data;
4472
+ },
4473
+ refetch: () => dispatch(queryAction(arg, {
4474
+ subscribe: false,
4475
+ forceRefetch: true
4476
+ })),
4477
+ unsubscribe() {
4478
+ if (subscribe) dispatch(unsubscribeQueryResult({
4479
+ queryCacheKey,
4480
+ requestId
4481
+ }));
4482
+ },
4483
+ updateSubscriptionOptions(options) {
4484
+ statePromise.subscriptionOptions = options;
4485
+ dispatch(updateSubscriptionOptions({
4486
+ endpointName,
4487
+ requestId,
4488
+ queryCacheKey,
4489
+ options
4490
+ }));
4491
+ }
4492
+ });
4493
+ if (!runningQuery && !skippedSynchronously && !forceQueryFn) {
4494
+ const running = runningQueries.get(dispatch) || {};
4495
+ running[queryCacheKey] = statePromise;
4496
+ runningQueries.set(dispatch, running);
4497
+ statePromise.then(() => {
4498
+ delete running[queryCacheKey];
4499
+ if (!countObjectKeys(running)) {
4500
+ runningQueries.delete(dispatch);
4501
+ }
4502
+ });
4503
+ }
4504
+ return statePromise;
4505
+ };
4506
+ return queryAction;
4507
+ }
4508
+ function buildInitiateMutation(endpointName) {
4509
+ return (arg, {
4510
+ track = true,
4511
+ fixedCacheKey
4512
+ } = {}) => (dispatch, getState) => {
4513
+ const thunk = mutationThunk({
4514
+ type: "mutation",
4515
+ endpointName,
4516
+ originalArgs: arg,
4517
+ track,
4518
+ fixedCacheKey
4519
+ });
4520
+ const thunkResult = dispatch(thunk);
4521
+ middlewareWarning(dispatch);
4522
+ const {
4523
+ requestId,
4524
+ abort,
4525
+ unwrap
4526
+ } = thunkResult;
4527
+ const returnValuePromise = asSafePromise(thunkResult.unwrap().then((data) => ({
4528
+ data
4529
+ })), (error) => ({
4530
+ error
4531
+ }));
4532
+ const reset = () => {
4533
+ dispatch(removeMutationResult({
4534
+ requestId,
4535
+ fixedCacheKey
4536
+ }));
4537
+ };
4538
+ const ret = Object.assign(returnValuePromise, {
4539
+ arg: thunkResult.arg,
4540
+ requestId,
4541
+ abort,
4542
+ unwrap,
4543
+ reset
4544
+ });
4545
+ const running = runningMutations.get(dispatch) || {};
4546
+ runningMutations.set(dispatch, running);
4547
+ running[requestId] = ret;
4548
+ ret.then(() => {
4549
+ delete running[requestId];
4550
+ if (!countObjectKeys(running)) {
4551
+ runningMutations.delete(dispatch);
4552
+ }
4553
+ });
4554
+ if (fixedCacheKey) {
4555
+ running[fixedCacheKey] = ret;
4556
+ ret.then(() => {
4557
+ if (running[fixedCacheKey] === ret) {
4558
+ delete running[fixedCacheKey];
4559
+ if (!countObjectKeys(running)) {
4560
+ runningMutations.delete(dispatch);
4561
+ }
4562
+ }
4563
+ });
4564
+ }
4565
+ return ret;
4566
+ };
4567
+ }
4568
+ }
4569
+
4570
+ // src/query/core/buildThunks.ts
4571
+ function defaultTransformResponse(baseQueryReturnValue) {
4572
+ return baseQueryReturnValue;
4573
+ }
4574
+ function buildThunks({
4575
+ reducerPath,
4576
+ baseQuery,
4577
+ context: {
4578
+ endpointDefinitions
4579
+ },
4580
+ serializeQueryArgs,
4581
+ api,
4582
+ assertTagType
4583
+ }) {
4584
+ const patchQueryData = (endpointName, arg, patches, updateProvided) => (dispatch, getState) => {
4585
+ const endpointDefinition = endpointDefinitions[endpointName];
4586
+ const queryCacheKey = serializeQueryArgs({
4587
+ queryArgs: arg,
4588
+ endpointDefinition,
4589
+ endpointName
4590
+ });
4591
+ dispatch(api.internalActions.queryResultPatched({
4592
+ queryCacheKey,
4593
+ patches
4594
+ }));
4595
+ if (!updateProvided) {
4596
+ return;
4597
+ }
4598
+ const newValue = api.endpoints[endpointName].select(arg)(
4599
+ // Work around TS 4.1 mismatch
4600
+ getState()
4601
+ );
4602
+ const providedTags = calculateProvidedBy(endpointDefinition.providesTags, newValue.data, void 0, arg, {}, assertTagType);
4603
+ dispatch(api.internalActions.updateProvidedBy({
4604
+ queryCacheKey,
4605
+ providedTags
4606
+ }));
4607
+ };
4608
+ const updateQueryData = (endpointName, arg, updateRecipe, updateProvided = true) => (dispatch, getState) => {
4609
+ const endpointDefinition = api.endpoints[endpointName];
4610
+ const currentState = endpointDefinition.select(arg)(
4611
+ // Work around TS 4.1 mismatch
4612
+ getState()
4613
+ );
4614
+ const ret = {
4615
+ patches: [],
4616
+ inversePatches: [],
4617
+ undo: () => dispatch(api.util.patchQueryData(endpointName, arg, ret.inversePatches, updateProvided))
4618
+ };
4619
+ if (currentState.status === "uninitialized" /* uninitialized */) {
4620
+ return ret;
4621
+ }
4622
+ let newValue;
4623
+ if ("data" in currentState) {
4624
+ if (isDraftable(currentState.data)) {
4625
+ const [value, patches, inversePatches] = produceWithPatches(currentState.data, updateRecipe);
4626
+ ret.patches.push(...patches);
4627
+ ret.inversePatches.push(...inversePatches);
4628
+ newValue = value;
4629
+ } else {
4630
+ newValue = updateRecipe(currentState.data);
4631
+ ret.patches.push({
4632
+ op: "replace",
4633
+ path: [],
4634
+ value: newValue
4635
+ });
4636
+ ret.inversePatches.push({
4637
+ op: "replace",
4638
+ path: [],
4639
+ value: currentState.data
4640
+ });
4641
+ }
4642
+ }
4643
+ if (ret.patches.length === 0) {
4644
+ return ret;
4645
+ }
4646
+ dispatch(api.util.patchQueryData(endpointName, arg, ret.patches, updateProvided));
4647
+ return ret;
4648
+ };
4649
+ const upsertQueryData = (endpointName, arg, value) => (dispatch) => {
4650
+ return dispatch(api.endpoints[endpointName].initiate(arg, {
4651
+ subscribe: false,
4652
+ forceRefetch: true,
4653
+ [forceQueryFnSymbol]: () => ({
4654
+ data: value
4655
+ })
4656
+ }));
4657
+ };
4658
+ const executeEndpoint = async (arg, {
4659
+ signal,
4660
+ abort,
4661
+ rejectWithValue,
4662
+ fulfillWithValue,
4663
+ dispatch,
4664
+ getState,
4665
+ extra
4666
+ }) => {
4667
+ const endpointDefinition = endpointDefinitions[arg.endpointName];
4668
+ try {
4669
+ let transformResponse = defaultTransformResponse;
4670
+ let result;
4671
+ const baseQueryApi = {
4672
+ signal,
4673
+ abort,
4674
+ dispatch,
4675
+ getState,
4676
+ extra,
4677
+ endpoint: arg.endpointName,
4678
+ type: arg.type,
4679
+ forced: arg.type === "query" ? isForcedQuery(arg, getState()) : void 0,
4680
+ queryCacheKey: arg.type === "query" ? arg.queryCacheKey : void 0
4681
+ };
4682
+ const forceQueryFn = arg.type === "query" ? arg[forceQueryFnSymbol] : void 0;
4683
+ if (forceQueryFn) {
4684
+ result = forceQueryFn();
4685
+ } else if (endpointDefinition.query) {
4686
+ result = await baseQuery(endpointDefinition.query(arg.originalArgs), baseQueryApi, endpointDefinition.extraOptions);
4687
+ if (endpointDefinition.transformResponse) {
4688
+ transformResponse = endpointDefinition.transformResponse;
4689
+ }
4690
+ } else {
4691
+ result = await endpointDefinition.queryFn(arg.originalArgs, baseQueryApi, endpointDefinition.extraOptions, (arg2) => baseQuery(arg2, baseQueryApi, endpointDefinition.extraOptions));
4692
+ }
4693
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
4694
+ const what = endpointDefinition.query ? "`baseQuery`" : "`queryFn`";
4695
+ let err;
4696
+ if (!result) {
4697
+ err = `${what} did not return anything.`;
4698
+ } else if (typeof result !== "object") {
4699
+ err = `${what} did not return an object.`;
4700
+ } else if (result.error && result.data) {
4701
+ err = `${what} returned an object containing both \`error\` and \`result\`.`;
4702
+ } else if (result.error === void 0 && result.data === void 0) {
4703
+ err = `${what} returned an object containing neither a valid \`error\` and \`result\`. At least one of them should not be \`undefined\``;
4704
+ } else {
4705
+ for (const key of Object.keys(result)) {
4706
+ if (key !== "error" && key !== "data" && key !== "meta") {
4707
+ err = `The object returned by ${what} has the unknown property ${key}.`;
4708
+ break;
4709
+ }
4710
+ }
4711
+ }
4712
+ if (err) {
4713
+ console.error(`Error encountered handling the endpoint ${arg.endpointName}.
4714
+ ${err}
4715
+ It needs to return an object with either the shape \`{ data: <value> }\` or \`{ error: <value> }\` that may contain an optional \`meta\` property.
4716
+ Object returned was:`, result);
4717
+ }
4718
+ }
4719
+ if (result.error) throw new HandledError(result.error, result.meta);
4720
+ return fulfillWithValue(await transformResponse(result.data, result.meta, arg.originalArgs), {
4721
+ fulfilledTimeStamp: Date.now(),
4722
+ baseQueryMeta: result.meta,
4723
+ [SHOULD_AUTOBATCH]: true
4724
+ });
4725
+ } catch (error) {
4726
+ let catchedError = error;
4727
+ if (catchedError instanceof HandledError) {
4728
+ let transformErrorResponse = defaultTransformResponse;
4729
+ if (endpointDefinition.query && endpointDefinition.transformErrorResponse) {
4730
+ transformErrorResponse = endpointDefinition.transformErrorResponse;
4731
+ }
4732
+ try {
4733
+ return rejectWithValue(await transformErrorResponse(catchedError.value, catchedError.meta, arg.originalArgs), {
4734
+ baseQueryMeta: catchedError.meta,
4735
+ [SHOULD_AUTOBATCH]: true
4736
+ });
4737
+ } catch (e) {
4738
+ catchedError = e;
4739
+ }
4740
+ }
4741
+ if (typeof process !== "undefined" && process.env.NODE_ENV !== "production") {
4742
+ console.error(`An unhandled error occurred processing a request for the endpoint "${arg.endpointName}".
4743
+ In the case of an unhandled error, no tags will be "provided" or "invalidated".`, catchedError);
4744
+ } else {
4745
+ console.error(catchedError);
4746
+ }
4747
+ throw catchedError;
4748
+ }
4749
+ };
4750
+ function isForcedQuery(arg, state) {
4751
+ const requestState = state[reducerPath]?.queries?.[arg.queryCacheKey];
4752
+ const baseFetchOnMountOrArgChange = state[reducerPath]?.config.refetchOnMountOrArgChange;
4753
+ const fulfilledVal = requestState?.fulfilledTimeStamp;
4754
+ const refetchVal = arg.forceRefetch ?? (arg.subscribe && baseFetchOnMountOrArgChange);
4755
+ if (refetchVal) {
4756
+ return refetchVal === true || (Number(/* @__PURE__ */ new Date()) - Number(fulfilledVal)) / 1e3 >= refetchVal;
4757
+ }
4758
+ return false;
4759
+ }
4760
+ const queryThunk = createAsyncThunk(`${reducerPath}/executeQuery`, executeEndpoint, {
4761
+ getPendingMeta() {
4762
+ return {
4763
+ startedTimeStamp: Date.now(),
4764
+ [SHOULD_AUTOBATCH]: true
4765
+ };
4766
+ },
4767
+ condition(queryThunkArgs, {
4768
+ getState
4769
+ }) {
4770
+ const state = getState();
4771
+ const requestState = state[reducerPath]?.queries?.[queryThunkArgs.queryCacheKey];
4772
+ const fulfilledVal = requestState?.fulfilledTimeStamp;
4773
+ const currentArg = queryThunkArgs.originalArgs;
4774
+ const previousArg = requestState?.originalArgs;
4775
+ const endpointDefinition = endpointDefinitions[queryThunkArgs.endpointName];
4776
+ if (isUpsertQuery(queryThunkArgs)) {
4777
+ return true;
4778
+ }
4779
+ if (requestState?.status === "pending") {
4780
+ return false;
4781
+ }
4782
+ if (isForcedQuery(queryThunkArgs, state)) {
4783
+ return true;
4784
+ }
4785
+ if (isQueryDefinition(endpointDefinition) && endpointDefinition?.forceRefetch?.({
4786
+ currentArg,
4787
+ previousArg,
4788
+ endpointState: requestState,
4789
+ state
4790
+ })) {
4791
+ return true;
4792
+ }
4793
+ if (fulfilledVal) {
4794
+ return false;
4795
+ }
4796
+ return true;
4797
+ },
4798
+ dispatchConditionRejection: true
4799
+ });
4800
+ const mutationThunk = createAsyncThunk(`${reducerPath}/executeMutation`, executeEndpoint, {
4801
+ getPendingMeta() {
4802
+ return {
4803
+ startedTimeStamp: Date.now(),
4804
+ [SHOULD_AUTOBATCH]: true
4805
+ };
4806
+ }
4807
+ });
4808
+ const hasTheForce = (options) => "force" in options;
4809
+ const hasMaxAge = (options) => "ifOlderThan" in options;
4810
+ const prefetch = (endpointName, arg, options) => (dispatch, getState) => {
4811
+ const force = hasTheForce(options) && options.force;
4812
+ const maxAge = hasMaxAge(options) && options.ifOlderThan;
4813
+ const queryAction = (force2 = true) => {
4814
+ const options2 = {
4815
+ forceRefetch: force2,
4816
+ isPrefetch: true
4817
+ };
4818
+ return api.endpoints[endpointName].initiate(arg, options2);
4819
+ };
4820
+ const latestStateValue = api.endpoints[endpointName].select(arg)(getState());
4821
+ if (force) {
4822
+ dispatch(queryAction());
4823
+ } else if (maxAge) {
4824
+ const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp;
4825
+ if (!lastFulfilledTs) {
4826
+ dispatch(queryAction());
4827
+ return;
4828
+ }
4829
+ const shouldRetrigger = (Number(/* @__PURE__ */ new Date()) - Number(new Date(lastFulfilledTs))) / 1e3 >= maxAge;
4830
+ if (shouldRetrigger) {
4831
+ dispatch(queryAction());
4832
+ }
4833
+ } else {
4834
+ dispatch(queryAction(false));
4835
+ }
4836
+ };
4837
+ function matchesEndpoint(endpointName) {
4838
+ return (action) => action?.meta?.arg?.endpointName === endpointName;
4839
+ }
4840
+ function buildMatchThunkActions(thunk, endpointName) {
4841
+ return {
4842
+ matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),
4843
+ matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpointName)),
4844
+ matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName))
4845
+ };
4846
+ }
4847
+ return {
4848
+ queryThunk,
4849
+ mutationThunk,
4850
+ prefetch,
4851
+ updateQueryData,
4852
+ upsertQueryData,
4853
+ patchQueryData,
4854
+ buildMatchThunkActions
4855
+ };
4856
+ }
4857
+ function calculateProvidedByThunk(action, type, endpointDefinitions, assertTagType) {
4858
+ 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);
4859
+ }
4860
+ function updateQuerySubstateIfExists(state, queryCacheKey, update) {
4861
+ const substate = state[queryCacheKey];
4862
+ if (substate) {
4863
+ update(substate);
4864
+ }
4865
+ }
4866
+ function getMutationCacheKey(id) {
4867
+ return ("arg" in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId;
4868
+ }
4869
+ function updateMutationSubstateIfExists(state, id, update) {
4870
+ const substate = state[getMutationCacheKey(id)];
4871
+ if (substate) {
4872
+ update(substate);
4873
+ }
4874
+ }
4875
+ var initialState = {};
4876
+ function buildSlice({
4877
+ reducerPath,
4878
+ queryThunk,
4879
+ mutationThunk,
4880
+ serializeQueryArgs,
4881
+ context: {
4882
+ endpointDefinitions: definitions,
4883
+ apiUid,
4884
+ extractRehydrationInfo,
4885
+ hasRehydrationInfo
4886
+ },
4887
+ assertTagType,
4888
+ config
4889
+ }) {
4890
+ const resetApiState = createAction(`${reducerPath}/resetApiState`);
4891
+ function writePendingCacheEntry(draft, arg, upserting, meta) {
4892
+ draft[arg.queryCacheKey] ??= {
4893
+ status: "uninitialized" /* uninitialized */,
4894
+ endpointName: arg.endpointName
4895
+ };
4896
+ updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
4897
+ substate.status = "pending" /* pending */;
4898
+ substate.requestId = upserting && substate.requestId ? (
4899
+ // for `upsertQuery` **updates**, keep the current `requestId`
4900
+ substate.requestId
4901
+ ) : (
4902
+ // for normal queries or `upsertQuery` **inserts** always update the `requestId`
4903
+ meta.requestId
4904
+ );
4905
+ if (arg.originalArgs !== void 0) {
4906
+ substate.originalArgs = arg.originalArgs;
4907
+ }
4908
+ substate.startedTimeStamp = meta.startedTimeStamp;
4909
+ });
4910
+ }
4911
+ function writeFulfilledCacheEntry(draft, meta, payload) {
4912
+ updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, (substate) => {
4913
+ if (substate.requestId !== meta.requestId && !isUpsertQuery(meta.arg)) return;
4914
+ const {
4915
+ merge
4916
+ } = definitions[meta.arg.endpointName];
4917
+ substate.status = "fulfilled" /* fulfilled */;
4918
+ if (merge) {
4919
+ if (substate.data !== void 0) {
4920
+ const {
4921
+ fulfilledTimeStamp,
4922
+ arg,
4923
+ baseQueryMeta,
4924
+ requestId
4925
+ } = meta;
4926
+ let newData = produce(substate.data, (draftSubstateData) => {
4927
+ return merge(draftSubstateData, payload, {
4928
+ arg: arg.originalArgs,
4929
+ baseQueryMeta,
4930
+ fulfilledTimeStamp,
4931
+ requestId
4932
+ });
4933
+ });
4934
+ substate.data = newData;
4935
+ } else {
4936
+ substate.data = payload;
4937
+ }
4938
+ } else {
4939
+ substate.data = definitions[meta.arg.endpointName].structuralSharing ?? true ? copyWithStructuralSharing(isDraft(substate.data) ? original$1(substate.data) : substate.data, payload) : payload;
4940
+ }
4941
+ delete substate.error;
4942
+ substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
4943
+ });
4944
+ }
4945
+ const querySlice = createSlice({
4946
+ name: `${reducerPath}/queries`,
4947
+ initialState,
4948
+ reducers: {
4949
+ removeQueryResult: {
4950
+ reducer(draft, {
4951
+ payload: {
4952
+ queryCacheKey
4953
+ }
4954
+ }) {
4955
+ delete draft[queryCacheKey];
4956
+ },
4957
+ prepare: prepareAutoBatched()
4958
+ },
4959
+ cacheEntriesUpserted: {
4960
+ reducer(draft, action) {
4961
+ for (const entry of action.payload) {
4962
+ const {
4963
+ queryDescription: arg,
4964
+ value
4965
+ } = entry;
4966
+ writePendingCacheEntry(draft, arg, true, {
4967
+ arg,
4968
+ requestId: action.meta.requestId,
4969
+ startedTimeStamp: action.meta.timestamp
4970
+ });
4971
+ writeFulfilledCacheEntry(draft, {
4972
+ arg,
4973
+ requestId: action.meta.requestId,
4974
+ fulfilledTimeStamp: action.meta.timestamp,
4975
+ baseQueryMeta: {}
4976
+ }, value);
4977
+ }
4978
+ },
4979
+ prepare: (payload) => {
4980
+ const queryDescriptions = payload.map((entry) => {
4981
+ const {
4982
+ endpointName,
4983
+ arg,
4984
+ value
4985
+ } = entry;
4986
+ const endpointDefinition = definitions[endpointName];
4987
+ const queryDescription = {
4988
+ type: "query",
4989
+ endpointName,
4990
+ originalArgs: entry.arg,
4991
+ queryCacheKey: serializeQueryArgs({
4992
+ queryArgs: arg,
4993
+ endpointDefinition,
4994
+ endpointName
4995
+ })
4996
+ };
4997
+ return {
4998
+ queryDescription,
4999
+ value
5000
+ };
5001
+ });
5002
+ const result = {
5003
+ payload: queryDescriptions,
5004
+ meta: {
5005
+ [SHOULD_AUTOBATCH]: true,
5006
+ requestId: nanoid(),
5007
+ timestamp: Date.now()
5008
+ }
5009
+ };
5010
+ return result;
5011
+ }
5012
+ },
5013
+ queryResultPatched: {
5014
+ reducer(draft, {
5015
+ payload: {
5016
+ queryCacheKey,
5017
+ patches
5018
+ }
5019
+ }) {
5020
+ updateQuerySubstateIfExists(draft, queryCacheKey, (substate) => {
5021
+ substate.data = applyPatches(substate.data, patches.concat());
5022
+ });
5023
+ },
5024
+ prepare: prepareAutoBatched()
5025
+ }
5026
+ },
5027
+ extraReducers(builder) {
5028
+ builder.addCase(queryThunk.pending, (draft, {
5029
+ meta,
5030
+ meta: {
5031
+ arg
5032
+ }
5033
+ }) => {
5034
+ const upserting = isUpsertQuery(arg);
5035
+ writePendingCacheEntry(draft, arg, upserting, meta);
5036
+ }).addCase(queryThunk.fulfilled, (draft, {
5037
+ meta,
5038
+ payload
5039
+ }) => {
5040
+ writeFulfilledCacheEntry(draft, meta, payload);
5041
+ }).addCase(queryThunk.rejected, (draft, {
5042
+ meta: {
5043
+ condition,
5044
+ arg,
5045
+ requestId
5046
+ },
5047
+ error,
5048
+ payload
5049
+ }) => {
5050
+ updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
5051
+ if (condition) ; else {
5052
+ if (substate.requestId !== requestId) return;
5053
+ substate.status = "rejected" /* rejected */;
5054
+ substate.error = payload ?? error;
5055
+ }
5056
+ });
5057
+ }).addMatcher(hasRehydrationInfo, (draft, action) => {
5058
+ const {
5059
+ queries
5060
+ } = extractRehydrationInfo(action);
5061
+ for (const [key, entry] of Object.entries(queries)) {
5062
+ if (
5063
+ // do not rehydrate entries that were currently in flight.
5064
+ entry?.status === "fulfilled" /* fulfilled */ || entry?.status === "rejected" /* rejected */
5065
+ ) {
5066
+ draft[key] = entry;
5067
+ }
5068
+ }
5069
+ });
5070
+ }
5071
+ });
5072
+ const mutationSlice = createSlice({
5073
+ name: `${reducerPath}/mutations`,
5074
+ initialState,
5075
+ reducers: {
5076
+ removeMutationResult: {
5077
+ reducer(draft, {
5078
+ payload
5079
+ }) {
5080
+ const cacheKey = getMutationCacheKey(payload);
5081
+ if (cacheKey in draft) {
5082
+ delete draft[cacheKey];
5083
+ }
5084
+ },
5085
+ prepare: prepareAutoBatched()
5086
+ }
5087
+ },
5088
+ extraReducers(builder) {
5089
+ builder.addCase(mutationThunk.pending, (draft, {
5090
+ meta,
5091
+ meta: {
5092
+ requestId,
5093
+ arg,
5094
+ startedTimeStamp
5095
+ }
5096
+ }) => {
5097
+ if (!arg.track) return;
5098
+ draft[getMutationCacheKey(meta)] = {
5099
+ requestId,
5100
+ status: "pending" /* pending */,
5101
+ endpointName: arg.endpointName,
5102
+ startedTimeStamp
5103
+ };
5104
+ }).addCase(mutationThunk.fulfilled, (draft, {
5105
+ payload,
5106
+ meta
5107
+ }) => {
5108
+ if (!meta.arg.track) return;
5109
+ updateMutationSubstateIfExists(draft, meta, (substate) => {
5110
+ if (substate.requestId !== meta.requestId) return;
5111
+ substate.status = "fulfilled" /* fulfilled */;
5112
+ substate.data = payload;
5113
+ substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
5114
+ });
5115
+ }).addCase(mutationThunk.rejected, (draft, {
5116
+ payload,
5117
+ error,
5118
+ meta
5119
+ }) => {
5120
+ if (!meta.arg.track) return;
5121
+ updateMutationSubstateIfExists(draft, meta, (substate) => {
5122
+ if (substate.requestId !== meta.requestId) return;
5123
+ substate.status = "rejected" /* rejected */;
5124
+ substate.error = payload ?? error;
5125
+ });
5126
+ }).addMatcher(hasRehydrationInfo, (draft, action) => {
5127
+ const {
5128
+ mutations
5129
+ } = extractRehydrationInfo(action);
5130
+ for (const [key, entry] of Object.entries(mutations)) {
5131
+ if (
5132
+ // do not rehydrate entries that were currently in flight.
5133
+ (entry?.status === "fulfilled" /* fulfilled */ || entry?.status === "rejected" /* rejected */) && // only rehydrate endpoints that were persisted using a `fixedCacheKey`
5134
+ key !== entry?.requestId
5135
+ ) {
5136
+ draft[key] = entry;
5137
+ }
5138
+ }
5139
+ });
5140
+ }
5141
+ });
5142
+ const invalidationSlice = createSlice({
5143
+ name: `${reducerPath}/invalidation`,
5144
+ initialState,
5145
+ reducers: {
5146
+ updateProvidedBy: {
5147
+ reducer(draft, action) {
5148
+ const {
5149
+ queryCacheKey,
5150
+ providedTags
5151
+ } = action.payload;
5152
+ for (const tagTypeSubscriptions of Object.values(draft)) {
5153
+ for (const idSubscriptions of Object.values(tagTypeSubscriptions)) {
5154
+ const foundAt = idSubscriptions.indexOf(queryCacheKey);
5155
+ if (foundAt !== -1) {
5156
+ idSubscriptions.splice(foundAt, 1);
5157
+ }
5158
+ }
5159
+ }
5160
+ for (const {
5161
+ type,
5162
+ id
5163
+ } of providedTags) {
5164
+ const subscribedQueries = (draft[type] ??= {})[id || "__internal_without_id"] ??= [];
5165
+ const alreadySubscribed = subscribedQueries.includes(queryCacheKey);
5166
+ if (!alreadySubscribed) {
5167
+ subscribedQueries.push(queryCacheKey);
5168
+ }
5169
+ }
5170
+ },
5171
+ prepare: prepareAutoBatched()
5172
+ }
5173
+ },
5174
+ extraReducers(builder) {
5175
+ builder.addCase(querySlice.actions.removeQueryResult, (draft, {
5176
+ payload: {
5177
+ queryCacheKey
5178
+ }
5179
+ }) => {
5180
+ for (const tagTypeSubscriptions of Object.values(draft)) {
5181
+ for (const idSubscriptions of Object.values(tagTypeSubscriptions)) {
5182
+ const foundAt = idSubscriptions.indexOf(queryCacheKey);
5183
+ if (foundAt !== -1) {
5184
+ idSubscriptions.splice(foundAt, 1);
5185
+ }
5186
+ }
5187
+ }
5188
+ }).addMatcher(hasRehydrationInfo, (draft, action) => {
5189
+ const {
5190
+ provided
5191
+ } = extractRehydrationInfo(action);
5192
+ for (const [type, incomingTags] of Object.entries(provided)) {
5193
+ for (const [id, cacheKeys] of Object.entries(incomingTags)) {
5194
+ const subscribedQueries = (draft[type] ??= {})[id || "__internal_without_id"] ??= [];
5195
+ for (const queryCacheKey of cacheKeys) {
5196
+ const alreadySubscribed = subscribedQueries.includes(queryCacheKey);
5197
+ if (!alreadySubscribed) {
5198
+ subscribedQueries.push(queryCacheKey);
5199
+ }
5200
+ }
5201
+ }
5202
+ }
5203
+ }).addMatcher(isAnyOf(isFulfilled(queryThunk), isRejectedWithValue(queryThunk)), (draft, action) => {
5204
+ const providedTags = calculateProvidedByThunk(action, "providesTags", definitions, assertTagType);
5205
+ const {
5206
+ queryCacheKey
5207
+ } = action.meta.arg;
5208
+ invalidationSlice.caseReducers.updateProvidedBy(draft, invalidationSlice.actions.updateProvidedBy({
5209
+ queryCacheKey,
5210
+ providedTags
5211
+ }));
5212
+ });
5213
+ }
5214
+ });
5215
+ const subscriptionSlice = createSlice({
5216
+ name: `${reducerPath}/subscriptions`,
5217
+ initialState,
5218
+ reducers: {
5219
+ updateSubscriptionOptions(d, a) {
5220
+ },
5221
+ unsubscribeQueryResult(d, a) {
5222
+ },
5223
+ internal_getRTKQSubscriptions() {
5224
+ }
5225
+ }
5226
+ });
5227
+ const internalSubscriptionsSlice = createSlice({
5228
+ name: `${reducerPath}/internalSubscriptions`,
5229
+ initialState,
5230
+ reducers: {
5231
+ subscriptionsUpdated: {
5232
+ reducer(state, action) {
5233
+ return applyPatches(state, action.payload);
5234
+ },
5235
+ prepare: prepareAutoBatched()
5236
+ }
5237
+ }
5238
+ });
5239
+ const configSlice = createSlice({
5240
+ name: `${reducerPath}/config`,
5241
+ initialState: {
5242
+ online: isOnline(),
5243
+ focused: isDocumentVisible(),
5244
+ middlewareRegistered: false,
5245
+ ...config
5246
+ },
5247
+ reducers: {
5248
+ middlewareRegistered(state, {
5249
+ payload
5250
+ }) {
5251
+ state.middlewareRegistered = state.middlewareRegistered === "conflict" || apiUid !== payload ? "conflict" : true;
5252
+ }
5253
+ },
5254
+ extraReducers: (builder) => {
5255
+ builder.addCase(onOnline, (state) => {
5256
+ state.online = true;
5257
+ }).addCase(onOffline, (state) => {
5258
+ state.online = false;
5259
+ }).addCase(onFocus, (state) => {
5260
+ state.focused = true;
5261
+ }).addCase(onFocusLost, (state) => {
5262
+ state.focused = false;
5263
+ }).addMatcher(hasRehydrationInfo, (draft) => ({
5264
+ ...draft
5265
+ }));
5266
+ }
5267
+ });
5268
+ const combinedReducer = combineReducers({
5269
+ queries: querySlice.reducer,
5270
+ mutations: mutationSlice.reducer,
5271
+ provided: invalidationSlice.reducer,
5272
+ subscriptions: internalSubscriptionsSlice.reducer,
5273
+ config: configSlice.reducer
5274
+ });
5275
+ const reducer = (state, action) => combinedReducer(resetApiState.match(action) ? void 0 : state, action);
5276
+ const actions = {
5277
+ ...configSlice.actions,
5278
+ ...querySlice.actions,
5279
+ ...subscriptionSlice.actions,
5280
+ ...internalSubscriptionsSlice.actions,
5281
+ ...mutationSlice.actions,
5282
+ ...invalidationSlice.actions,
5283
+ resetApiState
5284
+ };
5285
+ return {
5286
+ reducer,
5287
+ actions
5288
+ };
5289
+ }
5290
+
5291
+ // src/query/core/buildSelectors.ts
5292
+ var skipToken = /* @__PURE__ */ Symbol.for("RTKQ/skipToken");
5293
+ var initialSubState = {
5294
+ status: "uninitialized" /* uninitialized */
5295
+ };
5296
+ var defaultQuerySubState = /* @__PURE__ */ produce(initialSubState, () => {
5297
+ });
5298
+ var defaultMutationSubState = /* @__PURE__ */ produce(initialSubState, () => {
5299
+ });
5300
+ function buildSelectors({
5301
+ serializeQueryArgs,
5302
+ reducerPath,
5303
+ createSelector: createSelector2
5304
+ }) {
5305
+ const selectSkippedQuery = (state) => defaultQuerySubState;
5306
+ const selectSkippedMutation = (state) => defaultMutationSubState;
5307
+ return {
5308
+ buildQuerySelector,
5309
+ buildMutationSelector,
5310
+ selectInvalidatedBy,
5311
+ selectCachedArgsForQuery
5312
+ };
5313
+ function withRequestFlags(substate) {
5314
+ return {
5315
+ ...substate,
5316
+ ...getRequestStatusFlags(substate.status)
5317
+ };
5318
+ }
5319
+ function selectInternalState(rootState) {
5320
+ const state = rootState[reducerPath];
5321
+ if (process.env.NODE_ENV !== "production") {
5322
+ if (!state) {
5323
+ if (selectInternalState.triggered) return state;
5324
+ selectInternalState.triggered = true;
5325
+ console.error(`Error: No data found at \`state.${reducerPath}\`. Did you forget to add the reducer to the store?`);
5326
+ }
5327
+ }
5328
+ return state;
5329
+ }
5330
+ function buildQuerySelector(endpointName, endpointDefinition) {
5331
+ return (queryArgs) => {
5332
+ const serializedArgs = serializeQueryArgs({
5333
+ queryArgs,
5334
+ endpointDefinition,
5335
+ endpointName
5336
+ });
5337
+ const selectQuerySubstate = (state) => selectInternalState(state)?.queries?.[serializedArgs] ?? defaultQuerySubState;
5338
+ const finalSelectQuerySubState = queryArgs === skipToken ? selectSkippedQuery : selectQuerySubstate;
5339
+ return createSelector2(finalSelectQuerySubState, withRequestFlags);
5340
+ };
5341
+ }
5342
+ function buildMutationSelector() {
5343
+ return (id) => {
5344
+ let mutationId;
5345
+ if (typeof id === "object") {
5346
+ mutationId = getMutationCacheKey(id) ?? skipToken;
5347
+ } else {
5348
+ mutationId = id;
5349
+ }
5350
+ const selectMutationSubstate = (state) => selectInternalState(state)?.mutations?.[mutationId] ?? defaultMutationSubState;
5351
+ const finalSelectMutationSubstate = mutationId === skipToken ? selectSkippedMutation : selectMutationSubstate;
5352
+ return createSelector2(finalSelectMutationSubstate, withRequestFlags);
5353
+ };
5354
+ }
5355
+ function selectInvalidatedBy(state, tags) {
5356
+ const apiState = state[reducerPath];
5357
+ const toInvalidate = /* @__PURE__ */ new Set();
5358
+ for (const tag of tags.map(expandTagDescription)) {
5359
+ const provided = apiState.provided[tag.type];
5360
+ if (!provided) {
5361
+ continue;
5362
+ }
5363
+ let invalidateSubscriptions = (tag.id !== void 0 ? (
5364
+ // id given: invalidate all queries that provide this type & id
5365
+ provided[tag.id]
5366
+ ) : (
5367
+ // no id: invalidate all queries that provide this type
5368
+ flatten(Object.values(provided))
5369
+ )) ?? [];
5370
+ for (const invalidate of invalidateSubscriptions) {
5371
+ toInvalidate.add(invalidate);
5372
+ }
5373
+ }
5374
+ return flatten(Array.from(toInvalidate.values()).map((queryCacheKey) => {
5375
+ const querySubState = apiState.queries[queryCacheKey];
5376
+ return querySubState ? [{
5377
+ queryCacheKey,
5378
+ endpointName: querySubState.endpointName,
5379
+ originalArgs: querySubState.originalArgs
5380
+ }] : [];
5381
+ }));
5382
+ }
5383
+ function selectCachedArgsForQuery(state, queryName) {
5384
+ return Object.values(state[reducerPath].queries).filter((entry) => entry?.endpointName === queryName && entry.status !== "uninitialized" /* uninitialized */).map((entry) => entry.originalArgs);
5385
+ }
5386
+ }
5387
+
5388
+ // src/query/defaultSerializeQueryArgs.ts
5389
+ var cache = WeakMap ? /* @__PURE__ */ new WeakMap() : void 0;
5390
+ var defaultSerializeQueryArgs = ({
5391
+ endpointName,
5392
+ queryArgs
5393
+ }) => {
5394
+ let serialized = "";
5395
+ const cached = cache?.get(queryArgs);
5396
+ if (typeof cached === "string") {
5397
+ serialized = cached;
5398
+ } else {
5399
+ const stringified = JSON.stringify(queryArgs, (key, value) => {
5400
+ value = typeof value === "bigint" ? {
5401
+ $bigint: value.toString()
5402
+ } : value;
5403
+ value = isPlainObject$1(value) ? Object.keys(value).sort().reduce((acc, key2) => {
5404
+ acc[key2] = value[key2];
5405
+ return acc;
5406
+ }, {}) : value;
5407
+ return value;
5408
+ });
5409
+ if (isPlainObject$1(queryArgs)) {
5410
+ cache?.set(queryArgs, stringified);
5411
+ }
5412
+ serialized = stringified;
5413
+ }
5414
+ return `${endpointName}(${serialized})`;
5415
+ };
5416
+ function buildCreateApi(...modules) {
5417
+ return function baseCreateApi(options) {
5418
+ const extractRehydrationInfo = weakMapMemoize((action) => options.extractRehydrationInfo?.(action, {
5419
+ reducerPath: options.reducerPath ?? "api"
5420
+ }));
5421
+ const optionsWithDefaults = {
5422
+ reducerPath: "api",
5423
+ keepUnusedDataFor: 60,
5424
+ refetchOnMountOrArgChange: false,
5425
+ refetchOnFocus: false,
5426
+ refetchOnReconnect: false,
5427
+ invalidationBehavior: "delayed",
5428
+ ...options,
5429
+ extractRehydrationInfo,
5430
+ serializeQueryArgs(queryArgsApi) {
5431
+ let finalSerializeQueryArgs = defaultSerializeQueryArgs;
5432
+ if ("serializeQueryArgs" in queryArgsApi.endpointDefinition) {
5433
+ const endpointSQA = queryArgsApi.endpointDefinition.serializeQueryArgs;
5434
+ finalSerializeQueryArgs = (queryArgsApi2) => {
5435
+ const initialResult = endpointSQA(queryArgsApi2);
5436
+ if (typeof initialResult === "string") {
5437
+ return initialResult;
5438
+ } else {
5439
+ return defaultSerializeQueryArgs({
5440
+ ...queryArgsApi2,
5441
+ queryArgs: initialResult
5442
+ });
5443
+ }
5444
+ };
5445
+ } else if (options.serializeQueryArgs) {
5446
+ finalSerializeQueryArgs = options.serializeQueryArgs;
5447
+ }
5448
+ return finalSerializeQueryArgs(queryArgsApi);
5449
+ },
5450
+ tagTypes: [...options.tagTypes || []]
5451
+ };
5452
+ const context = {
5453
+ endpointDefinitions: {},
5454
+ batch(fn) {
5455
+ fn();
5456
+ },
5457
+ apiUid: nanoid(),
5458
+ extractRehydrationInfo,
5459
+ hasRehydrationInfo: weakMapMemoize((action) => extractRehydrationInfo(action) != null)
5460
+ };
5461
+ const api = {
5462
+ injectEndpoints,
5463
+ enhanceEndpoints({
5464
+ addTagTypes,
5465
+ endpoints
5466
+ }) {
5467
+ if (addTagTypes) {
5468
+ for (const eT of addTagTypes) {
5469
+ if (!optionsWithDefaults.tagTypes.includes(eT)) {
5470
+ optionsWithDefaults.tagTypes.push(eT);
5471
+ }
5472
+ }
5473
+ }
5474
+ if (endpoints) {
5475
+ for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {
5476
+ if (typeof partialDefinition === "function") {
5477
+ partialDefinition(context.endpointDefinitions[endpointName]);
5478
+ } else {
5479
+ Object.assign(context.endpointDefinitions[endpointName] || {}, partialDefinition);
5480
+ }
5481
+ }
5482
+ }
5483
+ return api;
5484
+ }
5485
+ };
5486
+ const initializedModules = modules.map((m) => m.init(api, optionsWithDefaults, context));
5487
+ function injectEndpoints(inject) {
5488
+ const evaluatedEndpoints = inject.endpoints({
5489
+ query: (x) => ({
5490
+ ...x,
5491
+ type: "query" /* query */
5492
+ }),
5493
+ mutation: (x) => ({
5494
+ ...x,
5495
+ type: "mutation" /* mutation */
5496
+ })
5497
+ });
5498
+ for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {
5499
+ if (inject.overrideExisting !== true && endpointName in context.endpointDefinitions) {
5500
+ if (inject.overrideExisting === "throw") {
5501
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(39) : `called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``);
5502
+ } else if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
5503
+ console.error(`called \`injectEndpoints\` to override already-existing endpointName ${endpointName} without specifying \`overrideExisting: true\``);
5504
+ }
5505
+ continue;
5506
+ }
5507
+ context.endpointDefinitions[endpointName] = definition;
5508
+ for (const m of initializedModules) {
5509
+ m.injectEndpoint(endpointName, definition);
5510
+ }
5511
+ }
5512
+ return api;
5513
+ }
5514
+ return api.injectEndpoints({
5515
+ endpoints: options.endpoints
5516
+ });
5517
+ };
5518
+ }
5519
+ var _NEVER = /* @__PURE__ */ Symbol();
5520
+ function fakeBaseQuery() {
5521
+ return function() {
5522
+ throw new Error(process.env.NODE_ENV === "production" ? formatProdErrorMessage(33) : "When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.");
5523
+ };
5524
+ }
5525
+ function safeAssign(target, ...args) {
5526
+ return Object.assign(target, ...args);
5527
+ }
5528
+ var buildBatchedActionsHandler = ({
5529
+ api,
5530
+ queryThunk,
5531
+ internalState
5532
+ }) => {
5533
+ const subscriptionsPrefix = `${api.reducerPath}/subscriptions`;
5534
+ let previousSubscriptions = null;
5535
+ let updateSyncTimer = null;
5536
+ const {
5537
+ updateSubscriptionOptions,
5538
+ unsubscribeQueryResult
5539
+ } = api.internalActions;
5540
+ const actuallyMutateSubscriptions = (mutableState, action) => {
5541
+ if (updateSubscriptionOptions.match(action)) {
5542
+ const {
5543
+ queryCacheKey,
5544
+ requestId,
5545
+ options
5546
+ } = action.payload;
5547
+ if (mutableState?.[queryCacheKey]?.[requestId]) {
5548
+ mutableState[queryCacheKey][requestId] = options;
5549
+ }
5550
+ return true;
5551
+ }
5552
+ if (unsubscribeQueryResult.match(action)) {
5553
+ const {
5554
+ queryCacheKey,
5555
+ requestId
5556
+ } = action.payload;
5557
+ if (mutableState[queryCacheKey]) {
5558
+ delete mutableState[queryCacheKey][requestId];
5559
+ }
5560
+ return true;
5561
+ }
5562
+ if (api.internalActions.removeQueryResult.match(action)) {
5563
+ delete mutableState[action.payload.queryCacheKey];
5564
+ return true;
5565
+ }
5566
+ if (queryThunk.pending.match(action)) {
5567
+ const {
5568
+ meta: {
5569
+ arg,
5570
+ requestId
5571
+ }
5572
+ } = action;
5573
+ const substate = mutableState[arg.queryCacheKey] ??= {};
5574
+ substate[`${requestId}_running`] = {};
5575
+ if (arg.subscribe) {
5576
+ substate[requestId] = arg.subscriptionOptions ?? substate[requestId] ?? {};
5577
+ }
5578
+ return true;
5579
+ }
5580
+ let mutated = false;
5581
+ if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action)) {
5582
+ const state = mutableState[action.meta.arg.queryCacheKey] || {};
5583
+ const key = `${action.meta.requestId}_running`;
5584
+ mutated ||= !!state[key];
5585
+ delete state[key];
5586
+ }
5587
+ if (queryThunk.rejected.match(action)) {
5588
+ const {
5589
+ meta: {
5590
+ condition,
5591
+ arg,
5592
+ requestId
5593
+ }
5594
+ } = action;
5595
+ if (condition && arg.subscribe) {
5596
+ const substate = mutableState[arg.queryCacheKey] ??= {};
5597
+ substate[requestId] = arg.subscriptionOptions ?? substate[requestId] ?? {};
5598
+ mutated = true;
5599
+ }
5600
+ }
5601
+ return mutated;
5602
+ };
5603
+ const getSubscriptions = () => internalState.currentSubscriptions;
5604
+ const getSubscriptionCount = (queryCacheKey) => {
5605
+ const subscriptions = getSubscriptions();
5606
+ const subscriptionsForQueryArg = subscriptions[queryCacheKey] ?? {};
5607
+ return countObjectKeys(subscriptionsForQueryArg);
5608
+ };
5609
+ const isRequestSubscribed = (queryCacheKey, requestId) => {
5610
+ const subscriptions = getSubscriptions();
5611
+ return !!subscriptions?.[queryCacheKey]?.[requestId];
5612
+ };
5613
+ const subscriptionSelectors = {
5614
+ getSubscriptions,
5615
+ getSubscriptionCount,
5616
+ isRequestSubscribed
5617
+ };
5618
+ return (action, mwApi) => {
5619
+ if (!previousSubscriptions) {
5620
+ previousSubscriptions = JSON.parse(JSON.stringify(internalState.currentSubscriptions));
5621
+ }
5622
+ if (api.util.resetApiState.match(action)) {
5623
+ previousSubscriptions = internalState.currentSubscriptions = {};
5624
+ updateSyncTimer = null;
5625
+ return [true, false];
5626
+ }
5627
+ if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {
5628
+ return [false, subscriptionSelectors];
5629
+ }
5630
+ const didMutate = actuallyMutateSubscriptions(internalState.currentSubscriptions, action);
5631
+ let actionShouldContinue = true;
5632
+ if (didMutate) {
5633
+ if (!updateSyncTimer) {
5634
+ updateSyncTimer = setTimeout(() => {
5635
+ const newSubscriptions = JSON.parse(JSON.stringify(internalState.currentSubscriptions));
5636
+ const [, patches] = produceWithPatches(previousSubscriptions, () => newSubscriptions);
5637
+ mwApi.next(api.internalActions.subscriptionsUpdated(patches));
5638
+ previousSubscriptions = newSubscriptions;
5639
+ updateSyncTimer = null;
5640
+ }, 500);
5641
+ }
5642
+ const isSubscriptionSliceAction = typeof action.type == "string" && !!action.type.startsWith(subscriptionsPrefix);
5643
+ const isAdditionalSubscriptionAction = queryThunk.rejected.match(action) && action.meta.condition && !!action.meta.arg.subscribe;
5644
+ actionShouldContinue = !isSubscriptionSliceAction && !isAdditionalSubscriptionAction;
5645
+ }
5646
+ return [actionShouldContinue, false];
5647
+ };
5648
+ };
5649
+
5650
+ // src/query/core/buildMiddleware/cacheCollection.ts
5651
+ function isObjectEmpty(obj) {
5652
+ for (const k in obj) {
5653
+ return false;
5654
+ }
5655
+ return true;
5656
+ }
5657
+ var THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2147483647 / 1e3 - 1;
5658
+ var buildCacheCollectionHandler = ({
5659
+ reducerPath,
5660
+ api,
5661
+ queryThunk,
5662
+ context,
5663
+ internalState
5664
+ }) => {
5665
+ const {
5666
+ removeQueryResult,
5667
+ unsubscribeQueryResult,
5668
+ cacheEntriesUpserted
5669
+ } = api.internalActions;
5670
+ const canTriggerUnsubscribe = isAnyOf(unsubscribeQueryResult.match, queryThunk.fulfilled, queryThunk.rejected, cacheEntriesUpserted.match);
5671
+ function anySubscriptionsRemainingForKey(queryCacheKey) {
5672
+ const subscriptions = internalState.currentSubscriptions[queryCacheKey];
5673
+ return !!subscriptions && !isObjectEmpty(subscriptions);
5674
+ }
5675
+ const currentRemovalTimeouts = {};
5676
+ const handler = (action, mwApi, internalState2) => {
5677
+ if (canTriggerUnsubscribe(action)) {
5678
+ const state = mwApi.getState()[reducerPath];
5679
+ let queryCacheKeys;
5680
+ if (cacheEntriesUpserted.match(action)) {
5681
+ queryCacheKeys = action.payload.map((entry) => entry.queryDescription.queryCacheKey);
5682
+ } else {
5683
+ const {
5684
+ queryCacheKey
5685
+ } = unsubscribeQueryResult.match(action) ? action.payload : action.meta.arg;
5686
+ queryCacheKeys = [queryCacheKey];
5687
+ }
5688
+ for (const queryCacheKey of queryCacheKeys) {
5689
+ handleUnsubscribe(queryCacheKey, state.queries[queryCacheKey]?.endpointName, mwApi, state.config);
5690
+ }
5691
+ }
5692
+ if (api.util.resetApiState.match(action)) {
5693
+ for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {
5694
+ if (timeout) clearTimeout(timeout);
5695
+ delete currentRemovalTimeouts[key];
5696
+ }
5697
+ }
5698
+ if (context.hasRehydrationInfo(action)) {
5699
+ const state = mwApi.getState()[reducerPath];
5700
+ const {
5701
+ queries
5702
+ } = context.extractRehydrationInfo(action);
5703
+ for (const [queryCacheKey, queryState] of Object.entries(queries)) {
5704
+ handleUnsubscribe(queryCacheKey, queryState?.endpointName, mwApi, state.config);
5705
+ }
5706
+ }
5707
+ };
5708
+ function handleUnsubscribe(queryCacheKey, endpointName, api2, config) {
5709
+ const endpointDefinition = context.endpointDefinitions[endpointName];
5710
+ const keepUnusedDataFor = endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor;
5711
+ if (keepUnusedDataFor === Infinity) {
5712
+ return;
5713
+ }
5714
+ const finalKeepUnusedDataFor = Math.max(0, Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS));
5715
+ if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
5716
+ const currentTimeout = currentRemovalTimeouts[queryCacheKey];
5717
+ if (currentTimeout) {
5718
+ clearTimeout(currentTimeout);
5719
+ }
5720
+ currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {
5721
+ if (!anySubscriptionsRemainingForKey(queryCacheKey)) {
5722
+ api2.dispatch(removeQueryResult({
5723
+ queryCacheKey
5724
+ }));
5725
+ }
5726
+ delete currentRemovalTimeouts[queryCacheKey];
5727
+ }, finalKeepUnusedDataFor * 1e3);
5728
+ }
5729
+ }
5730
+ return handler;
5731
+ };
5732
+
5733
+ // src/query/core/buildMiddleware/cacheLifecycle.ts
5734
+ var neverResolvedError = new Error("Promise never resolved before cacheEntryRemoved.");
5735
+ var buildCacheLifecycleHandler = ({
5736
+ api,
5737
+ reducerPath,
5738
+ context,
5739
+ queryThunk,
5740
+ mutationThunk,
5741
+ internalState
5742
+ }) => {
5743
+ const isQueryThunk = isAsyncThunkAction(queryThunk);
5744
+ const isMutationThunk = isAsyncThunkAction(mutationThunk);
5745
+ const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk);
5746
+ const lifecycleMap = {};
5747
+ function resolveLifecycleEntry(cacheKey, data, meta) {
5748
+ const lifecycle = lifecycleMap[cacheKey];
5749
+ if (lifecycle?.valueResolved) {
5750
+ lifecycle.valueResolved({
5751
+ data,
5752
+ meta
5753
+ });
5754
+ delete lifecycle.valueResolved;
5755
+ }
5756
+ }
5757
+ function removeLifecycleEntry(cacheKey) {
5758
+ const lifecycle = lifecycleMap[cacheKey];
5759
+ if (lifecycle) {
5760
+ delete lifecycleMap[cacheKey];
5761
+ lifecycle.cacheEntryRemoved();
5762
+ }
5763
+ }
5764
+ const handler = (action, mwApi, stateBefore) => {
5765
+ const cacheKey = getCacheKey(action);
5766
+ function checkForNewCacheKey(endpointName, cacheKey2, requestId, originalArgs) {
5767
+ const oldState = stateBefore[reducerPath].queries[cacheKey2];
5768
+ const state = mwApi.getState()[reducerPath].queries[cacheKey2];
5769
+ if (!oldState && state) {
5770
+ handleNewKey(endpointName, originalArgs, cacheKey2, mwApi, requestId);
5771
+ }
5772
+ }
5773
+ if (queryThunk.pending.match(action)) {
5774
+ checkForNewCacheKey(action.meta.arg.endpointName, cacheKey, action.meta.requestId, action.meta.arg.originalArgs);
5775
+ } else if (api.internalActions.cacheEntriesUpserted.match(action)) {
5776
+ for (const {
5777
+ queryDescription,
5778
+ value
5779
+ } of action.payload) {
5780
+ const {
5781
+ endpointName,
5782
+ originalArgs,
5783
+ queryCacheKey
5784
+ } = queryDescription;
5785
+ checkForNewCacheKey(endpointName, queryCacheKey, action.meta.requestId, originalArgs);
5786
+ resolveLifecycleEntry(queryCacheKey, value, {});
5787
+ }
5788
+ } else if (mutationThunk.pending.match(action)) {
5789
+ const state = mwApi.getState()[reducerPath].mutations[cacheKey];
5790
+ if (state) {
5791
+ handleNewKey(action.meta.arg.endpointName, action.meta.arg.originalArgs, cacheKey, mwApi, action.meta.requestId);
5792
+ }
5793
+ } else if (isFulfilledThunk(action)) {
5794
+ resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta);
5795
+ } else if (api.internalActions.removeQueryResult.match(action) || api.internalActions.removeMutationResult.match(action)) {
5796
+ removeLifecycleEntry(cacheKey);
5797
+ } else if (api.util.resetApiState.match(action)) {
5798
+ for (const cacheKey2 of Object.keys(lifecycleMap)) {
5799
+ removeLifecycleEntry(cacheKey2);
5800
+ }
5801
+ }
5802
+ };
5803
+ function getCacheKey(action) {
5804
+ if (isQueryThunk(action)) return action.meta.arg.queryCacheKey;
5805
+ if (isMutationThunk(action)) {
5806
+ return action.meta.arg.fixedCacheKey ?? action.meta.requestId;
5807
+ }
5808
+ if (api.internalActions.removeQueryResult.match(action)) return action.payload.queryCacheKey;
5809
+ if (api.internalActions.removeMutationResult.match(action)) return getMutationCacheKey(action.payload);
5810
+ return "";
5811
+ }
5812
+ function handleNewKey(endpointName, originalArgs, queryCacheKey, mwApi, requestId) {
5813
+ const endpointDefinition = context.endpointDefinitions[endpointName];
5814
+ const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded;
5815
+ if (!onCacheEntryAdded) return;
5816
+ const lifecycle = {};
5817
+ const cacheEntryRemoved = new Promise((resolve) => {
5818
+ lifecycle.cacheEntryRemoved = resolve;
5819
+ });
5820
+ const cacheDataLoaded = Promise.race([new Promise((resolve) => {
5821
+ lifecycle.valueResolved = resolve;
5822
+ }), cacheEntryRemoved.then(() => {
5823
+ throw neverResolvedError;
5824
+ })]);
5825
+ cacheDataLoaded.catch(() => {
5826
+ });
5827
+ lifecycleMap[queryCacheKey] = lifecycle;
5828
+ const selector = api.endpoints[endpointName].select(endpointDefinition.type === "query" /* query */ ? originalArgs : queryCacheKey);
5829
+ const extra = mwApi.dispatch((_, __, extra2) => extra2);
5830
+ const lifecycleApi = {
5831
+ ...mwApi,
5832
+ getCacheEntry: () => selector(mwApi.getState()),
5833
+ requestId,
5834
+ extra,
5835
+ updateCachedData: endpointDefinition.type === "query" /* query */ ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
5836
+ cacheDataLoaded,
5837
+ cacheEntryRemoved
5838
+ };
5839
+ const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi);
5840
+ Promise.resolve(runningHandler).catch((e) => {
5841
+ if (e === neverResolvedError) return;
5842
+ throw e;
5843
+ });
5844
+ }
5845
+ return handler;
5846
+ };
5847
+
5848
+ // src/query/core/buildMiddleware/devMiddleware.ts
5849
+ var buildDevCheckHandler = ({
5850
+ api,
5851
+ context: {
5852
+ apiUid
5853
+ },
5854
+ reducerPath
5855
+ }) => {
5856
+ return (action, mwApi) => {
5857
+ if (api.util.resetApiState.match(action)) {
5858
+ mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
5859
+ }
5860
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
5861
+ if (api.internalActions.middlewareRegistered.match(action) && action.payload === apiUid && mwApi.getState()[reducerPath]?.config?.middlewareRegistered === "conflict") {
5862
+ console.warn(`There is a mismatch between slice and middleware for the reducerPath "${reducerPath}".
5863
+ You can only have one api per reducer path, this will lead to crashes in various situations!${reducerPath === "api" ? `
5864
+ If you have multiple apis, you *have* to specify the reducerPath option when using createApi!` : ""}`);
5865
+ }
5866
+ }
5867
+ };
5868
+ };
5869
+
5870
+ // src/query/core/buildMiddleware/invalidationByTags.ts
5871
+ var buildInvalidationByTagsHandler = ({
5872
+ reducerPath,
5873
+ context,
5874
+ context: {
5875
+ endpointDefinitions
5876
+ },
5877
+ mutationThunk,
5878
+ queryThunk,
5879
+ api,
5880
+ assertTagType,
5881
+ refetchQuery,
5882
+ internalState
5883
+ }) => {
5884
+ const {
5885
+ removeQueryResult
5886
+ } = api.internalActions;
5887
+ const isThunkActionWithTags = isAnyOf(isFulfilled(mutationThunk), isRejectedWithValue(mutationThunk));
5888
+ const isQueryEnd = isAnyOf(isFulfilled(mutationThunk, queryThunk), isRejected(mutationThunk, queryThunk));
5889
+ let pendingTagInvalidations = [];
5890
+ const handler = (action, mwApi) => {
5891
+ if (isThunkActionWithTags(action)) {
5892
+ invalidateTags(calculateProvidedByThunk(action, "invalidatesTags", endpointDefinitions, assertTagType), mwApi);
5893
+ } else if (isQueryEnd(action)) {
5894
+ invalidateTags([], mwApi);
5895
+ } else if (api.util.invalidateTags.match(action)) {
5896
+ invalidateTags(calculateProvidedBy(action.payload, void 0, void 0, void 0, void 0, assertTagType), mwApi);
5897
+ }
5898
+ };
5899
+ function hasPendingRequests(state) {
5900
+ for (const key in state.queries) {
5901
+ if (state.queries[key]?.status === "pending" /* pending */) return true;
5902
+ }
5903
+ for (const key in state.mutations) {
5904
+ if (state.mutations[key]?.status === "pending" /* pending */) return true;
5905
+ }
5906
+ return false;
5907
+ }
5908
+ function invalidateTags(newTags, mwApi) {
5909
+ const rootState = mwApi.getState();
5910
+ const state = rootState[reducerPath];
5911
+ pendingTagInvalidations.push(...newTags);
5912
+ if (state.config.invalidationBehavior === "delayed" && hasPendingRequests(state)) {
5913
+ return;
5914
+ }
5915
+ const tags = pendingTagInvalidations;
5916
+ pendingTagInvalidations = [];
5917
+ if (tags.length === 0) return;
5918
+ const toInvalidate = api.util.selectInvalidatedBy(rootState, tags);
5919
+ context.batch(() => {
5920
+ const valuesArray = Array.from(toInvalidate.values());
5921
+ for (const {
5922
+ queryCacheKey
5923
+ } of valuesArray) {
5924
+ const querySubState = state.queries[queryCacheKey];
5925
+ const subscriptionSubState = internalState.currentSubscriptions[queryCacheKey] ?? {};
5926
+ if (querySubState) {
5927
+ if (countObjectKeys(subscriptionSubState) === 0) {
5928
+ mwApi.dispatch(removeQueryResult({
5929
+ queryCacheKey
5930
+ }));
5931
+ } else if (querySubState.status !== "uninitialized" /* uninitialized */) {
5932
+ mwApi.dispatch(refetchQuery(querySubState));
5933
+ }
5934
+ }
5935
+ }
5936
+ });
5937
+ }
5938
+ return handler;
5939
+ };
5940
+
5941
+ // src/query/core/buildMiddleware/polling.ts
5942
+ var buildPollingHandler = ({
5943
+ reducerPath,
5944
+ queryThunk,
5945
+ api,
5946
+ refetchQuery,
5947
+ internalState
5948
+ }) => {
5949
+ const currentPolls = {};
5950
+ const handler = (action, mwApi) => {
5951
+ if (api.internalActions.updateSubscriptionOptions.match(action) || api.internalActions.unsubscribeQueryResult.match(action)) {
5952
+ updatePollingInterval(action.payload, mwApi);
5953
+ }
5954
+ if (queryThunk.pending.match(action) || queryThunk.rejected.match(action) && action.meta.condition) {
5955
+ updatePollingInterval(action.meta.arg, mwApi);
5956
+ }
5957
+ if (queryThunk.fulfilled.match(action) || queryThunk.rejected.match(action) && !action.meta.condition) {
5958
+ startNextPoll(action.meta.arg, mwApi);
5959
+ }
5960
+ if (api.util.resetApiState.match(action)) {
5961
+ clearPolls();
5962
+ }
5963
+ };
5964
+ function startNextPoll({
5965
+ queryCacheKey
5966
+ }, api2) {
5967
+ const state = api2.getState()[reducerPath];
5968
+ const querySubState = state.queries[queryCacheKey];
5969
+ const subscriptions = internalState.currentSubscriptions[queryCacheKey];
5970
+ if (!querySubState || querySubState.status === "uninitialized" /* uninitialized */) return;
5971
+ const {
5972
+ lowestPollingInterval,
5973
+ skipPollingIfUnfocused
5974
+ } = findLowestPollingInterval(subscriptions);
5975
+ if (!Number.isFinite(lowestPollingInterval)) return;
5976
+ const currentPoll = currentPolls[queryCacheKey];
5977
+ if (currentPoll?.timeout) {
5978
+ clearTimeout(currentPoll.timeout);
5979
+ currentPoll.timeout = void 0;
5980
+ }
5981
+ const nextPollTimestamp = Date.now() + lowestPollingInterval;
5982
+ currentPolls[queryCacheKey] = {
5983
+ nextPollTimestamp,
5984
+ pollingInterval: lowestPollingInterval,
5985
+ timeout: setTimeout(() => {
5986
+ if (state.config.focused || !skipPollingIfUnfocused) {
5987
+ api2.dispatch(refetchQuery(querySubState));
5988
+ }
5989
+ startNextPoll({
5990
+ queryCacheKey
5991
+ }, api2);
5992
+ }, lowestPollingInterval)
5993
+ };
5994
+ }
5995
+ function updatePollingInterval({
5996
+ queryCacheKey
5997
+ }, api2) {
5998
+ const state = api2.getState()[reducerPath];
5999
+ const querySubState = state.queries[queryCacheKey];
6000
+ const subscriptions = internalState.currentSubscriptions[queryCacheKey];
6001
+ if (!querySubState || querySubState.status === "uninitialized" /* uninitialized */) {
6002
+ return;
6003
+ }
6004
+ const {
6005
+ lowestPollingInterval
6006
+ } = findLowestPollingInterval(subscriptions);
6007
+ if (!Number.isFinite(lowestPollingInterval)) {
6008
+ cleanupPollForKey(queryCacheKey);
6009
+ return;
6010
+ }
6011
+ const currentPoll = currentPolls[queryCacheKey];
6012
+ const nextPollTimestamp = Date.now() + lowestPollingInterval;
6013
+ if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {
6014
+ startNextPoll({
6015
+ queryCacheKey
6016
+ }, api2);
6017
+ }
6018
+ }
6019
+ function cleanupPollForKey(key) {
6020
+ const existingPoll = currentPolls[key];
6021
+ if (existingPoll?.timeout) {
6022
+ clearTimeout(existingPoll.timeout);
6023
+ }
6024
+ delete currentPolls[key];
6025
+ }
6026
+ function clearPolls() {
6027
+ for (const key of Object.keys(currentPolls)) {
6028
+ cleanupPollForKey(key);
6029
+ }
6030
+ }
6031
+ function findLowestPollingInterval(subscribers = {}) {
6032
+ let skipPollingIfUnfocused = false;
6033
+ let lowestPollingInterval = Number.POSITIVE_INFINITY;
6034
+ for (let key in subscribers) {
6035
+ if (!!subscribers[key].pollingInterval) {
6036
+ lowestPollingInterval = Math.min(subscribers[key].pollingInterval, lowestPollingInterval);
6037
+ skipPollingIfUnfocused = subscribers[key].skipPollingIfUnfocused || skipPollingIfUnfocused;
6038
+ }
6039
+ }
6040
+ return {
6041
+ lowestPollingInterval,
6042
+ skipPollingIfUnfocused
6043
+ };
6044
+ }
6045
+ return handler;
6046
+ };
6047
+
6048
+ // src/query/core/buildMiddleware/queryLifecycle.ts
6049
+ var buildQueryLifecycleHandler = ({
6050
+ api,
6051
+ context,
6052
+ queryThunk,
6053
+ mutationThunk
6054
+ }) => {
6055
+ const isPendingThunk = isPending(queryThunk, mutationThunk);
6056
+ const isRejectedThunk = isRejected(queryThunk, mutationThunk);
6057
+ const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk);
6058
+ const lifecycleMap = {};
6059
+ const handler = (action, mwApi) => {
6060
+ if (isPendingThunk(action)) {
6061
+ const {
6062
+ requestId,
6063
+ arg: {
6064
+ endpointName,
6065
+ originalArgs
6066
+ }
6067
+ } = action.meta;
6068
+ const endpointDefinition = context.endpointDefinitions[endpointName];
6069
+ const onQueryStarted = endpointDefinition?.onQueryStarted;
6070
+ if (onQueryStarted) {
6071
+ const lifecycle = {};
6072
+ const queryFulfilled = new Promise((resolve, reject) => {
6073
+ lifecycle.resolve = resolve;
6074
+ lifecycle.reject = reject;
6075
+ });
6076
+ queryFulfilled.catch(() => {
6077
+ });
6078
+ lifecycleMap[requestId] = lifecycle;
6079
+ const selector = api.endpoints[endpointName].select(endpointDefinition.type === "query" /* query */ ? originalArgs : requestId);
6080
+ const extra = mwApi.dispatch((_, __, extra2) => extra2);
6081
+ const lifecycleApi = {
6082
+ ...mwApi,
6083
+ getCacheEntry: () => selector(mwApi.getState()),
6084
+ requestId,
6085
+ extra,
6086
+ updateCachedData: endpointDefinition.type === "query" /* query */ ? (updateRecipe) => mwApi.dispatch(api.util.updateQueryData(endpointName, originalArgs, updateRecipe)) : void 0,
6087
+ queryFulfilled
6088
+ };
6089
+ onQueryStarted(originalArgs, lifecycleApi);
6090
+ }
6091
+ } else if (isFullfilledThunk(action)) {
6092
+ const {
6093
+ requestId,
6094
+ baseQueryMeta
6095
+ } = action.meta;
6096
+ lifecycleMap[requestId]?.resolve({
6097
+ data: action.payload,
6098
+ meta: baseQueryMeta
6099
+ });
6100
+ delete lifecycleMap[requestId];
6101
+ } else if (isRejectedThunk(action)) {
6102
+ const {
6103
+ requestId,
6104
+ rejectedWithValue,
6105
+ baseQueryMeta
6106
+ } = action.meta;
6107
+ lifecycleMap[requestId]?.reject({
6108
+ error: action.payload ?? action.error,
6109
+ isUnhandledError: !rejectedWithValue,
6110
+ meta: baseQueryMeta
6111
+ });
6112
+ delete lifecycleMap[requestId];
6113
+ }
6114
+ };
6115
+ return handler;
6116
+ };
6117
+
6118
+ // src/query/core/buildMiddleware/windowEventHandling.ts
6119
+ var buildWindowEventHandler = ({
6120
+ reducerPath,
6121
+ context,
6122
+ api,
6123
+ refetchQuery,
6124
+ internalState
6125
+ }) => {
6126
+ const {
6127
+ removeQueryResult
6128
+ } = api.internalActions;
6129
+ const handler = (action, mwApi) => {
6130
+ if (onFocus.match(action)) {
6131
+ refetchValidQueries(mwApi, "refetchOnFocus");
6132
+ }
6133
+ if (onOnline.match(action)) {
6134
+ refetchValidQueries(mwApi, "refetchOnReconnect");
6135
+ }
6136
+ };
6137
+ function refetchValidQueries(api2, type) {
6138
+ const state = api2.getState()[reducerPath];
6139
+ const queries = state.queries;
6140
+ const subscriptions = internalState.currentSubscriptions;
6141
+ context.batch(() => {
6142
+ for (const queryCacheKey of Object.keys(subscriptions)) {
6143
+ const querySubState = queries[queryCacheKey];
6144
+ const subscriptionSubState = subscriptions[queryCacheKey];
6145
+ if (!subscriptionSubState || !querySubState) continue;
6146
+ const shouldRefetch = Object.values(subscriptionSubState).some((sub) => sub[type] === true) || Object.values(subscriptionSubState).every((sub) => sub[type] === void 0) && state.config[type];
6147
+ if (shouldRefetch) {
6148
+ if (countObjectKeys(subscriptionSubState) === 0) {
6149
+ api2.dispatch(removeQueryResult({
6150
+ queryCacheKey
6151
+ }));
6152
+ } else if (querySubState.status !== "uninitialized" /* uninitialized */) {
6153
+ api2.dispatch(refetchQuery(querySubState));
6154
+ }
6155
+ }
6156
+ }
6157
+ });
6158
+ }
6159
+ return handler;
6160
+ };
6161
+
6162
+ // src/query/core/buildMiddleware/index.ts
6163
+ function buildMiddleware(input) {
6164
+ const {
6165
+ reducerPath,
6166
+ queryThunk,
6167
+ api,
6168
+ context
6169
+ } = input;
6170
+ const {
6171
+ apiUid
6172
+ } = context;
6173
+ const actions = {
6174
+ invalidateTags: createAction(`${reducerPath}/invalidateTags`)
6175
+ };
6176
+ const isThisApiSliceAction = (action) => action.type.startsWith(`${reducerPath}/`);
6177
+ const handlerBuilders = [buildDevCheckHandler, buildCacheCollectionHandler, buildInvalidationByTagsHandler, buildPollingHandler, buildCacheLifecycleHandler, buildQueryLifecycleHandler];
6178
+ const middleware = (mwApi) => {
6179
+ let initialized2 = false;
6180
+ const internalState = {
6181
+ currentSubscriptions: {}
6182
+ };
6183
+ const builderArgs = {
6184
+ ...input,
6185
+ internalState,
6186
+ refetchQuery,
6187
+ isThisApiSliceAction
6188
+ };
6189
+ const handlers = handlerBuilders.map((build) => build(builderArgs));
6190
+ const batchedActionsHandler = buildBatchedActionsHandler(builderArgs);
6191
+ const windowEventsHandler = buildWindowEventHandler(builderArgs);
6192
+ return (next) => {
6193
+ return (action) => {
6194
+ if (!isAction(action)) {
6195
+ return next(action);
6196
+ }
6197
+ if (!initialized2) {
6198
+ initialized2 = true;
6199
+ mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid));
6200
+ }
6201
+ const mwApiWithNext = {
6202
+ ...mwApi,
6203
+ next
6204
+ };
6205
+ const stateBefore = mwApi.getState();
6206
+ const [actionShouldContinue, internalProbeResult] = batchedActionsHandler(action, mwApiWithNext, stateBefore);
6207
+ let res;
6208
+ if (actionShouldContinue) {
6209
+ res = next(action);
6210
+ } else {
6211
+ res = internalProbeResult;
6212
+ }
6213
+ if (!!mwApi.getState()[reducerPath]) {
6214
+ windowEventsHandler(action, mwApiWithNext, stateBefore);
6215
+ if (isThisApiSliceAction(action) || context.hasRehydrationInfo(action)) {
6216
+ for (const handler of handlers) {
6217
+ handler(action, mwApiWithNext, stateBefore);
6218
+ }
6219
+ }
6220
+ }
6221
+ return res;
6222
+ };
6223
+ };
6224
+ };
6225
+ return {
6226
+ middleware,
6227
+ actions
6228
+ };
6229
+ function refetchQuery(querySubState) {
6230
+ return input.api.endpoints[querySubState.endpointName].initiate(querySubState.originalArgs, {
6231
+ subscribe: false,
6232
+ forceRefetch: true
6233
+ });
6234
+ }
6235
+ }
6236
+
6237
+ // src/query/core/module.ts
6238
+ var coreModuleName = /* @__PURE__ */ Symbol();
6239
+ var coreModule = ({
6240
+ createSelector: createSelector2 = createSelector
6241
+ } = {}) => ({
6242
+ name: coreModuleName,
6243
+ init(api, {
6244
+ baseQuery,
6245
+ tagTypes,
6246
+ reducerPath,
6247
+ serializeQueryArgs,
6248
+ keepUnusedDataFor,
6249
+ refetchOnMountOrArgChange,
6250
+ refetchOnFocus,
6251
+ refetchOnReconnect,
6252
+ invalidationBehavior
6253
+ }, context) {
6254
+ enablePatches();
6255
+ const assertTagType = (tag) => {
6256
+ if (typeof process !== "undefined" && process.env.NODE_ENV === "development") {
6257
+ if (!tagTypes.includes(tag.type)) {
6258
+ console.error(`Tag type '${tag.type}' was used, but not specified in \`tagTypes\`!`);
6259
+ }
6260
+ }
6261
+ return tag;
6262
+ };
6263
+ Object.assign(api, {
6264
+ reducerPath,
6265
+ endpoints: {},
6266
+ internalActions: {
6267
+ onOnline,
6268
+ onOffline,
6269
+ onFocus,
6270
+ onFocusLost
6271
+ },
6272
+ util: {}
6273
+ });
6274
+ const {
6275
+ queryThunk,
6276
+ mutationThunk,
6277
+ patchQueryData,
6278
+ updateQueryData,
6279
+ upsertQueryData,
6280
+ prefetch,
6281
+ buildMatchThunkActions
6282
+ } = buildThunks({
6283
+ baseQuery,
6284
+ reducerPath,
6285
+ context,
6286
+ api,
6287
+ serializeQueryArgs,
6288
+ assertTagType
6289
+ });
6290
+ const {
6291
+ reducer,
6292
+ actions: sliceActions
6293
+ } = buildSlice({
6294
+ context,
6295
+ queryThunk,
6296
+ mutationThunk,
6297
+ serializeQueryArgs,
6298
+ reducerPath,
6299
+ assertTagType,
6300
+ config: {
6301
+ refetchOnFocus,
6302
+ refetchOnReconnect,
6303
+ refetchOnMountOrArgChange,
6304
+ keepUnusedDataFor,
6305
+ reducerPath,
6306
+ invalidationBehavior
6307
+ }
6308
+ });
6309
+ safeAssign(api.util, {
6310
+ patchQueryData,
6311
+ updateQueryData,
6312
+ upsertQueryData,
6313
+ prefetch,
6314
+ resetApiState: sliceActions.resetApiState,
6315
+ upsertQueryEntries: sliceActions.cacheEntriesUpserted
6316
+ });
6317
+ safeAssign(api.internalActions, sliceActions);
6318
+ const {
6319
+ middleware,
6320
+ actions: middlewareActions
6321
+ } = buildMiddleware({
6322
+ reducerPath,
6323
+ context,
6324
+ queryThunk,
6325
+ mutationThunk,
6326
+ api,
6327
+ assertTagType
6328
+ });
6329
+ safeAssign(api.util, middlewareActions);
6330
+ safeAssign(api, {
6331
+ reducer,
6332
+ middleware
6333
+ });
6334
+ const {
6335
+ buildQuerySelector,
6336
+ buildMutationSelector,
6337
+ selectInvalidatedBy,
6338
+ selectCachedArgsForQuery
6339
+ } = buildSelectors({
6340
+ serializeQueryArgs,
6341
+ reducerPath,
6342
+ createSelector: createSelector2
6343
+ });
6344
+ safeAssign(api.util, {
6345
+ selectInvalidatedBy,
6346
+ selectCachedArgsForQuery
6347
+ });
6348
+ const {
6349
+ buildInitiateQuery,
6350
+ buildInitiateMutation,
6351
+ getRunningMutationThunk,
6352
+ getRunningMutationsThunk,
6353
+ getRunningQueriesThunk,
6354
+ getRunningQueryThunk
6355
+ } = buildInitiate({
6356
+ queryThunk,
6357
+ mutationThunk,
6358
+ api,
6359
+ serializeQueryArgs,
6360
+ context
6361
+ });
6362
+ safeAssign(api.util, {
6363
+ getRunningMutationThunk,
6364
+ getRunningMutationsThunk,
6365
+ getRunningQueryThunk,
6366
+ getRunningQueriesThunk
6367
+ });
6368
+ return {
6369
+ name: coreModuleName,
6370
+ injectEndpoint(endpointName, definition) {
6371
+ const anyApi = api;
6372
+ anyApi.endpoints[endpointName] ??= {};
6373
+ if (isQueryDefinition(definition)) {
6374
+ safeAssign(anyApi.endpoints[endpointName], {
6375
+ name: endpointName,
6376
+ select: buildQuerySelector(endpointName, definition),
6377
+ initiate: buildInitiateQuery(endpointName, definition)
6378
+ }, buildMatchThunkActions(queryThunk, endpointName));
6379
+ } else if (isMutationDefinition(definition)) {
6380
+ safeAssign(anyApi.endpoints[endpointName], {
6381
+ name: endpointName,
6382
+ select: buildMutationSelector(),
6383
+ initiate: buildInitiateMutation(endpointName)
6384
+ }, buildMatchThunkActions(mutationThunk, endpointName));
6385
+ }
6386
+ }
6387
+ };
6388
+ }
6389
+ });
6390
+
6391
+ // src/query/core/index.ts
6392
+ var createApi = /* @__PURE__ */ buildCreateApi(coreModule());
6393
+
6394
+ exports.QueryStatus = QueryStatus;
3720
6395
  exports.ReducerType = ReducerType;
3721
6396
  exports.SHOULD_AUTOBATCH = SHOULD_AUTOBATCH;
3722
6397
  exports.TaskAbortError = TaskAbortError;
3723
6398
  exports.Tuple = Tuple;
6399
+ exports._NEVER = _NEVER;
3724
6400
  exports.__DO_NOT_USE__ActionTypes = actionTypes_default;
3725
6401
  exports.addListener = addListener;
3726
6402
  exports.applyMiddleware = applyMiddleware;
3727
6403
  exports.asyncThunkCreator = asyncThunkCreator;
3728
6404
  exports.autoBatchEnhancer = autoBatchEnhancer;
3729
6405
  exports.bindActionCreators = bindActionCreators;
6406
+ exports.buildCreateApi = buildCreateApi;
3730
6407
  exports.buildCreateSlice = buildCreateSlice;
3731
6408
  exports.clearAllListeners = clearAllListeners;
3732
6409
  exports.combineReducers = combineReducers;
3733
6410
  exports.combineSlices = combineSlices;
3734
6411
  exports.compose = compose;
3735
6412
  exports.configureStore = configureStore;
6413
+ exports.copyWithStructuralSharing = copyWithStructuralSharing;
6414
+ exports.coreModule = coreModule;
6415
+ exports.coreModuleName = coreModuleName;
3736
6416
  exports.createAction = createAction;
3737
6417
  exports.createActionCreatorInvariantMiddleware = createActionCreatorInvariantMiddleware;
6418
+ exports.createApi = createApi;
3738
6419
  exports.createAsyncThunk = createAsyncThunk;
3739
6420
  exports.createDraftSafeSelector = createDraftSafeSelector;
3740
6421
  exports.createDraftSafeSelectorCreator = createDraftSafeSelectorCreator;
@@ -3750,6 +6431,9 @@ exports.createSerializableStateInvariantMiddleware = createSerializableStateInva
3750
6431
  exports.createSlice = createSlice;
3751
6432
  exports.createStore = createStore;
3752
6433
  exports.current = current;
6434
+ exports.defaultSerializeQueryArgs = defaultSerializeQueryArgs;
6435
+ exports.fakeBaseQuery = fakeBaseQuery;
6436
+ exports.fetchBaseQuery = fetchBaseQuery;
3753
6437
  exports.findNonSerializableValue = findNonSerializableValue;
3754
6438
  exports.formatProdErrorMessage = formatProdErrorMessage;
3755
6439
  exports.freeze = freeze;
@@ -3774,6 +6458,9 @@ exports.nanoid = nanoid;
3774
6458
  exports.original = original$1;
3775
6459
  exports.prepareAutoBatched = prepareAutoBatched;
3776
6460
  exports.removeListener = removeListener;
6461
+ exports.retry = retry;
6462
+ exports.setupListeners = setupListeners;
6463
+ exports.skipToken = skipToken;
3777
6464
  exports.unwrapResult = unwrapResult;
3778
6465
  exports.weakMapMemoize = weakMapMemoize;
3779
6466
  //# sourceMappingURL=index.cjs.js.map