1import * as Log from '../../log';
2import { FetchLike } from './client.types';
3
4export function wrapFetchWithProgress(fetch: FetchLike): FetchLike {
5  return async (url, init) => {
6    const res = await fetch(url, init);
7    if (res.ok && init?.onProgress) {
8      const totalDownloadSize = res.headers.get('Content-Length');
9      const total = Number(totalDownloadSize);
10
11      if (!totalDownloadSize || isNaN(total) || total < 0) {
12        Log.warn(
13          'Progress callback not supported for network request because "Content-Length" header missing or invalid in response from URL:',
14          url.toString()
15        );
16        return res;
17      }
18
19      let length = 0;
20
21      res.body.on('data', (chunk) => {
22        length += chunk.length;
23        onProgress();
24      });
25
26      res.body.on('end', () => {
27        onProgress();
28      });
29
30      const onProgress = () => {
31        const progress = length / total;
32
33        init.onProgress?.({
34          progress,
35          total,
36          loaded: length,
37        });
38      };
39    }
40    return res;
41  };
42}
43