@hyper-fetch/core 9.5.2 → 9.6.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.
package/dist/index.mjs CHANGED
@@ -4516,6 +4516,270 @@ var createConfiguration = () => {
4516
4516
  return (defaults) => defaults;
4517
4517
  };
4518
4518
  //#endregion
4519
- export { AbortError, Adapter, AppEvents, AppManager, Cache, Client, DeletedError, Dispatcher, DispatcherMode, EventEmitter, HttpAdapter, HttpMethods, LoggerManager, Plugin, Request, RequestManager, RequestProcessingError, SAFE_HTTP_METHODS, Time, TimeoutError, UnexpectedError, appManagerInitialOptions, canRetryRequest, createClient, createConfiguration, createRequestHooks, createSdk, defaultMapper, defaultTimeout, getAbortByAbortKey, getAbortByIdKey, getAbortKey, getAdapter, getAdapterBindings, getAdapterHeaders, getAdapterOnError, getAdapterPayload, getAppManagerEvents, getCacheByKey, getCacheData, getCacheEvents, getCacheKey, getDeleteByKey, getDeleteKey, getDispatcherChangeByKey, getDispatcherChangeKey, getDispatcherDrainedByKey, getDispatcherDrainedKey, getDispatcherEvents, getDispatcherRunningByKey, getDispatcherRunningKey, getDispatcherStatusByKey, getDispatcherStatusKey, getDownloadProgressByIdKey, getDownloadProgressByQueryKey, getDownloadProgressKey, getErrorMessage, getInvalidateByKey, getInvalidateKey, getIsEqualTimestamp, getLoadingByCacheKey, getLoadingByIdKey, getLoadingByQueryKey, getLoadingKey, getProgressData, getProgressValue, getRemoveByIdKey, getRemoveByQueryKey, getRemoveKey, getRequestDeduplicatedByCacheKey, getRequestDeduplicatedByIdKey, getRequestDeduplicatedByQueryKey, getRequestDeduplicatedKey, getRequestDispatcher, getRequestEta, getRequestKey, getRequestManagerEvents, getRequestStarByQueryKey, getRequestStartByIdKey, getRequestStartKey, getRequestType, getResponseByCacheKey, getResponseByIdKey, getResponseHeaders, getResponseKey, getResponseStartByIdKey, getResponseStartByQueryKey, getResponseStartKey, getSimpleKey, getTime, getUniqueRequestId, getUploadProgressByIdKey, getUploadProgressByQueryKey, getUploadProgressKey, handleResponse, hasDocument, hasWindow, interceptRequest, interceptResponse, isNavigatorOnline, isPlainObject, logLevelOrder, logger, loggerColors, loggerStyles, mapResponseForSend, mocker, onDocumentEvent, onWindowEvent, parseErrorResponse, parseResponse, replaceEqualDeep, resolveClientMode, runResponseMapper, scopeKey, sendRequest, stringifyDefaultOptions, stringifyKey, stringifyQueryParams, stringifyValue, xhrExtra };
4519
+ //#region src/infinite/infinite.utils.ts
4520
+ var isEmptyCursor = (value) => value === null || value === void 0 || value === "";
4521
+ var toNumber = (value) => {
4522
+ if (value === null || value === void 0 || value === "") return;
4523
+ const number = Number(value);
4524
+ return Number.isFinite(number) ? number : void 0;
4525
+ };
4526
+ /**
4527
+ * Tells how the list is paged. Throws for a missing or incomplete pagination, because a list without it
4528
+ * would silently fetch the same page forever.
4529
+ */
4530
+ var getPaginationMode = (pagination) => {
4531
+ if (pagination?.cursor) {
4532
+ if (!pagination.next) throw new Error("Cursor pagination requires the \"next\" option");
4533
+ return "cursor";
4534
+ }
4535
+ if (pagination?.offset) return "offset";
4536
+ if (pagination?.page) return "page";
4537
+ throw new Error("Infinite requests require the \"pagination\" option with a \"page\", \"offset\" or \"cursor\" field");
4538
+ };
4539
+ var getPagingField = (pagination) => {
4540
+ return pagination.cursor ?? pagination.offset ?? pagination.page;
4541
+ };
4542
+ var getSourceValues = (request, pagination) => {
4543
+ const values = request[pagination.in ?? "queryParams"];
4544
+ return values && typeof values === "object" ? values : {};
4545
+ };
4546
+ var getPageLimit = (request, pagination) => {
4547
+ if (!pagination.limit) return;
4548
+ const limit = toNumber(getSourceValues(request, pagination)[pagination.limit]);
4549
+ return limit && limit > 0 ? limit : void 0;
4550
+ };
4551
+ /**
4552
+ * The value the list starts from: what the request already holds, otherwise the first page.
4553
+ */
4554
+ var getInitialPageParam = (request, pagination) => {
4555
+ const mode = getPaginationMode(pagination);
4556
+ const value = getSourceValues(request, pagination)[getPagingField(pagination)];
4557
+ if (mode === "cursor") return isEmptyCursor(value) ? void 0 : value;
4558
+ return toNumber(value) ?? (mode === "page" ? 1 : 0);
4559
+ };
4560
+ var getFirstPageNumber = (request, pagination) => {
4561
+ return getInitialPageParam(request, pagination) === 0 ? 0 : 1;
4562
+ };
4563
+ var setPagingValue = (request, pagination, value) => {
4564
+ const values = {
4565
+ ...getSourceValues(request, pagination),
4566
+ [getPagingField(pagination)]: value
4567
+ };
4568
+ switch (pagination.in) {
4569
+ case "params": return request.setParams(values);
4570
+ case "payload": return request.setPayload(values);
4571
+ default: return request.setQueryParams(values);
4572
+ }
4573
+ };
4574
+ var keyDependencies = /* @__PURE__ */ new WeakMap();
4575
+ /**
4576
+ * Generated keys contain the query params, so usually every page has its own. A custom key, or paging inside
4577
+ * the payload, gives all the pages the same key - they would overwrite each other in one cache slot.
4578
+ */
4579
+ var getKeyDependencies = (request, pagination) => {
4580
+ let dependencies = keyDependencies.get(request);
4581
+ if (!dependencies) {
4582
+ const first = setPagingValue(request, pagination, "__hyper_fetch_page_a__");
4583
+ const second = setPagingValue(request, pagination, "__hyper_fetch_page_b__");
4584
+ dependencies = {
4585
+ cacheKey: first.cacheKey !== second.cacheKey,
4586
+ queryKey: first.queryKey !== second.queryKey
4587
+ };
4588
+ keyDependencies.set(request, dependencies);
4589
+ }
4590
+ return dependencies;
4591
+ };
4592
+ /**
4593
+ * Creates the request of a single page. Generated keys are left untouched, so a page shares its cache
4594
+ * with any other request for the same data.
4595
+ */
4596
+ var getPageRequest = (request, pagination, param) => {
4597
+ if (param === void 0) return request;
4598
+ const dependencies = getKeyDependencies(request, pagination);
4599
+ let page = setPagingValue(request, pagination, param);
4600
+ if (!dependencies.cacheKey) page = page.setCacheKey(`${page.cacheKey}_${stringifyKey(param)}`);
4601
+ if (!dependencies.queryKey) page = page.setQueryKey(`${page.queryKey}_${stringifyKey(param)}`);
4602
+ return page;
4603
+ };
4604
+ var getCallbackContext = ({ data, param, pages }) => ({
4605
+ data,
4606
+ param,
4607
+ pages
4608
+ });
4609
+ var readOption = (option, context) => {
4610
+ if (typeof option === "function") return option(getCallbackContext(context));
4611
+ return typeof option === "string" ? context.data?.[option] : void 0;
4612
+ };
4613
+ /**
4614
+ * Items of a single page
4615
+ */
4616
+ var getPageItems = (context) => {
4617
+ const { pagination, data } = context;
4618
+ const items = pagination.items === void 0 ? data : readOption(pagination.items, context);
4619
+ return Array.isArray(items) ? items : [];
4620
+ };
4621
+ /**
4622
+ * Size of the whole list, when the pagination declares it
4623
+ */
4624
+ var getPageTotal = (context) => {
4625
+ return toNumber(readOption(context.pagination.total, context)) ?? null;
4626
+ };
4627
+ /**
4628
+ * Paging value of the page after the given one
4629
+ */
4630
+ var getNextPageParam = (context) => {
4631
+ const { request, pagination, param } = context;
4632
+ const mode = getPaginationMode(pagination);
4633
+ if (mode === "cursor") {
4634
+ const cursor = readOption(pagination.next, context);
4635
+ return isEmptyCursor(cursor) ? void 0 : cursor;
4636
+ }
4637
+ if (mode === "page") return Number(param) + 1;
4638
+ return Number(param) + (getPageLimit(request, pagination) ?? getPageItems(context).length);
4639
+ };
4640
+ /**
4641
+ * Paging value of the page before the given one
4642
+ */
4643
+ var getPreviousPageParam = (context) => {
4644
+ const { request, pagination, param } = context;
4645
+ const mode = getPaginationMode(pagination);
4646
+ if (mode === "cursor") {
4647
+ const cursor = readOption(pagination.previous, context);
4648
+ return isEmptyCursor(cursor) ? void 0 : cursor;
4649
+ }
4650
+ if (mode === "page") {
4651
+ const previous = Number(param) - 1;
4652
+ return previous >= getFirstPageNumber(request, pagination) ? previous : void 0;
4653
+ }
4654
+ if (Number(param) <= 0) return;
4655
+ const size = getPageLimit(request, pagination) ?? getPageItems(context).length;
4656
+ return Math.max(0, Number(param) - size);
4657
+ };
4658
+ /**
4659
+ * Tells whether the list continues after the given page
4660
+ */
4661
+ var getHasNextPage = (context) => {
4662
+ const { request, pagination, param } = context;
4663
+ const mode = getPaginationMode(pagination);
4664
+ if (getNextPageParam(context) === void 0) return false;
4665
+ if (pagination.hasNext) return !!pagination.hasNext(getCallbackContext(context));
4666
+ if (mode === "cursor") return true;
4667
+ const items = getPageItems(context);
4668
+ if (items.length === 0) return false;
4669
+ const limit = getPageLimit(request, pagination);
4670
+ const total = getPageTotal(context);
4671
+ if (total !== null) {
4672
+ if (mode === "offset") return Number(param) + items.length < total;
4673
+ return (Number(param) - getFirstPageNumber(request, pagination) + 1) * (limit ?? items.length) < total;
4674
+ }
4675
+ return limit === void 0 || items.length >= limit;
4676
+ };
4677
+ /**
4678
+ * Tells whether the list continues before the given page
4679
+ */
4680
+ var getHasPreviousPage = (context) => {
4681
+ if (getPreviousPageParam(context) === void 0) return false;
4682
+ return context.pagination.hasPrevious ? !!context.pagination.hasPrevious(getCallbackContext(context)) : true;
4683
+ };
4684
+ /**
4685
+ * Rebuilds a list from already stored pages: from the starting page forwards, then backwards, until a page
4686
+ * is missing. Nothing has to remember which pages were loaded.
4687
+ */
4688
+ var getCachedPages = ({ request, pagination, read, maxPages = Infinity }) => {
4689
+ const pages = [];
4690
+ const visited = /* @__PURE__ */ new Set();
4691
+ const readPage = (param) => {
4692
+ const key = stringifyKey(param);
4693
+ if (visited.has(key) || pages.length >= maxPages) return null;
4694
+ visited.add(key);
4695
+ const pageRequest = getPageRequest(request, pagination, param);
4696
+ const value = read(pageRequest);
4697
+ return value ? {
4698
+ param,
4699
+ request: pageRequest,
4700
+ value
4701
+ } : null;
4702
+ };
4703
+ const getContext = (page) => ({
4704
+ request,
4705
+ pagination,
4706
+ data: page.value.data,
4707
+ param: page.param,
4708
+ pages: pages.map((item) => item.value.data)
4709
+ });
4710
+ const first = readPage(getInitialPageParam(request, pagination));
4711
+ if (!first) return pages;
4712
+ pages.push(first);
4713
+ while (true) {
4714
+ const last = pages.at(-1);
4715
+ const param = getHasNextPage(getContext(last)) ? getNextPageParam(getContext(last)) : void 0;
4716
+ const page = param === void 0 ? null : readPage(param);
4717
+ if (!page) break;
4718
+ pages.push(page);
4719
+ }
4720
+ while (true) {
4721
+ const param = getHasPreviousPage(getContext(pages[0])) ? getPreviousPageParam(getContext(pages[0])) : void 0;
4722
+ const page = param === void 0 ? null : readPage(param);
4723
+ if (!page) break;
4724
+ pages.unshift(page);
4725
+ }
4726
+ return pages;
4727
+ };
4728
+ //#endregion
4729
+ //#region src/infinite/infinite.ts
4730
+ /**
4731
+ * Fetches the first pages of a list one after another, without touching the cache or the queues.
4732
+ * Made for server rendering: pass `dehydrated` to the `Hydrate` component to render them on the client.
4733
+ *
4734
+ * @example
4735
+ * ```ts
4736
+ * const { dehydrated } = await fetchInfinite(getFeed, {
4737
+ * pagination: { cursor: "cursor", next: "nextCursor", items: "data" },
4738
+ * pages: 2,
4739
+ * });
4740
+ * ```
4741
+ */
4742
+ var fetchInfinite = async (request, options) => {
4743
+ const pagination = options.pagination;
4744
+ const pageCount = Math.max(1, options.pages ?? 1);
4745
+ const result = {
4746
+ items: [],
4747
+ pages: [],
4748
+ pageParams: [],
4749
+ total: null,
4750
+ hasNextPage: false,
4751
+ error: null,
4752
+ responses: [],
4753
+ dehydrated: []
4754
+ };
4755
+ let param = getInitialPageParam(request, pagination);
4756
+ for (let index = 0; index < pageCount; index += 1) {
4757
+ const pageRequest = getPageRequest(request, pagination, param);
4758
+ const response = await pageRequest.exec({});
4759
+ result.responses.push(response);
4760
+ if (!response.success) {
4761
+ result.error = response.error;
4762
+ break;
4763
+ }
4764
+ const context = {
4765
+ request,
4766
+ pagination,
4767
+ data: response.data,
4768
+ param,
4769
+ pages: result.pages
4770
+ };
4771
+ result.pages.push(response.data);
4772
+ result.pageParams.push(param);
4773
+ result.items.push(...getPageItems(context));
4774
+ result.total = getPageTotal(context) ?? result.total;
4775
+ result.hasNextPage = getHasNextPage(context);
4776
+ result.dehydrated.push(pageRequest.dehydrate({ response }));
4777
+ if (!result.hasNextPage) break;
4778
+ param = getNextPageParam(context);
4779
+ }
4780
+ return result;
4781
+ };
4782
+ //#endregion
4783
+ export { AbortError, Adapter, AppEvents, AppManager, Cache, Client, DeletedError, Dispatcher, DispatcherMode, EventEmitter, HttpAdapter, HttpMethods, LoggerManager, Plugin, Request, RequestManager, RequestProcessingError, SAFE_HTTP_METHODS, Time, TimeoutError, UnexpectedError, appManagerInitialOptions, canRetryRequest, createClient, createConfiguration, createRequestHooks, createSdk, defaultMapper, defaultTimeout, fetchInfinite, getAbortByAbortKey, getAbortByIdKey, getAbortKey, getAdapter, getAdapterBindings, getAdapterHeaders, getAdapterOnError, getAdapterPayload, getAppManagerEvents, getCacheByKey, getCacheData, getCacheEvents, getCacheKey, getCachedPages, getDeleteByKey, getDeleteKey, getDispatcherChangeByKey, getDispatcherChangeKey, getDispatcherDrainedByKey, getDispatcherDrainedKey, getDispatcherEvents, getDispatcherRunningByKey, getDispatcherRunningKey, getDispatcherStatusByKey, getDispatcherStatusKey, getDownloadProgressByIdKey, getDownloadProgressByQueryKey, getDownloadProgressKey, getErrorMessage, getHasNextPage, getHasPreviousPage, getInitialPageParam, getInvalidateByKey, getInvalidateKey, getIsEqualTimestamp, getLoadingByCacheKey, getLoadingByIdKey, getLoadingByQueryKey, getLoadingKey, getNextPageParam, getPageItems, getPageRequest, getPageTotal, getPaginationMode, getPreviousPageParam, getProgressData, getProgressValue, getRemoveByIdKey, getRemoveByQueryKey, getRemoveKey, getRequestDeduplicatedByCacheKey, getRequestDeduplicatedByIdKey, getRequestDeduplicatedByQueryKey, getRequestDeduplicatedKey, getRequestDispatcher, getRequestEta, getRequestKey, getRequestManagerEvents, getRequestStarByQueryKey, getRequestStartByIdKey, getRequestStartKey, getRequestType, getResponseByCacheKey, getResponseByIdKey, getResponseHeaders, getResponseKey, getResponseStartByIdKey, getResponseStartByQueryKey, getResponseStartKey, getSimpleKey, getTime, getUniqueRequestId, getUploadProgressByIdKey, getUploadProgressByQueryKey, getUploadProgressKey, handleResponse, hasDocument, hasWindow, interceptRequest, interceptResponse, isNavigatorOnline, isPlainObject, logLevelOrder, logger, loggerColors, loggerStyles, mapResponseForSend, mocker, onDocumentEvent, onWindowEvent, parseErrorResponse, parseResponse, replaceEqualDeep, resolveClientMode, runResponseMapper, scopeKey, sendRequest, stringifyDefaultOptions, stringifyKey, stringifyQueryParams, stringifyValue, xhrExtra };
4520
4784
 
4521
4785
  //# sourceMappingURL=index.mjs.map