blossom-client-sdk 5.1.0 → 5.2.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 CHANGED
@@ -4,10 +4,60 @@ A client for managing blobs on blossom servers
4
4
 
5
5
  [Documentation](https://hzrd149.github.io/blossom-client-sdk/)
6
6
 
7
+ ## Testing
8
+
9
+ Install dependencies with `pnpm install --frozen-lockfile`.
10
+
11
+ - `pnpm test`: the Node Vitest suite.
12
+ - `pnpm test:browser`: the Vitest suite, including DOM/media tests, in headless Chromium, Firefox, and WebKit.
13
+ Install browsers first with `pnpm exec playwright install --with-deps`.
14
+ To run one browser, append `--browser.name=chromium` (or `firefox` / `webkit`).
15
+ - `pnpm test:node`, `pnpm test:deno`, `pnpm test:bun`: build the package and run the **same full Vitest suite**
16
+ in the selected runtime, followed by the same built-package export and HTTP integration tests.
17
+ Install Deno 2 or Bun for their respective commands. Worker runtime checks prevent accidental fallback to Node.
18
+ DOM-only tests run in browsers; Buffer-only tests run in server runtimes.
19
+ Deno needs `-A` for Vitest's workers, module loading, and local servers. TypeScript is checked during the build.
20
+ - `pnpm test:all`: run all of the above (requires all runtimes and browsers).
21
+
22
+ GitHub Actions runs the full suite across supported Node versions, Deno 2, the latest Bun, and all three browser engines.
23
+
24
+ ### ngit CI
25
+
26
+ The native [ngit CI workflow](https://ngit.dev/ci/workflows/) is `.grasp/nix/workflows/ci.yaml`.
27
+ It runs the same scripts in six independent jobs: Node 22, Deno, Bun, Chromium, Firefox, and WebKit.
28
+ The root `flake.lock` pins the Nix toolchain; `pnpm-lock.yaml` pins JavaScript dependencies and Playwright browser revisions.
29
+ Jobs require an x86_64 Linux provider with network access for package/browser downloads and support for
30
+ Bubblewrap's FHS environment (user namespaces). No repository secrets are needed.
31
+
32
+ With Nix flakes enabled, validate and run commands locally from this checkout:
33
+
34
+ ```sh
35
+ nix flake check --no-build
36
+ nix run .#install
37
+ nix run .#node
38
+ nix run .#deno
39
+ nix run .#bun
40
+ nix run .#chromium
41
+ nix run .#firefox
42
+ nix run .#webkit
43
+ ```
44
+
45
+ A maintainer must arrange a coordinator/provider and authorize the coordinator before automatic runs:
46
+
47
+ ```sh
48
+ ngit ci request <coordinator-npub>
49
+ # After publishing the committed workflow to the repository:
50
+ ngit ci trigger <coordinator-npub> HEAD --workflow .grasp/nix/workflows/ci.yaml
51
+ ngit ci status HEAD --json --require-ci-trust maintainer-directed
52
+ ```
53
+
54
+ The workflow responds to pushes and pull requests targeting `master`. Adding it alone does not activate a hosted CI service.
55
+
7
56
  ## Basic Usage
8
57
 
9
58
  ```js
10
- import { uploadBlob, createUploadAuth, encodeAuthorizationHeader } from "blossom-client-sdk";
59
+ import { createUploadAuth, encodeAuthorizationHeader } from "blossom-client-sdk";
60
+ import { uploadBlob } from "blossom-client-sdk/actions";
11
61
 
12
62
  async function signer(event) {
13
63
  return await window.nostr.signEvent(event);
@@ -230,7 +280,8 @@ hls.attachMedia(videoElement);
230
280
  ### List a page of blobs on a server
231
281
 
232
282
  ```js
233
- import { listBlobs, createListAuth } from "blossom-client-sdk";
283
+ import { createListAuth } from "blossom-client-sdk";
284
+ import { listBlobs } from "blossom-client-sdk/actions";
234
285
 
235
286
  async function signer(event) {
236
287
  return await window.nostr.signEvent(event);
@@ -247,7 +298,8 @@ const blobs = await listBlobs(server, pubkey, {
247
298
  ### Iterate blob pages on a server
248
299
 
249
300
  ```js
250
- import { iterateBlobs, createListAuth } from "blossom-client-sdk/actions";
301
+ import { createListAuth } from "blossom-client-sdk";
302
+ import { iterateBlobs } from "blossom-client-sdk/actions";
251
303
 
252
304
  async function signer(event) {
253
305
  return await window.nostr.signEvent(event);
@@ -267,7 +319,8 @@ for await (const page of iterateBlobs(server, pubkey, {
267
319
  ### Upload a single blob
268
320
 
269
321
  ```js
270
- import { uploadBlob, createUploadAuth } from "blossom-client-sdk";
322
+ import { createUploadAuth } from "blossom-client-sdk";
323
+ import { uploadBlob } from "blossom-client-sdk/actions";
271
324
 
272
325
  async function signer(event) {
273
326
  return await window.nostr.signEvent(event);
@@ -283,7 +336,8 @@ const blob = await uploadBlob(server, new File(["testing"], "test.txt"), {
283
336
  ### Upload a single blob to multiple servers
284
337
 
285
338
  ```js
286
- import { uploadBlob, createUploadAuth } from "blossom-client-sdk";
339
+ import { createUploadAuth } from "blossom-client-sdk";
340
+ import { uploadBlob } from "blossom-client-sdk/actions";
287
341
 
288
342
  async function signer(event) {
289
343
  return await window.nostr.signEvent(event);
@@ -304,7 +358,8 @@ for (let server of servers) {
304
358
  The `multiServerUpload` method uploads a blob to the first server, then mirrors it to the remaining servers. It runs parallel preflight checks (`HEAD /<sha256>`) to detect which servers already have the blob, using `/mirror` to register ownership on those servers instead of re-uploading.
305
359
 
306
360
  ```ts
307
- import { multiServerUpload, createUploadAuth } from "blossom-client-sdk";
361
+ import { createUploadAuth } from "blossom-client-sdk";
362
+ import { multiServerUpload } from "blossom-client-sdk/actions";
308
363
 
309
364
  async function signer(event: any) {
310
365
  // @ts-expect-error
@@ -336,7 +391,8 @@ const results = await multiServerUpload(servers, file, {
336
391
  The `multiServerMediaUpload` method is designed for media files (images, videos) that should be optimized before distribution. It uploads the blob to a single server's BUD-05 `/media` endpoint for processing, then mirrors the optimized result to all other servers. The original unprocessed blob is never uploaded to other servers since the `/media` endpoint may transform it (resize, re-encode, etc.).
337
392
 
338
393
  ```ts
339
- import { multiServerMediaUpload, createUploadAuth } from "blossom-client-sdk";
394
+ import { createUploadAuth } from "blossom-client-sdk";
395
+ import { multiServerMediaUpload } from "blossom-client-sdk/actions";
340
396
 
341
397
  async function signer(event: any) {
342
398
  // @ts-expect-error
@@ -362,7 +418,8 @@ const results = await multiServerMediaUpload(servers, media, {
362
418
  ### Upload and Mirror manually
363
419
 
364
420
  ```js
365
- import { uploadBlob, mirrorBlob, createUploadAuth } from "blossom-client-sdk";
421
+ import { createUploadAuth } from "blossom-client-sdk";
422
+ import { uploadBlob, mirrorBlob } from "blossom-client-sdk/actions";
366
423
 
367
424
  async function signer(event) {
368
425
  return await window.nostr.signEvent(event);
@@ -1,7 +1,7 @@
1
1
  import { encodeAuthorizationHeader, getReusableAuthEvent, storeAuthEvent } from "../auth.js";
2
2
  import HTTPError from "../error.js";
3
3
  import { fetchWithTimeout } from "../helpers/fetch.js";
4
- import { mergeHeaders } from "../helpers/headers.js";
4
+ import { handleChallenges } from "../internal/challenges.js";
5
5
  /** Deletes a blob to a server */
6
6
  export async function deleteBlob(server, hash, opts) {
7
7
  const url = new URL("/" + hash, server);
@@ -28,50 +28,25 @@ export async function deleteBlob(server, hash, opts) {
28
28
  headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
29
29
  }
30
30
  }
31
- let res = await fetchWithTimeout(url, {
32
- method: "DELETE",
33
- headers,
31
+ const request = (headers) => fetchWithTimeout(url, { method: "DELETE", headers, signal: opts?.signal, timeout: opts?.timeout });
32
+ const res = await handleChallenges(await request(headers), headers, request, {
34
33
  signal: opts?.signal,
35
- timeout: opts?.timeout,
36
- });
37
- // handle auth and payment
38
- switch (res.status) {
39
- case 401: {
40
- // throw an error if authorization is required but disabled
34
+ auth: async () => {
41
35
  if (opts?.auth === false)
42
36
  throw new Error("Authorization disabled");
43
- // request authorization for this request
44
- const auth = await resolveAuth();
45
- // Try delete with auth
46
- res = await fetchWithTimeout(url, {
47
- signal: opts?.signal,
48
- method: "DELETE",
49
- headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
50
- timeout: opts?.timeout,
51
- });
52
- break;
53
- }
54
- case 402: {
55
- let paymentHeaders;
37
+ return { Authorization: encodeAuthorizationHeader(await resolveAuth()) };
38
+ },
39
+ payment: async (headers) => {
56
40
  if (opts?.onPaymentRequired)
57
- paymentHeaders = await opts.onPaymentRequired(server, hash, res.headers);
58
- else if (opts?.onPayment) {
41
+ return opts.onPaymentRequired(server, hash, headers);
42
+ if (opts?.onPayment) {
59
43
  const { encodePaymentToken, getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
60
- const request = await getPaymentRequestFromHeaders(res.headers);
61
- paymentHeaders = { "X-Cashu": encodePaymentToken(await opts.onPayment(server, hash, request)) };
44
+ const request = await getPaymentRequestFromHeaders(headers);
45
+ return { "X-Cashu": encodePaymentToken(await opts.onPayment(server, hash, request)) };
62
46
  }
63
- else
64
- throw new Error("Missing payment handler");
65
- // Try delete with payment
66
- res = await fetchWithTimeout(url, {
67
- signal: opts?.signal,
68
- method: "DELETE",
69
- headers: mergeHeaders(headers, paymentHeaders),
70
- timeout: opts?.timeout,
71
- });
72
- break;
73
- }
74
- }
47
+ throw new Error("Missing payment handler");
48
+ },
49
+ });
75
50
  // handle errors
76
51
  await HTTPError.handleErrorResponse(res);
77
52
  // return blob descriptor
@@ -1,7 +1,7 @@
1
1
  import HTTPError from "../error.js";
2
2
  import { encodeAuthorizationHeader, getReusableAuthEvent, storeAuthEvent } from "../auth.js";
3
3
  import { fetchWithTimeout } from "../helpers/index.js";
4
- import { mergeHeaders } from "../helpers/headers.js";
4
+ import { handleChallenges } from "../internal/challenges.js";
5
5
  /** Downloads a blob from a server and returns the Response */
6
6
  export async function downloadBlob(server, hash, opts) {
7
7
  const url = new URL("/" + hash, server);
@@ -28,47 +28,25 @@ export async function downloadBlob(server, hash, opts) {
28
28
  headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
29
29
  }
30
30
  }
31
- let download = await fetchWithTimeout(url, {
32
- headers,
31
+ const request = (headers) => fetchWithTimeout(url, { headers, signal: opts?.signal, timeout: opts?.timeout });
32
+ const download = await handleChallenges(await request(headers), headers, request, {
33
33
  signal: opts?.signal,
34
- timeout: opts?.timeout,
35
- });
36
- // handle auth and payment
37
- switch (download.status) {
38
- case 401: {
39
- // throw an error if auth is requested and disabled
34
+ auth: async () => {
40
35
  if (opts?.auth === false)
41
36
  throw new Error("Authorization disabled");
42
- // Request authorization for this request
43
- const auth = await resolveAuth();
44
- // Try download with auth
45
- download = await fetchWithTimeout(url, {
46
- headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
47
- signal: opts?.signal,
48
- timeout: opts?.timeout,
49
- });
50
- break;
51
- }
52
- case 402: {
53
- let paymentHeaders;
37
+ return { Authorization: encodeAuthorizationHeader(await resolveAuth()) };
38
+ },
39
+ payment: async (headers) => {
54
40
  if (opts?.onPaymentRequired)
55
- paymentHeaders = await opts.onPaymentRequired(server, hash, download.headers);
56
- else if (opts?.onPayment) {
41
+ return opts.onPaymentRequired(server, hash, headers);
42
+ if (opts?.onPayment) {
57
43
  const { encodePaymentToken, getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
58
- const request = await getPaymentRequestFromHeaders(download.headers);
59
- paymentHeaders = { "X-Cashu": encodePaymentToken(await opts.onPayment(server, hash, request)) };
44
+ const request = await getPaymentRequestFromHeaders(headers);
45
+ return { "X-Cashu": encodePaymentToken(await opts.onPayment(server, hash, request)) };
60
46
  }
61
- else
62
- throw new Error("Missing payment handler");
63
- // Try download with payment
64
- download = await fetchWithTimeout(url, {
65
- headers: mergeHeaders(headers, paymentHeaders),
66
- signal: opts?.signal,
67
- timeout: opts?.timeout,
68
- });
69
- break;
70
- }
71
- }
47
+ throw new Error("Missing payment handler");
48
+ },
49
+ });
72
50
  // check download errors
73
51
  await HTTPError.handleErrorResponse(download);
74
52
  // return the raw response
@@ -5,5 +5,5 @@ export type HasBlobOptions = {
5
5
  /** Request timeout */
6
6
  timeout?: number;
7
7
  };
8
- /** Checks if a blob exists on a server */
8
+ /** Returns false for a missing blob (404), true on success, and throws on other HTTP errors. */
9
9
  export declare function hasBlob<S extends ServerType>(server: S, hash: string, opts?: HasBlobOptions): Promise<boolean>;
@@ -1,10 +1,14 @@
1
1
  import { fetchWithTimeout } from "../helpers/index.js";
2
- /** Checks if a blob exists on a server */
2
+ import HTTPError from "../error.js";
3
+ /** Returns false for a missing blob (404), true on success, and throws on other HTTP errors. */
3
4
  export async function hasBlob(server, hash, opts) {
4
5
  const res = await fetchWithTimeout(new URL("/" + hash, server), {
5
6
  method: "HEAD",
6
7
  signal: opts?.signal,
7
8
  timeout: opts?.timeout,
8
9
  });
9
- return res.status !== 404;
10
+ if (res.status === 404)
11
+ return false;
12
+ await HTTPError.handleErrorResponse(res);
13
+ return true;
10
14
  }
@@ -1,7 +1,7 @@
1
1
  import HTTPError from "../error.js";
2
2
  import { encodeAuthorizationHeader, getReusableAuthEvent, storeAuthEvent } from "../auth.js";
3
3
  import { fetchWithTimeout } from "../helpers/index.js";
4
- import { mergeHeaders } from "../helpers/headers.js";
4
+ import { handleChallenges } from "../internal/challenges.js";
5
5
  /** Lists a page of blobs from a server */
6
6
  export async function listBlobs(server, pubkey, opts) {
7
7
  const url = new URL(`/list/` + pubkey, server);
@@ -35,42 +35,25 @@ export async function listBlobs(server, pubkey, opts) {
35
35
  headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
36
36
  }
37
37
  }
38
- let list = await fetchWithTimeout(url, { headers, signal: opts?.signal, timeout: opts?.timeout });
39
- // handle auth and payments
40
- switch (list.status) {
41
- case 401: {
42
- // throw an error if auth is requested and disabled
38
+ const request = (headers) => fetchWithTimeout(url, { headers, signal: opts?.signal, timeout: opts?.timeout });
39
+ const list = await handleChallenges(await request(headers), headers, request, {
40
+ signal: opts?.signal,
41
+ auth: async () => {
43
42
  if (opts?.auth === false)
44
43
  throw new Error("Authorization disabled");
45
- const auth = await resolveAuth();
46
- // Try list with auth
47
- list = await fetchWithTimeout(url, {
48
- headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
49
- signal: opts?.signal,
50
- timeout: opts?.timeout,
51
- });
52
- break;
53
- }
54
- case 402: {
55
- let paymentHeaders;
44
+ return { Authorization: encodeAuthorizationHeader(await resolveAuth()) };
45
+ },
46
+ payment: async (headers) => {
56
47
  if (opts?.onPaymentRequired)
57
- paymentHeaders = await opts.onPaymentRequired(server, list.headers);
58
- else if (opts?.onPayment) {
48
+ return opts.onPaymentRequired(server, headers);
49
+ if (opts?.onPayment) {
59
50
  const { encodePaymentToken, getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
60
- const request = await getPaymentRequestFromHeaders(list.headers);
61
- paymentHeaders = { "X-Cashu": encodePaymentToken(await opts.onPayment(server, request)) };
51
+ const request = await getPaymentRequestFromHeaders(headers);
52
+ return { "X-Cashu": encodePaymentToken(await opts.onPayment(server, request)) };
62
53
  }
63
- else
64
- throw new Error("Missing payment handler");
65
- // Try list with payment
66
- list = await fetchWithTimeout(url, {
67
- headers: mergeHeaders(headers, paymentHeaders),
68
- signal: opts?.signal,
69
- timeout: opts?.timeout,
70
- });
71
- break;
72
- }
73
- }
54
+ throw new Error("Missing payment handler");
55
+ },
56
+ });
74
57
  // handle errors
75
58
  await HTTPError.handleErrorResponse(list);
76
59
  // return blob descriptor
@@ -1,7 +1,8 @@
1
1
  import { getBlobSha256, getBlobSize, getBlobType } from "../helpers/index.js";
2
- import { mergeHeaders } from "../helpers/headers.js";
2
+ import { handleChallenges } from "../internal/challenges.js";
3
3
  import HTTPError from "../error.js";
4
4
  import { encodeAuthorizationHeader, getReusableAuthEvent, storeAuthEvent } from "../auth.js";
5
+ import { toWebBytes } from "../internal/bytes.js";
5
6
  /** Error thrown when /media endpoint is not present on a server */
6
7
  export class MediaEndpointMissingError extends Error {
7
8
  }
@@ -9,6 +10,7 @@ export class MediaEndpointMissingError extends Error {
9
10
  export async function uploadMedia(server, blob, opts) {
10
11
  const url = new URL("/media", server);
11
12
  const sha256 = await getBlobSha256(blob);
13
+ const body = blob instanceof Blob ? blob : toWebBytes(blob);
12
14
  const authEvents = opts?.authEvents;
13
15
  const resolveAuth = async (preset = false) => {
14
16
  const reused = authEvents
@@ -44,64 +46,41 @@ export async function uploadMedia(server, blob, opts) {
44
46
  if (type)
45
47
  checkHeaders["X-Content-Type"] = type;
46
48
  // check upload with HEAD /media
47
- let firstTry = await fetch(url, {
49
+ const firstTry = await fetch(url, {
48
50
  method: "HEAD",
49
51
  signal: opts?.signal,
50
52
  headers: checkHeaders,
51
53
  });
52
- let upload = undefined;
53
54
  if (firstTry.status === 404) {
54
55
  // HEAD endpoint is not supported. abort
55
56
  throw new MediaEndpointMissingError("/media endpoint not supported");
56
57
  }
57
- // handle auth and payment
58
- switch (firstTry.status) {
59
- case 401: {
60
- // throw an error if auth is requested and disabled
58
+ if (![401, 402].includes(firstTry.status))
59
+ await HTTPError.handleErrorResponse(firstTry);
60
+ const request = (headers) => fetch(url, {
61
+ signal: opts?.signal,
62
+ method: "PUT",
63
+ body,
64
+ headers,
65
+ });
66
+ const upload = await handleChallenges(firstTry.ok ? await request(headers) : firstTry, headers, request, {
67
+ signal: opts?.signal,
68
+ auth: async () => {
61
69
  if (opts?.auth === false)
62
70
  throw new Error("Authorization disabled");
63
- // Request authorization event for this upload
64
- const auth = await resolveAuth();
65
- // Try upload with auth
66
- upload = await fetch(url, {
67
- signal: opts?.signal,
68
- method: "PUT",
69
- body: blob,
70
- headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
71
- });
72
- break;
73
- }
74
- case 402: {
75
- let paymentHeaders;
71
+ return { Authorization: encodeAuthorizationHeader(await resolveAuth()) };
72
+ },
73
+ payment: async (headers) => {
76
74
  if (opts?.onPaymentRequired)
77
- paymentHeaders = await opts.onPaymentRequired(server, sha256, blob, firstTry.headers);
78
- else if (opts?.onPayment) {
75
+ return opts.onPaymentRequired(server, sha256, blob, headers);
76
+ if (opts?.onPayment) {
79
77
  const { encodePaymentToken, getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
80
- const request = await getPaymentRequestFromHeaders(firstTry.headers);
81
- paymentHeaders = { "X-Cashu": encodePaymentToken(await opts.onPayment(server, sha256, blob, request)) };
78
+ const request = await getPaymentRequestFromHeaders(headers);
79
+ return { "X-Cashu": encodePaymentToken(await opts.onPayment(server, sha256, blob, request)) };
82
80
  }
83
- else
84
- throw new Error("Missing payment handler");
85
- // Try upload with payment
86
- upload = await fetch(url, {
87
- signal: opts?.signal,
88
- method: "PUT",
89
- body: blob,
90
- headers: mergeHeaders(headers, paymentHeaders),
91
- });
92
- break;
93
- }
94
- }
95
- if (firstTry.status >= 500)
96
- throw new Error("Server error");
97
- // check passed, upload
98
- if (!upload)
99
- upload = await fetch(url, {
100
- signal: opts?.signal,
101
- method: "PUT",
102
- body: blob,
103
- headers: { ...headers },
104
- });
81
+ throw new Error("Missing payment handler");
82
+ },
83
+ });
105
84
  // handle errors
106
85
  await HTTPError.handleErrorResponse(upload);
107
86
  // return blob descriptor
@@ -1,7 +1,7 @@
1
1
  import { encodeAuthorizationHeader, getReusableAuthEvent, storeAuthEvent } from "../auth.js";
2
2
  import HTTPError from "../error.js";
3
3
  import { fetchWithTimeout } from "../helpers/index.js";
4
- import { mergeHeaders } from "../helpers/headers.js";
4
+ import { handleChallenges } from "../internal/challenges.js";
5
5
  /** Mirrors a blob to a server */
6
6
  export async function mirrorBlob(server, blob, opts) {
7
7
  const url = new URL("/mirror", server);
@@ -35,52 +35,25 @@ export async function mirrorBlob(server, blob, opts) {
35
35
  }
36
36
  }
37
37
  const body = JSON.stringify({ url: blob.url });
38
- let mirror = await fetchWithTimeout(url, {
39
- method: "PUT",
38
+ const request = (headers) => fetchWithTimeout(url, { method: "PUT", body, headers, signal: opts?.signal, timeout: opts?.timeout });
39
+ const mirror = await handleChallenges(await request(headers), headers, request, {
40
40
  signal: opts?.signal,
41
- headers,
42
- body,
43
- timeout: opts?.timeout,
44
- });
45
- switch (mirror.status) {
46
- case 401: {
47
- // throw an error if auth is requested and disabled
41
+ auth: async () => {
48
42
  if (opts?.auth === false)
49
43
  throw new Error("Authorization disabled");
50
- // Request authorization event for this mirror
51
- const auth = await resolveAuth();
52
- // Try mirror with auth
53
- mirror = await fetchWithTimeout(url, {
54
- signal: opts?.signal,
55
- method: "PUT",
56
- body,
57
- headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
58
- timeout: opts?.timeout,
59
- });
60
- break;
61
- }
62
- case 402: {
63
- let paymentHeaders;
44
+ return { Authorization: encodeAuthorizationHeader(await resolveAuth()) };
45
+ },
46
+ payment: async (headers) => {
64
47
  if (opts?.onPaymentRequired)
65
- paymentHeaders = await opts.onPaymentRequired(server, blob.sha256, blob, mirror.headers);
66
- else if (opts?.onPayment) {
48
+ return opts.onPaymentRequired(server, blob.sha256, blob, headers);
49
+ if (opts?.onPayment) {
67
50
  const { encodePaymentToken, getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
68
- const request = await getPaymentRequestFromHeaders(mirror.headers);
69
- paymentHeaders = { "X-Cashu": encodePaymentToken(await opts.onPayment(server, blob.sha256, blob, request)) };
51
+ const request = await getPaymentRequestFromHeaders(headers);
52
+ return { "X-Cashu": encodePaymentToken(await opts.onPayment(server, blob.sha256, blob, request)) };
70
53
  }
71
- else
72
- throw new Error("Missing payment handler");
73
- // Try mirror with payment
74
- mirror = await fetchWithTimeout(url, {
75
- signal: opts?.signal,
76
- method: "PUT",
77
- body,
78
- headers: mergeHeaders(headers, paymentHeaders),
79
- timeout: opts?.timeout,
80
- });
81
- break;
82
- }
83
- }
54
+ throw new Error("Missing payment handler");
55
+ },
56
+ });
84
57
  // handle errors
85
58
  await HTTPError.handleErrorResponse(mirror);
86
59
  // return blob descriptor
@@ -34,10 +34,12 @@ const defaultMediaUploadOptions = {
34
34
  */
35
35
  export async function multiServerUpload(servers, blob, opts) {
36
36
  const options = { ...defaultMultiServerOptions, ...opts };
37
+ options.signal?.throwIfAborted();
37
38
  let initialUpload;
38
39
  const results = new Map();
39
40
  const authEvents = options.authEvents ?? new Set();
40
41
  const blobSha256 = await getBlobSha256(blob);
42
+ options.signal?.throwIfAborted();
41
43
  if (typeof options.auth === "object")
42
44
  authEvents.add(options.auth);
43
45
  const handleAuthRequest = async (server, sha256, type) => {
@@ -81,6 +83,7 @@ export async function multiServerUpload(servers, blob, opts) {
81
83
  });
82
84
  return { server, exists };
83
85
  }));
86
+ options.signal?.throwIfAborted();
84
87
  for (const result of preflightResults) {
85
88
  if (result.status === "fulfilled" && result.value.exists) {
86
89
  serversWithBlob.add(result.value.server);
@@ -89,6 +92,7 @@ export async function multiServerUpload(servers, blob, opts) {
89
92
  }
90
93
  // upload to each server
91
94
  for (const server of uploadServers) {
95
+ options.signal?.throwIfAborted();
92
96
  const serverHasBlob = serversWithBlob.has(server);
93
97
  try {
94
98
  let metadata = undefined;
@@ -112,6 +116,7 @@ export async function multiServerUpload(servers, blob, opts) {
112
116
  });
113
117
  }
114
118
  catch (error) {
119
+ options.signal?.throwIfAborted();
115
120
  // mirror failed, if server already has blob skip upload fallback
116
121
  if (serverHasBlob)
117
122
  continue;
@@ -135,6 +140,7 @@ export async function multiServerUpload(servers, blob, opts) {
135
140
  options.onUpload?.(server, metadata.sha256, blob);
136
141
  }
137
142
  catch (error) {
143
+ options.signal?.throwIfAborted();
138
144
  const rejection = await handleRejection(server, blobSha256, error);
139
145
  if (rejection === "cancel")
140
146
  return results;
@@ -164,10 +170,12 @@ export async function multiServerUpload(servers, blob, opts) {
164
170
  */
165
171
  export async function multiServerMediaUpload(servers, blob, opts) {
166
172
  const options = { ...defaultMediaUploadOptions, ...opts };
173
+ options.signal?.throwIfAborted();
167
174
  let initialUpload;
168
175
  const results = new Map();
169
176
  const authEvents = options.authEvents ?? new Set();
170
177
  const blobSha256 = await getBlobSha256(blob);
178
+ options.signal?.throwIfAborted();
171
179
  if (typeof options.auth === "object")
172
180
  authEvents.add(options.auth);
173
181
  const handleAuthRequest = async (server, sha256, type) => {
@@ -205,6 +213,7 @@ export async function multiServerMediaUpload(servers, blob, opts) {
205
213
  let mediaUploadServer;
206
214
  // phase 1: upload to /media on one server for optimization
207
215
  for (const server of mediaServers) {
216
+ options.signal?.throwIfAborted();
208
217
  try {
209
218
  options.onStart?.(server, blobSha256, blob);
210
219
  initialUpload = await uploadMedia(server, blob, {
@@ -219,6 +228,7 @@ export async function multiServerMediaUpload(servers, blob, opts) {
219
228
  options.onUpload?.(server, initialUpload.sha256, blob);
220
229
  }
221
230
  catch (error) {
231
+ options.signal?.throwIfAborted();
222
232
  if (error instanceof MediaEndpointMissingError) {
223
233
  // ignore, try next server
224
234
  }
@@ -254,6 +264,7 @@ export async function multiServerMediaUpload(servers, blob, opts) {
254
264
  });
255
265
  return { server, exists };
256
266
  }));
267
+ options.signal?.throwIfAborted();
257
268
  for (const result of preflightResults) {
258
269
  if (result.status === "fulfilled" && result.value.exists) {
259
270
  serversWithBlob.add(result.value.server);
@@ -262,6 +273,7 @@ export async function multiServerMediaUpload(servers, blob, opts) {
262
273
  }
263
274
  // mirror to remaining servers
264
275
  for (const server of remainingServers) {
276
+ options.signal?.throwIfAborted();
265
277
  try {
266
278
  options.onStart?.(server, initialUpload.sha256, blob);
267
279
  const metadata = await mirrorBlob(server, initialUpload, {
@@ -276,6 +288,7 @@ export async function multiServerMediaUpload(servers, blob, opts) {
276
288
  options.onUpload?.(server, metadata.sha256, blob);
277
289
  }
278
290
  catch (error) {
291
+ options.signal?.throwIfAborted();
279
292
  const rejection = await handleRejection(server, initialUpload.sha256, error);
280
293
  if (rejection === "cancel")
281
294
  return results;