From 64df1535afb52de3ae8d30d6612c39c95fd8917b Mon Sep 17 00:00:00 2001 From: Simon Lecoq <22963968+lowlighter@users.noreply.github.com> Date: Sun, 1 Sep 2024 14:50:01 -0400 Subject: [PATCH] feat(markdown): support not throwing when creating custom renderer from `Renderer.with` --- markdown/renderer.ts | 14 ++++++++++++-- markdown/renderer_test.ts | 5 +++++ 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/markdown/renderer.ts b/markdown/renderer.ts index a6ad80da..13aa740a 100644 --- a/markdown/renderer.ts +++ b/markdown/renderer.ts @@ -107,9 +107,19 @@ export class Renderer { * await renderer.render("# foo") * ``` */ - static async with({ plugins = [] }: { plugins: Array }): Promise { + static async with({ plugins = [], throw: throws = true }: { plugins: Array; throw?: boolean }): Promise { plugins = plugins.map((plugin) => plugin instanceof URL ? plugin.href : plugin) - const resolved = await Promise.all(plugins.map((plugin) => (typeof plugin === "string") ? import(plugin) : plugin)) + const imported = await Promise.allSettled(plugins.map((plugin) => (typeof plugin === "string") ? import(plugin) : plugin)) + const resolved = imported + .filter((result): result is PromiseFulfilledResult => result.status === "fulfilled") + .map(({ value }) => value) + if (throws && (imported.some(({ status }) => status === "rejected"))) { + const errors = imported + .filter((result): result is PromiseRejectedResult => result.status === "rejected") + .map(({ reason }) => reason) + .join(", ") + throw new ReferenceError(`Failed to import some plugins: ${errors}`) + } return new Renderer({ plugins: resolved }) } } diff --git a/markdown/renderer_test.ts b/markdown/renderer_test.ts index 77121328..ba6bd74f 100644 --- a/markdown/renderer_test.ts +++ b/markdown/renderer_test.ts @@ -12,3 +12,8 @@ test("deno")("Renderer.with() instantiates a new customized renderer", async () const markdown = await Renderer.with({ plugins: ["./plugins/gfm.ts", new URL("./plugins/gfm.ts", import.meta.url), pluginGfm] }) await expect(markdown.render("# foo")).resolves.toBe("

foo

") }) + +test("deno")("Renderer.with() honors throw option when creating a new customized renderer", async () => { + await expect(Renderer.with({ plugins: ["unknown"], throw: false })).resolves.toBeInstanceOf(Renderer) + await expect(Renderer.with({ plugins: ["unknown"], throw: true })).rejects.toThrow(ReferenceError) +})