From 7fcb7b418c2d0e4db741434e78bddd641388c6f4 Mon Sep 17 00:00:00 2001 From: Tanuj Singh <119559937+ts7000@users.noreply.github.com> Date: Tue, 11 Feb 2025 14:05:15 +0530 Subject: [PATCH] Fix: Add error handling and cyclic reference detection in update-3rd-party.ts - Added import for `fetch` from 'node-fetch'. - Implemented error handling for `fetch` requests. - Added cyclic reference detection to prevent infinite loops. - Improved type checking for response body. --- scripts/update-3rd-party.ts | 38 +++++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/scripts/update-3rd-party.ts b/scripts/update-3rd-party.ts index 212d53fe2b0..1f0eb2e559b 100644 --- a/scripts/update-3rd-party.ts +++ b/scripts/update-3rd-party.ts @@ -31,23 +31,33 @@ const cleanSchemaObject = (obj: any) => { * Flatten remotely referenced schemas into a single, combined schema. * Handles merging `properties` and `definitions` from a root `allOf`. */ -const inlineRemoteRefs = async (json: any): Promise => { - for (const entry of json.allOf) { - if (entry.$ref && entry.$ref.startsWith('https://')) { - const res = await fetch(entry.$ref); - - if (res.body && (res.body as any).message) { - throw new Error((res.body as any).message); +const inlineRemoteRefs = async (json: any, seenRefs = new Set()) => { + if (json.allOf) { + for (const entry of json.allOf) { + if (entry.$ref && entry.$ref.startsWith('https://')) { + if (seenRefs.has(entry.$ref)) { + throw new Error(`Cyclic reference detected: ${entry.$ref}`); + } + seenRefs.add(entry.$ref); + + try { + const res = await fetch(entry.$ref); + if (!res.ok) { + throw new Error(`Failed to fetch ${entry.$ref}: ${res.statusText}`); + } + + const refJson = await res.json(); + + json.properties = { ...json.properties, ...refJson.properties }; + json.definitions = { ...json.definitions, ...refJson.definitions }; + } catch (err) { + throw new Error(`Error fetching or parsing ${entry.$ref}: ${err.message}`); + } } - - const refJson = await res.json(); - - json.properties = { ...json.properties, ...refJson.properties }; - json.definitions = { ...json.definitions, ...refJson.definitions }; } - } - delete json.allOf; + delete json.allOf; + } }; /**