blossom-client-sdk 3.0.0 → 4.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.
Files changed (47) hide show
  1. package/lib/actions/delete.d.ts +2 -3
  2. package/lib/actions/delete.js +2 -2
  3. package/lib/actions/download.d.ts +2 -3
  4. package/lib/actions/download.js +2 -1
  5. package/lib/actions/list.d.ts +2 -3
  6. package/lib/actions/list.js +9 -4
  7. package/lib/actions/media.js +2 -1
  8. package/lib/actions/mirror.d.ts +2 -3
  9. package/lib/actions/mirror.js +6 -4
  10. package/lib/actions/multi-server.js +1 -1
  11. package/lib/actions/upload.d.ts +2 -3
  12. package/lib/actions/upload.js +3 -2
  13. package/lib/auth.d.ts +1 -0
  14. package/lib/auth.js +13 -5
  15. package/lib/helpers/blob.d.ts +2 -0
  16. package/lib/helpers/blob.js +8 -5
  17. package/lib/helpers/cashu.js +14 -0
  18. package/lib/helpers/index.d.ts +1 -1
  19. package/lib/helpers/index.js +1 -1
  20. package/lib/helpers/signal.js +1 -1
  21. package/lib/image.js +25 -11
  22. package/lib/types.d.ts +20 -4
  23. package/package.json +18 -17
  24. package/src/actions/delete.ts +85 -0
  25. package/src/actions/download.ts +84 -0
  26. package/src/actions/index.ts +7 -0
  27. package/src/actions/list.ts +83 -0
  28. package/src/actions/media.ts +102 -0
  29. package/src/actions/mirror.ts +99 -0
  30. package/src/actions/multi-server.ts +207 -0
  31. package/src/actions/upload.ts +129 -0
  32. package/src/auth.ts +137 -0
  33. package/src/client.ts +221 -0
  34. package/src/const.ts +1 -0
  35. package/src/error.ts +23 -0
  36. package/src/helpers/blob.ts +62 -0
  37. package/src/helpers/cashu.ts +21 -0
  38. package/src/helpers/fetch.ts +16 -0
  39. package/src/helpers/index.ts +5 -0
  40. package/src/helpers/signal.ts +20 -0
  41. package/src/helpers/url.ts +16 -0
  42. package/src/image.ts +122 -0
  43. package/src/index.ts +9 -0
  44. package/src/nostr.ts +17 -0
  45. package/src/types.ts +63 -0
  46. package/lib/helpers/cachu.js +0 -6
  47. /package/lib/helpers/{cachu.d.ts → cashu.d.ts} +0 -0
@@ -0,0 +1,84 @@
1
+ import { ServerType } from "../client.js";
2
+ import { PaymentRequest, PaymentToken, SignedEvent } from "../types.js";
3
+ import HTTPError from "../error.js";
4
+ import { encodeAuthorizationHeader } from "../auth.js";
5
+ import { fetchWithTimeout } from "../helpers/index.js";
6
+
7
+ export type DownloadOptions<S extends ServerType> = {
8
+ /** AbortSignal to cancel the action */
9
+ signal?: AbortSignal;
10
+ /** Override auth event to use */
11
+ auth?: SignedEvent;
12
+ /** Request timeout */
13
+ timeout?: number;
14
+ /**
15
+ * A method used to request payment when downloading
16
+ * @param server the server requiring payment
17
+ * @param sha256 the sha256 of the blob being uploaded or mirrored
18
+ * @param request the payment request
19
+ */
20
+ onPayment?: (server: S, sha256: string, request: PaymentRequest) => Promise<PaymentToken>;
21
+ /**
22
+ * A method used to request a signed auth event for a server and sha256
23
+ * @param server the server requesting the auth
24
+ * @param sha256 the sha256 of the blob being upload or mirror to the server
25
+ */
26
+ onAuth?: (server: S, sha256: string) => Promise<SignedEvent>;
27
+ };
28
+
29
+ /** Downloads a blob from a server and returns the Response */
30
+ export async function downloadBlob<S extends ServerType>(server: S, hash: string, opts?: DownloadOptions<S>) {
31
+ const url = new URL("/" + hash, server);
32
+
33
+ const headers: HeadersInit = {};
34
+
35
+ // attach the auth if its already set
36
+ if (opts?.auth) headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
37
+
38
+ let download = await fetchWithTimeout(url, {
39
+ headers,
40
+ signal: opts?.signal,
41
+ timeout: opts?.timeout,
42
+ });
43
+
44
+ // handle auth and payment
45
+ switch (download.status) {
46
+ case 401: {
47
+ const auth = opts?.auth || (await opts?.onAuth?.(server, hash));
48
+ if (!auth) throw new Error("Missing auth handler");
49
+
50
+ // Try download with auth
51
+ download = await fetchWithTimeout(url, {
52
+ headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
53
+ signal: opts?.signal,
54
+ timeout: opts?.timeout,
55
+ });
56
+
57
+ break;
58
+ }
59
+ case 402: {
60
+ if (!opts?.onPayment) throw new Error("Missing payment handler");
61
+ const { getEncodedToken } = await import("@cashu/cashu-ts");
62
+ const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
63
+ const request = getPaymentRequestFromHeaders(download.headers);
64
+
65
+ const token = await opts.onPayment(server, hash, request);
66
+ const payment = getEncodedToken(token);
67
+
68
+ // Try download with payment
69
+ download = await fetchWithTimeout(url, {
70
+ headers: { ...headers, "X-Cashu": payment },
71
+ signal: opts?.signal,
72
+ timeout: opts?.timeout,
73
+ });
74
+
75
+ break;
76
+ }
77
+ }
78
+
79
+ // check download errors
80
+ await HTTPError.handleErrorResponse(download);
81
+
82
+ // return the raw response
83
+ return download;
84
+ }
@@ -0,0 +1,7 @@
1
+ export * from "./upload.js";
2
+ export * from "./mirror.js";
3
+ export * from "./list.js";
4
+ export * from "./delete.js";
5
+ export * from "./download.js";
6
+ export * from "./multi-server.js";
7
+ export * from "./media.js";
@@ -0,0 +1,83 @@
1
+ import HTTPError from "../error.js";
2
+ import { ServerType } from "../client.js";
3
+ import { BlobDescriptor, PaymentRequest, PaymentToken, SignedEvent } from "../types.js";
4
+ import { encodeAuthorizationHeader } from "../auth.js";
5
+ import { fetchWithTimeout } from "../helpers/index.js";
6
+
7
+ export type ListOptions<S extends ServerType> = {
8
+ /** AbortSignal to cancel the action */
9
+ signal?: AbortSignal;
10
+ /** Override auth event to use */
11
+ auth?: SignedEvent;
12
+ /** Request timeout */
13
+ timeout?: number;
14
+ since?: number;
15
+ until?: number;
16
+ /**
17
+ * A method used to request payment
18
+ * @param server the server requiring payment
19
+ * @param request the payment request
20
+ */
21
+ onPayment?: (server: S, request: PaymentRequest) => Promise<PaymentToken>;
22
+ /**
23
+ * A method used to request a signed auth event for a server
24
+ * @param server the server requesting the auth
25
+ */
26
+ onAuth?: (server: S) => Promise<SignedEvent>;
27
+ };
28
+
29
+ /** Mirrors a blob to a server */
30
+ export async function listBlobs<S extends ServerType>(
31
+ server: S,
32
+ pubkey: string,
33
+ opts?: ListOptions<S>,
34
+ ): Promise<BlobDescriptor[]> {
35
+ const url = new URL(`/list/` + pubkey, server);
36
+ if (opts?.since) url.searchParams.append("since", String(opts.since));
37
+ if (opts?.until) url.searchParams.append("until", String(opts.until));
38
+
39
+ // attach the auth if its already set
40
+ const headers: HeadersInit = {};
41
+ if (opts?.auth) headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
42
+
43
+ let list = await fetchWithTimeout(url, { headers, signal: opts?.signal, timeout: opts?.timeout });
44
+
45
+ // handle auth and payments
46
+ switch (list.status) {
47
+ case 401: {
48
+ const auth = opts?.auth || (await opts?.onAuth?.(server));
49
+ if (!auth) throw new Error("Missing auth handler");
50
+
51
+ // Try list with auth
52
+ list = await fetchWithTimeout(url, {
53
+ headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
54
+ signal: opts?.signal,
55
+ timeout: opts?.timeout,
56
+ });
57
+ break;
58
+ }
59
+ case 402: {
60
+ if (!opts?.onPayment) throw new Error("Missing payment handler");
61
+ const { getEncodedToken } = await import("@cashu/cashu-ts");
62
+ const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
63
+ const request = getPaymentRequestFromHeaders(list.headers);
64
+
65
+ const token = await opts.onPayment(server, request);
66
+ const payment = getEncodedToken(token);
67
+
68
+ // Try list with payment
69
+ list = await fetchWithTimeout(url, {
70
+ headers: { ...headers, "X-Cashu": payment },
71
+ signal: opts?.signal,
72
+ timeout: opts?.timeout,
73
+ });
74
+ break;
75
+ }
76
+ }
77
+
78
+ // handle errors
79
+ await HTTPError.handleErrorResponse(list);
80
+
81
+ // return blob descriptor
82
+ return list.json();
83
+ }
@@ -0,0 +1,102 @@
1
+ import { ServerType, UploadType } from "../client.js";
2
+ import { BlobDescriptor } from "../types.js";
3
+ import { getBlobSha256, getBlobSize, getBlobType } from "../helpers/index.js";
4
+ import HTTPError from "../error.js";
5
+ import { encodeAuthorizationHeader } from "../auth.js";
6
+ import { UploadOptions } from "./upload.js";
7
+
8
+ /** Error thrown when /media endpoint is not present on a server */
9
+ export class MediaEndpointMissingError extends Error {}
10
+
11
+ export type UploadMediaOptions<S extends ServerType, B extends UploadType> = UploadOptions<S, B>;
12
+
13
+ /** Upload a media blob to a server using the /media endpoint, handles payment and auth */
14
+ export async function uploadMedia<S extends ServerType, B extends UploadType>(
15
+ server: S,
16
+ blob: B,
17
+ opts?: UploadMediaOptions<S, B>,
18
+ ): Promise<BlobDescriptor> {
19
+ const url = new URL("/media", server);
20
+ const sha256 = await getBlobSha256(blob);
21
+
22
+ const headers: Record<string, string> = {
23
+ "X-SHA-256": sha256,
24
+ };
25
+
26
+ // attach the auth if its already set
27
+ if (opts?.auth) headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
28
+
29
+ // build check headers
30
+ const checkHeaders: Record<string, string> = {
31
+ ...headers,
32
+ "X-Content-Length": String(getBlobSize(blob)),
33
+ };
34
+ const type = getBlobType(blob);
35
+ if (type) checkHeaders["X-Content-Type"] = type;
36
+
37
+ // check upload with HEAD /media
38
+ let firstTry = await fetch(url, {
39
+ method: "HEAD",
40
+ signal: opts?.signal,
41
+ headers: checkHeaders,
42
+ });
43
+
44
+ let upload: Response | undefined = undefined;
45
+
46
+ if (firstTry.status === 404) {
47
+ // HEAD endpoint is not supported. abort
48
+ throw new MediaEndpointMissingError("/media endpoint not supported");
49
+ }
50
+
51
+ // handle auth and payment
52
+ switch (firstTry.status) {
53
+ case 401: {
54
+ const auth = opts?.auth || (await opts?.onAuth?.(server, sha256, "media", blob));
55
+ if (!auth) throw new Error("Missing auth handler");
56
+
57
+ // Try upload with auth
58
+ upload = await fetch(url, {
59
+ signal: opts?.signal,
60
+ method: "PUT",
61
+ body: blob,
62
+ headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
63
+ });
64
+ break;
65
+ }
66
+ case 402: {
67
+ if (!opts?.onPayment) throw new Error("Missing payment handler");
68
+ const { getEncodedToken } = await import("@cashu/cashu-ts");
69
+ const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
70
+ const request = getPaymentRequestFromHeaders(firstTry.headers);
71
+
72
+ const token = await opts.onPayment(server, sha256, blob, request);
73
+ const payment = getEncodedToken(token);
74
+
75
+ // Try upload with payment
76
+ upload = await fetch(url, {
77
+ signal: opts?.signal,
78
+ method: "PUT",
79
+ body: blob,
80
+ headers: { ...headers, "X-Cashu": payment },
81
+ });
82
+ break;
83
+ }
84
+ }
85
+
86
+ if (firstTry.status >= 500) throw new Error("Server error");
87
+
88
+ // check passed, upload
89
+ if (!upload)
90
+ upload = await fetch(url, {
91
+ signal: opts?.signal,
92
+ method: "PUT",
93
+ body: blob,
94
+ headers: { ...headers },
95
+ });
96
+
97
+ // handle errors
98
+ await HTTPError.handleErrorResponse(upload);
99
+
100
+ // return blob descriptor
101
+ return upload.json();
102
+ }
@@ -0,0 +1,99 @@
1
+ import { encodeAuthorizationHeader } from "../auth.js";
2
+ import { ServerType } from "../client.js";
3
+ import HTTPError from "../error.js";
4
+ import { fetchWithTimeout } from "../helpers/index.js";
5
+ import { BlobDescriptor, PaymentRequest, PaymentToken, SignedEvent } from "../types.js";
6
+
7
+ export type MirrorOptions<S extends ServerType> = {
8
+ /** AbortSignal to cancel the action */
9
+ signal?: AbortSignal;
10
+ /** Override auth event to use */
11
+ auth?: SignedEvent;
12
+ /** Request timeout */
13
+ timeout?: number;
14
+ /**
15
+ * A method used to request payment when uploading or mirroring a blob
16
+ * @param server the server requiring payment
17
+ * @param sha256 the sha256 of the blob being uploaded or mirrored
18
+ * @param blob the original blob
19
+ * @param request the payment request
20
+ */
21
+ onPayment?: (server: S, sha256: string, blob: BlobDescriptor, request: PaymentRequest) => Promise<PaymentToken>;
22
+ /**
23
+ * A method used to request a signed auth event for a server and sha256
24
+ * @param server the server requesting the auth
25
+ * @param sha256 the sha256 of the blob being upload or mirror to the server
26
+ * @param blob the original blob passed to the method
27
+ */
28
+ onAuth?: (server: S, sha256: string, blob: BlobDescriptor) => Promise<SignedEvent>;
29
+ };
30
+
31
+ /** Mirrors a blob to a server */
32
+ export async function mirrorBlob<S extends ServerType>(
33
+ server: S,
34
+ blob: BlobDescriptor,
35
+ opts?: MirrorOptions<S>,
36
+ ): Promise<BlobDescriptor> {
37
+ const url = new URL("/mirror", server);
38
+
39
+ const headers: Record<string, string> = {
40
+ "X-SHA-256": blob.sha256,
41
+ "X-Content-Length": String(blob.size),
42
+ "Content-Type": "application/json",
43
+ };
44
+ if (blob.type) headers["X-Content-Type"] = blob.type;
45
+
46
+ // attach the auth if its already set
47
+ if (opts?.auth) headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
48
+
49
+ const body = JSON.stringify({ url: blob.url });
50
+ let mirror = await fetchWithTimeout(url, {
51
+ method: "PUT",
52
+ signal: opts?.signal,
53
+ headers,
54
+ body,
55
+ timeout: opts?.timeout,
56
+ });
57
+
58
+ switch (mirror.status) {
59
+ case 401: {
60
+ const auth = opts?.auth || (await opts?.onAuth?.(server, blob.sha256, blob));
61
+ if (!auth) throw new Error("Missing auth handler");
62
+
63
+ // Try mirror with auth
64
+ mirror = await fetchWithTimeout(url, {
65
+ signal: opts?.signal,
66
+ method: "PUT",
67
+ body,
68
+ headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
69
+ timeout: opts?.timeout,
70
+ });
71
+ break;
72
+ }
73
+ case 402: {
74
+ if (!opts?.onPayment) throw new Error("Missing payment handler");
75
+ const { getEncodedToken } = await import("@cashu/cashu-ts");
76
+ const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
77
+ const request = getPaymentRequestFromHeaders(mirror.headers);
78
+
79
+ const token = await opts.onPayment(server, blob.sha256, blob, request);
80
+ const payment = getEncodedToken(token);
81
+
82
+ // Try mirror with payment
83
+ mirror = await fetchWithTimeout(url, {
84
+ signal: opts?.signal,
85
+ method: "PUT",
86
+ body,
87
+ headers: { ...headers, "X-Cashu": payment },
88
+ timeout: opts?.timeout,
89
+ });
90
+ break;
91
+ }
92
+ }
93
+
94
+ // handle errors
95
+ await HTTPError.handleErrorResponse(mirror);
96
+
97
+ // return blob descriptor
98
+ return mirror.json();
99
+ }
@@ -0,0 +1,207 @@
1
+ import { doseAuthMatchUpload } from "../auth.js";
2
+ import { ServerType, UploadType } from "../client.js";
3
+ import { getBlobSha256 } from "../helpers/index.js";
4
+ import { BlobDescriptor, PaymentRequest } from "../types.js";
5
+ import { MediaEndpointMissingError, uploadMedia } from "./media.js";
6
+ import { mirrorBlob } from "./mirror.js";
7
+ import { uploadBlob, UploadOptions } from "./upload.js";
8
+
9
+ export type MultiServerUploadOptions<S extends ServerType, B extends UploadType> = UploadOptions<S, B> & {
10
+ /**
11
+ * Signals this blob should be treated as a media file and should attempt to use BUD-05 /media endpoint for upload on first server
12
+ * @default false
13
+ */
14
+ isMedia?: boolean;
15
+ /**
16
+ * If isMedia is enabled, this determines how /media endpoints should be prioritized
17
+ * - "first" Only use the first server in the list to optimize the media
18
+ * - "any" Use any server in the list to optimize the media
19
+ * @default "first"
20
+ */
21
+ mediaUploadBehavior?: "first" | "any";
22
+ /**
23
+ * If isMedia is enabled, should the raw blob be uploaded if no /media endpoint can be found
24
+ * @default false
25
+ */
26
+ mediaUploadFallback?: boolean;
27
+ /**
28
+ * Timeout for mirror requests
29
+ * @default 5000
30
+ */
31
+ mirrorTimeout?: number;
32
+ /**
33
+ * called on blob when uploaded to started to a server
34
+ * @param server
35
+ * @param sha256 the hash of the blob being uploaded or mirrored
36
+ * @param blob the original blob
37
+ */
38
+ onStart?: (server: S, sha256: string, blob: B) => void;
39
+ /** called when upload to a server is complete */
40
+ onUpload?: (server: S, sha256: string, blob: B) => void;
41
+ /** called when upload to a server fails */
42
+ onError?: (server: S, sha256: string, blob: B, error: Error) => void;
43
+ };
44
+
45
+ const defaultMultiServerOptions: MultiServerUploadOptions<any, any> = {
46
+ isMedia: false,
47
+ mediaUploadBehavior: "first",
48
+ mediaUploadFallback: false,
49
+ mirrorTimeout: 5000,
50
+ };
51
+
52
+ /**
53
+ * Creates an AsyncGenerator that can be used to upload a blob to multiple servers
54
+ * @param servers A Set or Array of servers to upload to
55
+ * @param blob The blob to be uploaded
56
+ * @param signer An async function used for signing nostr events
57
+ * @returns The BlobDescriptor if successful
58
+ *
59
+ * ```mermaid
60
+ * flowchart LR
61
+ * isMedia{"isMedia"} -- yes --> media["/media"]
62
+ * isMedia -- no --> upload["/upload"]
63
+ * media --> ifmedia{"Successful"}
64
+ * ifmedia -- yes --> next["Next server"]
65
+ * ifmedia -- no --> iffallback{"fallback"}
66
+ * iffallback -- yes --> upload
67
+ * iffallback -- no --> abort
68
+ * upload -- complete --> next
69
+ * next --> uploaded{"Uploaded"}
70
+ * uploaded -- yes --> mirror["/mirror"]
71
+ * uploaded -- no --> upload
72
+ * mirror --> isMirror{"Successful"}
73
+ * isMirror -- yes --> next
74
+ * isMirror -- no --> ifMediaAbort{"isMedia"}
75
+ * ifMediaAbort -- no --> upload
76
+ * ifMediaAbort -- yes --> next
77
+ * ```
78
+ */
79
+ export async function multiServerUpload<S extends ServerType, B extends UploadType>(
80
+ servers: Iterable<S>,
81
+ blob: B,
82
+ opts?: MultiServerUploadOptions<S, B>,
83
+ ) {
84
+ const options = { ...defaultMultiServerOptions, ...opts };
85
+ let initialUpload: BlobDescriptor | undefined;
86
+ const results = new Map<S, BlobDescriptor>();
87
+
88
+ // reuse auth events
89
+ let authEvents = options.auth ? [options.auth] : [];
90
+ const handleAuthRequest = async (server: S, sha256: string, type: "upload" | "media") => {
91
+ // check if any existing auth events match
92
+ for (const auth of authEvents) {
93
+ if (await doseAuthMatchUpload(auth, server, sha256)) return auth;
94
+ }
95
+
96
+ // create a new auth event
97
+ if (options.onAuth) {
98
+ const auth = await options.onAuth(server, sha256, type, blob);
99
+ authEvents.push(auth);
100
+ return auth;
101
+ } else throw new Error("Missing onAuth handler");
102
+ };
103
+
104
+ // handle payment requests for servers
105
+ const handlePaymentRequest = async (server: S, sha256: string, _blog: any, request: PaymentRequest) => {
106
+ if (!options.onPayment) throw new Error("Missing payment handler");
107
+
108
+ return options.onPayment(server, sha256, blob, request);
109
+ };
110
+
111
+ // servers to upload the blob to
112
+ const uploadServers = Array.from(servers);
113
+
114
+ // start media upload
115
+ if (options.isMedia) {
116
+ const mediaServers = options.mediaUploadBehavior === "any" ? Array.from(servers) : [Array.from(servers)[0]];
117
+
118
+ for (const server of mediaServers) {
119
+ try {
120
+ const sha256 = await getBlobSha256(blob);
121
+ options.onStart?.(server, sha256, blob);
122
+
123
+ // attempt to upload media
124
+ initialUpload = await uploadMedia(server, blob, {
125
+ onAuth: handleAuthRequest,
126
+ onPayment: handlePaymentRequest,
127
+ });
128
+
129
+ // save result
130
+ results.set(server, initialUpload);
131
+
132
+ // finished upload to server
133
+ options.onUpload?.(server, initialUpload.sha256, blob);
134
+ } catch (error) {
135
+ if (error instanceof MediaEndpointMissingError) {
136
+ // ignore error
137
+ } else if (error instanceof Error) {
138
+ const sha256 = await getBlobSha256(blob);
139
+ options.onError?.(server, sha256, blob, error);
140
+ }
141
+ }
142
+
143
+ if (initialUpload) {
144
+ // remove server from upload array
145
+ if (uploadServers.includes(server)) uploadServers.splice(uploadServers.indexOf(server), 1);
146
+
147
+ // exit on first successful media upload
148
+ break;
149
+ }
150
+ }
151
+
152
+ if (!options.mediaUploadFallback && !initialUpload) {
153
+ // failed to find a /media endpoint, abort
154
+ throw new Error("Failed to find media processing endpoint");
155
+ }
156
+ }
157
+
158
+ // start server uploads
159
+ for (const server of uploadServers) {
160
+ try {
161
+ let metadata: BlobDescriptor | undefined = undefined;
162
+
163
+ // attempt to mirror the initial upload
164
+ if (initialUpload) {
165
+ try {
166
+ options.onStart?.(server, initialUpload.sha256, blob);
167
+
168
+ metadata = await mirrorBlob(server, initialUpload, {
169
+ signal: options.signal,
170
+ onAuth: (server, sha256) => handleAuthRequest(server, sha256, "upload"),
171
+ onPayment: handlePaymentRequest,
172
+ timeout: options.mirrorTimeout,
173
+ });
174
+ } catch (error) {
175
+ // mirror failed, if isMedia skip server since we don't want to upload two versions of the blob
176
+ if (options.isMedia) continue;
177
+ }
178
+ }
179
+
180
+ // attempt to upload if first upload or mirror failed
181
+ if (!metadata) {
182
+ const sha256 = await getBlobSha256(blob);
183
+ options.onStart?.(server, sha256, blob);
184
+
185
+ metadata = await uploadBlob(server, blob, {
186
+ onAuth: handleAuthRequest,
187
+ onPayment: handlePaymentRequest,
188
+ timeout: options.mirrorTimeout,
189
+ });
190
+
191
+ // save first upload
192
+ if (!initialUpload) initialUpload = metadata;
193
+ }
194
+
195
+ // save result
196
+ results.set(server, metadata);
197
+
198
+ // finished upload to server
199
+ options.onUpload?.(server, metadata.sha256, blob);
200
+ } catch (error) {
201
+ // failed to upload to server
202
+ if (error instanceof Error) options.onError?.(server, await getBlobSha256(blob), blob, error);
203
+ }
204
+ }
205
+
206
+ return results;
207
+ }