From 44069dd5fa01ce08a8bbe908c72863768746eefd Mon Sep 17 00:00:00 2001 From: Aponia Date: Sat, 10 Aug 2024 20:04:46 -0700 Subject: [PATCH] feat(twoslash): configure whether to throw, tests --- packages/twoslash/src/includes.ts | 10 ++++++---- packages/twoslash/test/includes.test.ts | 18 +++++++++++++++++- 2 files changed, 23 insertions(+), 5 deletions(-) diff --git a/packages/twoslash/src/includes.ts b/packages/twoslash/src/includes.ts index 0732949b..522f7099 100644 --- a/packages/twoslash/src/includes.ts +++ b/packages/twoslash/src/includes.ts @@ -15,7 +15,7 @@ export function addIncludes(map: Map, name: string, code: string map.set(name, lines.join('\n')) } -export function replaceIncludesInCode(_map: Map, code: string) { +export function replaceIncludesInCode(_map: Map, code: string, shouldThrow = true) { const includes = /\/\/ @include: (.*)$/gm // Basically run a regex over the code replacing any // @include: thing with @@ -36,10 +36,12 @@ export function replaceIncludesInCode(_map: Map, code: string) { if (!replaceWith) { const msg = `Could not find an include with the key: '${key}'.\nThere is: ${Array.from(_map.keys())}.` - throw new Error(msg) + if (shouldThrow) + throw new Error(msg) + } + else { + toReplace.push([match.index, match[0].length, replaceWith]) } - - toReplace.push([match.index, match[0].length, replaceWith]) } let newCode = code.toString() diff --git a/packages/twoslash/test/includes.test.ts b/packages/twoslash/test/includes.test.ts index 74487bb7..8649d292 100644 --- a/packages/twoslash/test/includes.test.ts +++ b/packages/twoslash/test/includes.test.ts @@ -56,6 +56,20 @@ it('replaces the code', () => { `) }) +it('throws an error if key not found', () => { + const map = new Map() + + const sample = `// @include: main` + expect(() => replaceIncludesInCode(map, sample)).toThrow() +}) + +it('does not throw an error if key not found but shouldThrow is false', () => { + const map = new Map() + + const sample = `// @include: main` + expect(() => replaceIncludesInCode(map, sample, false)).not.toThrow() +}) + it('replaces @include directives with previously transformed code blocks', async () => { const main = ` export const hello = { str: "world" }; @@ -104,5 +118,7 @@ hello. transformers: [transformer], }) - expect(styleTag + html).toMatchFileSnapshot('./out/includes/replaced_directives.html') + expect(styleTag + html).toMatchFileSnapshot( + './out/includes/replaced_directives.html', + ) })