Line data Source code
1 : import { toValue } from 'vue'
2 :
3 : import { useFeatureFlags } from '@/composables/useFeatureFlags'
4 : import { assetResponseSchema } from '@/platform/assets/schemas/assetSchema'
5 : import type { AssetItem } from '@/platform/assets/schemas/assetSchema'
6 : import { getAssetSubfolder } from '@/platform/assets/utils/assetUrlUtil'
7 : import { api } from '@/scripts/api'
8 : import { useAssetsStore } from '@/stores/assetsStore'
9 : import { parseAnnotatedPath } from '@/utils/createAnnotatedPath'
10 : import { parseFilePath } from '@/utils/formatUtil'
11 : import { encodeParams } from '@/utils/requestUtil'
12 :
13 32 : function getAssetRelativePath(asset: AssetItem): string {
14 32 : const subfolder = getAssetSubfolder(asset)
15 32 : return subfolder ? `${subfolder}/${asset.name}` : asset.name
16 : }
17 :
18 : /** Resolve a widget value to its asset: `null` when confirmed absent, `undefined` when unknown. */
19 13 : export async function resolveWidgetValueAsset(
20 : widgetValue: string,
21 : { signal }: { signal?: AbortSignal } = {}
22 : ): Promise<AssetItem | null | undefined> {
23 13 : const { filepath, rootFolder } = parseAnnotatedPath(widgetValue)
24 13 : const { filename: hashFilename } = parseFilePath(
25 : /[\\/]$/.test(filepath) ? '' : filepath
26 : )
27 13 : const relativePath = filepath.replaceAll('\\', '/')
28 13 : const assetMatches = (asset: AssetItem) =>
29 : asset.hash
30 : ? asset.hash === hashFilename
31 : : getAssetRelativePath(asset) === relativePath
32 13 : const assetsStore = useAssetsStore()
33 13 : const inputItems = toValue(assetsStore.inputAssets.items)
34 13 : const outputItems = toValue(assetsStore.outputAssets.items)
35 13 : const [ownRootItems, otherRootItems] =
36 : rootFolder === 'input'
37 : ? [inputItems, outputItems]
38 : : [outputItems, inputItems]
39 13 : const storedAsset =
40 : ownRootItems.find(assetMatches) ?? otherRootItems.find(assetMatches)
41 13 : if (storedAsset) return storedAsset
42 :
43 9 : if (!useFeatureFlags().flags.assetsEnabled) return undefined
44 0 : if (!hashFilename) return null
45 :
46 0 : const query = encodeParams({
47 : limit: 1,
48 : hash: hashFilename,
49 : include_public: true
50 : })
51 : const resp = await api.fetchApi(`/assets?${query}`, { signal })
52 0 : const json = await resp.json().catch(() => {})
53 0 : const parseResult = assetResponseSchema.safeParse(json)
54 13 : return parseResult.success ? (parseResult.data.assets[0] ?? null) : undefined
55 : }
|