Skip to content

Commit

Permalink
feat(markdown): support not throwing when creating custom renderer fr…
Browse files Browse the repository at this point in the history
…om `Renderer.with`
  • Loading branch information
lowlighter committed Sep 1, 2024
1 parent 75667b4 commit 64df153
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
14 changes: 12 additions & 2 deletions markdown/renderer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,19 @@ export class Renderer {
* await renderer.render("# foo")
* ```
*/
static async with({ plugins = [] }: { plugins: Array<Plugin | URL | string> }): Promise<Renderer> {
static async with({ plugins = [], throw: throws = true }: { plugins: Array<Plugin | URL | string>; throw?: boolean }): Promise<Renderer> {
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<Plugin> => 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 })
}
}
Expand Down
5 changes: 5 additions & 0 deletions markdown/renderer_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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("<h1>foo</h1>")
})

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)
})

0 comments on commit 64df153

Please sign in to comment.