@hyper-fetch/core 9.5.1 → 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.
@@ -0,0 +1,180 @@
1
+ import type { ResponseType } from "adapter";
2
+ import type { RequestInstance } from "request";
3
+ import type {
4
+ ExtractAdapterType,
5
+ ExtractErrorType,
6
+ ExtractParamsType,
7
+ ExtractPayloadType,
8
+ ExtractQueryParamsType,
9
+ ExtractResponseType,
10
+ HydrateDataType,
11
+ } from "types";
12
+
13
+ /** Part of the request that holds the paging field */
14
+ export type PaginationSource = "queryParams" | "params" | "payload";
15
+
16
+ export type PaginationMode = "page" | "offset" | "cursor";
17
+
18
+ type PaginationFields<R, In extends PaginationSource> = NonNullable<
19
+ In extends "params" ? ExtractParamsType<R> : In extends "payload" ? ExtractPayloadType<R> : ExtractQueryParamsType<R>
20
+ >;
21
+
22
+ type KeyOf<T> = Extract<keyof T, string>;
23
+
24
+ type NumericFieldKey<T> = { [K in KeyOf<T>]-?: number extends NonNullable<T[K]> ? K : never }[KeyOf<T>];
25
+ type ArrayFieldKey<T> = { [K in KeyOf<T>]-?: NonNullable<T[K]> extends readonly unknown[] ? K : never }[KeyOf<T>];
26
+ type NumberFieldKey<T> = { [K in KeyOf<T>]-?: NonNullable<T[K]> extends number ? K : never }[KeyOf<T>];
27
+ type CursorFieldKey<T> = { [K in KeyOf<T>]-?: NonNullable<T[K]> extends string | number ? K : never }[KeyOf<T>];
28
+
29
+ /**
30
+ * Passed to every pagination callback
31
+ */
32
+ export type PaginationContext<R> = {
33
+ /** Response data of the page */
34
+ data: ExtractResponseType<R>;
35
+ /** Value of the paging field used to fetch this page */
36
+ param: unknown;
37
+ /** Response data of the pages loaded so far */
38
+ pages: ExtractResponseType<R>[];
39
+ };
40
+
41
+ type PaginationItems<R> = (context: PaginationContext<R>) => readonly unknown[];
42
+ type PaginationCursor<R> = (context: PaginationContext<R>) => string | number | null | undefined;
43
+
44
+ type PaginationItemsOption<R> =
45
+ ExtractResponseType<R> extends readonly unknown[]
46
+ ? {
47
+ /** Where the items are. Not needed when the response is an array. */
48
+ items?: PaginationItems<R>;
49
+ }
50
+ : {
51
+ /** Array field of the response holding the items, or a function returning them */
52
+ items: ArrayFieldKey<NonNullable<ExtractResponseType<R>>> | PaginationItems<R>;
53
+ };
54
+
55
+ type PaginationShared<R> = PaginationItemsOption<R> & {
56
+ /** Number field of the response with the size of the whole list, or a function returning it */
57
+ total?:
58
+ | NumberFieldKey<NonNullable<ExtractResponseType<R>>>
59
+ | ((context: PaginationContext<R>) => number | null | undefined);
60
+ /** Overrides detecting the end of the list */
61
+ hasNext?: (context: PaginationContext<R>) => boolean;
62
+ /** Overrides detecting the start of the list */
63
+ hasPrevious?: (context: PaginationContext<R>) => boolean;
64
+ };
65
+
66
+ type PaginationModes<R, In extends PaginationSource> =
67
+ | {
68
+ /** Numeric field holding the page number */
69
+ page: NumericFieldKey<PaginationFields<R, In>>;
70
+ /** Numeric field holding the page size */
71
+ limit?: NumericFieldKey<PaginationFields<R, In>>;
72
+ offset?: never;
73
+ cursor?: never;
74
+ next?: never;
75
+ previous?: never;
76
+ }
77
+ | {
78
+ /** Numeric field holding the number of skipped items */
79
+ offset: NumericFieldKey<PaginationFields<R, In>>;
80
+ /** Numeric field holding the page size */
81
+ limit: NumericFieldKey<PaginationFields<R, In>>;
82
+ page?: never;
83
+ cursor?: never;
84
+ next?: never;
85
+ previous?: never;
86
+ }
87
+ | {
88
+ /** Field holding the cursor */
89
+ cursor: KeyOf<PaginationFields<R, In>>;
90
+ /** Response field with the cursor of the next page, or a function returning it */
91
+ next: CursorFieldKey<NonNullable<ExtractResponseType<R>>> | PaginationCursor<R>;
92
+ /** Response field with the cursor of the previous page, or a function returning it */
93
+ previous?: CursorFieldKey<NonNullable<ExtractResponseType<R>>> | PaginationCursor<R>;
94
+ page?: never;
95
+ offset?: never;
96
+ limit?: never;
97
+ };
98
+
99
+ /**
100
+ * Describes which fields of a request page through a list. Every key is checked against the request types.
101
+ *
102
+ * @example
103
+ * ```ts
104
+ * const pagination = { cursor: "cursor", next: "nextCursor", items: "data" } satisfies Pagination<typeof getFeed>;
105
+ * ```
106
+ */
107
+ export type Pagination<R> = PaginationShared<R> &
108
+ (
109
+ | (PaginationModes<R, "queryParams"> & { in?: "queryParams" })
110
+ | (PaginationModes<R, "params"> & { in: "params" })
111
+ | (PaginationModes<R, "payload"> & { in: "payload" })
112
+ );
113
+
114
+ type ArrayItem<T> = NonNullable<T> extends readonly (infer Item)[] ? Item : never;
115
+
116
+ /**
117
+ * Type of a single list item for the given request and pagination
118
+ */
119
+ export type PaginationItem<R, P> = P extends { items: infer Items }
120
+ ? Items extends (...args: any[]) => infer Output
121
+ ? ArrayItem<Output>
122
+ : Items extends keyof NonNullable<ExtractResponseType<R>>
123
+ ? ArrayItem<NonNullable<ExtractResponseType<R>>[Items]>
124
+ : never
125
+ : ArrayItem<ExtractResponseType<R>>;
126
+
127
+ /**
128
+ * Untyped form of the pagination, used where the request type is not known
129
+ */
130
+ export type PaginationConfig = {
131
+ page?: string;
132
+ offset?: string;
133
+ limit?: string;
134
+ cursor?: string;
135
+ next?: string | ((context: any) => unknown);
136
+ previous?: string | ((context: any) => unknown);
137
+ items?: string | ((context: any) => readonly unknown[]);
138
+ total?: string | ((context: any) => number | null | undefined);
139
+ hasNext?: (context: any) => boolean;
140
+ hasPrevious?: (context: any) => boolean;
141
+ in?: PaginationSource;
142
+ };
143
+
144
+ export type PaginationPageContext = {
145
+ request: RequestInstance;
146
+ pagination: PaginationConfig;
147
+ data: any;
148
+ param: unknown;
149
+ pages: any[];
150
+ };
151
+
152
+ export type CachedInfinitePage<T = any> = {
153
+ param: unknown;
154
+ request: RequestInstance;
155
+ value: T;
156
+ };
157
+
158
+ export type FetchInfiniteOptions<P> = {
159
+ pagination: P;
160
+ /** How many pages to fetch, one after another. Defaults to 1. */
161
+ pages?: number;
162
+ };
163
+
164
+ export type FetchInfiniteResult<R extends RequestInstance, P> = {
165
+ /** Items of all the fetched pages */
166
+ items: PaginationItem<R, P>[];
167
+ /** Response data of the fetched pages */
168
+ pages: ExtractResponseType<R>[];
169
+ /** Paging values of the fetched pages */
170
+ pageParams: unknown[];
171
+ /** Size of the whole list, when the pagination declares `total` */
172
+ total: number | null;
173
+ hasNextPage: boolean;
174
+ /** Error of the page that stopped fetching */
175
+ error: ExtractErrorType<R> | null;
176
+ /** Full responses of the fetched pages */
177
+ responses: ResponseType<ExtractResponseType<R>, ExtractErrorType<R>, ExtractAdapterType<R>>[];
178
+ /** Pass it to `client.hydrate()` or the `Hydrate` component */
179
+ dehydrated: HydrateDataType[];
180
+ };
@@ -0,0 +1,306 @@
1
+ import type { RequestInstance } from "request";
2
+ import { stringifyKey } from "request/request.utils";
3
+
4
+ import type { CachedInfinitePage, PaginationConfig, PaginationMode, PaginationPageContext } from "./infinite.types";
5
+
6
+ const isEmptyCursor = (value: unknown) => value === null || value === undefined || value === "";
7
+
8
+ const toNumber = (value: unknown): number | undefined => {
9
+ if (value === null || value === undefined || value === "") {
10
+ return undefined;
11
+ }
12
+ const number = Number(value);
13
+ return Number.isFinite(number) ? number : undefined;
14
+ };
15
+
16
+ /**
17
+ * Tells how the list is paged. Throws for a missing or incomplete pagination, because a list without it
18
+ * would silently fetch the same page forever.
19
+ */
20
+ export const getPaginationMode = (pagination: PaginationConfig): PaginationMode => {
21
+ if (pagination?.cursor) {
22
+ if (!pagination.next) {
23
+ throw new Error('Cursor pagination requires the "next" option');
24
+ }
25
+ return "cursor";
26
+ }
27
+ if (pagination?.offset) {
28
+ return "offset";
29
+ }
30
+ if (pagination?.page) {
31
+ return "page";
32
+ }
33
+ throw new Error('Infinite requests require the "pagination" option with a "page", "offset" or "cursor" field');
34
+ };
35
+
36
+ const getPagingField = (pagination: PaginationConfig) => {
37
+ return (pagination.cursor ?? pagination.offset ?? pagination.page) as string;
38
+ };
39
+
40
+ const getSourceValues = (request: RequestInstance, pagination: PaginationConfig): Record<string, unknown> => {
41
+ const values = request[pagination.in ?? "queryParams"];
42
+ return values && typeof values === "object" ? (values as Record<string, unknown>) : {};
43
+ };
44
+
45
+ const getPageLimit = (request: RequestInstance, pagination: PaginationConfig) => {
46
+ if (!pagination.limit) {
47
+ return;
48
+ }
49
+ const limit = toNumber(getSourceValues(request, pagination)[pagination.limit]);
50
+ return limit && limit > 0 ? limit : undefined;
51
+ };
52
+
53
+ /**
54
+ * The value the list starts from: what the request already holds, otherwise the first page.
55
+ */
56
+ export const getInitialPageParam = (request: RequestInstance, pagination: PaginationConfig): unknown => {
57
+ const mode = getPaginationMode(pagination);
58
+ const value = getSourceValues(request, pagination)[getPagingField(pagination)];
59
+
60
+ if (mode === "cursor") {
61
+ return isEmptyCursor(value) ? undefined : value;
62
+ }
63
+ return toNumber(value) ?? (mode === "page" ? 1 : 0);
64
+ };
65
+
66
+ // Lists numbered from zero say so by starting at zero, any other start means numbering from one
67
+ const getFirstPageNumber = (request: RequestInstance, pagination: PaginationConfig) => {
68
+ return getInitialPageParam(request, pagination) === 0 ? 0 : 1;
69
+ };
70
+
71
+ const setPagingValue = (request: RequestInstance, pagination: PaginationConfig, value: unknown): RequestInstance => {
72
+ const values = { ...getSourceValues(request, pagination), [getPagingField(pagination)]: value };
73
+
74
+ switch (pagination.in) {
75
+ case "params": {
76
+ return request.setParams(values as any) as RequestInstance;
77
+ }
78
+ case "payload": {
79
+ return request.setPayload(values as any) as RequestInstance;
80
+ }
81
+ default: {
82
+ return request.setQueryParams(values as any) as RequestInstance;
83
+ }
84
+ }
85
+ };
86
+
87
+ const keyDependencies = new WeakMap<RequestInstance, { cacheKey: boolean; queryKey: boolean }>();
88
+
89
+ /**
90
+ * Generated keys contain the query params, so usually every page has its own. A custom key, or paging inside
91
+ * the payload, gives all the pages the same key - they would overwrite each other in one cache slot.
92
+ */
93
+ const getKeyDependencies = (request: RequestInstance, pagination: PaginationConfig) => {
94
+ let dependencies = keyDependencies.get(request);
95
+ if (!dependencies) {
96
+ const first = setPagingValue(request, pagination, "__hyper_fetch_page_a__");
97
+ const second = setPagingValue(request, pagination, "__hyper_fetch_page_b__");
98
+ dependencies = {
99
+ cacheKey: first.cacheKey !== second.cacheKey,
100
+ queryKey: first.queryKey !== second.queryKey,
101
+ };
102
+ keyDependencies.set(request, dependencies);
103
+ }
104
+ return dependencies;
105
+ };
106
+
107
+ /**
108
+ * Creates the request of a single page. Generated keys are left untouched, so a page shares its cache
109
+ * with any other request for the same data.
110
+ */
111
+ export const getPageRequest = <R extends RequestInstance>(
112
+ request: R,
113
+ pagination: PaginationConfig,
114
+ param: unknown,
115
+ ): R => {
116
+ if (param === undefined) {
117
+ return request;
118
+ }
119
+
120
+ const dependencies = getKeyDependencies(request, pagination);
121
+ let page = setPagingValue(request, pagination, param);
122
+
123
+ if (!dependencies.cacheKey) {
124
+ page = page.setCacheKey(`${page.cacheKey}_${stringifyKey(param)}`) as RequestInstance;
125
+ }
126
+ if (!dependencies.queryKey) {
127
+ page = page.setQueryKey(`${page.queryKey}_${stringifyKey(param)}`) as RequestInstance;
128
+ }
129
+ return page as R;
130
+ };
131
+
132
+ const getCallbackContext = ({ data, param, pages }: PaginationPageContext) => ({ data, param, pages });
133
+
134
+ const readOption = (option: unknown, context: PaginationPageContext): unknown => {
135
+ if (typeof option === "function") {
136
+ return option(getCallbackContext(context));
137
+ }
138
+ return typeof option === "string" ? context.data?.[option] : undefined;
139
+ };
140
+
141
+ /**
142
+ * Items of a single page
143
+ */
144
+ export const getPageItems = (context: PaginationPageContext): unknown[] => {
145
+ const { pagination, data } = context;
146
+ const items = pagination.items === undefined ? data : readOption(pagination.items, context);
147
+ return Array.isArray(items) ? items : [];
148
+ };
149
+
150
+ /**
151
+ * Size of the whole list, when the pagination declares it
152
+ */
153
+ export const getPageTotal = (context: PaginationPageContext): number | null => {
154
+ return toNumber(readOption(context.pagination.total, context)) ?? null;
155
+ };
156
+
157
+ /**
158
+ * Paging value of the page after the given one
159
+ */
160
+ export const getNextPageParam = (context: PaginationPageContext): unknown => {
161
+ const { request, pagination, param } = context;
162
+ const mode = getPaginationMode(pagination);
163
+
164
+ if (mode === "cursor") {
165
+ const cursor = readOption(pagination.next, context);
166
+ return isEmptyCursor(cursor) ? undefined : cursor;
167
+ }
168
+ if (mode === "page") {
169
+ return Number(param) + 1;
170
+ }
171
+ return Number(param) + (getPageLimit(request, pagination) ?? getPageItems(context).length);
172
+ };
173
+
174
+ /**
175
+ * Paging value of the page before the given one
176
+ */
177
+ export const getPreviousPageParam = (context: PaginationPageContext): unknown => {
178
+ const { request, pagination, param } = context;
179
+ const mode = getPaginationMode(pagination);
180
+
181
+ if (mode === "cursor") {
182
+ const cursor = readOption(pagination.previous, context);
183
+ return isEmptyCursor(cursor) ? undefined : cursor;
184
+ }
185
+ if (mode === "page") {
186
+ const previous = Number(param) - 1;
187
+ return previous >= getFirstPageNumber(request, pagination) ? previous : undefined;
188
+ }
189
+ if (Number(param) <= 0) {
190
+ return undefined;
191
+ }
192
+ const size = getPageLimit(request, pagination) ?? getPageItems(context).length;
193
+ return Math.max(0, Number(param) - size);
194
+ };
195
+
196
+ /**
197
+ * Tells whether the list continues after the given page
198
+ */
199
+ export const getHasNextPage = (context: PaginationPageContext): boolean => {
200
+ const { request, pagination, param } = context;
201
+ const mode = getPaginationMode(pagination);
202
+
203
+ if (getNextPageParam(context) === undefined) {
204
+ return false;
205
+ }
206
+ if (pagination.hasNext) {
207
+ return !!pagination.hasNext(getCallbackContext(context));
208
+ }
209
+ if (mode === "cursor") {
210
+ return true;
211
+ }
212
+
213
+ const items = getPageItems(context);
214
+ if (items.length === 0) {
215
+ return false;
216
+ }
217
+
218
+ const limit = getPageLimit(request, pagination);
219
+ const total = getPageTotal(context);
220
+ if (total !== null) {
221
+ if (mode === "offset") {
222
+ return Number(param) + items.length < total;
223
+ }
224
+ const pageIndex = Number(param) - getFirstPageNumber(request, pagination);
225
+ return (pageIndex + 1) * (limit ?? items.length) < total;
226
+ }
227
+
228
+ return limit === undefined || items.length >= limit;
229
+ };
230
+
231
+ /**
232
+ * Tells whether the list continues before the given page
233
+ */
234
+ export const getHasPreviousPage = (context: PaginationPageContext): boolean => {
235
+ if (getPreviousPageParam(context) === undefined) {
236
+ return false;
237
+ }
238
+ return context.pagination.hasPrevious ? !!context.pagination.hasPrevious(getCallbackContext(context)) : true;
239
+ };
240
+
241
+ /**
242
+ * Rebuilds a list from already stored pages: from the starting page forwards, then backwards, until a page
243
+ * is missing. Nothing has to remember which pages were loaded.
244
+ */
245
+ export const getCachedPages = <T extends { data: unknown }>({
246
+ request,
247
+ pagination,
248
+ read,
249
+ maxPages = Infinity,
250
+ }: {
251
+ request: RequestInstance;
252
+ pagination: PaginationConfig;
253
+ read: (pageRequest: RequestInstance) => T | null | undefined;
254
+ maxPages?: number;
255
+ }): CachedInfinitePage<T>[] => {
256
+ const pages: CachedInfinitePage<T>[] = [];
257
+ // Cursors returned by the server could point back at an earlier page
258
+ const visited = new Set<string>();
259
+
260
+ const readPage = (param: unknown) => {
261
+ const key = stringifyKey(param);
262
+ if (visited.has(key) || pages.length >= maxPages) {
263
+ return null;
264
+ }
265
+ visited.add(key);
266
+
267
+ const pageRequest = getPageRequest(request, pagination, param);
268
+ const value = read(pageRequest);
269
+ return value ? { param, request: pageRequest, value } : null;
270
+ };
271
+
272
+ const getContext = (page: CachedInfinitePage<T>): PaginationPageContext => ({
273
+ request,
274
+ pagination,
275
+ data: page.value.data,
276
+ param: page.param,
277
+ pages: pages.map((item) => item.value.data),
278
+ });
279
+
280
+ const first = readPage(getInitialPageParam(request, pagination));
281
+ if (!first) {
282
+ return pages;
283
+ }
284
+ pages.push(first);
285
+
286
+ while (true) {
287
+ const last = pages.at(-1) as CachedInfinitePage<T>;
288
+ const param = getHasNextPage(getContext(last)) ? getNextPageParam(getContext(last)) : undefined;
289
+ const page = param === undefined ? null : readPage(param);
290
+ if (!page) {
291
+ break;
292
+ }
293
+ pages.push(page);
294
+ }
295
+
296
+ while (true) {
297
+ const param = getHasPreviousPage(getContext(pages[0])) ? getPreviousPageParam(getContext(pages[0])) : undefined;
298
+ const page = param === undefined ? null : readPage(param);
299
+ if (!page) {
300
+ break;
301
+ }
302
+ pages.unshift(page);
303
+ }
304
+
305
+ return pages;
306
+ };
@@ -138,11 +138,43 @@ export const getRequestDispatcher = <Request extends RequestInstance>(
138
138
  return [dispatcher, isFetchDispatcher];
139
139
  };
140
140
 
141
+ /**
142
+ * Runs the response mapper of the request. Mapper is user code running in the middle of the response handling,
143
+ * so its failure is logged and ends up as a failed response carrying the thrown value as the `error`.
144
+ * Failures are always delivered through a promise, so sync and async mappers fail the same way.
145
+ * @internal
146
+ * @param request request with the optional response mapper
147
+ * @param response response to be mapped
148
+ * @returns mapped response, promise of it for async and failed mappers, `undefined` when there is no mapper
149
+ */
150
+ export const runResponseMapper = <Request extends RequestInstance>(
151
+ request: Request,
152
+ response: ResponseType<any, any, AdapterInstance>,
153
+ ): MappedResponse => {
154
+ const getFailedResponse = (error: unknown) => {
155
+ request.client.logger.error({
156
+ title: "Response mapper failed",
157
+ type: "system",
158
+ extra: { error, request, response },
159
+ });
160
+
161
+ return { ...response, data: null, error, success: false } as ResponseType<any, any, AdapterInstance>;
162
+ };
163
+
164
+ try {
165
+ const mapping = request.unstable_responseMapper?.(response as ResponseType<any, any, ExtractAdapterType<Request>>);
166
+
167
+ return mapping instanceof Promise ? mapping.catch(getFailedResponse) : mapping;
168
+ } catch (error) {
169
+ return Promise.resolve(getFailedResponse(error));
170
+ }
171
+ };
172
+
141
173
  export const mapResponseForSend = async <Request extends RequestInstance>(
142
174
  request: Request,
143
175
  response: ResponseType<any, any, AdapterInstance>,
144
176
  ): Promise<RequestResponseType<Request>> => {
145
- const mapping = request.unstable_responseMapper?.(response as ResponseType<any, any, ExtractAdapterType<Request>>);
177
+ const mapping = runResponseMapper(request, response);
146
178
 
147
179
  if (mapping instanceof Promise) {
148
180
  return (await mapping) as RequestResponseType<Request>;
@@ -240,10 +272,7 @@ export const sendRequest = async <Request extends RequestInstance>(
240
272
  const mappings = new WeakMap<RequestResponseEventType<Request>, MappedResponse>();
241
273
  const getMapping = (values: RequestResponseEventType<Request>) => {
242
274
  if (!mappings.has(values)) {
243
- mappings.set(
244
- values,
245
- request.unstable_responseMapper?.(values.response as ResponseType<any, any, ExtractAdapterType<Request>>),
246
- );
275
+ mappings.set(values, runResponseMapper(request, values.response));
247
276
  }
248
277
  return mappings.get(values);
249
278
  };
package/release.config.js DELETED
@@ -1,6 +0,0 @@
1
- // eslint-disable-next-line @typescript-eslint/no-var-requires
2
- const config = require("../../release.config");
3
-
4
- const newConfig = { ...config, publish: undefined, success: undefined, fail: undefined };
5
-
6
- module.exports = newConfig;