@@ -43,38 +43,36 @@ export async function fetchStream(url, requestOptions = {}, options = {}) {
4343 return response
4444 }
4545
46- return new ReadableStream ( {
47- start ( ) {
48- this . startByte = 0
49- this . contentLength = null
50- this . abortController = new AbortController ( )
51- } ,
46+ const abortController = new AbortController ( )
47+ let startByte = 0
48+ let contentLength = null
5249
53- async pull ( streamController ) {
50+ return new ReadableStream ( {
51+ async pull ( controller ) {
5452 for ( let attempt = 0 ; attempt <= maxRetries ; attempt ++ ) {
5553 try {
56- const response = await fetchRange ( this . startByte , this . abortController . signal )
57- if ( this . contentLength === null ) {
58- this . contentLength = getContentLength ( response )
54+ const response = await fetchRange ( startByte , abortController . signal )
55+ if ( contentLength === null ) {
56+ contentLength = getContentLength ( response )
5957 }
6058
6159 const reader = response . body . getReader ( )
6260 while ( true ) {
6361 const { done, value } = await reader . read ( )
6462 if ( done ) {
65- streamController . close ( )
63+ controller . close ( )
6664 return
6765 }
6866
69- this . startByte += value . byteLength
70- streamController . enqueue ( value )
71- options . onProgress ?. ( this . startByte / this . contentLength )
67+ startByte += value . byteLength
68+ controller . enqueue ( value )
69+ options . onProgress ?. ( startByte / contentLength )
7270 }
7371 } catch ( err ) {
7472 console . warn ( `Attempt ${ attempt + 1 } failed:` , err )
7573 if ( attempt === maxRetries ) {
76- this . abortController . abort ( )
77- streamController . error ( new Error ( 'Max retries reached' , { cause : err } ) )
74+ abortController . abort ( )
75+ controller . error ( new Error ( 'Max retries reached' , { cause : err } ) )
7876 return
7977 }
8078 await new Promise ( ( res ) => setTimeout ( res , retryDelay ) )
@@ -84,7 +82,7 @@ export async function fetchStream(url, requestOptions = {}, options = {}) {
8482
8583 cancel ( reason ) {
8684 console . warn ( 'Stream canceled:' , reason )
87- this . abortController . abort ( )
85+ abortController . abort ( )
8886 } ,
8987 } )
9088}
0 commit comments