All files / compiler-sfc/src/template transformAssetUrl.ts

98.46% Statements 64/65
93.93% Branches 62/66
100% Functions 11/11
98.43% Lines 63/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278                                                                              18x             18x                 18x     18x   1x         17x           18x     13x 42x       6x                               18x         246x 134x 45x     89x 134x 134x 134x 42x     47x 134x 49x         5x     44x 44x 44x           13x     31x 31x       5x 5x 5x 5x       5x     5x           26x 26x                                                     25x 25x 17x   25x 7x           18x 18x                 18x         18x                         26x 1x       25x 2x 2x       23x 21x 21x       2x     2x 2x               2x         2x 1x                 2x 1x                 1x    
import path from 'path'
import {
  ConstantTypes,
  type ExpressionNode,
  type NodeTransform,
  NodeTypes,
  type SimpleExpressionNode,
  type SourceLocation,
  type TransformContext,
  createSimpleExpression,
} from '@vue/compiler-core'
import {
  isDataUrl,
  isExternalUrl,
  isRelativeUrl,
  normalizeDecodedImportPath,
  parseUrl,
} from './templateUtils'
import { isArray } from '@vue/shared'
 
export interface AssetURLTagConfig {
  [name: string]: string[]
}
 
export interface AssetURLOptions {
  /**
   * If base is provided, instead of transforming relative asset urls into
   * imports, they will be directly rewritten to absolute urls.
   */
  base?: string | null
  /**
   * If true, also processes absolute urls.
   */
  includeAbsolute?: boolean
  tags?: AssetURLTagConfig
}
 
// Built-in attrs that always represent resource URLs. `use` is intentionally
// omitted because its hash-only values may still be fragment references.
const resourceUrlTagConfig: AssetURLTagConfig = {
  video: ['src', 'poster'],
  source: ['src'],
  img: ['src'],
  image: ['xlink:href', 'href'],
}
 
export const defaultAssetUrlOptions: Required<AssetURLOptions> = {
  base: null,
  includeAbsolute: false,
  tags: {
    ...resourceUrlTagConfig,
    use: ['xlink:href', 'href'],
  },
}
 
export const normalizeOptions = (
  options: AssetURLOptions | AssetURLTagConfig,
): Required<AssetURLOptions> => {
  if (Object.keys(options).some(key => isArray((options as any)[key]))) {
    // legacy option format which directly passes in tags config
    return {
      ...defaultAssetUrlOptions,
      tags: options as any,
    }
  }
  return {
    ...defaultAssetUrlOptions,
    ...options,
  }
}
 
export const createAssetUrlTransformWithOptions = (
  options: Required<AssetURLOptions>,
): NodeTransform => {
  return (node, context) =>
    (transformAssetUrl as Function)(node, context, options)
}
 
function canTransformHashImport(tag: string, attrName: string): boolean {
  return !!resourceUrlTagConfig[tag]?.includes(attrName)
}
 
/**
 * A `@vue/compiler-core` plugin that transforms relative asset urls into
 * either imports or absolute urls.
 *
 * ``` js
 * // Before
 * createVNode('img', { src: './logo.png' })
 *
 * // After
 * import _imports_0 from './logo.png'
 * createVNode('img', { src: _imports_0 })
 * ```
 */
export const transformAssetUrl: NodeTransform = (
  node,
  context,
  options: AssetURLOptions = defaultAssetUrlOptions,
) => {
  if (node.type === NodeTypes.ELEMENT) {
    if (!node.props.length) {
      return
    }
 
    const tags = options.tags || defaultAssetUrlOptions.tags
    const attrs = tags[node.tag]
    const wildCardAttrs = tags['*']
    if (!attrs && !wildCardAttrs) {
      return
    }
 
    const assetAttrs = (attrs || []).concat(wildCardAttrs || [])
    node.props.forEach((attr, index) => {
      if (
        attr.type !== NodeTypes.ATTRIBUTE ||
        !assetAttrs.includes(attr.name) ||
        !attr.value
      ) {
        return
      }
 
      const urlValue = attr.value.content
      const isHashOnlyValue = urlValue[0] === '#'
      if (
        isExternalUrl(urlValue) ||
        isDataUrl(urlValue) ||
        (isHashOnlyValue && !canTransformHashImport(node.tag, attr.name)) ||
        (!options.includeAbsolute && !isRelativeUrl(urlValue))
      ) {
        return
      }
 
      const url = parseUrl(urlValue)
      if (options.base && urlValue[0] === '.') {
        // explicit base - directly rewrite relative urls into absolute url
        // to avoid generating extra imports
        // Allow for full hostnames provided in options.base
        const base = parseUrl(options.base)
        const protocol = base.protocol || ''
        const host = base.host ? protocol + '//' + base.host : ''
        const basePath = base.path || '/'
 
        // when packaged in the browser, path will be using the posix-
        // only version provided by rollup-plugin-node-builtins.
        attr.value.content =
          host +
          (path.posix || path).join(basePath, url.path + (url.hash || ''))
        return
      }
 
      // otherwise, transform the url into an import.
      // this assumes a bundler will resolve the import into the correct
      // absolute url (e.g. webpack file-loader)
      const exp = getImportsExpressionExp(url.path, url.hash, attr.loc, context)
      node.props[index] = {
        type: NodeTypes.DIRECTIVE,
        name: 'bind',
        arg: createSimpleExpression(attr.name, true, attr.loc),
        exp,
        modifiers: [],
        loc: attr.loc,
      }
    })
  }
}
 
/**
 * Resolves or registers an import for the given source path
 * @param source - Path to resolve import for
 * @param loc - Source location
 * @param context - Transform context
 * @returns Object containing import name and expression
 */
function resolveOrRegisterImport(
  source: string,
  loc: SourceLocation,
  context: TransformContext,
): {
  name: string
  exp: SimpleExpressionNode
} {
  const normalizedSource = normalizeDecodedImportPath(source)
  const existingIndex = context.imports.findIndex(
    i => i.path === normalizedSource,
  )
  if (existingIndex > -1) {
    return {
      name: `_imports_${existingIndex}`,
      exp: context.imports[existingIndex].exp as SimpleExpressionNode,
    }
  }
 
  const name = `_imports_${context.imports.length}`
  const exp = createSimpleExpression(
    name,
    false,
    loc,
    ConstantTypes.CAN_STRINGIFY,
  )
 
  // We need to ensure the path is not encoded (to %2F),
  // so we decode it back in case it is encoded
  context.imports.push({
    exp,
    path: normalizedSource,
  })
 
  return { name, exp }
}
 
/**
 * Transforms asset URLs into import expressions or string literals
 */
function getImportsExpressionExp(
  path: string | null,
  hash: string | null,
  loc: SourceLocation,
  context: TransformContext,
): ExpressionNode {
  // Neither path nor hash - return empty string
  if (!path && !hash) {
    return createSimpleExpression(`''`, false, loc, ConstantTypes.CAN_STRINGIFY)
  }
 
  // Only hash without path - treat hash as the import source (likely a subpath import)
  if (!path && hash) {
    const { exp } = resolveOrRegisterImport(hash, loc, context)
    return exp
  }
 
  // Only path without hash - straightforward import
  if (path && !hash) {
    const { exp } = resolveOrRegisterImport(path, loc, context)
    return exp
  }
 
  // At this point, we know we have both path and hash components
  const { name } = resolveOrRegisterImport(path!, loc, context)
 
  // Combine path import with hash
  const hashExp = `${name} + '${hash}'`
  const finalExp = createSimpleExpression(
    hashExp,
    false,
    loc,
    ConstantTypes.CAN_STRINGIFY,
  )
 
  // No hoisting needed
  Iif (!context.hoistStatic) {
    return finalExp
  }
 
  // Check for existing hoisted expression
  const existingHoistIndex = context.hoists.findIndex(h => {
    return (
      h &&
      h.type === NodeTypes.SIMPLE_EXPRESSION &&
      !h.isStatic &&
      h.content === hashExp
    )
  })
 
  // Return existing hoisted expression if found
  if (existingHoistIndex > -1) {
    return createSimpleExpression(
      `_hoisted_${existingHoistIndex + 1}`,
      false,
      loc,
      ConstantTypes.CAN_STRINGIFY,
    )
  }
 
  // Hoist the expression and return the hoisted expression
  return context.hoist(finalExp)
}