From 53ec046d56f496f41eed5f37f8b1faffaea2b428 Mon Sep 17 00:00:00 2001 From: Borewit Date: Fri, 2 Aug 2024 10:51:09 +0200 Subject: [PATCH] Run detection prior to TransformStream initialization (`start(controller)`). --- core.js | 53 ++++++++++++++++++++++++----------------------------- 1 file changed, 24 insertions(+), 29 deletions(-) diff --git a/core.js b/core.js index 2cc5af04..50809027 100644 --- a/core.js +++ b/core.js @@ -111,42 +111,37 @@ export class FileTypeParser { async toDetectionStream(stream, options) { const {sampleSize = reasonableDetectionSizeInBytes} = options; let detectedFileType; - let firstChunk = null; + let firstChunk; - // Create a new ReadableStream to manage locking issues - const transformStream = new TransformStream({ - async start(controller) { - const reader = stream.getReader({mode: 'byob'}); + const reader = stream.getReader({mode: 'byob'}); + try { + // Read the first chunk from the stream + const {value: chunk, done} = await reader.read(new Uint8Array(sampleSize)); + firstChunk = chunk; + if (!done && chunk) { try { - // Read the first chunk from the stream - const {value: chunk, done} = await reader.read(new Uint8Array(sampleSize)); - firstChunk = chunk; - if (!done && chunk) { - try { - // Attempt to detect the file type from the chunk - detectedFileType = await this.fromBuffer(chunk.slice(0, sampleSize)); - } catch (error) { - if (!(error instanceof strtok3.EndOfStreamError)) { - throw error; // Re-throw non-EndOfStreamError - } - - detectedFileType = undefined; - } + // Attempt to detect the file type from the chunk + detectedFileType = await this.fromBuffer(chunk.slice(0, sampleSize)); + } catch (error) { + if (!(error instanceof strtok3.EndOfStreamError)) { + throw error; // Re-throw non-EndOfStreamError } - firstChunk = chunk; - } catch (error) { - controller.error(error); // Handle errors during start - } finally { - reader.releaseLock(); // Ensure the reader is released + detectedFileType = undefined; } + } + + firstChunk = chunk; + } finally { + reader.releaseLock(); // Ensure the reader is released + } + + // Create a new ReadableStream to manage locking issues + const transformStream = new TransformStream({ + async start(controller) { + controller.enqueue(firstChunk); // Enqueue the initial chunk }, transform(chunk, controller) { - if (firstChunk) { - firstChunk = null; - controller.enqueue(firstChunk); // Enqueue the initial chunk - } - // Pass through the chunks without modification controller.enqueue(chunk); },