All files / core/src/fetch index.ts

100% Statements 287/287
100% Branches 93/93
100% Functions 14/14
100% Lines 287/287

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 5171x 1x 1x 1x 1x   1x                                 1x 1x 1x 1x 1x 1x                                                                                                                                     20x 20x 14x 14x   20x 20x   20x 20x 22x   22x 2x 2x   21x 22x 3x 3x   21x 21x 17x 14x 14x   14x 6x 6x 6x 6x 6x 6x 6x 1x 1x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 17x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 21x 21x 5x 5x 21x 21x 20x 21x   21x 22x   20x 20x 20x 20x 20x 20x 1x 1x 20x 20x 20x   20x 19x 19x   20x 20x   1x 3x 3x   1x                                                                                                                                     23x 23x 23x 23x 23x 6x 6x   23x 23x   23x 23x 25x   25x 2x 2x   24x 25x 3x 3x   24x 24x 22x 20x   20x 1x 1x 1x 1x   18x 18x 18x 18x 34x 34x 18x 17x 17x 17x 18x 20x 1x 1x 1x 22x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 24x 24x 3x 3x 24x 24x 24x 24x   24x 25x   23x 23x 23x 23x 23x 23x 1x 1x 23x 23x 23x   23x 22x 22x   23x 23x   1x 3x 3x   1x 8x 8x 8x 8x   8x 8x 8x 8x 24x   24x 6x 6x 24x 1x 1x 18x 17x 10x 17x 4x 7x 2x 2x 17x 8x 8x 8x   8x 8x   1x                         48x 48x 48x 48x 48x 48x   48x 17x 4x 4x   4x 4x   4x 2x 2x 4x   17x 48x 30x 30x   30x 30x   30x 23x 23x   30x 30x 48x                               51x 51x 47x 47x   51x 25x 1x 1x 1x   24x 22x 22x 31x 6x 1x 1x 1x   6x 4x 4x 26x 3x 1x 1x 1x   2x 2x 2x 3x 51x                       1x 6x 4x 4x 11x 4x 2x 2x 2x 2x   4x 4x 4x 4x 4x   2x 2x  
import { anchor } from '../anchor.js';
import { captureStack } from '../exception.js';
import { linkable } from '../internal.js';
import { mutable } from '../ref.js';
import { subscribe } from '../subscription.js';
import type { Enum, Linkable, LinkableSchema, ObjLike, StateOptions } from '../types.js';
import { isArray, isDefined, isFunction, isObject, isString, typeOf } from '../utils/index.js';
 
export type GetMethod = 'GET' | 'DELETE' | 'HEAD' | 'OPTIONS';
export type GetMethods = GetMethod | Lowercase<GetMethod> | string;
export type PutMethod = 'POST' | 'PUT' | 'PATCH';
export type PutMethods = PutMethod | Lowercase<PutMethod> | string;
export type ReqMethods = GetMethods | PutMethods;
export type RequestInitOptions = Omit<RequestInit, 'body' | 'method'> & {
  url: string | URL;
};
export type RequestOptions = { [K in keyof RequestInitOptions]: RequestInitOptions[K] } & {};
export type FetchOptions<S extends LinkableSchema = LinkableSchema> = StateOptions<S> & RequestOptions;
 
export type StreamOptions<T, S extends LinkableSchema = LinkableSchema> = FetchOptions<S> & {
  transform?: (current: T, chunk: T) => T;
};
 
export const FetchStatus = {
  Idle: 'idle',
  Pending: 'pending',
  Success: 'success',
  Error: 'error',
} as const;
 
export type FetchStatus = Enum<typeof FetchStatus>;
 
export type ReadableState<T> = {
  data: T;
  status: FetchStatus;
  error?: Error;
};
 
export type FetchState<T, P = undefined> = ReadableState<T> & {
  response?: Response;
  fetch: (options?: Partial<RequestOptions & { body?: P | string }>) => void;
  abort: () => void;
};
 
export interface FetchFn {
  /**
   * Create a reactive fetch state object for GET-like requests.
   *
   * @template T - The type of data being fetched
   * @template S - The linkable schema type
   * @param init - Initial data value
   * @param options - Fetch configuration options including URL and request settings for GET-like methods
   * @returns A reactive state object containing data, status, error and response
   */
  <T, S extends LinkableSchema = LinkableSchema>(
    init: T,
    options: FetchOptions<S> & { method?: GetMethods }
  ): FetchState<T>;
 
  /**
   * Create a reactive fetch state object for POST-like requests with body.
   *
   * @template T - The type of data being fetched
   * @template P - The type of request body
   * @template S - The linkable schema type
   * @param init - Initial data value
   * @param options - Fetch configuration options including URL, request settings and body for POST-like methods
   * @returns A reactive state object containing data, status, error, response and body type
   */
  <T, P, S extends LinkableSchema = LinkableSchema>(
    init: T,
    options: FetchOptions<S> & { method?: PutMethods; body: P }
  ): FetchState<T, P>;
 
  /**
   * Converts a FetchState object to a Promise that resolves when the fetch operation completes.
   *
   * @template T - The type of data in the FetchState object
   * @template S - The type of the FetchState object
   * @param state - The FetchState object to convert to a promise
   * @returns A promise that resolves with the final state or rejects with an error
   */
  promise<T, S extends FetchState<T>>(state: S): Promise<S>;
}
 
/**
 * Create a reactive fetch state object.
 * Reactive fetch state object will sync with fetch response.
 *
 * @template T - The type of data being fetched
 * @template S - The linkable schema type
 * @param {T} init - Initial data value
 * @param {FetchOptions<S>} options - Fetch configuration options including URL and request settings
 * @returns {FetchState<T>} A reactive state object containing data, status, error and response
 */
function fetchStateFn<T, S extends LinkableSchema = LinkableSchema>(init: T, options: FetchOptions<S>): FetchState<T> {
  if (linkable(init)) {
    init = mutable(init, options);
  }
 
  const controller = new AbortController();
  const signal = controller.signal;
 
  let started = false;
  const start = (newOptions?: RequestOptions & { body: string }) => {
    if (started) return;
 
    if (state.status !== FetchStatus.Pending) {
      state.status = FetchStatus.Pending;
    }
 
    const reqOptions = { ...options, ...newOptions, signal };
    if (typeof reqOptions.body === 'object') {
      reqOptions.body = JSON.stringify(reqOptions.body) as never;
    }
 
    fetch(options.url, reqOptions)
      .then(async (response) => {
        if (response.ok) {
          const contentType = response.headers.get('content-type');
          const body = await response.text();
 
          if (typeof contentType === 'string' && contentType.includes('application/json')) {
            try {
              anchor.assign(state, {
                response,
                data: JSON.parse(body),
                status: FetchStatus.Success,
              });
            } catch (error) {
              captureStack.error.external('Unable to parse JSON body', error as Error);
              anchor.assign(state, {
                error,
                response,
                status: FetchStatus.Error,
              } as FetchState<T>);
            }
          } else {
            anchor.assign(state, {
              response,
              data: body as T,
              status: FetchStatus.Success,
            });
          }
        } else {
          captureStack.error.external(
            'Something went wrong when fetching response',
            new Error(response.statusText),
            fetchStateFn
          );
          anchor.assign(state, {
            response,
            status: FetchStatus.Error,
            error: new Error(response.statusText),
          });
        }
      })
      .catch((error) => {
        captureStack.error.external('Something went wrong when fetching response', error as Error);
        anchor.assign(state, { status: FetchStatus.Error, error });
      })
      .finally(() => {
        started = false;
      });
 
    started = true;
  };
 
  const state = mutable(
    {
      data: init,
      status: options.deferred ? FetchStatus.Idle : FetchStatus.Pending,
      fetch: start as FetchState<T>['fetch'],
      abort() {
        controller.abort();
      },
    },
    { ...options, recursive: false }
  ) as FetchState<T>;
 
  if (!options.deferred) {
    start();
  }
 
  return state;
}
 
fetchStateFn.promise = <T extends FetchState<Linkable>>(state: T) => {
  return toPromise(state);
};
 
export const fetchState = fetchStateFn as FetchFn;
 
export interface StreamFn {
  /**
   * Create a reactive stream state object for GET-like requests.
   *
   * @template T - The type of data being streamed
   * @template S - The linkable schema type
   * @param init - Initial data value
   * @param options - Stream configuration options including URL, request settings, and optional transform function for GET-like methods
   * @returns A reactive state object containing data, status, error and response
   */
  <T, S extends LinkableSchema = LinkableSchema>(
    init: T,
    options?: StreamOptions<T, S> & { method?: GetMethods }
  ): FetchState<T>;
 
  /**
   * Create a reactive stream state object for POST-like requests with body.
   *
   * @template T - The type of data being streamed
   * @template P - The type of request body
   * @template S - The linkable schema type
   * @param init - Initial data value
   * @param options - Stream configuration options including URL, request settings, body, and optional transform function for POST-like methods
   * @returns A reactive state object containing data, status, error, response and body type
   */
  <T, P, S extends LinkableSchema = LinkableSchema>(
    init: T,
    options?: StreamOptions<T, S> & { method?: PutMethods; body: P }
  ): FetchState<T, P>;
 
  /**
   * Converts a FetchState object to a Promise that resolves when the fetch operation completes.
   * If the state is still pending, it creates a promise that listens for state changes and resolves
   * or rejects based on the final status. If the state is already completed (success or error),
   * it returns a resolved promise with the current state.
   *
   * @template T - The type of data in the FetchState object
   * @template S - The type of the FetchState object
   * @param {S} state - The FetchState object to convert to a promise
   * @returns {Promise<S>} A promise that resolves with the final state or rejects with an error
   */
  promise<T, S extends FetchState<T>>(state: S): Promise<S>;
 
  /**
   * Creates a readable stream from an initial value, returning both a reactive state object
   * and a ReadableStream. The state object tracks whether the stream is done and contains
   * the current piped value. The ReadableStream emits values as they change in the state.
   *
   * @template T - The type of data being streamed
   * @param {T} init - The initial value for the stream
   * @returns {[ReadableState<T>, ReadableStream<T>]} A tuple containing the reactive state and the ReadableStream
   */
  readable<T>(init: T): [ReadableState<T>, ReadableStream<T>];
}
 
/**
 * Create a reactive stream state object that handles streaming responses.
 * The stream state will update incrementally as data chunks are received.
 *
 * @template T - The type of data being streamed
 * @template S - The linkable schema type
 * @param {T} init - Initial data value
 * @param {StreamOptions<T, S>} options - Stream configuration options including URL, request settings, and optional transform function
 * @returns {FetchState<T>} A reactive state object containing data, status, error and response
 */
function streamStateFn<T, S extends LinkableSchema = LinkableSchema>(
  init: T,
  options: StreamOptions<T, S>
): FetchState<T> {
  if (linkable(init)) {
    init = mutable(init, options);
  }
 
  const controller = new AbortController();
  const signal = controller.signal;
 
  let started = false;
  const start = (newOptions?: RequestOptions & { body: string }) => {
    if (started) return;
 
    if (state.status !== FetchStatus.Pending) {
      state.status = FetchStatus.Pending;
    }
 
    const reqOptions = { ...options, ...newOptions, signal };
    if (typeof reqOptions.body === 'object') {
      reqOptions.body = JSON.stringify(reqOptions.body) as never;
    }
 
    fetch(options.url, reqOptions)
      .then(async (response) => {
        if (response.ok) {
          const readable = response.body?.getReader?.();
 
          if (!isDefined(readable) || !isFunction(readable?.read)) {
            const error = new Error(`Invalid response body. Expected readable stream, got: "${typeOf(readable)}.`);
            anchor.assign(state, { response, status: FetchStatus.Error, error });
            return;
          }
 
          try {
            await readStream<T>(
              readable,
              (chunk) => {
                appendChunk(state, chunk, options.transform);
              },
              (chunk) => {
                appendChunk(state, chunk as T, options.transform);
                anchor.assign(state, { response, status: FetchStatus.Success });
              }
            );
          } catch (error) {
            captureStack.error.external('Something went wrong when streaming response', error as Error);
            anchor.assign(state, { response, error, status: FetchStatus.Error } as FetchState<T>);
          }
        } else {
          captureStack.error.external(
            'Something went wrong when fetching response',
            new Error(response.statusText),
            streamStateFn
          );
          anchor.assign(state, {
            response,
            status: FetchStatus.Error,
            error: new Error(response.statusText),
          });
        }
      })
      .catch((error) => {
        captureStack.error.external('Something went wrong when fetching stream', error as Error);
        anchor.assign(state, { status: FetchStatus.Error, error });
      })
      .finally(() => {
        started = false;
      });
 
    started = true;
  };
 
  const state = mutable(
    {
      data: init,
      status: options.deferred ? FetchStatus.Idle : FetchStatus.Pending,
      fetch: start as FetchState<T>['fetch'],
      abort() {
        controller.abort();
      },
    },
    { ...options, recursive: false }
  ) as FetchState<T>;
 
  if (!options.deferred) {
    start();
  }
 
  return state;
}
 
streamStateFn.promise = <T extends FetchState<Linkable>>(state: T) => {
  return toPromise(state);
};
 
streamStateFn.readable = <T>(init: T) => {
  const state = mutable<ReadableState<T>>({
    data: init,
    status: FetchStatus.Idle,
  });
 
  const encoder = new TextEncoder();
  const stream = new ReadableStream({
    start(controller) {
      subscribe(state, (current) => {
        const { data, status, error } = current;
 
        if (status === FetchStatus.Success) {
          controller.close();
          anchor.destroy(state);
        } else if (status === FetchStatus.Error) {
          controller.error(error ?? new Error('Unknown error'));
          anchor.destroy(state);
        } else {
          if (typeof data === 'string') {
            controller.enqueue(encoder.encode(data));
          } else if (typeof data === 'object') {
            controller.enqueue(encoder.encode(JSON.stringify(data)));
          } else if (typeof data !== 'undefined') {
            controller.enqueue(encoder.encode(String(data)));
          }
        }
      });
    },
  });
 
  return [state, stream];
};
 
export const streamState = streamStateFn as StreamFn;
 
/**
 * Reads data chunks from a ReadableStream and processes them through receiver and finalizer callbacks.
 * This function recursively reads from the stream until it's done, decoding each chunk and attempting
 * to parse it as JSON. If JSON parsing fails, the raw string is passed to the receiver instead.
 *
 * @template T - The type of data being processed
 * @param {ReadableStreamDefaultReader<Uint8Array>} readable - The stream reader to read data from
 * @param {(chunk: T) => void} receiver - Callback function to process each data chunk
 * @param {(chunk?: T) => void} finalizer - Callback function to finalize processing when stream is done
 * @returns {Promise<void>} A promise that resolves when the stream has been fully read
 */
async function readStream<T>(
  readable: ReadableStreamDefaultReader<Uint8Array>,
  receiver: (chunk: T) => void,
  finalizer: (chunk?: T) => void
): Promise<void> {
  const { done, value } = await readable.read();
 
  if (done) {
    if (value) {
      const decoder = new TextDecoder();
      const chunk = decoder.decode(value);
 
      try {
        receiver(JSON.parse(chunk));
        // eslint-disable-next-line @typescript-eslint/no-unused-vars
      } catch (error) {
        receiver(chunk as T);
      }
    }
 
    finalizer(value as T);
  } else {
    const decoder = new TextDecoder();
    const chunk = decoder.decode(value);
 
    try {
      receiver(JSON.parse(chunk));
      // eslint-disable-next-line @typescript-eslint/no-unused-vars
    } catch (error) {
      receiver(chunk as T);
    }
 
    await readStream(readable, receiver, finalizer);
  }
}
 
/**
 * Appends a data chunk to the fetch state, applying transformation logic based on data types.
 * This function handles different data types (string, object, array) appropriately:
 * - Strings are concatenated
 * - Objects are merged using `anchor.assign`
 * - Arrays have their elements pushed
 * If no transform function is provided, the chunk replaces the current data.
 *
 * @template T - The type of data being processed
 * @param {FetchState<T>} state - The fetch state object to update
 * @param {T} chunk - The data chunk to append
 * @param {(current: T, chunk: T) => T} [transform] - Optional transformation function to apply to the data
 * @returns {void}
 */
function appendChunk<T>(state: FetchState<T>, chunk: T, transform?: (current: T, chunk: T) => T): void {
  if (typeof transform !== 'function') {
    transform = () => chunk;
  }
 
  if (isString(chunk)) {
    if (typeof state.data === 'undefined') {
      state.data = transform(state.data, chunk);
      return;
    }
 
    if (isString(state.data)) {
      (state as { data: string }).data += transform(state.data, chunk) as string;
    }
  } else if (isObject(chunk)) {
    if (typeof state.data === 'undefined') {
      state.data = transform(state.data, chunk);
      return;
    }
 
    if (isObject(state.data)) {
      anchor.assign(state.data as ObjLike, transform(state.data, chunk) as ObjLike);
    }
  } else if (isArray(chunk)) {
    if (typeof state.data === 'undefined') {
      state.data = transform(state.data, chunk);
      return;
    }
 
    if (isArray(state.data)) {
      (state.data as unknown[]).push(...(transform(state.data, chunk) as unknown[]));
    }
  }
}
 
/**
 * Converts a FetchState object to a Promise that resolves when the fetch operation completes.
 * If the state is still pending, it creates a promise that listens for state changes and resolves
 * or rejects based on the final status. If the state is already completed (success or error),
 * it returns a resolved promise with the current state.
 *
 * @template T - The type of the FetchState object
 * @param {T} state - The FetchState object to convert to a promise
 * @returns {Promise<T>} A promise that resolves with the final state or rejects with an error
 */
const toPromise = <T, S extends FetchState<T>>(state: S): Promise<S> => {
  if (state.status === FetchStatus.Pending) {
    return new Promise((resolve, reject) => {
      const unsubscribe = subscribe(state, (_s, event) => {
        if (event.type !== 'init' && !event.keys.includes('data')) {
          if (state.status === FetchStatus.Error) {
            reject(state.error);
          } else if (state.status === FetchStatus.Success) {
            resolve(state);
          }
 
          unsubscribe();
        }
      });
    });
  }
 
  return Promise.resolve(state);
};