blossom-client-sdk 4.1.0 → 5.0.0-0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +246 -92
- package/lib/actions/delete.d.ts +3 -1
- package/lib/actions/delete.js +16 -7
- package/lib/actions/download.d.ts +3 -1
- package/lib/actions/download.js +16 -7
- package/lib/actions/has.d.ts +9 -0
- package/lib/actions/has.js +10 -0
- package/lib/actions/index.d.ts +3 -0
- package/lib/actions/index.js +3 -0
- package/lib/actions/list.d.ts +8 -2
- package/lib/actions/list.js +34 -8
- package/lib/actions/media.d.ts +1 -1
- package/lib/actions/media.js +17 -7
- package/lib/actions/mirror.d.ts +3 -1
- package/lib/actions/mirror.js +16 -7
- package/lib/actions/multi-server.d.ts +63 -43
- package/lib/actions/multi-server.js +205 -96
- package/lib/actions/report.d.ts +11 -0
- package/lib/actions/report.js +35 -0
- package/lib/actions/resolve.d.ts +27 -0
- package/lib/actions/resolve.js +129 -0
- package/lib/actions/upload.d.ts +3 -1
- package/lib/actions/upload.js +16 -7
- package/lib/auth.d.ts +20 -1
- package/lib/auth.js +80 -22
- package/lib/error.d.ts +5 -0
- package/lib/error.js +11 -0
- package/lib/helpers/blob.d.ts +1 -1
- package/lib/helpers/blossom-uri.d.ts +20 -0
- package/lib/helpers/blossom-uri.js +77 -0
- package/lib/helpers/cachu.d.ts +5 -0
- package/lib/helpers/cachu.js +14 -0
- package/lib/helpers/index.d.ts +1 -0
- package/lib/helpers/index.js +1 -0
- package/lib/helpers/url.d.ts +2 -0
- package/lib/helpers/url.js +9 -3
- package/lib/helpers.d.ts +20 -0
- package/lib/helpers.js +73 -0
- package/lib/hls.d.ts +20 -0
- package/lib/hls.js +182 -0
- package/lib/index.d.ts +1 -2
- package/lib/index.js +1 -2
- package/lib/media.d.ts +37 -0
- package/lib/media.js +179 -0
- package/lib/types.d.ts +3 -1
- package/lib/upload.d.ts +13 -0
- package/lib/upload.js +37 -0
- package/package.json +16 -7
- package/src/actions/delete.ts +18 -6
- package/src/actions/download.ts +18 -6
- package/src/actions/has.ts +19 -0
- package/src/actions/index.ts +3 -0
- package/src/actions/list.ts +42 -7
- package/src/actions/media.ts +18 -6
- package/src/actions/mirror.ts +18 -6
- package/src/actions/multi-server.ts +264 -118
- package/src/actions/report.ts +54 -0
- package/src/actions/resolve.ts +159 -0
- package/src/actions/upload.ts +18 -6
- package/src/auth.ts +99 -21
- package/src/error.ts +15 -0
- package/src/helpers/blob.ts +1 -1
- package/src/helpers/blossom-uri.ts +99 -0
- package/src/helpers/index.ts +1 -0
- package/src/helpers/url.ts +10 -3
- package/src/hls.ts +255 -0
- package/src/index.ts +1 -2
- package/src/media.ts +200 -0
- package/src/types.ts +4 -1
- package/lib/client.d.ts +0 -61
- package/lib/client.js +0 -160
- package/lib/image.d.ts +0 -17
- package/lib/image.js +0 -107
- package/src/client.ts +0 -221
- package/src/image.ts +0 -122
|
@@ -1,125 +1,104 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { getReusableAuthEvent, storeAuthEvent } from "../auth.js";
|
|
2
2
|
import { getBlobSha256 } from "../helpers/index.js";
|
|
3
|
+
import HTTPError from "../error.js";
|
|
3
4
|
import { MediaEndpointMissingError, uploadMedia } from "./media.js";
|
|
4
5
|
import { mirrorBlob } from "./mirror.js";
|
|
6
|
+
import { hasBlob } from "./has.js";
|
|
5
7
|
import { uploadBlob } from "./upload.js";
|
|
6
8
|
const defaultMultiServerOptions = {
|
|
7
|
-
|
|
9
|
+
mirrorTimeout: 5000,
|
|
10
|
+
preflight: true,
|
|
11
|
+
};
|
|
12
|
+
const defaultMediaUploadOptions = {
|
|
13
|
+
...defaultMultiServerOptions,
|
|
8
14
|
mediaUploadBehavior: "first",
|
|
9
15
|
mediaUploadFallback: false,
|
|
10
|
-
mirrorTimeout: 5000,
|
|
11
16
|
};
|
|
12
17
|
/**
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* @returns The BlobDescriptor if successful
|
|
18
|
+
* Upload a blob to multiple servers
|
|
19
|
+
*
|
|
20
|
+
* Uploads the blob to the first server, then mirrors to the remaining servers.
|
|
21
|
+
* Uses parallel preflight checks (HEAD /<sha256>) to detect which servers already have the blob.
|
|
18
22
|
*
|
|
19
23
|
* ```mermaid
|
|
20
24
|
* flowchart LR
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
* iffallback -- no --> abort
|
|
28
|
-
* upload -- complete --> next
|
|
29
|
-
* next --> uploaded{"Uploaded"}
|
|
30
|
-
* uploaded -- yes --> mirror["/mirror"]
|
|
31
|
-
* uploaded -- no --> upload
|
|
32
|
-
* mirror --> isMirror{"Successful"}
|
|
25
|
+
* preflight["HEAD /<sha256>"] --> hasBlob{"Has blob?"}
|
|
26
|
+
* hasBlob -- yes --> mirror["/mirror"]
|
|
27
|
+
* hasBlob -- no --> upload["/upload"]
|
|
28
|
+
* upload -- complete --> next["Next server"]
|
|
29
|
+
* next --> hasBlob
|
|
30
|
+
* mirror --> isMirror{"Successful?"}
|
|
33
31
|
* isMirror -- yes --> next
|
|
34
|
-
* isMirror -- no -->
|
|
35
|
-
* ifMediaAbort -- no --> upload
|
|
36
|
-
* ifMediaAbort -- yes --> next
|
|
32
|
+
* isMirror -- no --> upload
|
|
37
33
|
* ```
|
|
38
34
|
*/
|
|
39
35
|
export async function multiServerUpload(servers, blob, opts) {
|
|
40
36
|
const options = { ...defaultMultiServerOptions, ...opts };
|
|
41
37
|
let initialUpload;
|
|
42
38
|
const results = new Map();
|
|
43
|
-
|
|
44
|
-
|
|
39
|
+
const authEvents = options.authEvents ?? new Set();
|
|
40
|
+
const blobSha256 = await getBlobSha256(blob);
|
|
41
|
+
if (typeof options.auth === "object")
|
|
42
|
+
authEvents.add(options.auth);
|
|
45
43
|
const handleAuthRequest = async (server, sha256, type) => {
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
return auth;
|
|
50
|
-
}
|
|
51
|
-
// create a new auth event
|
|
44
|
+
const reused = await getReusableAuthEvent(authEvents, { server, type, blob: sha256 });
|
|
45
|
+
if (reused)
|
|
46
|
+
return reused;
|
|
52
47
|
if (options.onAuth) {
|
|
53
48
|
const auth = await options.onAuth(server, sha256, type, blob);
|
|
54
|
-
authEvents
|
|
55
|
-
return auth;
|
|
49
|
+
return storeAuthEvent(authEvents, auth);
|
|
56
50
|
}
|
|
57
51
|
else
|
|
58
52
|
throw new Error("Missing onAuth handler");
|
|
59
53
|
};
|
|
60
|
-
|
|
61
|
-
const handlePaymentRequest = async (server, sha256, _blog, request) => {
|
|
54
|
+
const handlePaymentRequest = async (server, sha256, _blob, request) => {
|
|
62
55
|
if (!options.onPayment)
|
|
63
56
|
throw new Error("Missing payment handler");
|
|
64
57
|
return options.onPayment(server, sha256, blob, request);
|
|
65
58
|
};
|
|
66
|
-
|
|
59
|
+
const handleRejection = async (server, sha256, error) => {
|
|
60
|
+
if (!HTTPError.isRejection(error))
|
|
61
|
+
return false;
|
|
62
|
+
if (options.onRejection) {
|
|
63
|
+
return await options.onRejection(server, sha256, blob, error);
|
|
64
|
+
}
|
|
65
|
+
options.onError?.(server, sha256, blob, error);
|
|
66
|
+
return "skip";
|
|
67
|
+
};
|
|
67
68
|
const uploadServers = Array.from(servers);
|
|
68
|
-
//
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
options.
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
onAuth: handleAuthRequest,
|
|
82
|
-
onPayment: handlePaymentRequest,
|
|
83
|
-
});
|
|
84
|
-
// save result
|
|
85
|
-
results.set(server, initialUpload);
|
|
86
|
-
// finished upload to server
|
|
87
|
-
options.onUpload?.(server, initialUpload.sha256, blob);
|
|
88
|
-
}
|
|
89
|
-
catch (error) {
|
|
90
|
-
if (error instanceof MediaEndpointMissingError) {
|
|
91
|
-
// ignore error
|
|
92
|
-
}
|
|
93
|
-
else if (error instanceof Error) {
|
|
94
|
-
const sha256 = await getBlobSha256(blob);
|
|
95
|
-
options.onError?.(server, sha256, blob, error);
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
|
-
if (initialUpload) {
|
|
99
|
-
// remove server from upload array
|
|
100
|
-
if (uploadServers.includes(server))
|
|
101
|
-
uploadServers.splice(uploadServers.indexOf(server), 1);
|
|
102
|
-
// exit on first successful media upload
|
|
103
|
-
break;
|
|
69
|
+
// parallel preflight: check which servers already have the blob
|
|
70
|
+
const serversWithBlob = new Set();
|
|
71
|
+
if (options.preflight !== false && uploadServers.length > 0) {
|
|
72
|
+
const preflightResults = await Promise.allSettled(uploadServers.map(async (server) => {
|
|
73
|
+
const exists = await hasBlob(server, blobSha256, {
|
|
74
|
+
signal: options.signal,
|
|
75
|
+
timeout: options.mirrorTimeout,
|
|
76
|
+
});
|
|
77
|
+
return { server, exists };
|
|
78
|
+
}));
|
|
79
|
+
for (const result of preflightResults) {
|
|
80
|
+
if (result.status === "fulfilled" && result.value.exists) {
|
|
81
|
+
serversWithBlob.add(result.value.server);
|
|
104
82
|
}
|
|
105
83
|
}
|
|
106
|
-
if (!options.mediaUploadFallback && !initialUpload) {
|
|
107
|
-
// failed to find a /media endpoint, abort
|
|
108
|
-
throw new Error("Failed to find media processing endpoint");
|
|
109
|
-
}
|
|
110
84
|
}
|
|
111
|
-
//
|
|
85
|
+
// upload to each server
|
|
112
86
|
for (const server of uploadServers) {
|
|
87
|
+
const serverHasBlob = serversWithBlob.has(server);
|
|
113
88
|
try {
|
|
114
89
|
let metadata = undefined;
|
|
115
|
-
// attempt to mirror
|
|
116
|
-
if (initialUpload) {
|
|
90
|
+
// attempt to mirror if we have an initial upload or server already has the blob
|
|
91
|
+
if (initialUpload || serverHasBlob) {
|
|
92
|
+
const mirrorSource = initialUpload ?? {
|
|
93
|
+
url: new URL("/" + blobSha256, server).toString(),
|
|
94
|
+
sha256: blobSha256,
|
|
95
|
+
size: 0,
|
|
96
|
+
uploaded: 0,
|
|
97
|
+
};
|
|
117
98
|
try {
|
|
118
|
-
options.onStart?.(server,
|
|
119
|
-
metadata = await mirrorBlob(server,
|
|
120
|
-
// pass through abort signal
|
|
99
|
+
options.onStart?.(server, blobSha256, blob);
|
|
100
|
+
metadata = await mirrorBlob(server, mirrorSource, {
|
|
121
101
|
signal: options.signal,
|
|
122
|
-
// pass through authorization flag
|
|
123
102
|
auth: typeof options.auth === "boolean" ? options.auth : undefined,
|
|
124
103
|
onAuth: (server, sha256) => handleAuthRequest(server, sha256, "upload"),
|
|
125
104
|
onPayment: handlePaymentRequest,
|
|
@@ -127,37 +106,167 @@ export async function multiServerUpload(servers, blob, opts) {
|
|
|
127
106
|
});
|
|
128
107
|
}
|
|
129
108
|
catch (error) {
|
|
130
|
-
// mirror failed, if
|
|
131
|
-
if (
|
|
109
|
+
// mirror failed, if server already has blob skip upload fallback
|
|
110
|
+
if (serverHasBlob)
|
|
132
111
|
continue;
|
|
133
112
|
}
|
|
134
113
|
}
|
|
135
|
-
// attempt to upload if
|
|
114
|
+
// attempt to upload if mirror failed
|
|
136
115
|
if (!metadata) {
|
|
137
|
-
|
|
138
|
-
options.onStart?.(server, sha256, blob);
|
|
116
|
+
options.onStart?.(server, blobSha256, blob);
|
|
139
117
|
metadata = await uploadBlob(server, blob, {
|
|
140
|
-
// pass through abort signal
|
|
141
118
|
signal: options.signal,
|
|
142
|
-
// pass through authorization flag
|
|
143
119
|
auth: typeof options.auth === "boolean" ? options.auth : undefined,
|
|
144
120
|
onAuth: handleAuthRequest,
|
|
145
121
|
onPayment: handlePaymentRequest,
|
|
146
122
|
timeout: options.mirrorTimeout,
|
|
147
123
|
});
|
|
148
|
-
// save first upload
|
|
149
124
|
if (!initialUpload)
|
|
150
125
|
initialUpload = metadata;
|
|
151
126
|
}
|
|
152
|
-
// save result
|
|
153
127
|
results.set(server, metadata);
|
|
154
|
-
// finished upload to server
|
|
155
128
|
options.onUpload?.(server, metadata.sha256, blob);
|
|
156
129
|
}
|
|
157
130
|
catch (error) {
|
|
158
|
-
|
|
159
|
-
if (
|
|
160
|
-
|
|
131
|
+
const rejection = await handleRejection(server, blobSha256, error);
|
|
132
|
+
if (rejection === "cancel")
|
|
133
|
+
return results;
|
|
134
|
+
if (!rejection && error instanceof Error)
|
|
135
|
+
options.onError?.(server, blobSha256, blob, error);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return results;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Upload media to multiple servers using BUD-05 optimization
|
|
142
|
+
*
|
|
143
|
+
* Uploads the blob to a /media endpoint on one server for optimization,
|
|
144
|
+
* then mirrors the optimized result to the remaining servers.
|
|
145
|
+
* The blob is never re-uploaded to other servers since the /media endpoint may transform it.
|
|
146
|
+
*
|
|
147
|
+
* ```mermaid
|
|
148
|
+
* flowchart LR
|
|
149
|
+
* media["/media"] --> ifmedia{"Successful?"}
|
|
150
|
+
* ifmedia -- yes --> preflight["HEAD /<sha256>"]
|
|
151
|
+
* ifmedia -- no --> iffallback{"fallback?"}
|
|
152
|
+
* iffallback -- yes --> upload["multiServerUpload"]
|
|
153
|
+
* iffallback -- no --> abort
|
|
154
|
+
* preflight --> mirror["/mirror"]
|
|
155
|
+
* mirror --> next["Next server"]
|
|
156
|
+
* ```
|
|
157
|
+
*/
|
|
158
|
+
export async function multiServerMediaUpload(servers, blob, opts) {
|
|
159
|
+
const options = { ...defaultMediaUploadOptions, ...opts };
|
|
160
|
+
let initialUpload;
|
|
161
|
+
const results = new Map();
|
|
162
|
+
const authEvents = options.authEvents ?? new Set();
|
|
163
|
+
const blobSha256 = await getBlobSha256(blob);
|
|
164
|
+
if (typeof options.auth === "object")
|
|
165
|
+
authEvents.add(options.auth);
|
|
166
|
+
const handleAuthRequest = async (server, sha256, type) => {
|
|
167
|
+
const reused = await getReusableAuthEvent(authEvents, { server, type, blob: sha256 });
|
|
168
|
+
if (reused)
|
|
169
|
+
return reused;
|
|
170
|
+
if (options.onAuth) {
|
|
171
|
+
const auth = await options.onAuth(server, sha256, type, blob);
|
|
172
|
+
return storeAuthEvent(authEvents, auth);
|
|
173
|
+
}
|
|
174
|
+
else
|
|
175
|
+
throw new Error("Missing onAuth handler");
|
|
176
|
+
};
|
|
177
|
+
const handlePaymentRequest = async (server, sha256, _blob, request) => {
|
|
178
|
+
if (!options.onPayment)
|
|
179
|
+
throw new Error("Missing payment handler");
|
|
180
|
+
return options.onPayment(server, sha256, blob, request);
|
|
181
|
+
};
|
|
182
|
+
const handleRejection = async (server, sha256, error) => {
|
|
183
|
+
if (!HTTPError.isRejection(error))
|
|
184
|
+
return false;
|
|
185
|
+
if (options.onRejection) {
|
|
186
|
+
return await options.onRejection(server, sha256, blob, error);
|
|
187
|
+
}
|
|
188
|
+
options.onError?.(server, sha256, blob, error);
|
|
189
|
+
return "skip";
|
|
190
|
+
};
|
|
191
|
+
const allServers = Array.from(servers);
|
|
192
|
+
const mediaServers = options.mediaUploadBehavior === "any" ? Array.from(allServers) : [allServers[0]];
|
|
193
|
+
let mediaUploadServer;
|
|
194
|
+
// phase 1: upload to /media on one server for optimization
|
|
195
|
+
for (const server of mediaServers) {
|
|
196
|
+
try {
|
|
197
|
+
options.onStart?.(server, blobSha256, blob);
|
|
198
|
+
initialUpload = await uploadMedia(server, blob, {
|
|
199
|
+
signal: options.signal,
|
|
200
|
+
auth: typeof options.auth === "boolean" ? options.auth : undefined,
|
|
201
|
+
onAuth: handleAuthRequest,
|
|
202
|
+
onPayment: handlePaymentRequest,
|
|
203
|
+
});
|
|
204
|
+
results.set(server, initialUpload);
|
|
205
|
+
mediaUploadServer = server;
|
|
206
|
+
options.onUpload?.(server, initialUpload.sha256, blob);
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
if (error instanceof MediaEndpointMissingError) {
|
|
210
|
+
// ignore, try next server
|
|
211
|
+
}
|
|
212
|
+
else {
|
|
213
|
+
const rejection = await handleRejection(server, blobSha256, error);
|
|
214
|
+
if (rejection === "cancel")
|
|
215
|
+
return results;
|
|
216
|
+
if (!rejection && error instanceof Error) {
|
|
217
|
+
options.onError?.(server, blobSha256, blob, error);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
if (initialUpload)
|
|
222
|
+
break;
|
|
223
|
+
}
|
|
224
|
+
// if no /media endpoint found, fall back to regular upload or abort
|
|
225
|
+
if (!initialUpload) {
|
|
226
|
+
if (!options.mediaUploadFallback) {
|
|
227
|
+
throw new Error("Failed to find media processing endpoint");
|
|
228
|
+
}
|
|
229
|
+
// fall back to regular multi-server upload
|
|
230
|
+
return multiServerUpload(servers, blob, options);
|
|
231
|
+
}
|
|
232
|
+
// phase 2: mirror the optimized blob to remaining servers
|
|
233
|
+
const remainingServers = allServers.filter((s) => s !== mediaUploadServer);
|
|
234
|
+
// parallel preflight on remaining servers using the optimized blob's sha256
|
|
235
|
+
const serversWithBlob = new Set();
|
|
236
|
+
if (options.preflight !== false && remainingServers.length > 0) {
|
|
237
|
+
const preflightResults = await Promise.allSettled(remainingServers.map(async (server) => {
|
|
238
|
+
const exists = await hasBlob(server, initialUpload.sha256, {
|
|
239
|
+
signal: options.signal,
|
|
240
|
+
timeout: options.mirrorTimeout,
|
|
241
|
+
});
|
|
242
|
+
return { server, exists };
|
|
243
|
+
}));
|
|
244
|
+
for (const result of preflightResults) {
|
|
245
|
+
if (result.status === "fulfilled" && result.value.exists) {
|
|
246
|
+
serversWithBlob.add(result.value.server);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
// mirror to remaining servers
|
|
251
|
+
for (const server of remainingServers) {
|
|
252
|
+
try {
|
|
253
|
+
options.onStart?.(server, initialUpload.sha256, blob);
|
|
254
|
+
const metadata = await mirrorBlob(server, initialUpload, {
|
|
255
|
+
signal: options.signal,
|
|
256
|
+
auth: typeof options.auth === "boolean" ? options.auth : undefined,
|
|
257
|
+
onAuth: (server, sha256) => handleAuthRequest(server, sha256, "upload"),
|
|
258
|
+
onPayment: handlePaymentRequest,
|
|
259
|
+
timeout: options.mirrorTimeout,
|
|
260
|
+
});
|
|
261
|
+
results.set(server, metadata);
|
|
262
|
+
options.onUpload?.(server, metadata.sha256, blob);
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
const rejection = await handleRejection(server, initialUpload.sha256, error);
|
|
266
|
+
if (rejection === "cancel")
|
|
267
|
+
return results;
|
|
268
|
+
if (!rejection && error instanceof Error)
|
|
269
|
+
options.onError?.(server, initialUpload.sha256, blob, error);
|
|
161
270
|
}
|
|
162
271
|
}
|
|
163
272
|
return results;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { ServerType, SignedEvent } from "../types.js";
|
|
2
|
+
export type ReportOptions<S extends ServerType> = {
|
|
3
|
+
/** AbortSignal to cancel the action */
|
|
4
|
+
signal?: AbortSignal;
|
|
5
|
+
/** Request timeout */
|
|
6
|
+
timeout?: number;
|
|
7
|
+
/** Called when reporting to a server fails */
|
|
8
|
+
onError?: (server: S, error: Error) => void;
|
|
9
|
+
};
|
|
10
|
+
/** Sends a signed NIP-56 report event to multiple servers */
|
|
11
|
+
export declare function reportBlobs<S extends ServerType>(servers: Iterable<S>, report: SignedEvent, opts?: ReportOptions<S>): Promise<Map<S, boolean>>;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import HTTPError from "../error.js";
|
|
2
|
+
import { fetchWithTimeout } from "../helpers/fetch.js";
|
|
3
|
+
function isBlobReportEvent(report) {
|
|
4
|
+
return report.kind === 1984 && report.tags.some((tag) => tag[0] === "x" && !!tag[1]);
|
|
5
|
+
}
|
|
6
|
+
/** Sends a signed NIP-56 report event to multiple servers */
|
|
7
|
+
export async function reportBlobs(servers, report, opts) {
|
|
8
|
+
if (!isBlobReportEvent(report))
|
|
9
|
+
throw new Error("Invalid blob report event");
|
|
10
|
+
const results = new Map();
|
|
11
|
+
const body = JSON.stringify(report);
|
|
12
|
+
for (const server of servers) {
|
|
13
|
+
try {
|
|
14
|
+
const res = await fetchWithTimeout(new URL("/report", server), {
|
|
15
|
+
method: "PUT",
|
|
16
|
+
headers: { "Content-Type": "application/json" },
|
|
17
|
+
body,
|
|
18
|
+
signal: opts?.signal,
|
|
19
|
+
timeout: opts?.timeout,
|
|
20
|
+
});
|
|
21
|
+
await HTTPError.handleErrorResponse(res);
|
|
22
|
+
results.set(server, true);
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
if (opts?.signal?.aborted ||
|
|
26
|
+
(error instanceof Error &&
|
|
27
|
+
(error.name === "AbortError" || error.name === "TimeoutError" || error.message === "Timeout"))) {
|
|
28
|
+
throw error;
|
|
29
|
+
}
|
|
30
|
+
if (error instanceof Error)
|
|
31
|
+
opts?.onError?.(server, error);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
return results;
|
|
35
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { BlossomURI } from "../helpers/blossom-uri.js";
|
|
2
|
+
import { DownloadOptions } from "./download.js";
|
|
3
|
+
type GetServers = (pubkey: string) => Promise<(string | URL)[] | undefined>;
|
|
4
|
+
export type ResolveOptions = Omit<DownloadOptions<string | URL>, "onAuth" | "onPayment"> & {
|
|
5
|
+
/** Callback to resolve author pubkeys to ordered server lists (e.g. kind 10063 lookup) */
|
|
6
|
+
getServers?: GetServers;
|
|
7
|
+
/** Additional fallback servers to try after URI hints */
|
|
8
|
+
fallbackServers?: (string | URL)[];
|
|
9
|
+
};
|
|
10
|
+
export type GetBlobUrlsOptions = {
|
|
11
|
+
/** Callback to resolve author pubkeys to ordered server lists (e.g. kind 10063 lookup) */
|
|
12
|
+
getServers?: GetServers;
|
|
13
|
+
/** Additional fallback servers to try after URI hints */
|
|
14
|
+
fallbackServers?: (string | URL)[];
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Returns an ordered list of URLs for a blob without fetching anything.
|
|
18
|
+
* Resolves servers from xs hints, author hints (via getServers callback), and fallback servers.
|
|
19
|
+
*
|
|
20
|
+
* Accepts a blossom URI string, URL, or pre-parsed BlossomURI.
|
|
21
|
+
*/
|
|
22
|
+
export declare function getBlobUrls(uri: string | URL | BlossomURI, opts?: GetBlobUrlsOptions): Promise<string[]>;
|
|
23
|
+
/** Resolves a blossom URI to a downloaded blob by trying servers from hints sequentially */
|
|
24
|
+
export declare function resolveBlob(uri: string | URL | BlossomURI, opts?: ResolveOptions): Promise<Response>;
|
|
25
|
+
/** Resolves a blossom URI and returns a blob: object URL that works anywhere a URL string is accepted */
|
|
26
|
+
export declare function resolveToObjectURL(uri: string | URL | BlossomURI, opts?: ResolveOptions): Promise<string>;
|
|
27
|
+
export {};
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { blossomURIFromURL, parseBlossomURI } from "../helpers/blossom-uri.js";
|
|
2
|
+
import { fetchWithTimeout } from "../helpers/fetch.js";
|
|
3
|
+
function normalizeServer(server) {
|
|
4
|
+
if (server instanceof URL)
|
|
5
|
+
return server.origin;
|
|
6
|
+
// if it looks like a bare domain, try https first
|
|
7
|
+
if (!server.includes("://"))
|
|
8
|
+
return `https://${server}`;
|
|
9
|
+
try {
|
|
10
|
+
return new URL(server).origin;
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return `https://${server}`;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function parseInput(uri) {
|
|
17
|
+
return uri instanceof URL ? blossomURIFromURL(uri) : typeof uri === "string" ? parseBlossomURI(uri) : uri;
|
|
18
|
+
}
|
|
19
|
+
function buildBlobPath(sha256, ext) {
|
|
20
|
+
return ext ? `/${sha256}.${ext}` : `/${sha256}`;
|
|
21
|
+
}
|
|
22
|
+
/** Deduplicating server collector — normalizes and tracks seen servers */
|
|
23
|
+
function createServerCollector(path) {
|
|
24
|
+
const seen = new Set();
|
|
25
|
+
return {
|
|
26
|
+
get size() {
|
|
27
|
+
return seen.size;
|
|
28
|
+
},
|
|
29
|
+
add(sources) {
|
|
30
|
+
const urls = [];
|
|
31
|
+
for (const server of sources) {
|
|
32
|
+
const normalized = normalizeServer(server);
|
|
33
|
+
if (!seen.has(normalized)) {
|
|
34
|
+
seen.add(normalized);
|
|
35
|
+
urls.push(normalized + path);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return urls;
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Returns an ordered list of URLs for a blob without fetching anything.
|
|
44
|
+
* Resolves servers from xs hints, author hints (via getServers callback), and fallback servers.
|
|
45
|
+
*
|
|
46
|
+
* Accepts a blossom URI string, URL, or pre-parsed BlossomURI.
|
|
47
|
+
*/
|
|
48
|
+
export async function getBlobUrls(uri, opts) {
|
|
49
|
+
const parsed = parseInput(uri);
|
|
50
|
+
const collector = createServerCollector(buildBlobPath(parsed.sha256, parsed.ext));
|
|
51
|
+
const urls = [];
|
|
52
|
+
// 1. xs server hints (synchronous)
|
|
53
|
+
urls.push(...collector.add(parsed.servers));
|
|
54
|
+
// 2. author hints (async — requires relay queries)
|
|
55
|
+
if (opts?.getServers) {
|
|
56
|
+
for (const pubkey of parsed.authors) {
|
|
57
|
+
const authorServers = await opts.getServers(pubkey);
|
|
58
|
+
if (authorServers)
|
|
59
|
+
urls.push(...collector.add(authorServers));
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
// 3. fallback servers
|
|
63
|
+
if (opts?.fallbackServers)
|
|
64
|
+
urls.push(...collector.add(opts.fallbackServers));
|
|
65
|
+
return urls;
|
|
66
|
+
}
|
|
67
|
+
/** Resolves a blossom URI to a downloaded blob by trying servers from hints sequentially */
|
|
68
|
+
export async function resolveBlob(uri, opts) {
|
|
69
|
+
const parsed = parseInput(uri);
|
|
70
|
+
const collector = createServerCollector(buildBlobPath(parsed.sha256, parsed.ext));
|
|
71
|
+
/** Try GET on each URL, return the first successful response */
|
|
72
|
+
const tryUrls = async (urls) => {
|
|
73
|
+
for (const url of urls) {
|
|
74
|
+
try {
|
|
75
|
+
const res = await fetchWithTimeout(new URL(url), {
|
|
76
|
+
signal: opts?.signal,
|
|
77
|
+
timeout: opts?.timeout,
|
|
78
|
+
});
|
|
79
|
+
if (res.ok)
|
|
80
|
+
return res;
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
// server unreachable or error — try next
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return undefined;
|
|
88
|
+
};
|
|
89
|
+
// 1. try xs server hints first (fastest — no async resolution needed)
|
|
90
|
+
const xsUrls = collector.add(parsed.servers);
|
|
91
|
+
if (xsUrls.length > 0) {
|
|
92
|
+
const result = await tryUrls(xsUrls);
|
|
93
|
+
if (result)
|
|
94
|
+
return result;
|
|
95
|
+
}
|
|
96
|
+
// 2. resolve and try author hints (deferred — requires relay queries)
|
|
97
|
+
if (opts?.getServers) {
|
|
98
|
+
for (const pubkey of parsed.authors) {
|
|
99
|
+
const authorServers = await opts.getServers(pubkey);
|
|
100
|
+
if (authorServers) {
|
|
101
|
+
const urls = collector.add(authorServers);
|
|
102
|
+
if (urls.length > 0) {
|
|
103
|
+
const result = await tryUrls(urls);
|
|
104
|
+
if (result)
|
|
105
|
+
return result;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
// 3. try fallback servers
|
|
111
|
+
if (opts?.fallbackServers) {
|
|
112
|
+
const urls = collector.add(opts.fallbackServers);
|
|
113
|
+
if (urls.length > 0) {
|
|
114
|
+
const result = await tryUrls(urls);
|
|
115
|
+
if (result)
|
|
116
|
+
return result;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (collector.size === 0) {
|
|
120
|
+
throw new Error("No servers available to resolve blossom URI");
|
|
121
|
+
}
|
|
122
|
+
throw new Error(`Blob ${parsed.sha256} not found on any server`);
|
|
123
|
+
}
|
|
124
|
+
/** Resolves a blossom URI and returns a blob: object URL that works anywhere a URL string is accepted */
|
|
125
|
+
export async function resolveToObjectURL(uri, opts) {
|
|
126
|
+
const response = await resolveBlob(uri, opts);
|
|
127
|
+
const blob = await response.blob();
|
|
128
|
+
return URL.createObjectURL(blob);
|
|
129
|
+
}
|
package/lib/actions/upload.d.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
|
-
import { ServerType, UploadType } from "../
|
|
1
|
+
import { ServerType, UploadType } from "../types.js";
|
|
2
2
|
import { BlobDescriptor, PaymentRequest, PaymentToken, SignedEvent } from "../types.js";
|
|
3
3
|
export type UploadOptions<S extends ServerType, B extends UploadType> = {
|
|
4
4
|
/** AbortSignal to cancel the action */
|
|
5
5
|
signal?: AbortSignal;
|
|
6
6
|
/** Override authorization event, or true to always use authorization, false to disable authorization */
|
|
7
7
|
auth?: SignedEvent | boolean;
|
|
8
|
+
/** Shared auth event store used to reuse non-expired auth events between requests */
|
|
9
|
+
authEvents?: Set<SignedEvent>;
|
|
8
10
|
/** Request timeout */
|
|
9
11
|
timeout?: number;
|
|
10
12
|
/**
|
package/lib/actions/upload.js
CHANGED
|
@@ -1,19 +1,30 @@
|
|
|
1
|
-
import { encodeAuthorizationHeader } from "../auth.js";
|
|
1
|
+
import { encodeAuthorizationHeader, getReusableAuthEvent, storeAuthEvent } from "../auth.js";
|
|
2
2
|
import HTTPError from "../error.js";
|
|
3
3
|
import { fetchWithTimeout, getBlobSha256, getBlobSize, getBlobType } from "../helpers/index.js";
|
|
4
4
|
/** Upload a blob to a server, handles payment and auth */
|
|
5
5
|
export async function uploadBlob(server, blob, opts) {
|
|
6
6
|
const url = new URL("/upload", server);
|
|
7
7
|
const sha256 = await getBlobSha256(blob);
|
|
8
|
+
const resolveAuth = async (preset = false) => {
|
|
9
|
+
const reused = opts?.authEvents
|
|
10
|
+
? await getReusableAuthEvent(opts.authEvents, { server, type: "upload", blob: sha256 })
|
|
11
|
+
: undefined;
|
|
12
|
+
if (reused)
|
|
13
|
+
return reused;
|
|
14
|
+
const auth = await opts?.onAuth?.(server, sha256, "upload", blob);
|
|
15
|
+
if (!auth)
|
|
16
|
+
throw new Error(preset ? "Missing onAuth handler" : "Missing auth handler");
|
|
17
|
+
if (opts?.authEvents)
|
|
18
|
+
storeAuthEvent(opts.authEvents, auth);
|
|
19
|
+
return auth;
|
|
20
|
+
};
|
|
8
21
|
const headers = {
|
|
9
22
|
"X-SHA-256": sha256,
|
|
10
23
|
};
|
|
11
24
|
// attach the authorization if its already set
|
|
12
25
|
if (opts?.auth) {
|
|
13
26
|
if (typeof opts.auth === "boolean") {
|
|
14
|
-
|
|
15
|
-
throw new Error("Missing onAuth handler");
|
|
16
|
-
headers["Authorization"] = encodeAuthorizationHeader(await opts.onAuth(server, sha256, "upload", blob));
|
|
27
|
+
headers["Authorization"] = encodeAuthorizationHeader(await resolveAuth(true));
|
|
17
28
|
}
|
|
18
29
|
else {
|
|
19
30
|
headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
|
|
@@ -51,9 +62,7 @@ export async function uploadBlob(server, blob, opts) {
|
|
|
51
62
|
if (opts?.auth === false)
|
|
52
63
|
throw new Error("Authorization disabled");
|
|
53
64
|
// Request authorization event for this upload
|
|
54
|
-
const auth = await
|
|
55
|
-
if (!auth)
|
|
56
|
-
throw new Error("Missing auth handler");
|
|
65
|
+
const auth = await resolveAuth();
|
|
57
66
|
// Try upload with auth
|
|
58
67
|
upload = await fetchWithTimeout(url, {
|
|
59
68
|
method: "PUT",
|
package/lib/auth.d.ts
CHANGED
|
@@ -1,11 +1,30 @@
|
|
|
1
|
-
import { ServerType, UploadType } from "./
|
|
1
|
+
import { ServerType, UploadType } from "./types.js";
|
|
2
2
|
import { SignedEvent, Signer } from "./types.js";
|
|
3
3
|
export declare const now: () => number;
|
|
4
4
|
export declare const oneHour: () => number;
|
|
5
|
+
export type AuthRequest = {
|
|
6
|
+
server: ServerType;
|
|
7
|
+
type: AuthType;
|
|
8
|
+
blob?: string | UploadType;
|
|
9
|
+
};
|
|
5
10
|
/** Encodes an auth event into a nostr authorization header */
|
|
6
11
|
export declare function encodeAuthorizationHeader(event: SignedEvent): string;
|
|
7
12
|
/** Checks if an auth event matches a server / blob upload */
|
|
8
13
|
export declare function doseAuthMatchBlob(auth: SignedEvent, server: ServerType, blob: string | UploadType, type?: string): Promise<boolean>;
|
|
14
|
+
/** Returns all tag values for a specific tag name */
|
|
15
|
+
export declare function getAuthTagValues(auth: SignedEvent, tagName: string): string[];
|
|
16
|
+
/** Returns the auth event expiration timestamp if one exists */
|
|
17
|
+
export declare function getAuthExpiration(auth: SignedEvent): number | undefined;
|
|
18
|
+
/** Returns true if an auth event has expired */
|
|
19
|
+
export declare function isAuthExpired(auth: SignedEvent, timestamp?: number): boolean;
|
|
20
|
+
/** Normalizes a server tag value to a lowercase hostname */
|
|
21
|
+
export declare function normalizeServerTag(server: string | URL): string;
|
|
22
|
+
/** Checks if an auth event can be reused for a request */
|
|
23
|
+
export declare function doesAuthMatchRequest(auth: SignedEvent, request: AuthRequest): Promise<boolean>;
|
|
24
|
+
/** Finds a reusable auth event in a store and prunes expired events */
|
|
25
|
+
export declare function getReusableAuthEvent(authEvents: Set<SignedEvent>, request: AuthRequest): Promise<SignedEvent | undefined>;
|
|
26
|
+
/** Stores a new auth event in the shared store */
|
|
27
|
+
export declare function storeAuthEvent(authEvents: Set<SignedEvent>, auth: SignedEvent): SignedEvent;
|
|
9
28
|
/** @deprecated Use `doseAuthMatchBlob` instead */
|
|
10
29
|
export declare const doseAuthMatchUpload: typeof doseAuthMatchBlob;
|
|
11
30
|
export type AuthType = "upload" | "list" | "delete" | "get" | "media";
|