Skip to content

Commit

Permalink
feat: graceful error handling of invalid svgs (#195)
Browse files Browse the repository at this point in the history
  • Loading branch information
andreasgangso authored Jul 15, 2024
1 parent e10740b commit 27004c7
Showing 1 changed file with 27 additions and 21 deletions.
48 changes: 27 additions & 21 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,8 @@ export default defineNuxtModule<ModuleOptions>({
...(isBundling
? []
: [
`import { createRequire } from 'module'`,
`const require = createRequire(import.meta.url)`,
`import { createRequire } from 'module'`,
`const require = createRequire(import.meta.url)`,
]
),
`export const collections = {`,
Expand Down Expand Up @@ -202,27 +202,33 @@ async function resolveCollection(nuxt: Nuxt, collection: string | IconifyJSON |
const files = (await fg('*.svg', { cwd: dir, onlyFiles: true }))
.sort()

const json: IconifyJSON = {
...collection,
icons: Object.fromEntries(await Promise.all(files.map(async (file) => {
const name = basename(file, '.svg')
let svg = await fs.readFile(join(dir, file), 'utf-8')
const cleanupIdx = svg.indexOf('<svg')
if (cleanupIdx > 0)
svg = svg.slice(cleanupIdx)
const data = convertParsedSVG(parseSVGContent(svg)!)!
if (data.top === 0)
delete data.top
if (data.left === 0)
delete data.left
return [name, data]
}))),
}
const parsedIcons = await Promise.all(files.map(async (file) => {
const name = basename(file, '.svg')
let svg = await fs.readFile(join(dir, file), 'utf-8')
const cleanupIdx = svg.indexOf('<svg')
if (cleanupIdx > 0)
svg = svg.slice(cleanupIdx)
const data = convertParsedSVG(parseSVGContent(svg)!)
if (!data) {
logger.error(`Nuxt Icon could not parse the SVG content for icon \`${name}\``)
return [name, {}]
}
if (data.top === 0)
delete data.top
if (data.left === 0)
delete data.left
return [name, data]
}))

const successfulIcons = parsedIcons.filter(([_, data]) => Object.keys(data).length > 0)
// @ts-expect-error remove extra properties
delete json.dir
delete collection.dir

logger.success(`Nuxt Icon loaded local collection \`${json.prefix}\` with ${files.length} icons`)
return json
logger.success(`Nuxt Icon loaded local collection \`${collection.prefix}\` with ${successfulIcons.length} icons`)
return {
...collection,
icons: Object.fromEntries(successfulIcons),
}
}
return collection
}

0 comments on commit 27004c7

Please sign in to comment.