From 47acece09b6d6c17cfe2ad04cb98deccbeebe6be Mon Sep 17 00:00:00 2001 From: Russell Dempsey <1173416+SgtPooki@users.noreply.github.com> Date: Fri, 28 Feb 2025 11:53:28 -0600 Subject: [PATCH] test: content-type supports json content-type in gwconformance (#187) * test: content-type supports json content-type in gwconformance * chore: apply self suggestions from code review --- .../src/fixtures/content-type-parser.ts | 27 ++++++++++++++----- .../src/utils/set-content-type.ts | 1 + 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/packages/gateway-conformance/src/fixtures/content-type-parser.ts b/packages/gateway-conformance/src/fixtures/content-type-parser.ts index 1704bd37..82d132cd 100644 --- a/packages/gateway-conformance/src/fixtures/content-type-parser.ts +++ b/packages/gateway-conformance/src/fixtures/content-type-parser.ts @@ -5,16 +5,24 @@ const log = logger('content-type-parser') // default from verified-fetch is application/octect-stream, which forces a download. This is not what we want for MANY file types. const defaultMimeType = 'text/html; charset=utf-8' -function checkForSvg (bytes: Uint8Array): string { +function checkForSvg (bytes: Uint8Array): boolean { log('checking for svg') - return /^(<\?xml[^>]+>)?[^<^\w]+]+>)?[^<^\w]+ { + log('checking for json') + try { + JSON.parse(new TextDecoder().decode(bytes)) + return true + } catch (err) { + log('failed to parse as json', err) + return false + } } export async function contentTypeParser (bytes: Uint8Array, fileName?: string): Promise { - log('contentTypeParser called for fileName: %s', fileName) + log('contentTypeParser called for fileName: %s, byte size=%s', fileName, bytes.length) const detectedType = (await fileTypeFromBuffer(bytes))?.mime if (detectedType != null) { log('detectedType: %s', detectedType) @@ -24,7 +32,12 @@ export async function contentTypeParser (bytes: Uint8Array, fileName?: string): if (fileName == null) { // no other way to determine file-type. - return checkForSvg(bytes) + if (checkForSvg(bytes)) { + return 'image/svg+xml' + } else if (await checkForJson(bytes)) { + return 'application/json' + } + return defaultMimeType } // no need to include file-types listed at https://github.com/SgtPooki/file-type#supported-file-types diff --git a/packages/verified-fetch/src/utils/set-content-type.ts b/packages/verified-fetch/src/utils/set-content-type.ts index d3b9af4d..b9d20708 100644 --- a/packages/verified-fetch/src/utils/set-content-type.ts +++ b/packages/verified-fetch/src/utils/set-content-type.ts @@ -29,6 +29,7 @@ export async function setContentType ({ bytes, path, response, contentTypeParser } else if (parsed != null) { contentType = parsed } + log.trace('contentTypeParser returned %s', contentType) } catch (err) { log.error('error parsing content type', err) }