File size: 1,431 Bytes
766d85d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
export async function getAuthUrl(url: string, purpose: 'download'): Promise<string> {
  if (!url) return url
  try {
    const resp = await fetch('/api/auth/resource-token', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      credentials: 'include',
      body: JSON.stringify({ purpose }),
    })
    if (!resp.ok) return url
    const { token } = await resp.json()
    return `${url}${url.includes('?') ? '&' : '?'}token=${token}`
  } catch {
    return url
  }
}

// ── Blob-based image fetching (Safari-safe, no ephemeral tokens needed) ────

const MAX_CONCURRENT = 6
let active = 0
const queue: Array<() => void> = []

function dequeue() {
  while (active < MAX_CONCURRENT && queue.length > 0) {
    active++
    queue.shift()!()
  }
}

export function clearImageQueue() {
  queue.length = 0
}

export async function fetchImageAsBlob(url: string): Promise<string> {
  if (!url) return ''
  return new Promise<string>((resolve) => {
    const run = async () => {
      try {
        const resp = await fetch(url, { credentials: 'include' })
        if (!resp.ok) { resolve(''); return }
        const blob = await resp.blob()
        resolve(URL.createObjectURL(blob))
      } catch {
        resolve('')
      } finally {
        active--
        dequeue()
      }
    }
    if (active < MAX_CONCURRENT) {
      active++
      run()
    } else {
      queue.push(run)
    }
  })
}