93 lines
2.3 KiB
JavaScript
93 lines
2.3 KiB
JavaScript
// @ts-nocheck
|
|
const { DEFAULT_API_BASE_URL, getApiBaseUrl, normalizeApiBaseUrl } = require('./constants')
|
|
|
|
function isLocalDevUrl(url) {
|
|
return /^https?:\/\/(127\.0\.0\.1|localhost|0\.0\.0\.0)(:\d+)?\//i.test(url)
|
|
}
|
|
|
|
function upgradeToHttpsIfNeeded(url) {
|
|
if (/^http:\/\//i.test(url) && !isLocalDevUrl(url)) {
|
|
return url.replace(/^http:\/\//i, 'https://')
|
|
}
|
|
return url
|
|
}
|
|
|
|
function canonicalizeImagePath(url) {
|
|
let value = String(url || '').trim()
|
|
if (!value) {
|
|
return ''
|
|
}
|
|
|
|
if (/^https?:\/\/[^/]+\/api\/v1\/static\//i.test(value)) {
|
|
return value
|
|
}
|
|
|
|
if (/^\/api\/v1\/static\//i.test(value)) {
|
|
return value
|
|
}
|
|
|
|
if (/^\/static\//i.test(value)) {
|
|
return `/api/v1${value}`
|
|
}
|
|
|
|
if (/^\/v1\/static\//i.test(value)) {
|
|
return value.replace(/^\/v1\//i, '/api/v1/')
|
|
}
|
|
|
|
if (/^https?:\/\/[^/]+\/static\//i.test(value)) {
|
|
const path = value.replace(/^https?:\/\/[^/]+/i, '')
|
|
return path.startsWith('/api/v1/') ? path : `/api/v1${path}`
|
|
}
|
|
|
|
if (/^https?:\/\/[^/]+\/v1\/static\//i.test(value)) {
|
|
return value.replace(/^https?:\/\/[^/]+\/v1\//i, '/api/v1/')
|
|
}
|
|
|
|
if (/^https?:\/\/[^/]/i.test(value)) {
|
|
value = value.replace(/^([a-z]+:)\/(?!\/)/i, '$1//')
|
|
}
|
|
|
|
if (/^\/api\/v1\/https?:\/\//i.test(value)) {
|
|
value = value.replace(/^\/api\/v1\//i, '')
|
|
}
|
|
if (/^https?:\/\/[^/]+\/api\/v1\/https?:\/\//i.test(value)) {
|
|
value = value.replace(/^https?:\/\/[^/]+\/api\/v1\//i, '')
|
|
}
|
|
|
|
return value
|
|
}
|
|
|
|
function resolveImageUrl(url) {
|
|
if (!url) {
|
|
return ''
|
|
}
|
|
if (/^(data:|blob:|wxfile:|file:)/i.test(url)) {
|
|
return url
|
|
}
|
|
|
|
const canonicalPath = canonicalizeImagePath(url)
|
|
if (/^https?:\/\//i.test(canonicalPath)) {
|
|
return upgradeToHttpsIfNeeded(canonicalPath)
|
|
}
|
|
|
|
const apiBaseUrl = normalizeApiBaseUrl(getApiBaseUrl() || DEFAULT_API_BASE_URL)
|
|
const baseUrl = apiBaseUrl.replace(/\/api\/v1\/?$/, '')
|
|
const resolvedPath = canonicalPath.startsWith('/') ? canonicalPath : `/${canonicalPath}`
|
|
const resolved = `${baseUrl}${resolvedPath}`
|
|
return upgradeToHttpsIfNeeded(resolved)
|
|
}
|
|
|
|
function resolveImageList(urls) {
|
|
if (!Array.isArray(urls)) {
|
|
return []
|
|
}
|
|
return urls.map((item) => resolveImageUrl(item)).filter(Boolean)
|
|
}
|
|
|
|
module.exports = {
|
|
resolveImageUrl,
|
|
resolveImageList,
|
|
upgradeToHttpsIfNeeded,
|
|
isLocalDevUrl
|
|
}
|