LCOV - code coverage report
Current view: top level - src/platform/assets/utils - assetUrlUtil.ts Coverage Total Hit
Test: ComfyUI E2E Coverage Lines: 66.7 % 45 30
Test Date: 2026-11-17 04:17:53

            Line data    Source code
       1              : /**
       2              :  * Utilities for constructing asset URLs
       3              :  */
       4              : 
       5              : import { useFeatureFlags } from '@/composables/useFeatureFlags'
       6              : import {
       7              :   isMediaRoute,
       8              :   scopeMediaRoute
       9              : } from '@comfyorg/api-client/sessionMediaUrl'
      10              : import { webSessionRequests } from '@comfyorg/api-client/webSessionFetch'
      11              : import { isCloud } from '@/platform/distribution/types'
      12              : import { api } from '@/scripts/api'
      13              : import { isResultItemType } from '@/utils/typeGuardUtil'
      14              : import { getOutputAssetMetadata } from '@/platform/assets/schemas/assetMetadataSchema'
      15              : import type { AssetItem } from '@/platform/assets/schemas/assetSchema'
      16              : import { getAssetType } from './assetTypeUtil'
      17              : 
      18              : /**
      19              :  * Get the download/view URL for an asset
      20              :  * Constructs the proper URL with filename encoding, type, and subfolder parameters
      21              :  *
      22              :  * @param asset The asset to get URL for
      23              :  * @param defaultType Default type if asset doesn't have tags (default: 'output')
      24              :  * @returns Full URL for viewing/downloading the asset
      25              :  *
      26              :  * @example
      27              :  * const url = getAssetUrl(asset)
      28              :  * downloadFile(url, asset.name)
      29              :  */
      30            1 : export function getAssetUrl(
      31              :   asset: AssetItem,
      32              :   defaultType: 'input' | 'output' = 'output'
      33              : ): string {
      34            1 :   const assetType = getAssetType(asset, defaultType)
      35            1 :   const subfolder = getAssetSubfolder(asset)
      36            1 :   const params = new URLSearchParams()
      37            1 :   params.set('filename', asset.name)
      38            1 :   params.set('type', assetType)
      39            1 :   if (subfolder) {
      40            1 :     params.set('subfolder', subfolder)
      41              :   }
      42            1 :   return api.apiURL(`/view?${params}`)
      43              : }
      44              : 
      45              : /** `/view` URL of the asset's own file, not its preview. */
      46            1 : export function getAssetViewUrl(asset: AssetItem): string {
      47            1 :   const root = asset.tags.find(isResultItemType)
      48            1 :   if (!asset.loader_path || !root) return getAssetUrl(asset)
      49            0 :   const slash = asset.loader_path.lastIndexOf('/')
      50            0 :   const params = new URLSearchParams({
      51              :     filename: asset.loader_path.slice(slash + 1),
      52              :     type: root
      53              :   })
      54            0 :   if (slash > 0) params.set('subfolder', asset.loader_path.slice(0, slash))
      55            0 :   return api.apiURL(`/view?${params}`)
      56              : }
      57              : 
      58              : /**
      59              :  * Get the subfolder an asset lives in, relative to its type root
      60              :  *
      61              :  * Reads `preview_url` first and falls back to `user_metadata`, mirroring how
      62              :  * {@link getAssetType} resolves the type.
      63              :  *
      64              :  * @param asset The asset to get the subfolder for
      65              :  * @returns The subfolder, or an empty string when the asset is at the root
      66              :  */
      67          837 : export function getAssetSubfolder(asset: AssetItem): string {
      68          837 :   const previewSubfolder = new URLSearchParams(
      69              :     (asset.preview_url ?? '').split('?')[1] ?? ''
      70              :   ).get('subfolder')
      71          837 :   if (previewSubfolder) return previewSubfolder
      72              : 
      73          837 :   const { subfolder } = asset.user_metadata ?? {}
      74          837 :   return typeof subfolder === 'string' ? subfolder : ''
      75              : }
      76              : 
      77              : /**
      78              :  * Id of the assets-API asset holding this item's own file. A card grouped per
      79              :  * job carries the job id as its `id` and keeps its own asset id in metadata.
      80              :  */
      81           23 : export function getAssetContentId(
      82              :   asset: Pick<AssetItem, 'id' | 'user_metadata'>
      83              : ): string {
      84           23 :   return getOutputAssetMetadata(asset.user_metadata)?.assetId || asset.id
      85              : }
      86              : 
      87              : /**
      88              :  * URL of the asset's own file, for downloading or loading it whole.
      89              :  *
      90              :  * With the assets API enabled the file is served by id, so no path inference
      91              :  * is needed and a preview that is only a thumbnail is never mistaken for the
      92              :  * file. Otherwise the item came from the history API, whose `preview_url`
      93              :  * already points at the file, with a `/view` URL as fallback.
      94              :  *
      95              :  * `disposition: 'inline'` asks the assets-API content endpoint to serve the
      96              :  * file for in-page rendering (e.g. a `<video>` source) instead of its
      97              :  * default `attachment` disposition, which browsers try to save rather than
      98              :  * play. It has no effect on the history-backed fallback, whose `/view`
      99              :  * endpoint has no such distinction.
     100              :  */
     101          806 : export function getAssetFileUrl(
     102              :   asset: AssetItem,
     103              :   options?: { disposition?: 'inline' | 'attachment' }
     104              : ): string {
     105          806 :   if (useFeatureFlags().flags.assetsEnabled) {
     106           23 :     const query = options?.disposition
     107              :       ? `?disposition=${options.disposition}`
     108              :       : ''
     109           23 :     return api.apiURL(`/assets/${getAssetContentId(asset)}/content${query}`)
     110              :   }
     111          806 :   return asset.preview_url || getAssetUrl(asset)
     112              : }
     113              : 
     114              : /**
     115              :  * URL for loading the asset's own video or audio file into a `<video>` or
     116              :  * `<audio>` `src`, which sends cookies but no headers.
     117              :  *
     118              :  * On Cloud, a cookie-authenticated `/assets/:id/content` request is looked up
     119              :  * in the session's default workspace only, so it 404s for an asset that lives
     120              :  * in another workspace. `/view` looks across the user's workspaces, so an
     121              :  * asset with a content hash is loaded through `/view?filename=<hash>`, the same
     122              :  * way image previews are. Without a hash (or off Cloud) this falls back to
     123              :  * {@link getAssetFileUrl} with an inline disposition.
     124              :  *
     125              :  * @param asset The asset whose file should be played
     126              :  * @returns The URL to set as the media element's `src`
     127              :  */
     128          804 : export function getAssetInlineMediaUrl(asset: AssetItem): string {
     129              :   if (isCloud && asset.hash) {
     130              :     const params = new URLSearchParams({
     131              :       filename: asset.hash,
     132              :       type: getAssetType(asset)
     133              :     })
     134              :     return api.apiURL(`/view?${params}`)
     135              :   }
     136          804 :   return getAssetFileUrl(asset, { disposition: 'inline' })
     137              : }
     138              : 
     139              : /**
     140              :  * Prepares a server-supplied media URL (e.g. `thumbnail_url`/`preview_url`)
     141              :  * for an `<img>`, `<video>` or `<audio>` `src`, which sends cookies but no
     142              :  * headers.
     143              :  *
     144              :  * Root-relative media routes go through `api.apiURL` so a web session names
     145              :  * its workspace on them, as do absolute URLs on this page's own origin. Any
     146              :  * other URL is returned as is: other-origin and signed external URLs, `blob:`
     147              :  * and `data:` URLs, protocol-relative URLs and non-media routes.
     148              :  *
     149              :  * @param url The URL the server supplied, if any
     150              :  * @returns The URL to load, or an empty string when there is none
     151              :  */
     152          435 : export function resolveMediaSrc(url: string | undefined): string {
     153          435 :   if (!url) return ''
     154          429 :   if (url.startsWith('//')) return url
     155          429 :   if (url.startsWith('/')) return isMediaRoute(url) ? api.apiURL(url) : url
     156            0 :   return scopeSameOriginMediaUrl(url)
     157              : }
     158              : 
     159            0 : function scopeSameOriginMediaUrl(url: string): string {
     160            0 :   const requests = webSessionRequests()
     161            0 :   if (!requests || !/^https?:\/\//i.test(url)) return url
     162            0 :   try {
     163            0 :     const parsed = new URL(url)
     164            0 :     if (parsed.origin !== window.location.origin) return url
     165            0 :     const route = `${parsed.pathname}${parsed.search}${parsed.hash}`
     166            0 :     const scoped = scopeMediaRoute(route, requests.workspaceId())
     167            0 :     return scoped === route ? url : `${parsed.origin}${scoped}`
     168              :   } catch {
     169            0 :     return url
     170              :   }
     171              : }
        

Generated by: LCOV version 2.0-1