Skip to content

Commit

Permalink
refactor: reduce duplication, improve readability
Browse files Browse the repository at this point in the history
  • Loading branch information
thebanjomatic committed Apr 13, 2024
1 parent 76b0efb commit 259ba21
Showing 1 changed file with 11 additions and 13 deletions.
24 changes: 11 additions & 13 deletions packages/vite/src/node/plugins/html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1180,31 +1180,29 @@ export function injectNonceAttributeTagHook(
return
}

const { nodeName, attrs, sourceCodeLocation } = node

if (
node.nodeName === 'script' ||
(node.nodeName === 'link' &&
node.attrs.some(
nodeName === 'script' ||
(nodeName === 'link' &&
attrs.some(
(attr) =>
attr.name === 'rel' &&
parseRelAttr(attr.value).some((a) => processRelType.has(a)),
))
) {
const alreadyContainsNonce = node.attrs.some(
({ name }) => name === 'nonce',
)
if (alreadyContainsNonce) {
// If we already have a nonce attribute, we don't need to add another one
if (attrs.some(({ name }) => name === 'nonce')) {
return
}

const startTagEndOffset = sourceCodeLocation!.startTag!.endOffset

// if the closing of the start tag includes a `/`, the offset should be 2 so the nonce
// is appended prior to the `/`
const appendOffset =
html[node.sourceCodeLocation!.startTag!.endOffset - 2] === '/' ? 2 : 1
const appendOffset = html[startTagEndOffset - 2] === '/' ? 2 : 1

s.appendRight(
node.sourceCodeLocation!.startTag!.endOffset - appendOffset,
` nonce="${nonce}"`,
)
s.appendRight(startTagEndOffset - appendOffset, ` nonce="${nonce}"`)
}
})

Expand Down

0 comments on commit 259ba21

Please sign in to comment.