@techstuff-dev/foundation-api-utils 2.1.1 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -47,7 +47,7 @@ var errors = process.env.NODE_ENV !== "production" ? [
47
47
  function die(error, ...args) {
48
48
  if (process.env.NODE_ENV !== "production") {
49
49
  const e = errors[error];
50
- const msg = typeof e === "function" ? e.apply(null, args) : e;
50
+ const msg = isFunction$1(e) ? e.apply(null, args) : e;
51
51
  throw new Error(`[Immer] ${msg}`);
52
52
  }
53
53
  throw new Error(
@@ -56,36 +56,49 @@ function die(error, ...args) {
56
56
  }
57
57
 
58
58
  // src/utils/common.ts
59
- var getPrototypeOf = Object.getPrototypeOf;
60
- function isDraft(value) {
61
- return !!value && !!value[DRAFT_STATE];
62
- }
59
+ var O = Object;
60
+ var getPrototypeOf = O.getPrototypeOf;
61
+ var CONSTRUCTOR = "constructor";
62
+ var PROTOTYPE = "prototype";
63
+ var CONFIGURABLE = "configurable";
64
+ var ENUMERABLE = "enumerable";
65
+ var WRITABLE = "writable";
66
+ var VALUE = "value";
67
+ var isDraft = (value) => !!value && !!value[DRAFT_STATE];
63
68
  function isDraftable(value) {
64
69
  if (!value)
65
70
  return false;
66
- return isPlainObject(value) || Array.isArray(value) || !!value[DRAFTABLE] || !!value.constructor?.[DRAFTABLE] || isMap(value) || isSet(value);
71
+ return isPlainObject(value) || isArray(value) || !!value[DRAFTABLE] || !!value[CONSTRUCTOR]?.[DRAFTABLE] || isMap(value) || isSet(value);
67
72
  }
68
- var objectCtorString = Object.prototype.constructor.toString();
73
+ var objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString();
74
+ var cachedCtorStrings = /* @__PURE__ */ new WeakMap();
69
75
  function isPlainObject(value) {
70
- if (!value || typeof value !== "object")
76
+ if (!value || !isObjectish(value))
71
77
  return false;
72
78
  const proto = getPrototypeOf(value);
73
- if (proto === null) {
79
+ if (proto === null || proto === O[PROTOTYPE])
74
80
  return true;
75
- }
76
- const Ctor = Object.hasOwnProperty.call(proto, "constructor") && proto.constructor;
81
+ const Ctor = O.hasOwnProperty.call(proto, CONSTRUCTOR) && proto[CONSTRUCTOR];
77
82
  if (Ctor === Object)
78
83
  return true;
79
- return typeof Ctor == "function" && Function.toString.call(Ctor) === objectCtorString;
84
+ if (!isFunction$1(Ctor))
85
+ return false;
86
+ let ctorString = cachedCtorStrings.get(Ctor);
87
+ if (ctorString === void 0) {
88
+ ctorString = Function.toString.call(Ctor);
89
+ cachedCtorStrings.set(Ctor, ctorString);
90
+ }
91
+ return ctorString === objectCtorString;
80
92
  }
81
93
  function original(value) {
82
94
  if (!isDraft(value))
83
95
  die(15, value);
84
96
  return value[DRAFT_STATE].base_;
85
97
  }
86
- function each(obj, iter) {
98
+ function each(obj, iter, strict = true) {
87
99
  if (getArchtype(obj) === 0 /* Object */) {
88
- Reflect.ownKeys(obj).forEach((key) => {
100
+ const keys = strict ? Reflect.ownKeys(obj) : O.keys(obj);
101
+ keys.forEach((key) => {
89
102
  iter(key, obj[key], obj);
90
103
  });
91
104
  } else {
@@ -94,23 +107,21 @@ function each(obj, iter) {
94
107
  }
95
108
  function getArchtype(thing) {
96
109
  const state = thing[DRAFT_STATE];
97
- return state ? state.type_ : Array.isArray(thing) ? 1 /* Array */ : isMap(thing) ? 2 /* Map */ : isSet(thing) ? 3 /* Set */ : 0 /* Object */;
98
- }
99
- function has(thing, prop) {
100
- return getArchtype(thing) === 2 /* Map */ ? thing.has(prop) : Object.prototype.hasOwnProperty.call(thing, prop);
101
- }
102
- function get(thing, prop) {
103
- return getArchtype(thing) === 2 /* Map */ ? thing.get(prop) : thing[prop];
110
+ return state ? state.type_ : isArray(thing) ? 1 /* Array */ : isMap(thing) ? 2 /* Map */ : isSet(thing) ? 3 /* Set */ : 0 /* Object */;
104
111
  }
105
- function set(thing, propOrOldValue, value) {
106
- const t = getArchtype(thing);
107
- if (t === 2 /* Map */)
112
+ var has = (thing, prop, type = getArchtype(thing)) => type === 2 /* Map */ ? thing.has(prop) : O[PROTOTYPE].hasOwnProperty.call(thing, prop);
113
+ var get = (thing, prop, type = getArchtype(thing)) => (
114
+ // @ts-ignore
115
+ type === 2 /* Map */ ? thing.get(prop) : thing[prop]
116
+ );
117
+ var set = (thing, propOrOldValue, value, type = getArchtype(thing)) => {
118
+ if (type === 2 /* Map */)
108
119
  thing.set(propOrOldValue, value);
109
- else if (t === 3 /* Set */) {
120
+ else if (type === 3 /* Set */) {
110
121
  thing.add(value);
111
122
  } else
112
123
  thing[propOrOldValue] = value;
113
- }
124
+ };
114
125
  function is(x, y) {
115
126
  if (x === y) {
116
127
  return x !== 0 || 1 / x === 1 / y;
@@ -118,15 +129,23 @@ function is(x, y) {
118
129
  return x !== x && y !== y;
119
130
  }
120
131
  }
121
- function isMap(target) {
122
- return target instanceof Map;
123
- }
124
- function isSet(target) {
125
- return target instanceof Set;
126
- }
127
- function latest(state) {
128
- return state.copy_ || state.base_;
132
+ var isArray = Array.isArray;
133
+ var isMap = (target) => target instanceof Map;
134
+ var isSet = (target) => target instanceof Set;
135
+ var isObjectish = (target) => typeof target === "object";
136
+ var isFunction$1 = (target) => typeof target === "function";
137
+ var isBoolean = (target) => typeof target === "boolean";
138
+ function isArrayIndex(value) {
139
+ const n = +value;
140
+ return Number.isInteger(n) && String(n) === value;
129
141
  }
142
+ var getProxyDraft = (value) => {
143
+ if (!isObjectish(value))
144
+ return null;
145
+ return value?.[DRAFT_STATE];
146
+ };
147
+ var latest = (state) => state.copy_ || state.base_;
148
+ var getFinalValue = (state) => state.modified_ ? state.copy_ : state.base_;
130
149
  function shallowCopy(base, strict) {
131
150
  if (isMap(base)) {
132
151
  return new Map(base);
@@ -134,58 +153,77 @@ function shallowCopy(base, strict) {
134
153
  if (isSet(base)) {
135
154
  return new Set(base);
136
155
  }
137
- if (Array.isArray(base))
138
- return Array.prototype.slice.call(base);
156
+ if (isArray(base))
157
+ return Array[PROTOTYPE].slice.call(base);
139
158
  const isPlain = isPlainObject(base);
140
159
  if (strict === true || strict === "class_only" && !isPlain) {
141
- const descriptors = Object.getOwnPropertyDescriptors(base);
160
+ const descriptors = O.getOwnPropertyDescriptors(base);
142
161
  delete descriptors[DRAFT_STATE];
143
162
  let keys = Reflect.ownKeys(descriptors);
144
163
  for (let i = 0; i < keys.length; i++) {
145
164
  const key = keys[i];
146
165
  const desc = descriptors[key];
147
- if (desc.writable === false) {
148
- desc.writable = true;
149
- desc.configurable = true;
166
+ if (desc[WRITABLE] === false) {
167
+ desc[WRITABLE] = true;
168
+ desc[CONFIGURABLE] = true;
150
169
  }
151
170
  if (desc.get || desc.set)
152
171
  descriptors[key] = {
153
- configurable: true,
154
- writable: true,
172
+ [CONFIGURABLE]: true,
173
+ [WRITABLE]: true,
155
174
  // could live with !!desc.set as well here...
156
- enumerable: desc.enumerable,
157
- value: base[key]
175
+ [ENUMERABLE]: desc[ENUMERABLE],
176
+ [VALUE]: base[key]
158
177
  };
159
178
  }
160
- return Object.create(getPrototypeOf(base), descriptors);
179
+ return O.create(getPrototypeOf(base), descriptors);
161
180
  } else {
162
181
  const proto = getPrototypeOf(base);
163
182
  if (proto !== null && isPlain) {
164
183
  return { ...base };
165
184
  }
166
- const obj = Object.create(proto);
167
- return Object.assign(obj, base);
185
+ const obj = O.create(proto);
186
+ return O.assign(obj, base);
168
187
  }
169
188
  }
170
189
  function freeze(obj, deep = false) {
171
190
  if (isFrozen(obj) || isDraft(obj) || !isDraftable(obj))
172
191
  return obj;
173
192
  if (getArchtype(obj) > 1) {
174
- obj.set = obj.add = obj.clear = obj.delete = dontMutateFrozenCollections;
193
+ O.defineProperties(obj, {
194
+ set: dontMutateMethodOverride,
195
+ add: dontMutateMethodOverride,
196
+ clear: dontMutateMethodOverride,
197
+ delete: dontMutateMethodOverride
198
+ });
175
199
  }
176
- Object.freeze(obj);
200
+ O.freeze(obj);
177
201
  if (deep)
178
- Object.entries(obj).forEach(([key, value]) => freeze(value, true));
202
+ each(
203
+ obj,
204
+ (_key, value) => {
205
+ freeze(value, true);
206
+ },
207
+ false
208
+ );
179
209
  return obj;
180
210
  }
181
211
  function dontMutateFrozenCollections() {
182
212
  die(2);
183
213
  }
214
+ var dontMutateMethodOverride = {
215
+ [VALUE]: dontMutateFrozenCollections
216
+ };
184
217
  function isFrozen(obj) {
185
- return Object.isFrozen(obj);
218
+ if (obj === null || !isObjectish(obj))
219
+ return true;
220
+ return O.isFrozen(obj);
186
221
  }
187
222
 
188
223
  // src/utils/plugins.ts
224
+ var PluginMapSet = "MapSet";
225
+ var PluginPatches = "Patches";
226
+ var PluginArrayMethods = "ArrayMethods";
189
227
  var plugins = {};
190
228
  function getPlugin(pluginKey) {
191
229
  const plugin = plugins[pluginKey];
@@ -194,6 +232,7 @@ function getPlugin(pluginKey) {
194
232
  }
195
233
  return plugin;
196
234
  }
235
+ var isPluginLoaded = (pluginKey) => !!plugins[pluginKey];
197
236
  function loadPlugin(pluginKey, implementation) {
198
237
  if (!plugins[pluginKey])
199
238
  plugins[pluginKey] = implementation;
@@ -201,23 +240,23 @@ function loadPlugin(pluginKey, implementation) {
201
240
 
202
241
  // src/core/scope.ts
203
242
  var currentScope;
204
- function getCurrentScope() {
205
- return currentScope;
206
- }
207
- function createScope(parent_, immer_) {
208
- return {
209
- drafts_: [],
210
- parent_,
211
- immer_,
212
- // Whenever the modified draft contains a draft from another scope, we
213
- // need to prevent auto-freezing so the unowned draft can be finalized.
214
- canAutoFreeze_: true,
215
- unfinalizedDrafts_: 0
216
- };
217
- }
243
+ var getCurrentScope = () => currentScope;
244
+ var createScope = (parent_, immer_) => ({
245
+ drafts_: [],
246
+ parent_,
247
+ immer_,
248
+ // Whenever the modified draft contains a draft from another scope, we
249
+ // need to prevent auto-freezing so the unowned draft can be finalized.
250
+ canAutoFreeze_: true,
251
+ unfinalizedDrafts_: 0,
252
+ handledSet_: /* @__PURE__ */ new Set(),
253
+ processedForPatches_: /* @__PURE__ */ new Set(),
254
+ mapSetPlugin_: isPluginLoaded(PluginMapSet) ? getPlugin(PluginMapSet) : void 0,
255
+ arrayMethodsPlugin_: isPluginLoaded(PluginArrayMethods) ? getPlugin(PluginArrayMethods) : void 0
256
+ });
218
257
  function usePatchesInScope(scope, patchListener) {
219
258
  if (patchListener) {
220
- getPlugin("Patches");
259
+ scope.patchPlugin_ = getPlugin(PluginPatches);
221
260
  scope.patches_ = [];
222
261
  scope.inversePatches_ = [];
223
262
  scope.patchListener_ = patchListener;
@@ -233,9 +272,7 @@ function leaveScope(scope) {
233
272
  currentScope = scope.parent_;
234
273
  }
235
274
  }
236
- function enterScope(immer2) {
237
- return currentScope = createScope(currentScope, immer2);
238
- }
275
+ var enterScope = (immer2) => currentScope = createScope(currentScope, immer2);
239
276
  function revokeDraft(draft) {
240
277
  const state = draft[DRAFT_STATE];
241
278
  if (state.type_ === 0 /* Object */ || state.type_ === 1 /* Array */)
@@ -256,105 +293,166 @@ function processResult(result, scope) {
256
293
  }
257
294
  if (isDraftable(result)) {
258
295
  result = finalize(scope, result);
259
- if (!scope.parent_)
260
- maybeFreeze(scope, result);
261
296
  }
262
- if (scope.patches_) {
263
- getPlugin("Patches").generateReplacementPatches_(
297
+ const { patchPlugin_ } = scope;
298
+ if (patchPlugin_) {
299
+ patchPlugin_.generateReplacementPatches_(
264
300
  baseDraft[DRAFT_STATE].base_,
265
301
  result,
266
- scope.patches_,
267
- scope.inversePatches_
302
+ scope
268
303
  );
269
304
  }
270
305
  } else {
271
- result = finalize(scope, baseDraft, []);
306
+ result = finalize(scope, baseDraft);
272
307
  }
308
+ maybeFreeze(scope, result, true);
273
309
  revokeScope(scope);
274
310
  if (scope.patches_) {
275
311
  scope.patchListener_(scope.patches_, scope.inversePatches_);
276
312
  }
277
313
  return result !== NOTHING ? result : void 0;
278
314
  }
279
- function finalize(rootScope, value, path) {
315
+ function finalize(rootScope, value) {
280
316
  if (isFrozen(value))
281
317
  return value;
282
318
  const state = value[DRAFT_STATE];
283
319
  if (!state) {
284
- each(
285
- value,
286
- (key, childValue) => finalizeProperty(rootScope, state, value, key, childValue, path)
287
- );
288
- return value;
320
+ const finalValue = handleValue(value, rootScope.handledSet_, rootScope);
321
+ return finalValue;
289
322
  }
290
- if (state.scope_ !== rootScope)
323
+ if (!isSameScope(state, rootScope)) {
291
324
  return value;
325
+ }
292
326
  if (!state.modified_) {
293
- maybeFreeze(rootScope, state.base_, true);
294
327
  return state.base_;
295
328
  }
296
329
  if (!state.finalized_) {
297
- state.finalized_ = true;
298
- state.scope_.unfinalizedDrafts_--;
299
- const result = state.copy_;
300
- let resultEach = result;
301
- let isSet2 = false;
302
- if (state.type_ === 3 /* Set */) {
303
- resultEach = new Set(result);
304
- result.clear();
305
- isSet2 = true;
306
- }
307
- each(
308
- resultEach,
309
- (key, childValue) => finalizeProperty(rootScope, state, result, key, childValue, path, isSet2)
310
- );
311
- maybeFreeze(rootScope, result, false);
312
- if (path && rootScope.patches_) {
313
- getPlugin("Patches").generatePatches_(
314
- state,
315
- path,
316
- rootScope.patches_,
317
- rootScope.inversePatches_
318
- );
330
+ const { callbacks_ } = state;
331
+ if (callbacks_) {
332
+ while (callbacks_.length > 0) {
333
+ const callback = callbacks_.pop();
334
+ callback(rootScope);
335
+ }
319
336
  }
337
+ generatePatchesAndFinalize(state, rootScope);
320
338
  }
321
339
  return state.copy_;
322
340
  }
323
- function finalizeProperty(rootScope, parentState, targetObject, prop, childValue, rootPath, targetIsSet) {
324
- if (process.env.NODE_ENV !== "production" && childValue === targetObject)
325
- die(5);
326
- if (isDraft(childValue)) {
327
- const path = rootPath && parentState && parentState.type_ !== 3 /* Set */ && // Set objects are atomic since they have no keys.
328
- !has(parentState.assigned_, prop) ? rootPath.concat(prop) : void 0;
329
- const res = finalize(rootScope, childValue, path);
330
- set(targetObject, prop, res);
331
- if (isDraft(res)) {
332
- rootScope.canAutoFreeze_ = false;
333
- } else
341
+ function maybeFreeze(scope, value, deep = false) {
342
+ if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
343
+ freeze(value, deep);
344
+ }
345
+ }
346
+ function markStateFinalized(state) {
347
+ state.finalized_ = true;
348
+ state.scope_.unfinalizedDrafts_--;
349
+ }
350
+ var isSameScope = (state, rootScope) => state.scope_ === rootScope;
351
+ var EMPTY_LOCATIONS_RESULT = [];
352
+ function updateDraftInParent(parent, draftValue, finalizedValue, originalKey) {
353
+ const parentCopy = latest(parent);
354
+ const parentType = parent.type_;
355
+ if (originalKey !== void 0) {
356
+ const currentValue = get(parentCopy, originalKey, parentType);
357
+ if (currentValue === draftValue) {
358
+ set(parentCopy, originalKey, finalizedValue, parentType);
334
359
  return;
335
- } else if (targetIsSet) {
336
- targetObject.add(childValue);
360
+ }
361
+ }
362
+ if (!parent.draftLocations_) {
363
+ const draftLocations = parent.draftLocations_ = /* @__PURE__ */ new Map();
364
+ each(parentCopy, (key, value) => {
365
+ if (isDraft(value)) {
366
+ const keys = draftLocations.get(value) || [];
367
+ keys.push(key);
368
+ draftLocations.set(value, keys);
369
+ }
370
+ });
371
+ }
372
+ const locations = parent.draftLocations_.get(draftValue) ?? EMPTY_LOCATIONS_RESULT;
373
+ for (const location of locations) {
374
+ set(parentCopy, location, finalizedValue, parentType);
337
375
  }
338
- if (isDraftable(childValue) && !isFrozen(childValue)) {
339
- if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
376
+ }
377
+ function registerChildFinalizationCallback(parent, child, key) {
378
+ parent.callbacks_.push(function childCleanup(rootScope) {
379
+ const state = child;
380
+ if (!state || !isSameScope(state, rootScope)) {
340
381
  return;
341
382
  }
342
- finalize(rootScope, childValue);
343
- if ((!parentState || !parentState.scope_.parent_) && typeof prop !== "symbol" && Object.prototype.propertyIsEnumerable.call(targetObject, prop))
344
- maybeFreeze(rootScope, childValue);
383
+ rootScope.mapSetPlugin_?.fixSetContents(state);
384
+ const finalizedValue = getFinalValue(state);
385
+ updateDraftInParent(parent, state.draft_ ?? state, finalizedValue, key);
386
+ generatePatchesAndFinalize(state, rootScope);
387
+ });
388
+ }
389
+ function generatePatchesAndFinalize(state, rootScope) {
390
+ const shouldFinalize = state.modified_ && !state.finalized_ && (state.type_ === 3 /* Set */ || state.type_ === 1 /* Array */ && state.allIndicesReassigned_ || (state.assigned_?.size ?? 0) > 0);
391
+ if (shouldFinalize) {
392
+ const { patchPlugin_ } = rootScope;
393
+ if (patchPlugin_) {
394
+ const basePath = patchPlugin_.getPath(state);
395
+ if (basePath) {
396
+ patchPlugin_.generatePatches_(state, basePath, rootScope);
397
+ }
398
+ }
399
+ markStateFinalized(state);
345
400
  }
346
401
  }
347
- function maybeFreeze(scope, value, deep = false) {
348
- if (!scope.parent_ && scope.immer_.autoFreeze_ && scope.canAutoFreeze_) {
349
- freeze(value, deep);
402
+ function handleCrossReference(target, key, value) {
403
+ const { scope_ } = target;
404
+ if (isDraft(value)) {
405
+ const state = value[DRAFT_STATE];
406
+ if (isSameScope(state, scope_)) {
407
+ state.callbacks_.push(function crossReferenceCleanup() {
408
+ prepareCopy(target);
409
+ const finalizedValue = getFinalValue(state);
410
+ updateDraftInParent(target, value, finalizedValue, key);
411
+ });
412
+ }
413
+ } else if (isDraftable(value)) {
414
+ target.callbacks_.push(function nestedDraftCleanup() {
415
+ const targetCopy = latest(target);
416
+ if (get(targetCopy, key, target.type_) === value) {
417
+ if (scope_.drafts_.length > 1 && (target.assigned_.get(key) ?? false) === true && target.copy_) {
418
+ handleValue(
419
+ get(target.copy_, key, target.type_),
420
+ scope_.handledSet_,
421
+ scope_
422
+ );
423
+ }
424
+ }
425
+ });
350
426
  }
351
427
  }
428
+ function handleValue(target, handledSet, rootScope) {
429
+ if (!rootScope.immer_.autoFreeze_ && rootScope.unfinalizedDrafts_ < 1) {
430
+ return target;
431
+ }
432
+ if (isDraft(target) || handledSet.has(target) || !isDraftable(target) || isFrozen(target)) {
433
+ return target;
434
+ }
435
+ handledSet.add(target);
436
+ each(target, (key, value) => {
437
+ if (isDraft(value)) {
438
+ const state = value[DRAFT_STATE];
439
+ if (isSameScope(state, rootScope)) {
440
+ const updatedValue = getFinalValue(state);
441
+ set(target, key, updatedValue, target.type_);
442
+ markStateFinalized(state);
443
+ }
444
+ } else if (isDraftable(value)) {
445
+ handleValue(value, handledSet, rootScope);
446
+ }
447
+ });
448
+ return target;
449
+ }
352
450
 
353
451
  // src/core/proxy.ts
354
452
  function createProxyProxy(base, parent) {
355
- const isArray = Array.isArray(base);
453
+ const baseIsArray = isArray(base);
356
454
  const state = {
357
- type_: isArray ? 1 /* Array */ : 0 /* Object */,
455
+ type_: baseIsArray ? 1 /* Array */ : 0 /* Object */,
358
456
  // Track which produce call this is associated with.
359
457
  scope_: parent ? parent.scope_ : getCurrentScope(),
360
458
  // True for both shallow and deep changes.
@@ -362,7 +460,8 @@ function createProxyProxy(base, parent) {
362
460
  // Used during finalization.
363
461
  finalized_: false,
364
462
  // Track which properties have been assigned (true) or deleted (false).
365
- assigned_: {},
463
+ // actually instantiated in `prepareCopy()`
464
+ assigned_: void 0,
366
465
  // The parent draft state.
367
466
  parent_: parent,
368
467
  // The base state.
@@ -374,34 +473,50 @@ function createProxyProxy(base, parent) {
374
473
  copy_: null,
375
474
  // Called by the `produce` function.
376
475
  revoke_: null,
377
- isManual_: false
476
+ isManual_: false,
477
+ // `callbacks` actually gets assigned in `createProxy`
478
+ callbacks_: void 0
378
479
  };
379
480
  let target = state;
380
481
  let traps = objectTraps;
381
- if (isArray) {
482
+ if (baseIsArray) {
382
483
  target = [state];
383
484
  traps = arrayTraps;
384
485
  }
385
486
  const { revoke, proxy } = Proxy.revocable(target, traps);
386
487
  state.draft_ = proxy;
387
488
  state.revoke_ = revoke;
388
- return proxy;
489
+ return [proxy, state];
389
490
  }
390
491
  var objectTraps = {
391
492
  get(state, prop) {
392
493
  if (prop === DRAFT_STATE)
393
494
  return state;
495
+ let arrayPlugin = state.scope_.arrayMethodsPlugin_;
496
+ const isArrayWithStringProp = state.type_ === 1 /* Array */ && typeof prop === "string";
497
+ if (isArrayWithStringProp) {
498
+ if (arrayPlugin?.isArrayOperationMethod(prop)) {
499
+ return arrayPlugin.createMethodInterceptor(state, prop);
500
+ }
501
+ }
394
502
  const source = latest(state);
395
- if (!has(source, prop)) {
503
+ if (!has(source, prop, state.type_)) {
396
504
  return readPropFromProto(state, source, prop);
397
505
  }
398
506
  const value = source[prop];
399
507
  if (state.finalized_ || !isDraftable(value)) {
400
508
  return value;
401
509
  }
510
+ if (isArrayWithStringProp && state.operationMethod && arrayPlugin?.isMutatingArrayMethod(
511
+ state.operationMethod
512
+ ) && isArrayIndex(prop)) {
513
+ return value;
514
+ }
402
515
  if (value === peek(state.base_, prop)) {
403
516
  prepareCopy(state);
404
- return state.copy_[prop] = createProxy(value, state);
517
+ const childKey = state.type_ === 1 /* Array */ ? +prop : prop;
518
+ const childDraft = createProxy(state.scope_, value, state, childKey);
519
+ return state.copy_[childKey] = childDraft;
405
520
  }
406
521
  return value;
407
522
  },
@@ -422,10 +537,10 @@ var objectTraps = {
422
537
  const currentState = current2?.[DRAFT_STATE];
423
538
  if (currentState && currentState.base_ === value) {
424
539
  state.copy_[prop] = value;
425
- state.assigned_[prop] = false;
540
+ state.assigned_.set(prop, false);
426
541
  return true;
427
542
  }
428
- if (is(value, current2) && (value !== void 0 || has(state.base_, prop)))
543
+ if (is(value, current2) && (value !== void 0 || has(state.base_, prop, state.type_)))
429
544
  return true;
430
545
  prepareCopy(state);
431
546
  markChanged(state);
@@ -435,16 +550,17 @@ var objectTraps = {
435
550
  Number.isNaN(value) && Number.isNaN(state.copy_[prop]))
436
551
  return true;
437
552
  state.copy_[prop] = value;
438
- state.assigned_[prop] = true;
553
+ state.assigned_.set(prop, true);
554
+ handleCrossReference(state, prop, value);
439
555
  return true;
440
556
  },
441
557
  deleteProperty(state, prop) {
558
+ prepareCopy(state);
442
559
  if (peek(state.base_, prop) !== void 0 || prop in state.base_) {
443
- state.assigned_[prop] = false;
444
- prepareCopy(state);
560
+ state.assigned_.set(prop, false);
445
561
  markChanged(state);
446
562
  } else {
447
- delete state.assigned_[prop];
563
+ state.assigned_.delete(prop);
448
564
  }
449
565
  if (state.copy_) {
450
566
  delete state.copy_[prop];
@@ -459,10 +575,10 @@ var objectTraps = {
459
575
  if (!desc)
460
576
  return desc;
461
577
  return {
462
- writable: true,
463
- configurable: state.type_ !== 1 /* Array */ || prop !== "length",
464
- enumerable: desc.enumerable,
465
- value: owner[prop]
578
+ [WRITABLE]: true,
579
+ [CONFIGURABLE]: state.type_ !== 1 /* Array */ || prop !== "length",
580
+ [ENUMERABLE]: desc[ENUMERABLE],
581
+ [VALUE]: owner[prop]
466
582
  };
467
583
  },
468
584
  defineProperty() {
@@ -478,8 +594,9 @@ var objectTraps = {
478
594
  var arrayTraps = {};
479
595
  each(objectTraps, (key, fn) => {
480
596
  arrayTraps[key] = function() {
481
- arguments[0] = arguments[0][0];
482
- return fn.apply(this, arguments);
597
+ const args = arguments;
598
+ args[0] = args[0][0];
599
+ return fn.apply(this, args);
483
600
  };
484
601
  });
485
602
  arrayTraps.deleteProperty = function(state, prop) {
@@ -499,7 +616,7 @@ function peek(draft, prop) {
499
616
  }
500
617
  function readPropFromProto(state, source, prop) {
501
618
  const desc = getDescriptorFromProto(source, prop);
502
- return desc ? `value` in desc ? desc.value : (
619
+ return desc ? VALUE in desc ? desc[VALUE] : (
503
620
  // This is a very special case, if the prop is a getter defined by the
504
621
  // prototype, we should invoke it with the draft as context!
505
622
  desc.get?.call(state.draft_)
@@ -527,6 +644,7 @@ function markChanged(state) {
527
644
  }
528
645
  function prepareCopy(state) {
529
646
  if (!state.copy_) {
647
+ state.assigned_ = /* @__PURE__ */ new Map();
530
648
  state.copy_ = shallowCopy(
531
649
  state.base_,
532
650
  state.scope_.immer_.useStrictShallowCopy_
@@ -539,6 +657,7 @@ var Immer2 = class {
539
657
  constructor(config) {
540
658
  this.autoFreeze_ = true;
541
659
  this.useStrictShallowCopy_ = false;
660
+ this.useStrictIteration_ = false;
542
661
  /**
543
662
  * The `produce` function takes a value and a "recipe function" (whose
544
663
  * return value often depends on the base state). The recipe function is
@@ -559,7 +678,7 @@ var Immer2 = class {
559
678
  * @returns {any} a new state, or the initial state if nothing was modified
560
679
  */
561
680
  this.produce = (base, recipe, patchListener) => {
562
- if (typeof base === "function" && typeof recipe !== "function") {
681
+ if (isFunction$1(base) && !isFunction$1(recipe)) {
563
682
  const defaultBase = recipe;
564
683
  recipe = base;
565
684
  const self = this;
@@ -567,14 +686,14 @@ var Immer2 = class {
567
686
  return self.produce(base2, (draft) => recipe.call(this, draft, ...args));
568
687
  };
569
688
  }
570
- if (typeof recipe !== "function")
689
+ if (!isFunction$1(recipe))
571
690
  die(6);
572
- if (patchListener !== void 0 && typeof patchListener !== "function")
691
+ if (patchListener !== void 0 && !isFunction$1(patchListener))
573
692
  die(7);
574
693
  let result;
575
694
  if (isDraftable(base)) {
576
695
  const scope = enterScope(this);
577
- const proxy = createProxy(base, void 0);
696
+ const proxy = createProxy(scope, base, void 0);
578
697
  let hasError = true;
579
698
  try {
580
699
  result = recipe(proxy);
@@ -587,7 +706,7 @@ var Immer2 = class {
587
706
  }
588
707
  usePatchesInScope(scope, patchListener);
589
708
  return processResult(result, scope);
590
- } else if (!base || typeof base !== "object") {
709
+ } else if (!base || !isObjectish(base)) {
591
710
  result = recipe(base);
592
711
  if (result === void 0)
593
712
  result = base;
@@ -598,7 +717,10 @@ var Immer2 = class {
598
717
  if (patchListener) {
599
718
  const p = [];
600
719
  const ip = [];
601
- getPlugin("Patches").generateReplacementPatches_(base, result, p, ip);
720
+ getPlugin(PluginPatches).generateReplacementPatches_(base, result, {
721
+ patches_: p,
722
+ inversePatches_: ip
723
+ });
602
724
  patchListener(p, ip);
603
725
  }
604
726
  return result;
@@ -606,7 +728,7 @@ var Immer2 = class {
606
728
  die(1, base);
607
729
  };
608
730
  this.produceWithPatches = (base, recipe) => {
609
- if (typeof base === "function") {
731
+ if (isFunction$1(base)) {
610
732
  return (state, ...args) => this.produceWithPatches(state, (draft) => base(draft, ...args));
611
733
  }
612
734
  let patches, inversePatches;
@@ -616,10 +738,12 @@ var Immer2 = class {
616
738
  });
617
739
  return [result, patches, inversePatches];
618
740
  };
619
- if (typeof config?.autoFreeze === "boolean")
741
+ if (isBoolean(config?.autoFreeze))
620
742
  this.setAutoFreeze(config.autoFreeze);
621
- if (typeof config?.useStrictShallowCopy === "boolean")
743
+ if (isBoolean(config?.useStrictShallowCopy))
622
744
  this.setUseStrictShallowCopy(config.useStrictShallowCopy);
745
+ if (isBoolean(config?.useStrictIteration))
746
+ this.setUseStrictIteration(config.useStrictIteration);
623
747
  }
624
748
  createDraft(base) {
625
749
  if (!isDraftable(base))
@@ -627,7 +751,7 @@ var Immer2 = class {
627
751
  if (isDraft(base))
628
752
  base = current(base);
629
753
  const scope = enterScope(this);
630
- const proxy = createProxy(base, void 0);
754
+ const proxy = createProxy(scope, base, void 0);
631
755
  proxy[DRAFT_STATE].isManual_ = true;
632
756
  leaveScope(scope);
633
757
  return proxy;
@@ -656,6 +780,18 @@ var Immer2 = class {
656
780
  setUseStrictShallowCopy(value) {
657
781
  this.useStrictShallowCopy_ = value;
658
782
  }
783
+ /**
784
+ * Pass false to use faster iteration that skips non-enumerable properties
785
+ * but still handles symbols for compatibility.
786
+ *
787
+ * By default, strict iteration is enabled (includes all own properties).
788
+ */
789
+ setUseStrictIteration(value) {
790
+ this.useStrictIteration_ = value;
791
+ }
792
+ shouldUseStrictIteration() {
793
+ return this.useStrictIteration_;
794
+ }
659
795
  applyPatches(base, patches) {
660
796
  let i;
661
797
  for (i = patches.length - 1; i >= 0; i--) {
@@ -668,7 +804,7 @@ var Immer2 = class {
668
804
  if (i > -1) {
669
805
  patches = patches.slice(i + 1);
670
806
  }
671
- const applyPatchesImpl = getPlugin("Patches").applyPatches_;
807
+ const applyPatchesImpl = getPlugin(PluginPatches).applyPatches_;
672
808
  if (isDraft(base)) {
673
809
  return applyPatchesImpl(base, patches);
674
810
  }
@@ -678,10 +814,23 @@ var Immer2 = class {
678
814
  );
679
815
  }
680
816
  };
681
- function createProxy(value, parent) {
682
- const draft = isMap(value) ? getPlugin("MapSet").proxyMap_(value, parent) : isSet(value) ? getPlugin("MapSet").proxySet_(value, parent) : createProxyProxy(value, parent);
683
- const scope = parent ? parent.scope_ : getCurrentScope();
817
+ function createProxy(rootScope, value, parent, key) {
818
+ const [draft, state] = isMap(value) ? getPlugin(PluginMapSet).proxyMap_(value, parent) : isSet(value) ? getPlugin(PluginMapSet).proxySet_(value, parent) : createProxyProxy(value, parent);
819
+ const scope = parent?.scope_ ?? getCurrentScope();
684
820
  scope.drafts_.push(draft);
821
+ state.callbacks_ = parent?.callbacks_ ?? [];
822
+ state.key_ = key;
823
+ if (parent && key !== void 0) {
824
+ registerChildFinalizationCallback(parent, state, key);
825
+ } else {
826
+ state.callbacks_.push(function rootDraftCleanup(rootScope2) {
827
+ rootScope2.mapSetPlugin_?.fixSetContents(state);
828
+ const { patchPlugin_ } = rootScope2;
829
+ if (state.modified_ && patchPlugin_) {
830
+ patchPlugin_.generatePatches_(state, [], rootScope2);
831
+ }
832
+ });
833
+ }
685
834
  return draft;
686
835
  }
687
836
 
@@ -696,17 +845,23 @@ function currentImpl(value) {
696
845
  return value;
697
846
  const state = value[DRAFT_STATE];
698
847
  let copy;
848
+ let strict = true;
699
849
  if (state) {
700
850
  if (!state.modified_)
701
851
  return state.base_;
702
852
  state.finalized_ = true;
703
853
  copy = shallowCopy(value, state.scope_.immer_.useStrictShallowCopy_);
854
+ strict = state.scope_.immer_.shouldUseStrictIteration();
704
855
  } else {
705
856
  copy = shallowCopy(value, true);
706
857
  }
707
- each(copy, (key, childValue) => {
708
- set(copy, key, currentImpl(childValue));
709
- });
858
+ each(
859
+ copy,
860
+ (key, childValue) => {
861
+ set(copy, key, currentImpl(childValue));
862
+ },
863
+ strict
864
+ );
710
865
  if (state) {
711
866
  state.finalized_ = false;
712
867
  }
@@ -728,27 +883,86 @@ function enablePatches() {
728
883
  "Patching reserved attributes like __proto__, prototype and constructor is not allowed"
729
884
  );
730
885
  }
886
+ function getPath(state, path = []) {
887
+ if ("key_" in state && state.key_ !== void 0) {
888
+ const parentCopy = state.parent_.copy_ ?? state.parent_.base_;
889
+ const proxyDraft = getProxyDraft(get(parentCopy, state.key_));
890
+ const valueAtKey = get(parentCopy, state.key_);
891
+ if (valueAtKey === void 0) {
892
+ return null;
893
+ }
894
+ if (valueAtKey !== state.draft_ && valueAtKey !== state.base_ && valueAtKey !== state.copy_) {
895
+ return null;
896
+ }
897
+ if (proxyDraft != null && proxyDraft.base_ !== state.base_) {
898
+ return null;
899
+ }
900
+ const isSet2 = state.parent_.type_ === 3 /* Set */;
901
+ let key;
902
+ if (isSet2) {
903
+ const setParent = state.parent_;
904
+ key = Array.from(setParent.drafts_.keys()).indexOf(state.key_);
905
+ } else {
906
+ key = state.key_;
907
+ }
908
+ if (!(isSet2 && parentCopy.size > key || has(parentCopy, key))) {
909
+ return null;
910
+ }
911
+ path.push(key);
912
+ }
913
+ if (state.parent_) {
914
+ return getPath(state.parent_, path);
915
+ }
916
+ path.reverse();
917
+ try {
918
+ resolvePath(state.copy_, path);
919
+ } catch (e) {
920
+ return null;
921
+ }
922
+ return path;
923
+ }
924
+ function resolvePath(base, path) {
925
+ let current2 = base;
926
+ for (let i = 0; i < path.length - 1; i++) {
927
+ const key = path[i];
928
+ current2 = get(current2, key);
929
+ if (!isObjectish(current2) || current2 === null) {
930
+ throw new Error(`Cannot resolve path at '${path.join("/")}'`);
931
+ }
932
+ }
933
+ return current2;
934
+ }
731
935
  const REPLACE = "replace";
732
936
  const ADD = "add";
733
937
  const REMOVE = "remove";
734
- function generatePatches_(state, basePath, patches, inversePatches) {
938
+ function generatePatches_(state, basePath, scope) {
939
+ if (state.scope_.processedForPatches_.has(state)) {
940
+ return;
941
+ }
942
+ state.scope_.processedForPatches_.add(state);
943
+ const { patches_, inversePatches_ } = scope;
735
944
  switch (state.type_) {
736
945
  case 0 /* Object */:
737
946
  case 2 /* Map */:
738
947
  return generatePatchesFromAssigned(
739
948
  state,
740
949
  basePath,
741
- patches,
742
- inversePatches
950
+ patches_,
951
+ inversePatches_
743
952
  );
744
953
  case 1 /* Array */:
745
- return generateArrayPatches(state, basePath, patches, inversePatches);
954
+ return generateArrayPatches(
955
+ state,
956
+ basePath,
957
+ patches_,
958
+ inversePatches_
959
+ );
746
960
  case 3 /* Set */:
747
961
  return generateSetPatches(
748
962
  state,
749
963
  basePath,
750
- patches,
751
- inversePatches
964
+ patches_,
965
+ inversePatches_
752
966
  );
753
967
  }
754
968
  }
@@ -759,20 +973,28 @@ function enablePatches() {
759
973
  [base_, copy_] = [copy_, base_];
760
974
  [patches, inversePatches] = [inversePatches, patches];
761
975
  }
976
+ const allReassigned = state.allIndicesReassigned_ === true;
762
977
  for (let i = 0; i < base_.length; i++) {
763
- if (assigned_[i] && copy_[i] !== base_[i]) {
978
+ const copiedItem = copy_[i];
979
+ const baseItem = base_[i];
980
+ const isAssigned = allReassigned || assigned_?.get(i.toString());
981
+ if (isAssigned && copiedItem !== baseItem) {
982
+ const childState = copiedItem?.[DRAFT_STATE];
983
+ if (childState && childState.modified_) {
984
+ continue;
985
+ }
764
986
  const path = basePath.concat([i]);
765
987
  patches.push({
766
988
  op: REPLACE,
767
989
  path,
768
990
  // Need to maybe clone it, as it can in fact be the original value
769
991
  // due to the base/copy inversion at the start of this function
770
- value: clonePatchValueIfNeeded(copy_[i])
992
+ value: clonePatchValueIfNeeded(copiedItem)
771
993
  });
772
994
  inversePatches.push({
773
995
  op: REPLACE,
774
996
  path,
775
- value: clonePatchValueIfNeeded(base_[i])
997
+ value: clonePatchValueIfNeeded(baseItem)
776
998
  });
777
999
  }
778
1000
  }
@@ -795,15 +1017,17 @@ function enablePatches() {
795
1017
  }
796
1018
  }
797
1019
  function generatePatchesFromAssigned(state, basePath, patches, inversePatches) {
798
- const { base_, copy_ } = state;
1020
+ const { base_, copy_, type_ } = state;
799
1021
  each(state.assigned_, (key, assignedValue) => {
800
- const origValue = get(base_, key);
801
- const value = get(copy_, key);
1022
+ const origValue = get(base_, key, type_);
1023
+ const value = get(copy_, key, type_);
802
1024
  const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD;
803
1025
  if (origValue === value && op === REPLACE)
804
1026
  return;
805
1027
  const path = basePath.concat(key);
806
- patches.push(op === REMOVE ? { op, path } : { op, path, value });
1028
+ patches.push(
1029
+ op === REMOVE ? { op, path } : { op, path, value: clonePatchValueIfNeeded(value) }
1030
+ );
807
1031
  inversePatches.push(
808
1032
  op === ADD ? { op: REMOVE, path } : op === REMOVE ? { op: ADD, path, value: clonePatchValueIfNeeded(origValue) } : { op: REPLACE, path, value: clonePatchValueIfNeeded(origValue) }
809
1033
  );
@@ -846,13 +1070,14 @@ function enablePatches() {
846
1070
  i++;
847
1071
  });
848
1072
  }
849
- function generateReplacementPatches_(baseValue, replacement, patches, inversePatches) {
850
- patches.push({
1073
+ function generateReplacementPatches_(baseValue, replacement, scope) {
1074
+ const { patches_, inversePatches_ } = scope;
1075
+ patches_.push({
851
1076
  op: REPLACE,
852
1077
  path: [],
853
1078
  value: replacement === NOTHING ? void 0 : replacement
854
1079
  });
855
- inversePatches.push({
1080
+ inversePatches_.push({
856
1081
  op: REPLACE,
857
1082
  path: [],
858
1083
  value: baseValue
@@ -868,12 +1093,12 @@ function enablePatches() {
868
1093
  if (typeof p !== "string" && typeof p !== "number") {
869
1094
  p = "" + p;
870
1095
  }
871
- if ((parentType === 0 /* Object */ || parentType === 1 /* Array */) && (p === "__proto__" || p === "constructor"))
1096
+ if ((parentType === 0 /* Object */ || parentType === 1 /* Array */) && (p === "__proto__" || p === CONSTRUCTOR))
872
1097
  die(errorOffset + 3);
873
- if (typeof base === "function" && p === "prototype")
1098
+ if (isFunction$1(base) && p === PROTOTYPE)
874
1099
  die(errorOffset + 3);
875
1100
  base = get(base, p);
876
- if (typeof base !== "object")
1101
+ if (!isObjectish(base))
877
1102
  die(errorOffset + 2, path.join("/"));
878
1103
  }
879
1104
  const type = getArchtype(base);
@@ -920,7 +1145,7 @@ function enablePatches() {
920
1145
  function deepClonePatchValue(obj) {
921
1146
  if (!isDraftable(obj))
922
1147
  return obj;
923
- if (Array.isArray(obj))
1148
+ if (isArray(obj))
924
1149
  return obj.map(deepClonePatchValue);
925
1150
  if (isMap(obj))
926
1151
  return new Map(
@@ -941,24 +1166,21 @@ function enablePatches() {
941
1166
  } else
942
1167
  return obj;
943
1168
  }
944
- loadPlugin("Patches", {
1169
+ loadPlugin(PluginPatches, {
945
1170
  applyPatches_,
946
1171
  generatePatches_,
947
- generateReplacementPatches_
1172
+ generateReplacementPatches_,
1173
+ getPath
948
1174
  });
949
1175
  }
950
1176
 
951
1177
  // src/immer.ts
952
1178
  var immer = new Immer2();
953
1179
  immer.produce;
954
- var produceWithPatches = immer.produceWithPatches.bind(
1180
+ var produceWithPatches = /* @__PURE__ */ immer.produceWithPatches.bind(
955
1181
  immer
956
1182
  );
957
- immer.setAutoFreeze.bind(immer);
958
- immer.setUseStrictShallowCopy.bind(immer);
959
- var applyPatches = immer.applyPatches.bind(immer);
960
- immer.createDraft.bind(immer);
961
- immer.finishDraft.bind(immer);
1183
+ var applyPatches = /* @__PURE__ */ immer.applyPatches.bind(immer);
962
1184
 
963
1185
  // src/getDotPath/getDotPath.ts
964
1186
 
@@ -1301,20 +1523,24 @@ var createStructuredSelector = Object.assign(
1301
1523
  );
1302
1524
 
1303
1525
  // src/query/core/apiState.ts
1304
- var QueryStatus = /* @__PURE__ */ ((QueryStatus2) => {
1305
- QueryStatus2["uninitialized"] = "uninitialized";
1306
- QueryStatus2["pending"] = "pending";
1307
- QueryStatus2["fulfilled"] = "fulfilled";
1308
- QueryStatus2["rejected"] = "rejected";
1309
- return QueryStatus2;
1526
+ var QueryStatus = /* @__PURE__ */ ((QueryStatus7) => {
1527
+ QueryStatus7["uninitialized"] = "uninitialized";
1528
+ QueryStatus7["pending"] = "pending";
1529
+ QueryStatus7["fulfilled"] = "fulfilled";
1530
+ QueryStatus7["rejected"] = "rejected";
1531
+ return QueryStatus7;
1310
1532
  })(QueryStatus || {});
1533
+ var STATUS_UNINITIALIZED = "uninitialized" /* uninitialized */;
1534
+ var STATUS_PENDING = "pending" /* pending */;
1535
+ var STATUS_FULFILLED = "fulfilled" /* fulfilled */;
1536
+ var STATUS_REJECTED = "rejected" /* rejected */;
1311
1537
  function getRequestStatusFlags(status) {
1312
1538
  return {
1313
1539
  status,
1314
- isUninitialized: status === "uninitialized" /* uninitialized */,
1315
- isLoading: status === "pending" /* pending */,
1316
- isSuccess: status === "fulfilled" /* fulfilled */,
1317
- isError: status === "rejected" /* rejected */
1540
+ isUninitialized: status === STATUS_UNINITIALIZED,
1541
+ isLoading: status === STATUS_PENDING,
1542
+ isSuccess: status === STATUS_FULFILLED,
1543
+ isError: status === STATUS_REJECTED
1318
1544
  };
1319
1545
  }
1320
1546
 
@@ -1335,8 +1561,15 @@ function copyWithStructuralSharing(oldObj, newObj) {
1335
1561
  return isSameObject ? oldObj : mergeObj;
1336
1562
  }
1337
1563
 
1338
- // src/query/utils/flatten.ts
1339
- var flatten = (arr) => [].concat(...arr);
1564
+ // src/query/utils/filterMap.ts
1565
+ function filterMap(array, predicate, mapper) {
1566
+ return array.reduce((acc, item, i) => {
1567
+ if (predicate(item, i)) {
1568
+ acc.push(mapper(item, i));
1569
+ }
1570
+ return acc;
1571
+ }, []).flat();
1572
+ }
1340
1573
 
1341
1574
  // src/query/utils/isAbsoluteUrl.ts
1342
1575
  function isAbsoluteUrl(url) {
@@ -1390,6 +1623,33 @@ function getOrInsertComputed(map, key, compute) {
1390
1623
  }
1391
1624
  var createNewMap = () => /* @__PURE__ */ new Map();
1392
1625
 
1626
+ // src/query/utils/signals.ts
1627
+ var timeoutSignal = (milliseconds) => {
1628
+ const abortController = new AbortController();
1629
+ setTimeout(() => {
1630
+ const message = "signal timed out";
1631
+ const name = "TimeoutError";
1632
+ abortController.abort(
1633
+ // some environments (React Native, Node) don't have DOMException
1634
+ typeof DOMException !== "undefined" ? new DOMException(message, name) : Object.assign(new Error(message), {
1635
+ name
1636
+ })
1637
+ );
1638
+ }, milliseconds);
1639
+ return abortController.signal;
1640
+ };
1641
+ var anySignal = (...signals) => {
1642
+ for (const signal of signals) if (signal.aborted) return AbortSignal.abort(signal.reason);
1643
+ const abortController = new AbortController();
1644
+ for (const signal of signals) {
1645
+ signal.addEventListener("abort", () => abortController.abort(signal.reason), {
1646
+ signal: abortController.signal,
1647
+ once: true
1648
+ });
1649
+ }
1650
+ return abortController.signal;
1651
+ };
1652
+
1393
1653
  // src/query/fetchBaseQuery.ts
1394
1654
  var defaultFetchFn = (...args) => fetch(...args);
1395
1655
  var defaultValidateStatus = (response) => response.status >= 200 && response.status <= 299;
@@ -1446,15 +1706,9 @@ function fetchBaseQuery({
1446
1706
  } = typeof arg == "string" ? {
1447
1707
  url: arg
1448
1708
  } : arg;
1449
- let abortController, signal = api.signal;
1450
- if (timeout) {
1451
- abortController = new AbortController();
1452
- api.signal.addEventListener("abort", abortController.abort);
1453
- signal = abortController.signal;
1454
- }
1455
1709
  let config = {
1456
1710
  ...baseFetchOptions,
1457
- signal,
1711
+ signal: timeout ? anySignal(api.signal, timeoutSignal(timeout)) : api.signal,
1458
1712
  ...rest
1459
1713
  };
1460
1714
  headers = new Headers(stripUndefined(headers));
@@ -1495,23 +1749,17 @@ function fetchBaseQuery({
1495
1749
  meta = {
1496
1750
  request: requestClone
1497
1751
  };
1498
- let response, timedOut = false, timeoutId = abortController && setTimeout(() => {
1499
- timedOut = true;
1500
- abortController.abort();
1501
- }, timeout);
1752
+ let response;
1502
1753
  try {
1503
1754
  response = await fetchFn(request);
1504
1755
  } catch (e) {
1505
1756
  return {
1506
1757
  error: {
1507
- status: timedOut ? "TIMEOUT_ERROR" : "FETCH_ERROR",
1758
+ status: (e instanceof Error || typeof DOMException !== "undefined" && e instanceof DOMException) && e.name === "TimeoutError" ? "TIMEOUT_ERROR" : "FETCH_ERROR",
1508
1759
  error: String(e)
1509
1760
  },
1510
1761
  meta
1511
1762
  };
1512
- } finally {
1513
- if (timeoutId) clearTimeout(timeoutId);
1514
- abortController?.signal.removeEventListener("abort", abortController.abort);
1515
1763
  }
1516
1764
  const responseClone = response.clone();
1517
1765
  meta.response = responseClone;
@@ -1573,30 +1821,35 @@ var HandledError = class {
1573
1821
  };
1574
1822
 
1575
1823
  // src/query/core/setupListeners.ts
1576
- var onFocus = /* @__PURE__ */ toolkit.createAction("__rtkq/focused");
1577
- var onFocusLost = /* @__PURE__ */ toolkit.createAction("__rtkq/unfocused");
1578
- var onOnline = /* @__PURE__ */ toolkit.createAction("__rtkq/online");
1579
- var onOffline = /* @__PURE__ */ toolkit.createAction("__rtkq/offline");
1824
+ var INTERNAL_PREFIX = "__rtkq/";
1825
+ var ONLINE = "online";
1826
+ var OFFLINE = "offline";
1827
+ var FOCUSED = "focused";
1828
+ var onFocus = /* @__PURE__ */ toolkit.createAction(`${INTERNAL_PREFIX}${FOCUSED}`);
1829
+ var onFocusLost = /* @__PURE__ */ toolkit.createAction(`${INTERNAL_PREFIX}un${FOCUSED}`);
1830
+ var onOnline = /* @__PURE__ */ toolkit.createAction(`${INTERNAL_PREFIX}${ONLINE}`);
1831
+ var onOffline = /* @__PURE__ */ toolkit.createAction(`${INTERNAL_PREFIX}${OFFLINE}`);
1580
1832
 
1581
1833
  // src/query/endpointDefinitions.ts
1834
+ var ENDPOINT_QUERY$1 = "query" /* query */;
1835
+ var ENDPOINT_MUTATION$1 = "mutation" /* mutation */;
1836
+ var ENDPOINT_INFINITEQUERY$1 = "infinitequery" /* infinitequery */;
1582
1837
  function isQueryDefinition$1(e) {
1583
- return e.type === "query" /* query */;
1838
+ return e.type === ENDPOINT_QUERY$1;
1584
1839
  }
1585
1840
  function isMutationDefinition$1(e) {
1586
- return e.type === "mutation" /* mutation */;
1841
+ return e.type === ENDPOINT_MUTATION$1;
1587
1842
  }
1588
1843
  function isInfiniteQueryDefinition$1(e) {
1589
- return e.type === "infinitequery" /* infinitequery */;
1844
+ return e.type === ENDPOINT_INFINITEQUERY$1;
1590
1845
  }
1591
1846
  function isAnyQueryDefinition(e) {
1592
1847
  return isQueryDefinition$1(e) || isInfiniteQueryDefinition$1(e);
1593
1848
  }
1594
1849
  function calculateProvidedBy(description, result, error, queryArg, meta, assertTagTypes) {
1595
- if (isFunction(description)) {
1596
- return description(result, error, queryArg, meta).filter(isNotNullish).map(expandTagDescription).map(assertTagTypes);
1597
- }
1598
- if (Array.isArray(description)) {
1599
- return description.map(expandTagDescription).map(assertTagTypes);
1850
+ const finalDescription = isFunction(description) ? description(result, error, queryArg, meta) : description;
1851
+ if (finalDescription) {
1852
+ return filterMap(finalDescription, isNotNullish, (tag) => assertTagTypes(expandTagDescription(tag)));
1600
1853
  }
1601
1854
  return [];
1602
1855
  }
@@ -1614,6 +1867,9 @@ function asSafePromise(promise, fallback) {
1614
1867
  return promise.catch(fallback);
1615
1868
  }
1616
1869
 
1870
+ // src/query/apiTypes.ts
1871
+ var getEndpointDefinition = (context, endpointName) => context.endpointDefinitions[endpointName];
1872
+
1617
1873
  // src/query/core/buildInitiate.ts
1618
1874
  var forceQueryFnSymbol = Symbol("forceQueryFn");
1619
1875
  var isUpsertQuery = (arg) => typeof arg[forceQueryFnSymbol] === "function";
@@ -1644,7 +1900,7 @@ function buildInitiate({
1644
1900
  };
1645
1901
  function getRunningQueryThunk(endpointName, queryArgs) {
1646
1902
  return (dispatch) => {
1647
- const endpointDefinition = context.endpointDefinitions[endpointName];
1903
+ const endpointDefinition = getEndpointDefinition(context, endpointName);
1648
1904
  const queryCacheKey = serializeQueryArgs({
1649
1905
  queryArgs,
1650
1906
  endpointDefinition,
@@ -1691,7 +1947,7 @@ You must add the middleware for RTK-Query to function correctly!`);
1691
1947
  let thunk;
1692
1948
  const commonThunkArgs = {
1693
1949
  ...rest,
1694
- type: "query",
1950
+ type: ENDPOINT_QUERY$1,
1695
1951
  subscribe,
1696
1952
  forceRefetch,
1697
1953
  subscriptionOptions,
@@ -1705,14 +1961,16 @@ You must add the middleware for RTK-Query to function correctly!`);
1705
1961
  } else {
1706
1962
  const {
1707
1963
  direction,
1708
- initialPageParam
1964
+ initialPageParam,
1965
+ refetchCachedPages
1709
1966
  } = rest;
1710
1967
  thunk = infiniteQueryThunk({
1711
1968
  ...commonThunkArgs,
1712
1969
  // Supply these even if undefined. This helps with a field existence
1713
1970
  // check over in `buildSlice.ts`
1714
1971
  direction,
1715
- initialPageParam
1972
+ initialPageParam,
1973
+ refetchCachedPages
1716
1974
  });
1717
1975
  }
1718
1976
  const selector = api.endpoints[endpointName].select(arg);
@@ -1751,9 +2009,10 @@ You must add the middleware for RTK-Query to function correctly!`);
1751
2009
  }
1752
2010
  return result.data;
1753
2011
  },
1754
- refetch: () => dispatch(queryAction(arg, {
2012
+ refetch: (options) => dispatch(queryAction(arg, {
1755
2013
  subscribe: false,
1756
- forceRefetch: true
2014
+ forceRefetch: true,
2015
+ ...options
1757
2016
  })),
1758
2017
  unsubscribe() {
1759
2018
  if (subscribe) dispatch(unsubscribeQueryResult({
@@ -1928,7 +2187,7 @@ function buildThunks({
1928
2187
  inversePatches: [],
1929
2188
  undo: () => dispatch(api.util.patchQueryData(endpointName, arg, ret.inversePatches, updateProvided))
1930
2189
  };
1931
- if (currentState.status === "uninitialized" /* uninitialized */) {
2190
+ if (currentState.status === STATUS_UNINITIALIZED) {
1932
2191
  return ret;
1933
2192
  }
1934
2193
  let newValue;
@@ -1985,6 +2244,7 @@ function buildThunks({
1985
2244
  metaSchema,
1986
2245
  skipSchemaValidation = globalSkipSchemaValidation
1987
2246
  } = endpointDefinition;
2247
+ const isQuery = arg.type === ENDPOINT_QUERY$1;
1988
2248
  try {
1989
2249
  let transformResponse = defaultTransformResponse;
1990
2250
  const baseQueryApi = {
@@ -1995,10 +2255,10 @@ function buildThunks({
1995
2255
  extra,
1996
2256
  endpoint: arg.endpointName,
1997
2257
  type: arg.type,
1998
- forced: arg.type === "query" ? isForcedQuery(arg, getState()) : void 0,
1999
- queryCacheKey: arg.type === "query" ? arg.queryCacheKey : void 0
2258
+ forced: isQuery ? isForcedQuery(arg, getState()) : void 0,
2259
+ queryCacheKey: isQuery ? arg.queryCacheKey : void 0
2000
2260
  };
2001
- const forceQueryFn = arg.type === "query" ? arg[forceQueryFnSymbol] : void 0;
2261
+ const forceQueryFn = isQuery ? arg[forceQueryFnSymbol] : void 0;
2002
2262
  let finalQueryReturnValue;
2003
2263
  const fetchPage = async (data, param, maxPages, previous) => {
2004
2264
  if (param == null && data.pages.length) {
@@ -2087,13 +2347,14 @@ function buildThunks({
2087
2347
  data: transformedResponse
2088
2348
  };
2089
2349
  }
2090
- if (arg.type === "query" && "infiniteQueryOptions" in endpointDefinition) {
2350
+ if (isQuery && "infiniteQueryOptions" in endpointDefinition) {
2091
2351
  const {
2092
2352
  infiniteQueryOptions
2093
2353
  } = endpointDefinition;
2094
2354
  const {
2095
2355
  maxPages = Infinity
2096
2356
  } = infiniteQueryOptions;
2357
+ const refetchCachedPages = arg.refetchCachedPages ?? infiniteQueryOptions.refetchCachedPages ?? true;
2097
2358
  let result;
2098
2359
  const blankData = {
2099
2360
  pages: [],
@@ -2123,9 +2384,11 @@ function buildThunks({
2123
2384
  data: result.data.pages[0]
2124
2385
  };
2125
2386
  }
2126
- for (let i = 1; i < totalPages; i++) {
2127
- const param = getNextPageParam(infiniteQueryOptions, result.data, arg.originalArgs);
2128
- result = await fetchPage(result.data, param, maxPages);
2387
+ if (refetchCachedPages) {
2388
+ for (let i = 1; i < totalPages; i++) {
2389
+ const param = getNextPageParam(infiniteQueryOptions, result.data, arg.originalArgs);
2390
+ result = await fetchPage(result.data, param, maxPages);
2391
+ }
2129
2392
  }
2130
2393
  }
2131
2394
  finalQueryReturnValue = result;
@@ -2175,7 +2438,7 @@ function buildThunks({
2175
2438
  endpoint: arg.endpointName,
2176
2439
  arg: arg.originalArgs,
2177
2440
  type: arg.type,
2178
- queryCacheKey: arg.type === "query" ? arg.queryCacheKey : void 0
2441
+ queryCacheKey: isQuery ? arg.queryCacheKey : void 0
2179
2442
  };
2180
2443
  endpointDefinition.onSchemaFailure?.(caughtError, info);
2181
2444
  onSchemaFailure?.(caughtError, info);
@@ -2334,6 +2597,13 @@ function getPreviousPageParam(options, {
2334
2597
  function calculateProvidedByThunk(action, type, endpointDefinitions, assertTagType) {
2335
2598
  return calculateProvidedBy(endpointDefinitions[action.meta.arg.endpointName][type], toolkit.isFulfilled(action) ? action.payload : void 0, toolkit.isRejectedWithValue(action) ? action.payload : void 0, action.meta.arg.originalArgs, "baseQueryMeta" in action.meta ? action.meta.baseQueryMeta : void 0, assertTagType);
2336
2599
  }
2600
+
2601
+ // src/query/utils/getCurrent.ts
2602
+ function getCurrent(value) {
2603
+ return isDraft(value) ? current(value) : value;
2604
+ }
2605
+
2606
+ // src/query/core/buildSlice.ts
2337
2607
  function updateQuerySubstateIfExists(state, queryCacheKey, update) {
2338
2608
  const substate = state[queryCacheKey];
2339
2609
  if (substate) {
@@ -2367,11 +2637,11 @@ function buildSlice({
2367
2637
  const resetApiState = toolkit.createAction(`${reducerPath}/resetApiState`);
2368
2638
  function writePendingCacheEntry(draft, arg, upserting, meta) {
2369
2639
  draft[arg.queryCacheKey] ??= {
2370
- status: "uninitialized" /* uninitialized */,
2640
+ status: STATUS_UNINITIALIZED,
2371
2641
  endpointName: arg.endpointName
2372
2642
  };
2373
2643
  updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
2374
- substate.status = "pending" /* pending */;
2644
+ substate.status = STATUS_PENDING;
2375
2645
  substate.requestId = upserting && substate.requestId ? (
2376
2646
  // for `upsertQuery` **updates**, keep the current `requestId`
2377
2647
  substate.requestId
@@ -2395,7 +2665,7 @@ function buildSlice({
2395
2665
  const {
2396
2666
  merge
2397
2667
  } = definitions[meta.arg.endpointName];
2398
- substate.status = "fulfilled" /* fulfilled */;
2668
+ substate.status = STATUS_FULFILLED;
2399
2669
  if (merge) {
2400
2670
  if (substate.data !== void 0) {
2401
2671
  const {
@@ -2472,7 +2742,7 @@ function buildSlice({
2472
2742
  } = entry;
2473
2743
  const endpointDefinition = definitions[endpointName];
2474
2744
  const queryDescription = {
2475
- type: "query",
2745
+ type: ENDPOINT_QUERY$1,
2476
2746
  endpointName,
2477
2747
  originalArgs: entry.arg,
2478
2748
  queryCacheKey: serializeQueryArgs({
@@ -2538,7 +2808,7 @@ function buildSlice({
2538
2808
  updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {
2539
2809
  if (condition) ; else {
2540
2810
  if (substate.requestId !== requestId) return;
2541
- substate.status = "rejected" /* rejected */;
2811
+ substate.status = STATUS_REJECTED;
2542
2812
  substate.error = payload ?? error;
2543
2813
  }
2544
2814
  });
@@ -2549,7 +2819,7 @@ function buildSlice({
2549
2819
  for (const [key, entry] of Object.entries(queries)) {
2550
2820
  if (
2551
2821
  // do not rehydrate entries that were currently in flight.
2552
- entry?.status === "fulfilled" /* fulfilled */ || entry?.status === "rejected" /* rejected */
2822
+ entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED
2553
2823
  ) {
2554
2824
  draft[key] = entry;
2555
2825
  }
@@ -2585,7 +2855,7 @@ function buildSlice({
2585
2855
  if (!arg.track) return;
2586
2856
  draft[getMutationCacheKey(meta)] = {
2587
2857
  requestId,
2588
- status: "pending" /* pending */,
2858
+ status: STATUS_PENDING,
2589
2859
  endpointName: arg.endpointName,
2590
2860
  startedTimeStamp
2591
2861
  };
@@ -2596,7 +2866,7 @@ function buildSlice({
2596
2866
  if (!meta.arg.track) return;
2597
2867
  updateMutationSubstateIfExists(draft, meta, (substate) => {
2598
2868
  if (substate.requestId !== meta.requestId) return;
2599
- substate.status = "fulfilled" /* fulfilled */;
2869
+ substate.status = STATUS_FULFILLED;
2600
2870
  substate.data = payload;
2601
2871
  substate.fulfilledTimeStamp = meta.fulfilledTimeStamp;
2602
2872
  });
@@ -2608,7 +2878,7 @@ function buildSlice({
2608
2878
  if (!meta.arg.track) return;
2609
2879
  updateMutationSubstateIfExists(draft, meta, (substate) => {
2610
2880
  if (substate.requestId !== meta.requestId) return;
2611
- substate.status = "rejected" /* rejected */;
2881
+ substate.status = STATUS_REJECTED;
2612
2882
  substate.error = payload ?? error;
2613
2883
  });
2614
2884
  }).addMatcher(hasRehydrationInfo, (draft, action) => {
@@ -2618,7 +2888,7 @@ function buildSlice({
2618
2888
  for (const [key, entry] of Object.entries(mutations)) {
2619
2889
  if (
2620
2890
  // do not rehydrate entries that were currently in flight.
2621
- (entry?.status === "fulfilled" /* fulfilled */ || entry?.status === "rejected" /* rejected */) && // only rehydrate endpoints that were persisted using a `fixedCacheKey`
2891
+ (entry?.status === STATUS_FULFILLED || entry?.status === STATUS_REJECTED) && // only rehydrate endpoints that were persisted using a `fixedCacheKey`
2622
2892
  key !== entry?.requestId
2623
2893
  ) {
2624
2894
  draft[key] = entry;
@@ -2703,19 +2973,19 @@ function buildSlice({
2703
2973
  }
2704
2974
  });
2705
2975
  function removeCacheKeyFromTags(draft, queryCacheKey) {
2706
- const existingTags = draft.keys[queryCacheKey] ?? [];
2976
+ const existingTags = getCurrent(draft.keys[queryCacheKey] ?? []);
2707
2977
  for (const tag of existingTags) {
2708
2978
  const tagType = tag.type;
2709
2979
  const tagId = tag.id ?? "__internal_without_id";
2710
2980
  const tagSubscriptions = draft.tags[tagType]?.[tagId];
2711
2981
  if (tagSubscriptions) {
2712
- draft.tags[tagType][tagId] = tagSubscriptions.filter((qc) => qc !== queryCacheKey);
2982
+ draft.tags[tagType][tagId] = getCurrent(tagSubscriptions).filter((qc) => qc !== queryCacheKey);
2713
2983
  }
2714
2984
  }
2715
2985
  delete draft.keys[queryCacheKey];
2716
2986
  }
2717
- function writeProvidedTagsForQueries(draft, actions2) {
2718
- const providedByEntries = actions2.map((action) => {
2987
+ function writeProvidedTagsForQueries(draft, actions3) {
2988
+ const providedByEntries = actions3.map((action) => {
2719
2989
  const providedTags = calculateProvidedByThunk(action, "providesTags", definitions, assertTagType);
2720
2990
  const {
2721
2991
  queryCacheKey
@@ -2788,7 +3058,7 @@ function buildSlice({
2788
3058
  config: configSlice.reducer
2789
3059
  });
2790
3060
  const reducer = (state, action) => combinedReducer(resetApiState.match(action) ? void 0 : state, action);
2791
- const actions = {
3061
+ const actions2 = {
2792
3062
  ...configSlice.actions,
2793
3063
  ...querySlice.actions,
2794
3064
  ...subscriptionSlice.actions,
@@ -2799,14 +3069,14 @@ function buildSlice({
2799
3069
  };
2800
3070
  return {
2801
3071
  reducer,
2802
- actions
3072
+ actions: actions2
2803
3073
  };
2804
3074
  }
2805
3075
 
2806
3076
  // src/query/core/buildSelectors.ts
2807
3077
  var skipToken = /* @__PURE__ */ Symbol.for("RTKQ/skipToken");
2808
3078
  var initialSubState = {
2809
- status: "uninitialized" /* uninitialized */
3079
+ status: STATUS_UNINITIALIZED
2810
3080
  };
2811
3081
  var defaultQuerySubState = /* @__PURE__ */ toolkit.createNextState(initialSubState, () => {
2812
3082
  });
@@ -2921,7 +3191,8 @@ function buildSelectors({
2921
3191
  function selectInvalidatedBy(state, tags) {
2922
3192
  const apiState = state[reducerPath];
2923
3193
  const toInvalidate = /* @__PURE__ */ new Set();
2924
- for (const tag of tags.filter(isNotNullish).map(expandTagDescription)) {
3194
+ const finalTags = filterMap(tags, isNotNullish, expandTagDescription);
3195
+ for (const tag of finalTags) {
2925
3196
  const provided = apiState.provided.tags[tag.type];
2926
3197
  if (!provided) {
2927
3198
  continue;
@@ -2931,23 +3202,23 @@ function buildSelectors({
2931
3202
  provided[tag.id]
2932
3203
  ) : (
2933
3204
  // no id: invalidate all queries that provide this type
2934
- flatten(Object.values(provided))
3205
+ Object.values(provided).flat()
2935
3206
  )) ?? [];
2936
3207
  for (const invalidate of invalidateSubscriptions) {
2937
3208
  toInvalidate.add(invalidate);
2938
3209
  }
2939
3210
  }
2940
- return flatten(Array.from(toInvalidate.values()).map((queryCacheKey) => {
3211
+ return Array.from(toInvalidate.values()).flatMap((queryCacheKey) => {
2941
3212
  const querySubState = apiState.queries[queryCacheKey];
2942
- return querySubState ? [{
3213
+ return querySubState ? {
2943
3214
  queryCacheKey,
2944
3215
  endpointName: querySubState.endpointName,
2945
3216
  originalArgs: querySubState.originalArgs
2946
- }] : [];
2947
- }));
3217
+ } : [];
3218
+ });
2948
3219
  }
2949
3220
  function selectCachedArgsForQuery(state, queryName) {
2950
- return Object.values(selectQueries(state)).filter((entry) => entry?.endpointName === queryName && entry.status !== "uninitialized" /* uninitialized */).map((entry) => entry.originalArgs);
3221
+ return filterMap(Object.values(selectQueries(state)), (entry) => entry?.endpointName === queryName && entry.status !== STATUS_UNINITIALIZED, (entry) => entry.originalArgs);
2951
3222
  }
2952
3223
  function getHasNextPage(options, data, queryArg) {
2953
3224
  if (!data) return false;
@@ -3048,9 +3319,9 @@ function buildCreateApi(...modules) {
3048
3319
  if (endpoints) {
3049
3320
  for (const [endpointName, partialDefinition] of Object.entries(endpoints)) {
3050
3321
  if (typeof partialDefinition === "function") {
3051
- partialDefinition(context.endpointDefinitions[endpointName]);
3322
+ partialDefinition(getEndpointDefinition(context, endpointName));
3052
3323
  } else {
3053
- Object.assign(context.endpointDefinitions[endpointName] || {}, partialDefinition);
3324
+ Object.assign(getEndpointDefinition(context, endpointName) || {}, partialDefinition);
3054
3325
  }
3055
3326
  }
3056
3327
  }
@@ -3062,15 +3333,15 @@ function buildCreateApi(...modules) {
3062
3333
  const evaluatedEndpoints = inject.endpoints({
3063
3334
  query: (x) => ({
3064
3335
  ...x,
3065
- type: "query" /* query */
3336
+ type: ENDPOINT_QUERY$1
3066
3337
  }),
3067
3338
  mutation: (x) => ({
3068
3339
  ...x,
3069
- type: "mutation" /* mutation */
3340
+ type: ENDPOINT_MUTATION$1
3070
3341
  }),
3071
3342
  infiniteQuery: (x) => ({
3072
3343
  ...x,
3073
- type: "infinitequery" /* infinitequery */
3344
+ type: ENDPOINT_INFINITEQUERY$1
3074
3345
  })
3075
3346
  });
3076
3347
  for (const [endpointName, definition] of Object.entries(evaluatedEndpoints)) {
@@ -3116,6 +3387,8 @@ function buildCreateApi(...modules) {
3116
3387
  function safeAssign$1(target, ...args) {
3117
3388
  return Object.assign(target, ...args);
3118
3389
  }
3390
+
3391
+ // src/query/core/buildMiddleware/batchActions.ts
3119
3392
  var buildBatchedActionsHandler = ({
3120
3393
  api,
3121
3394
  queryThunk,
@@ -3316,7 +3589,7 @@ var buildCacheCollectionHandler = ({
3316
3589
  }
3317
3590
  }
3318
3591
  function handleUnsubscribe(queryCacheKey, endpointName, api2, config) {
3319
- const endpointDefinition = context.endpointDefinitions[endpointName];
3592
+ const endpointDefinition = getEndpointDefinition(context, endpointName);
3320
3593
  const keepUnusedDataFor = endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor;
3321
3594
  if (keepUnusedDataFor === Infinity) {
3322
3595
  return;
@@ -3363,6 +3636,11 @@ var buildCacheLifecycleHandler = ({
3363
3636
  const isMutationThunk = toolkit.isAsyncThunkAction(mutationThunk);
3364
3637
  const isFulfilledThunk = toolkit.isFulfilled(queryThunk, mutationThunk);
3365
3638
  const lifecycleMap = {};
3639
+ const {
3640
+ removeQueryResult,
3641
+ removeMutationResult,
3642
+ cacheEntriesUpserted
3643
+ } = api.internalActions;
3366
3644
  function resolveLifecycleEntry(cacheKey, data, meta) {
3367
3645
  const lifecycle = lifecycleMap[cacheKey];
3368
3646
  if (lifecycle?.valueResolved) {
@@ -3380,6 +3658,17 @@ var buildCacheLifecycleHandler = ({
3380
3658
  lifecycle.cacheEntryRemoved();
3381
3659
  }
3382
3660
  }
3661
+ function getActionMetaFields(action) {
3662
+ const {
3663
+ arg,
3664
+ requestId
3665
+ } = action.meta;
3666
+ const {
3667
+ endpointName,
3668
+ originalArgs
3669
+ } = arg;
3670
+ return [endpointName, originalArgs, requestId];
3671
+ }
3383
3672
  const handler = (action, mwApi, stateBefore) => {
3384
3673
  const cacheKey = getCacheKey(action);
3385
3674
  function checkForNewCacheKey(endpointName, cacheKey2, requestId, originalArgs) {
@@ -3390,8 +3679,9 @@ var buildCacheLifecycleHandler = ({
3390
3679
  }
3391
3680
  }
3392
3681
  if (queryThunk.pending.match(action)) {
3393
- checkForNewCacheKey(action.meta.arg.endpointName, cacheKey, action.meta.requestId, action.meta.arg.originalArgs);
3394
- } else if (api.internalActions.cacheEntriesUpserted.match(action)) {
3682
+ const [endpointName, originalArgs, requestId] = getActionMetaFields(action);
3683
+ checkForNewCacheKey(endpointName, cacheKey, requestId, originalArgs);
3684
+ } else if (cacheEntriesUpserted.match(action)) {
3395
3685
  for (const {
3396
3686
  queryDescription,
3397
3687
  value
@@ -3407,11 +3697,12 @@ var buildCacheLifecycleHandler = ({
3407
3697
  } else if (mutationThunk.pending.match(action)) {
3408
3698
  const state = mwApi.getState()[reducerPath].mutations[cacheKey];
3409
3699
  if (state) {
3410
- handleNewKey(action.meta.arg.endpointName, action.meta.arg.originalArgs, cacheKey, mwApi, action.meta.requestId);
3700
+ const [endpointName, originalArgs, requestId] = getActionMetaFields(action);
3701
+ handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId);
3411
3702
  }
3412
3703
  } else if (isFulfilledThunk(action)) {
3413
3704
  resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta);
3414
- } else if (api.internalActions.removeQueryResult.match(action) || api.internalActions.removeMutationResult.match(action)) {
3705
+ } else if (removeQueryResult.match(action) || removeMutationResult.match(action)) {
3415
3706
  removeLifecycleEntry(cacheKey);
3416
3707
  } else if (api.util.resetApiState.match(action)) {
3417
3708
  for (const cacheKey2 of Object.keys(lifecycleMap)) {
@@ -3424,12 +3715,12 @@ var buildCacheLifecycleHandler = ({
3424
3715
  if (isMutationThunk(action)) {
3425
3716
  return action.meta.arg.fixedCacheKey ?? action.meta.requestId;
3426
3717
  }
3427
- if (api.internalActions.removeQueryResult.match(action)) return action.payload.queryCacheKey;
3428
- if (api.internalActions.removeMutationResult.match(action)) return getMutationCacheKey(action.payload);
3718
+ if (removeQueryResult.match(action)) return action.payload.queryCacheKey;
3719
+ if (removeMutationResult.match(action)) return getMutationCacheKey(action.payload);
3429
3720
  return "";
3430
3721
  }
3431
3722
  function handleNewKey(endpointName, originalArgs, queryCacheKey, mwApi, requestId) {
3432
- const endpointDefinition = context.endpointDefinitions[endpointName];
3723
+ const endpointDefinition = getEndpointDefinition(context, endpointName);
3433
3724
  const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded;
3434
3725
  if (!onCacheEntryAdded) return;
3435
3726
  const lifecycle = {};
@@ -3504,9 +3795,16 @@ var buildInvalidationByTagsHandler = ({
3504
3795
  removeQueryResult
3505
3796
  } = api.internalActions;
3506
3797
  const isThunkActionWithTags = toolkit.isAnyOf(toolkit.isFulfilled(mutationThunk), toolkit.isRejectedWithValue(mutationThunk));
3507
- const isQueryEnd = toolkit.isAnyOf(toolkit.isFulfilled(mutationThunk, queryThunk), toolkit.isRejected(mutationThunk, queryThunk));
3798
+ const isQueryEnd = toolkit.isAnyOf(toolkit.isFulfilled(queryThunk, mutationThunk), toolkit.isRejected(queryThunk, mutationThunk));
3508
3799
  let pendingTagInvalidations = [];
3800
+ let pendingRequestCount = 0;
3509
3801
  const handler = (action, mwApi) => {
3802
+ if (queryThunk.pending.match(action) || mutationThunk.pending.match(action)) {
3803
+ pendingRequestCount++;
3804
+ }
3805
+ if (isQueryEnd(action)) {
3806
+ pendingRequestCount = Math.max(0, pendingRequestCount - 1);
3807
+ }
3510
3808
  if (isThunkActionWithTags(action)) {
3511
3809
  invalidateTags(calculateProvidedByThunk(action, "invalidatesTags", endpointDefinitions, assertTagType), mwApi);
3512
3810
  } else if (isQueryEnd(action)) {
@@ -3515,23 +3813,14 @@ var buildInvalidationByTagsHandler = ({
3515
3813
  invalidateTags(calculateProvidedBy(action.payload, void 0, void 0, void 0, void 0, assertTagType), mwApi);
3516
3814
  }
3517
3815
  };
3518
- function hasPendingRequests(state) {
3519
- const {
3520
- queries,
3521
- mutations
3522
- } = state;
3523
- for (const cacheRecord of [queries, mutations]) {
3524
- for (const key in cacheRecord) {
3525
- if (cacheRecord[key]?.status === "pending" /* pending */) return true;
3526
- }
3527
- }
3528
- return false;
3816
+ function hasPendingRequests() {
3817
+ return pendingRequestCount > 0;
3529
3818
  }
3530
3819
  function invalidateTags(newTags, mwApi) {
3531
3820
  const rootState = mwApi.getState();
3532
3821
  const state = rootState[reducerPath];
3533
3822
  pendingTagInvalidations.push(...newTags);
3534
- if (state.config.invalidationBehavior === "delayed" && hasPendingRequests(state)) {
3823
+ if (state.config.invalidationBehavior === "delayed" && hasPendingRequests()) {
3535
3824
  return;
3536
3825
  }
3537
3826
  const tags = pendingTagInvalidations;
@@ -3550,7 +3839,7 @@ var buildInvalidationByTagsHandler = ({
3550
3839
  mwApi.dispatch(removeQueryResult({
3551
3840
  queryCacheKey
3552
3841
  }));
3553
- } else if (querySubState.status !== "uninitialized" /* uninitialized */) {
3842
+ } else if (querySubState.status !== STATUS_UNINITIALIZED) {
3554
3843
  mwApi.dispatch(refetchQuery(querySubState));
3555
3844
  }
3556
3845
  }
@@ -3613,7 +3902,7 @@ var buildPollingHandler = ({
3613
3902
  const state = api2.getState()[reducerPath];
3614
3903
  const querySubState = state.queries[queryCacheKey];
3615
3904
  const subscriptions = currentSubscriptions.get(queryCacheKey);
3616
- if (!querySubState || querySubState.status === "uninitialized" /* uninitialized */) return;
3905
+ if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) return;
3617
3906
  const {
3618
3907
  lowestPollingInterval,
3619
3908
  skipPollingIfUnfocused
@@ -3644,7 +3933,7 @@ var buildPollingHandler = ({
3644
3933
  const state = api2.getState()[reducerPath];
3645
3934
  const querySubState = state.queries[queryCacheKey];
3646
3935
  const subscriptions = currentSubscriptions.get(queryCacheKey);
3647
- if (!querySubState || querySubState.status === "uninitialized" /* uninitialized */) {
3936
+ if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) {
3648
3937
  return;
3649
3938
  }
3650
3939
  const {
@@ -3716,7 +4005,7 @@ var buildQueryLifecycleHandler = ({
3716
4005
  originalArgs
3717
4006
  }
3718
4007
  } = action.meta;
3719
- const endpointDefinition = context.endpointDefinitions[endpointName];
4008
+ const endpointDefinition = getEndpointDefinition(context, endpointName);
3720
4009
  const onQueryStarted = endpointDefinition?.onQueryStarted;
3721
4010
  if (onQueryStarted) {
3722
4011
  const lifecycle = {};
@@ -3801,7 +4090,7 @@ var buildWindowEventHandler = ({
3801
4090
  api2.dispatch(removeQueryResult({
3802
4091
  queryCacheKey
3803
4092
  }));
3804
- } else if (querySubState.status !== "uninitialized" /* uninitialized */) {
4093
+ } else if (querySubState.status !== STATUS_UNINITIALIZED) {
3805
4094
  api2.dispatch(refetchQuery(querySubState));
3806
4095
  }
3807
4096
  }
@@ -3823,7 +4112,7 @@ function buildMiddleware(input) {
3823
4112
  const {
3824
4113
  apiUid
3825
4114
  } = context;
3826
- const actions = {
4115
+ const actions2 = {
3827
4116
  invalidateTags: toolkit.createAction(`${reducerPath}/invalidateTags`)
3828
4117
  };
3829
4118
  const isThisApiSliceAction = (action) => action.type.startsWith(`${reducerPath}/`);
@@ -3876,7 +4165,7 @@ function buildMiddleware(input) {
3876
4165
  };
3877
4166
  return {
3878
4167
  middleware,
3879
- actions
4168
+ actions: actions2
3880
4169
  };
3881
4170
  function refetchQuery(querySubState) {
3882
4171
  return input.api.endpoints[querySubState.endpointName].initiate(querySubState.originalArgs, {
@@ -4078,7 +4367,7 @@ var coreModule = ({
4078
4367
  // src/query/core/index.ts
4079
4368
  /* @__PURE__ */ buildCreateApi(coreModule());
4080
4369
 
4081
- // src/query/react/index.ts
4370
+ // src/query/react/rtkqImports.ts
4082
4371
 
4083
4372
  // src/query/utils/capitalize.ts
4084
4373
  function capitalize(str) {
@@ -4095,14 +4384,17 @@ function countObjectKeys(obj) {
4095
4384
  }
4096
4385
 
4097
4386
  // src/query/endpointDefinitions.ts
4387
+ var ENDPOINT_QUERY = "query" /* query */;
4388
+ var ENDPOINT_MUTATION = "mutation" /* mutation */;
4389
+ var ENDPOINT_INFINITEQUERY = "infinitequery" /* infinitequery */;
4098
4390
  function isQueryDefinition(e) {
4099
- return e.type === "query" /* query */;
4391
+ return e.type === ENDPOINT_QUERY;
4100
4392
  }
4101
4393
  function isMutationDefinition(e) {
4102
- return e.type === "mutation" /* mutation */;
4394
+ return e.type === ENDPOINT_MUTATION;
4103
4395
  }
4104
4396
  function isInfiniteQueryDefinition(e) {
4105
- return e.type === "infinitequery" /* infinitequery */;
4397
+ return e.type === ENDPOINT_INFINITEQUERY;
4106
4398
  }
4107
4399
 
4108
4400
  // src/query/tsHelpers.ts
@@ -4112,6 +4404,8 @@ function safeAssign(target, ...args) {
4112
4404
 
4113
4405
  // src/query/react/constants.ts
4114
4406
  var UNINITIALIZED_VALUE = Symbol();
4407
+
4408
+ // src/query/react/useSerializedStableValue.ts
4115
4409
  function useStableQueryArgs(queryArgs) {
4116
4410
  const cache = React.useRef(queryArgs);
4117
4411
  const copy = React.useMemo(() => copyWithStructuralSharing(cache.current, queryArgs), [queryArgs]);
@@ -4122,6 +4416,8 @@ function useStableQueryArgs(queryArgs) {
4122
4416
  }, [copy]);
4123
4417
  return copy;
4124
4418
  }
4419
+
4420
+ // src/query/react/useShallowStableValue.ts
4125
4421
  function useShallowStableValue(value) {
4126
4422
  const cache = React.useRef(value);
4127
4423
  React.useEffect(() => {
@@ -4146,6 +4442,8 @@ var noPendingQueryStateSelector = (selected) => {
4146
4442
  isUninitialized: false,
4147
4443
  isFetching: true,
4148
4444
  isLoading: selected.data !== void 0 ? false : true,
4445
+ // This is the one place where we still have to use `QueryStatus` as an enum,
4446
+ // since it's the only reference in the React package and not in the core.
4149
4447
  status: QueryStatus.pending
4150
4448
  };
4151
4449
  }
@@ -4175,6 +4473,8 @@ function buildHooks({
4175
4473
  context
4176
4474
  }) {
4177
4475
  const usePossiblyImmediateEffect = unstable__sideEffectsInRender ? (cb) => cb() : React.useEffect;
4476
+ const unsubscribePromiseRef = (ref) => ref.current?.unsubscribe?.();
4477
+ const endpointDefinitions = context.endpointDefinitions;
4178
4478
  return {
4179
4479
  buildQueryHooks,
4180
4480
  buildInfiniteQueryHooks,
@@ -4186,7 +4486,7 @@ function buildHooks({
4186
4486
  const {
4187
4487
  endpointName
4188
4488
  } = lastResult;
4189
- const endpointDefinition = context.endpointDefinitions[endpointName];
4489
+ const endpointDefinition = endpointDefinitions[endpointName];
4190
4490
  if (queryArgs !== skipToken && serializeQueryArgs({
4191
4491
  queryArgs: lastResult.originalArgs,
4192
4492
  endpointDefinition,
@@ -4217,7 +4517,7 @@ function buildHooks({
4217
4517
  const {
4218
4518
  endpointName
4219
4519
  } = lastResult;
4220
- const endpointDefinition = context.endpointDefinitions[endpointName];
4520
+ const endpointDefinition = endpointDefinitions[endpointName];
4221
4521
  if (queryArgs !== skipToken && serializeQueryArgs({
4222
4522
  queryArgs: lastResult.originalArgs,
4223
4523
  endpointDefinition,
@@ -4284,6 +4584,8 @@ function buildHooks({
4284
4584
  });
4285
4585
  const initialPageParam = rest.initialPageParam;
4286
4586
  const stableInitialPageParam = useShallowStableValue(initialPageParam);
4587
+ const refetchCachedPages = rest.refetchCachedPages;
4588
+ const stableRefetchCachedPages = useShallowStableValue(refetchCachedPages);
4287
4589
  const promiseRef = React.useRef(void 0);
4288
4590
  let {
4289
4591
  queryCacheKey,
@@ -4315,15 +4617,16 @@ function buildHooks({
4315
4617
  const promise = dispatch(initiate(stableArg, {
4316
4618
  subscriptionOptions: stableSubscriptionOptions,
4317
4619
  forceRefetch: refetchOnMountOrArgChange,
4318
- ...isInfiniteQueryDefinition(context.endpointDefinitions[endpointName]) ? {
4319
- initialPageParam: stableInitialPageParam
4620
+ ...isInfiniteQueryDefinition(endpointDefinitions[endpointName]) ? {
4621
+ initialPageParam: stableInitialPageParam,
4622
+ refetchCachedPages: stableRefetchCachedPages
4320
4623
  } : {}
4321
4624
  }));
4322
4625
  promiseRef.current = promise;
4323
4626
  } else if (stableSubscriptionOptions !== lastSubscriptionOptions) {
4324
4627
  lastPromise.updateSubscriptionOptions(stableSubscriptionOptions);
4325
4628
  }
4326
- }, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved, stableInitialPageParam, endpointName]);
4629
+ }, [dispatch, initiate, refetchOnMountOrArgChange, stableArg, stableSubscriptionOptions, subscriptionRemoved, stableInitialPageParam, stableRefetchCachedPages, endpointName]);
4327
4630
  return [promiseRef, dispatch, initiate, stableSubscriptionOptions];
4328
4631
  }
4329
4632
  function buildUseQueryState(endpointName, preSelector) {
@@ -4370,7 +4673,7 @@ function buildHooks({
4370
4673
  function usePromiseRefUnsubscribeOnUnmount(promiseRef) {
4371
4674
  React.useEffect(() => {
4372
4675
  return () => {
4373
- promiseRef.current?.unsubscribe?.();
4676
+ unsubscribePromiseRef(promiseRef);
4374
4677
  promiseRef.current = void 0;
4375
4678
  };
4376
4679
  }, [promiseRef]);
@@ -4421,7 +4724,7 @@ function buildHooks({
4421
4724
  const trigger = React.useCallback(function(arg2, preferCacheValue = false) {
4422
4725
  let promise;
4423
4726
  batch(() => {
4424
- promiseRef.current?.unsubscribe();
4727
+ unsubscribePromiseRef(promiseRef);
4425
4728
  promiseRef.current = promise = dispatch(initiate(arg2, {
4426
4729
  subscriptionOptions: subscriptionOptionsRef.current,
4427
4730
  forceRefetch: !preferCacheValue
@@ -4439,7 +4742,7 @@ function buildHooks({
4439
4742
  }, [dispatch]);
4440
4743
  React.useEffect(() => {
4441
4744
  return () => {
4442
- promiseRef?.current?.unsubscribe();
4745
+ unsubscribePromiseRef(promiseRef);
4443
4746
  };
4444
4747
  }, []);
4445
4748
  React.useEffect(() => {
@@ -4494,10 +4797,12 @@ function buildHooks({
4494
4797
  usePossiblyImmediateEffect(() => {
4495
4798
  subscriptionOptionsRef.current = stableSubscriptionOptions;
4496
4799
  }, [stableSubscriptionOptions]);
4800
+ const hookRefetchCachedPages = options.refetchCachedPages;
4801
+ const stableHookRefetchCachedPages = useShallowStableValue(hookRefetchCachedPages);
4497
4802
  const trigger = React.useCallback(function(arg2, direction) {
4498
4803
  let promise;
4499
4804
  batch(() => {
4500
- promiseRef.current?.unsubscribe();
4805
+ unsubscribePromiseRef(promiseRef);
4501
4806
  promiseRef.current = promise = dispatch(initiate(arg2, {
4502
4807
  subscriptionOptions: subscriptionOptionsRef.current,
4503
4808
  direction
@@ -4507,7 +4812,13 @@ function buildHooks({
4507
4812
  }, [promiseRef, dispatch, initiate]);
4508
4813
  usePromiseRefUnsubscribeOnUnmount(promiseRef);
4509
4814
  const stableArg = useStableQueryArgs(options.skip ? skipToken : arg);
4510
- const refetch = React.useCallback(() => refetchOrErrorIfUnmounted(promiseRef), [promiseRef]);
4815
+ const refetch = React.useCallback((options2) => {
4816
+ if (!promiseRef.current) throw new Error(process.env.NODE_ENV === "production" ? toolkit.formatProdErrorMessage(38) : "Cannot refetch a query that has not been started yet.");
4817
+ const mergedOptions = {
4818
+ refetchCachedPages: options2?.refetchCachedPages ?? stableHookRefetchCachedPages
4819
+ };
4820
+ return promiseRef.current.refetch(mergedOptions);
4821
+ }, [promiseRef, stableHookRefetchCachedPages]);
4511
4822
  return React.useMemo(() => {
4512
4823
  const fetchNextPage = () => {
4513
4824
  return trigger(stableArg, "forward");
@@ -5934,7 +6245,7 @@ const contentApi = createApi({
5934
6245
  const { useGetDataQuery, useLazyGetDataQuery, useGetDataByIdQuery, useLazyGetDataByIdQuery, } = contentApi;
5935
6246
 
5936
6247
  // Dynamic baseQuery that resolves URL at request time and unwraps standard responses
5937
- const dynamicBaseQuery = async (args, api, extraOptions) => {
6248
+ const dynamicBaseQuery$1 = async (args, api, extraOptions) => {
5938
6249
  // Resolve base URL at request time, not module load time
5939
6250
  const baseUrl = typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_API_PAYMENTS_PREFIX
5940
6251
  ? process.env.NEXT_PUBLIC_API_PAYMENTS_PREFIX
@@ -5960,7 +6271,7 @@ const dynamicBaseQuery = async (args, api, extraOptions) => {
5960
6271
  };
5961
6272
  const paymentApi = createApi({
5962
6273
  reducerPath: 'paymentApi',
5963
- baseQuery: dynamicBaseQuery,
6274
+ baseQuery: dynamicBaseQuery$1,
5964
6275
  tagTypes: ['UserSubscription', 'Plans', 'TaxRates', 'PromoCodes'],
5965
6276
  // keepUnusedDataFor: 300,
5966
6277
  endpoints: (builder) => ({
@@ -6002,6 +6313,73 @@ const paymentApi = createApi({
6002
6313
  // Export hooks for usage in functional components.
6003
6314
  const { useCheckUserSubscriptionQuery, useLazyCheckUserSubscriptionQuery, useGetPaymentPlansQuery, useLazyGetPaymentPlansQuery, useGetTaxRatesQuery, useLazyGetTaxRatesQuery, useCheckPromoCodeQuery, useLazyCheckPromoCodeQuery, } = paymentApi;
6004
6315
 
6316
+ // Dynamic baseQuery that resolves URL at request time and unwraps standard responses
6317
+ const dynamicBaseQuery = async (args, api, extraOptions) => {
6318
+ // Resolve base URL at request time, not module load time
6319
+ const baseUrl = typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_API_PAYMENTS_PREFIX
6320
+ ? process.env.NEXT_PUBLIC_API_PAYMENTS_PREFIX
6321
+ : (API_PAYMENTS_PREFIX || '');
6322
+ const baseQuery = createUnwrappingBaseQuery({
6323
+ baseUrl,
6324
+ prepareHeaders: async (headers) => {
6325
+ headers.set('Content-Type', 'application/json');
6326
+ // Try to add accessToken to headers, but don't fail if unavailable
6327
+ try {
6328
+ const session = await awsAmplify.Auth.currentSession();
6329
+ const idToken = session.getIdToken().getJwtToken(); // ID token
6330
+ const accessToken = session.getAccessToken().getJwtToken(); // Access token
6331
+ if (accessToken && idToken) {
6332
+ headers.set('accesstoken', accessToken);
6333
+ headers.set('idtoken', idToken);
6334
+ }
6335
+ }
6336
+ catch (error) {
6337
+ // Authentication not available - this is OK for public endpoints like getProducts
6338
+ console.log('Auth not available for products API request');
6339
+ }
6340
+ return headers;
6341
+ },
6342
+ credentials: 'include',
6343
+ });
6344
+ return baseQuery(args, api, extraOptions);
6345
+ };
6346
+ const productsApi = createApi({
6347
+ reducerPath: 'productsApi',
6348
+ baseQuery: dynamicBaseQuery,
6349
+ tagTypes: ['Products', 'Product'],
6350
+ endpoints: (builder) => ({
6351
+ /**
6352
+ * Get all products
6353
+ * Optional partnerId parameter for filtering
6354
+ */
6355
+ getProducts: builder.query({
6356
+ query: (params) => {
6357
+ const queryString = params?.partnerId ? `?partnerId=${params.partnerId}` : '';
6358
+ return `/payment/products${queryString}`;
6359
+ },
6360
+ providesTags: (result) => result
6361
+ ? [
6362
+ ...result.products.map(({ id }) => ({ type: 'Product', id })),
6363
+ { type: 'Products', id: 'LIST' },
6364
+ ]
6365
+ : [{ type: 'Products', id: 'LIST' }],
6366
+ }),
6367
+ /**
6368
+ * Purchase a product
6369
+ */
6370
+ purchaseProduct: builder.mutation({
6371
+ query: (body) => ({
6372
+ url: '/payment/product-purchase',
6373
+ method: 'POST',
6374
+ body,
6375
+ }),
6376
+ invalidatesTags: [{ type: 'Products', id: 'LIST' }],
6377
+ }),
6378
+ }),
6379
+ });
6380
+ // Export hooks for usage in functional components
6381
+ const { useGetProductsQuery, useLazyGetProductsQuery, usePurchaseProductMutation, } = productsApi;
6382
+
6005
6383
  // Create dynamic baseQuery that resolves URL at request time
6006
6384
  const createOrdersBaseQuery = () => {
6007
6385
  const baseUrl = typeof process !== 'undefined' && process.env?.NEXT_PUBLIC_API_ORDERS_PREFIX
@@ -6267,6 +6645,7 @@ exports.isWeb = isWeb;
6267
6645
  exports.onlyUnique = onlyUnique;
6268
6646
  exports.ordersApi = ordersApi;
6269
6647
  exports.paymentApi = paymentApi;
6648
+ exports.productsApi = productsApi;
6270
6649
  exports.removeFromCart = removeFromCart;
6271
6650
  exports.removePromoCode = removePromoCode;
6272
6651
  exports.resetTaxRate = resetTaxRate;
@@ -6287,11 +6666,14 @@ exports.toCamelCaseObject = toCamelCaseObject;
6287
6666
  exports.toggleCart = toggleCart;
6288
6667
  exports.updateCart = updateCart;
6289
6668
  exports.useForgottenPasswordMutation = useForgottenPasswordMutation;
6669
+ exports.useGetProductsQuery = useGetProductsQuery;
6290
6670
  exports.useGetUserInfoQuery = useGetUserInfoQuery;
6671
+ exports.useLazyGetProductsQuery = useLazyGetProductsQuery;
6291
6672
  exports.useLazyGetUserInfoQuery = useLazyGetUserInfoQuery;
6292
6673
  exports.useLazyVerifyUserAttributesQuery = useLazyVerifyUserAttributesQuery;
6293
6674
  exports.useLazyVerifyUserQuery = useLazyVerifyUserQuery;
6294
6675
  exports.useLazyVerifyUserResendQuery = useLazyVerifyUserResendQuery;
6676
+ exports.usePurchaseProductMutation = usePurchaseProductMutation;
6295
6677
  exports.useRegisterMutation = useRegisterMutation;
6296
6678
  exports.useResetPasswordAuthMutation = useResetPasswordAuthMutation;
6297
6679
  exports.useResetPasswordMutation = useResetPasswordMutation;
@@ -6300,4 +6682,4 @@ exports.useUpdateUserMutation = useUpdateUserMutation;
6300
6682
  exports.useVerifyUserAttributesQuery = useVerifyUserAttributesQuery;
6301
6683
  exports.useVerifyUserQuery = useVerifyUserQuery;
6302
6684
  exports.useVerifyUserResendQuery = useVerifyUserResendQuery;
6303
- //# sourceMappingURL=slice-CNrOPYxy.js.map
6685
+ //# sourceMappingURL=slice-CUaXwIIK.js.map