-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.js
More file actions
234 lines (213 loc) · 8.1 KB
/
Copy pathstorage.js
File metadata and controls
234 lines (213 loc) · 8.1 KB
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
let chatTitleCache = new Map()
let chatTitlesPromise = null
let chatTitlePermission = 'unknown'
async function responseDetail(response) {
try {
const body = await response.json()
return body?.detail || body?.error || ''
} catch {
return ''
}
}
async function responseError(response, fallback) {
const detail = await responseDetail(response)
const error = new Error(detail || fallback)
error.status = response.status
return error
}
export function makeStorage(appId, token) {
const runtime = (typeof window !== 'undefined' && window.mobius?.storage) || null
const auth = { Authorization: `Bearer ${token}` }
function artifactDataUrl(artifactId, key) {
return `/api/apps/${encodeURIComponent(appId)}/artifact-data/${encodeURIComponent(artifactId)}/${encodeURIComponent(key)}`
}
async function get(path) {
if (runtime?.get) return runtime.get(path)
const response = await fetch(`/api/storage/apps/${appId}/${path}`, { headers: auth })
if (response.status === 404) return null
if (!response.ok) throw new Error(`Could not read ${path} (${response.status}).`)
return response.json()
}
async function getFresh(path) {
const response = await fetch(`/api/storage/apps/${appId}/${path}`, { headers: auth })
if (response.status === 404) return null
if (!response.ok) throw new Error(`Could not read ${path} (${response.status}).`)
return response.json()
}
async function getText(path) {
if (runtime?.getText) return runtime.getText(path)
const response = await fetch(`/api/storage/apps/${appId}/${path}`, { headers: auth })
if (response.status === 404) return null
if (!response.ok) throw new Error(`Could not read ${path} (${response.status}).`)
return response.text()
}
async function setJSON(path, value) {
if (runtime?.set) return runtime.set(path, value)
const response = await fetch(`/api/storage/apps/${appId}/${path}`, {
method: 'PUT',
headers: { ...auth, 'Content-Type': 'application/json' },
body: JSON.stringify(value),
})
if (!response.ok) throw await responseError(response, `Could not save ${path} (${response.status}).`)
return { synced: true }
}
async function setText(path, value) {
if (runtime?.setText) return runtime.setText(path, value)
const response = await fetch(`/api/storage/apps/${appId}/${path}`, {
method: 'PUT',
headers: { ...auth, 'Content-Type': 'text/html;charset=utf-8' },
body: value,
})
if (!response.ok) throw await responseError(response, `Could not save ${path} (${response.status}).`)
return { synced: true }
}
async function remove(path) {
if (runtime?.remove) return runtime.remove(path)
const response = await fetch(`/api/storage/apps/${appId}/${path}`, {
method: 'DELETE', headers: auth,
})
if (!response.ok && response.status !== 404) {
throw new Error(`Could not remove ${path} (${response.status}).`)
}
return { synced: true }
}
async function list(prefix = '', options = {}) {
if (runtime?.list) return runtime.list(prefix, options)
const entries = []
let cursor = null
do {
const params = new URLSearchParams({ limit: '500' })
if (cursor) params.set('cursor', cursor)
if (options.includeContent) params.set('include_content', 'true')
const response = await fetch(`/api/storage/apps-list/${appId}/${prefix}?${params}`, { headers: auth })
if (!response.ok) throw new Error(`Could not list ${prefix} (${response.status}).`)
const page = await response.json()
entries.push(...(Array.isArray(page.entries) ? page.entries : []))
cursor = page.next_cursor || null
} while (cursor)
return entries
}
function subscribe(path, callback) {
if (runtime?.subscribe) return runtime.subscribe(path, callback)
let active = true
get(path).then((value) => { if (active) callback(value) }).catch(() => {})
return () => { active = false }
}
async function removeFolder(path) {
const response = await fetch(`/api/storage/apps/${appId}/folder/${path}`, {
method: 'DELETE', headers: auth,
})
if (!response.ok && response.status !== 404) {
const detail = await responseDetail(response)
throw new Error(detail || `Could not remove ${path} (${response.status}).`)
}
return { synced: true }
}
async function publish(projectId) {
const response = await fetch(`/api/apps/${appId}/publish`, {
method: 'POST',
headers: { ...auth, 'Content-Type': 'application/json' },
body: JSON.stringify({ project_id: projectId }),
})
if (!response.ok) {
throw await responseError(response, `Could not publish (${response.status}).`)
}
return response.json()
}
async function unpublish(projectId) {
const response = await fetch(`/api/apps/${appId}/publish?project_id=${encodeURIComponent(projectId)}`, {
method: 'DELETE', headers: auth,
})
if (!response.ok && response.status !== 404) {
const detail = await responseDetail(response)
throw new Error(detail || `Could not stop sharing (${response.status}).`)
}
}
async function artifactDataGet(artifactId, key) {
const response = await fetch(artifactDataUrl(artifactId, key), { headers: auth })
if (response.status === 404) return null
if (!response.ok) {
throw await responseError(response, `Could not read artifact data (${response.status}).`)
}
return response.json()
}
async function artifactDataKeys(artifactId) {
// Server-derived from the directory: no client index to keep in sync.
const response = await fetch(
`/api/apps/${appId}/artifact-data/${encodeURIComponent(artifactId)}`,
{ headers: auth },
)
if (response.status === 404) return []
if (!response.ok) {
throw await responseError(response, `Could not list artifact data (${response.status}).`)
}
const body = await response.json()
return Array.isArray(body?.keys) ? body.keys : []
}
async function artifactDataSet(artifactId, key, value) {
const response = await fetch(artifactDataUrl(artifactId, key), {
method: 'PUT',
headers: { ...auth, 'Content-Type': 'application/json' },
body: JSON.stringify(value),
})
if (!response.ok) {
throw await responseError(response, `Could not save artifact data (${response.status}).`)
}
}
async function artifactDataRemove(artifactId, key) {
const response = await fetch(artifactDataUrl(artifactId, key), {
method: 'DELETE',
headers: auth,
})
if (!response.ok && response.status !== 404) {
throw await responseError(response, `Could not remove artifact data (${response.status}).`)
}
}
return {
get,
getFresh,
getText,
setJSON,
setText,
remove,
list,
subscribe,
removeFolder,
publish,
unpublish,
artifactDataGet,
artifactDataKeys,
artifactDataSet,
artifactDataRemove,
}
}
export async function loadChatTitles(token) {
if (chatTitlePermission === 'forbidden') {
return { permission: 'forbidden', titles: chatTitleCache }
}
if (chatTitlesPromise) return chatTitlesPromise
chatTitlesPromise = (async () => {
let cursor = 0
const nextTitles = new Map()
do {
const params = new URLSearchParams({ limit: '100', cursor: String(cursor) })
const response = await fetch(`/api/chat-logs?${params}`, {
headers: { Authorization: `Bearer ${token}` },
})
if (response.status === 403) {
chatTitlePermission = 'forbidden'
return { permission: 'forbidden', titles: chatTitleCache }
}
if (!response.ok) throw new Error(`Could not load chat titles (${response.status}).`)
const page = await response.json()
for (const item of Array.isArray(page.items) ? page.items : []) {
if (item?.id) nextTitles.set(String(item.id), String(item.title || 'Untitled chat'))
}
cursor = page.next_cursor
} while (cursor !== null && cursor !== undefined)
chatTitleCache = nextTitles
chatTitlePermission = 'allowed'
return { permission: 'allowed', titles: chatTitleCache }
})().finally(() => { chatTitlesPromise = null })
return chatTitlesPromise
}