blossom-client-sdk 3.0.1 → 4.1.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 +4 -5
  2. package/lib/actions/delete.js +18 -6
  3. package/lib/actions/download.d.ts +4 -5
  4. package/lib/actions/download.js +18 -5
  5. package/lib/actions/list.d.ts +4 -5
  6. package/lib/actions/list.js +22 -5
  7. package/lib/actions/media.js +18 -5
  8. package/lib/actions/mirror.d.ts +4 -5
  9. package/lib/actions/mirror.js +19 -6
  10. package/lib/actions/multi-server.js +15 -4
  11. package/lib/actions/upload.d.ts +4 -5
  12. package/lib/actions/upload.js +19 -6
  13. package/lib/auth.d.ts +4 -1
  14. package/lib/auth.js +18 -8
  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 +96 -0
  25. package/src/actions/download.ts +95 -0
  26. package/src/actions/index.ts +7 -0
  27. package/src/actions/list.ts +95 -0
  28. package/src/actions/media.ts +113 -0
  29. package/src/actions/mirror.ts +110 -0
  30. package/src/actions/multi-server.ts +218 -0
  31. package/src/actions/upload.ts +140 -0
  32. package/src/auth.ts +145 -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
@@ -1,5 +1,5 @@
1
1
  export * from "./blob.js";
2
- export * from "./cachu.js";
2
+ export * from "./cashu.js";
3
3
  export * from "./fetch.js";
4
4
  export * from "./signal.js";
5
5
  export * from "./url.js";
@@ -4,7 +4,7 @@ export class TimeoutError extends Error {
4
4
  export function wrapSignalWithTimeout(timeout, message, signal) {
5
5
  const controller = new AbortController();
6
6
  if (signal)
7
- signal.addEventListener("abort", (err) => controller.abort(err));
7
+ signal.addEventListener("abort", (err) => controller.abort(err), { once: true });
8
8
  const t = setTimeout(() => {
9
9
  controller.abort(new TimeoutError(message));
10
10
  }, timeout);
package/lib/image.js CHANGED
@@ -59,20 +59,34 @@ export function handleBrokenImages(root, getServers) {
59
59
  const observer = new MutationObserver((changes) => {
60
60
  for (const change of changes) {
61
61
  if (change.type === "childList") {
62
- // add "error" event handles to any new <img/> elements
63
- change.addedNodes.forEach((el) => {
64
- if (el instanceof HTMLImageElement && !listeners.has(el)) {
65
- const listener = handleImageFallbacks(el, getServers);
66
- listeners.set(el, listener);
62
+ // Process added nodes and their children for images
63
+ change.addedNodes.forEach((node) => {
64
+ if (!(node instanceof HTMLElement))
65
+ return;
66
+ // Find all img elements in the added node and its children
67
+ const children = Array.from(node.querySelectorAll("img[src]"));
68
+ const images = node instanceof HTMLImageElement ? [node, ...children] : children;
69
+ for (const image of images) {
70
+ if (image instanceof HTMLImageElement && !listeners.has(image)) {
71
+ const listener = handleImageFallbacks(image, getServers);
72
+ listeners.set(image, listener);
73
+ }
67
74
  }
68
75
  });
69
76
  // cleanup removed nodes
70
- change.removedNodes.forEach((el) => {
71
- if (el instanceof HTMLImageElement) {
72
- const listener = listeners.get(el);
73
- if (listener) {
74
- listener();
75
- listeners.delete(el);
77
+ change.removedNodes.forEach((node) => {
78
+ if (!(node instanceof HTMLElement))
79
+ return;
80
+ // Find all img elements in the removed node and its children
81
+ const children = Array.from(node.querySelectorAll("img[src]"));
82
+ const images = node instanceof HTMLImageElement ? [node, ...children] : children;
83
+ for (const image of images) {
84
+ if (image instanceof HTMLImageElement) {
85
+ const listener = listeners.get(image);
86
+ if (listener) {
87
+ listener();
88
+ listeners.delete(image);
89
+ }
76
90
  }
77
91
  }
78
92
  });
package/lib/types.d.ts CHANGED
@@ -4,6 +4,7 @@ import { ListOptions } from "./actions/list.js";
4
4
  import { MirrorOptions } from "./actions/mirror.js";
5
5
  import { UploadOptions } from "./actions/upload.js";
6
6
  import { ServerType, UploadType } from "./client.js";
7
+ import { type PaymentRequest as CashuPaymentRequest } from "@cashu/cashu-ts";
7
8
  export type EventTemplate = {
8
9
  created_at: number;
9
10
  kind: number;
@@ -32,9 +33,24 @@ export type BlobDescriptor = {
32
33
  size: number;
33
34
  url: string;
34
35
  };
35
- export type PaymentRequest = {
36
+ export type PaymentRequest = CashuPaymentRequest;
37
+ type SerializedDLEQ = {
38
+ s: string;
39
+ e: string;
40
+ r?: string;
41
+ };
42
+ type Proof = {
43
+ id: string;
36
44
  amount: number;
37
- unit: string;
38
- mints: string[];
39
- pubkey?: string;
45
+ secret: string;
46
+ C: string;
47
+ dleq?: SerializedDLEQ;
48
+ };
49
+ /** Copy of the Token type from cashu-ts */
50
+ export type PaymentToken = {
51
+ mint: string;
52
+ proofs: Array<Proof>;
53
+ memo?: string;
54
+ unit?: string;
40
55
  };
56
+ export {};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "blossom-client-sdk",
3
- "version": "3.0.1",
4
- "description": "A simple client for manage blobs on blossom servers",
3
+ "version": "4.1.0",
4
+ "description": "Client SDK for talking to blossom servers",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
7
7
  "module": "./lib/index.js",
@@ -9,7 +9,8 @@
9
9
  "author": "hzrd149",
10
10
  "license": "MIT",
11
11
  "files": [
12
- "lib"
12
+ "lib",
13
+ "src"
13
14
  ],
14
15
  "exports": {
15
16
  ".": {
@@ -53,22 +54,23 @@
53
54
  "node": ">=18"
54
55
  },
55
56
  "dependencies": {
56
- "@cashu/cashu-ts": "^2.1.0",
57
- "@noble/hashes": "^1.4.0"
57
+ "@cashu/cashu-ts": "^2.4.3",
58
+ "@noble/hashes": "^1.8.0"
58
59
  },
59
60
  "devDependencies": {
60
- "@changesets/cli": "^2.27.1",
61
+ "@changesets/cli": "^2.29.3",
61
62
  "@testing-library/dom": "^10.4.0",
62
- "@types/node": "^22.5.5",
63
- "@vitest/browser": "^2.1.8",
64
- "@vitest/coverage-v8": "2.1.8",
65
- "nostr-tools": "^2.10.4",
66
- "playwright": "^1.49.1",
67
- "prettier": "^3.3.3",
68
- "typedoc": "^0.25.12",
63
+ "@types/node": "^22.15.14",
64
+ "@vitest/browser": "^3.1.3",
65
+ "@vitest/coverage-v8": "^3.1.3",
66
+ "nostr-tools": "^2.12.0",
67
+ "playwright": "^1.52.0",
68
+ "prettier": "^3.5.3",
69
+ "typedoc": "^0.25.13",
69
70
  "typedoc-plugin-mermaid": "^1.12.0",
70
- "typescript": "^5.3.3",
71
- "vitest": "^2.1.8"
71
+ "typescript": "^5.8.3",
72
+ "vitest": "^3.1.3",
73
+ "vitest-fetch-mock": "^0.4.5"
72
74
  },
73
75
  "scripts": {
74
76
  "build": "tsc",
@@ -76,7 +78,6 @@
76
78
  "test": "vitest run",
77
79
  "coverage": "vitest run --coverage",
78
80
  "format": "prettier -w .",
79
- "docs": "typedoc src/index.ts",
80
- "test:browser": "vitest"
81
+ "docs": "typedoc src/index.ts"
81
82
  }
82
83
  }
@@ -0,0 +1,96 @@
1
+ import { encodeAuthorizationHeader } from "../auth.js";
2
+ import { ServerType } from "../client.js";
3
+ import HTTPError from "../error.js";
4
+ import { fetchWithTimeout } from "../helpers/fetch.js";
5
+ import { PaymentRequest, PaymentToken, SignedEvent } from "../types.js";
6
+
7
+ export type DeleteOptions<S extends ServerType> = {
8
+ /** AbortSignal to cancel the action */
9
+ signal?: AbortSignal;
10
+ /** Override authorization event, or true to always use authorization, false to disable authorization */
11
+ auth?: SignedEvent | boolean;
12
+ /** Request timeout */
13
+ timeout?: number;
14
+ /**
15
+ * A method used to request payment when deleting
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
+ /** Deletes a blob to a server */
30
+ export async function deleteBlob<S extends ServerType>(server: S, hash: string, opts?: DeleteOptions<S>) {
31
+ const url = new URL("/" + hash, server);
32
+
33
+ const headers: HeadersInit = {};
34
+
35
+ // attach the authorization if its already set
36
+ if (opts?.auth) {
37
+ if (typeof opts.auth === "boolean") {
38
+ if (!opts.onAuth) throw new Error("Missing onAuth handler");
39
+ headers["Authorization"] = encodeAuthorizationHeader(await opts.onAuth(server, hash));
40
+ } else {
41
+ headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
42
+ }
43
+ }
44
+
45
+ let res = await fetchWithTimeout(url, {
46
+ method: "DELETE",
47
+ headers,
48
+ signal: opts?.signal,
49
+ timeout: opts?.timeout,
50
+ });
51
+
52
+ // handle auth and payment
53
+ switch (res.status) {
54
+ case 401: {
55
+ // throw an error if authorization is required but disabled
56
+ if (opts?.auth === false) throw new Error("Authorization disabled");
57
+
58
+ // request authorization for this request
59
+ const auth = await opts?.onAuth?.(server, hash);
60
+ if (!auth) throw new Error("Missing auth handler");
61
+
62
+ // Try delete with auth
63
+ res = await fetchWithTimeout(url, {
64
+ signal: opts?.signal,
65
+ method: "DELETE",
66
+ headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
67
+ timeout: opts?.timeout,
68
+ });
69
+ break;
70
+ }
71
+ case 402: {
72
+ if (!opts?.onPayment) throw new Error("Missing payment handler");
73
+ const { getEncodedToken } = await import("@cashu/cashu-ts");
74
+ const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
75
+ const request = getPaymentRequestFromHeaders(res.headers);
76
+
77
+ const token = await opts.onPayment(server, hash, request);
78
+ const payment = getEncodedToken(token);
79
+
80
+ // Try delete with payment
81
+ res = await fetchWithTimeout(url, {
82
+ signal: opts?.signal,
83
+ method: "DELETE",
84
+ headers: { ...headers, "X-Cashu": payment },
85
+ timeout: opts?.timeout,
86
+ });
87
+ break;
88
+ }
89
+ }
90
+
91
+ // handle errors
92
+ await HTTPError.handleErrorResponse(res);
93
+
94
+ // return blob descriptor
95
+ return res.ok;
96
+ }
@@ -0,0 +1,95 @@
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 authorization event, or true to always use authorization, false to disable authorization */
11
+ auth?: SignedEvent | boolean;
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 authorization if its already set
36
+ if (opts?.auth) {
37
+ if (typeof opts.auth === "boolean") {
38
+ if (!opts.onAuth) throw new Error("Missing onAuth handler");
39
+ headers["Authorization"] = encodeAuthorizationHeader(await opts.onAuth(server, hash));
40
+ } else {
41
+ headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
42
+ }
43
+ }
44
+
45
+ let download = await fetchWithTimeout(url, {
46
+ headers,
47
+ signal: opts?.signal,
48
+ timeout: opts?.timeout,
49
+ });
50
+
51
+ // handle auth and payment
52
+ switch (download.status) {
53
+ case 401: {
54
+ // throw an error if auth is requested and disabled
55
+ if (opts?.auth === false) throw new Error("Authorization disabled");
56
+
57
+ // Request authorization for this request
58
+ const auth = await opts?.onAuth?.(server, hash);
59
+ if (!auth) throw new Error("Missing auth handler");
60
+
61
+ // Try download with auth
62
+ download = await fetchWithTimeout(url, {
63
+ headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
64
+ signal: opts?.signal,
65
+ timeout: opts?.timeout,
66
+ });
67
+
68
+ break;
69
+ }
70
+ case 402: {
71
+ if (!opts?.onPayment) throw new Error("Missing payment handler");
72
+ const { getEncodedToken } = await import("@cashu/cashu-ts");
73
+ const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
74
+ const request = getPaymentRequestFromHeaders(download.headers);
75
+
76
+ const token = await opts.onPayment(server, hash, request);
77
+ const payment = getEncodedToken(token);
78
+
79
+ // Try download with payment
80
+ download = await fetchWithTimeout(url, {
81
+ headers: { ...headers, "X-Cashu": payment },
82
+ signal: opts?.signal,
83
+ timeout: opts?.timeout,
84
+ });
85
+
86
+ break;
87
+ }
88
+ }
89
+
90
+ // check download errors
91
+ await HTTPError.handleErrorResponse(download);
92
+
93
+ // return the raw response
94
+ return download;
95
+ }
@@ -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,95 @@
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 authorization event, or true to always use authorization, false to disable authorization */
11
+ auth?: SignedEvent | boolean;
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
+
42
+ // attach the authorization if its already set
43
+ if (opts?.auth) {
44
+ if (typeof opts.auth === "boolean") {
45
+ if (!opts.onAuth) throw new Error("Missing onAuth handler");
46
+ headers["Authorization"] = encodeAuthorizationHeader(await opts.onAuth(server));
47
+ } else {
48
+ headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
49
+ }
50
+ }
51
+
52
+ let list = await fetchWithTimeout(url, { headers, signal: opts?.signal, timeout: opts?.timeout });
53
+
54
+ // handle auth and payments
55
+ switch (list.status) {
56
+ case 401: {
57
+ // throw an error if auth is requested and disabled
58
+ if (opts?.auth === false) throw new Error("Authorization disabled");
59
+
60
+ const auth = await opts?.onAuth?.(server);
61
+ if (!auth) throw new Error("Missing auth handler");
62
+
63
+ // Try list with auth
64
+ list = await fetchWithTimeout(url, {
65
+ headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
66
+ signal: opts?.signal,
67
+ timeout: opts?.timeout,
68
+ });
69
+ break;
70
+ }
71
+ case 402: {
72
+ if (!opts?.onPayment) throw new Error("Missing payment handler");
73
+ const { getEncodedToken } = await import("@cashu/cashu-ts");
74
+ const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
75
+ const request = getPaymentRequestFromHeaders(list.headers);
76
+
77
+ const token = await opts.onPayment(server, request);
78
+ const payment = getEncodedToken(token);
79
+
80
+ // Try list with payment
81
+ list = await fetchWithTimeout(url, {
82
+ headers: { ...headers, "X-Cashu": payment },
83
+ signal: opts?.signal,
84
+ timeout: opts?.timeout,
85
+ });
86
+ break;
87
+ }
88
+ }
89
+
90
+ // handle errors
91
+ await HTTPError.handleErrorResponse(list);
92
+
93
+ // return blob descriptor
94
+ return list.json();
95
+ }
@@ -0,0 +1,113 @@
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 authorization if its already set
27
+ if (opts?.auth) {
28
+ if (typeof opts.auth === "boolean") {
29
+ if (!opts.onAuth) throw new Error("Missing onAuth handler");
30
+ headers["Authorization"] = encodeAuthorizationHeader(await opts.onAuth(server, sha256, "media", blob));
31
+ } else {
32
+ headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
33
+ }
34
+ }
35
+
36
+ // build check headers
37
+ const checkHeaders: Record<string, string> = {
38
+ ...headers,
39
+ "X-Content-Length": String(getBlobSize(blob)),
40
+ };
41
+ const type = getBlobType(blob);
42
+ if (type) checkHeaders["X-Content-Type"] = type;
43
+
44
+ // check upload with HEAD /media
45
+ let firstTry = await fetch(url, {
46
+ method: "HEAD",
47
+ signal: opts?.signal,
48
+ headers: checkHeaders,
49
+ });
50
+
51
+ let upload: Response | undefined = undefined;
52
+
53
+ if (firstTry.status === 404) {
54
+ // HEAD endpoint is not supported. abort
55
+ throw new MediaEndpointMissingError("/media endpoint not supported");
56
+ }
57
+
58
+ // handle auth and payment
59
+ switch (firstTry.status) {
60
+ case 401: {
61
+ // throw an error if auth is requested and disabled
62
+ if (opts?.auth === false) throw new Error("Authorization disabled");
63
+
64
+ // Request authorization event for this upload
65
+ const auth = await opts?.onAuth?.(server, sha256, "media", blob);
66
+ if (!auth) throw new Error("Missing auth handler");
67
+
68
+ // Try upload with auth
69
+ upload = await fetch(url, {
70
+ signal: opts?.signal,
71
+ method: "PUT",
72
+ body: blob,
73
+ headers: { ...headers, Authorization: encodeAuthorizationHeader(auth) },
74
+ });
75
+ break;
76
+ }
77
+ case 402: {
78
+ if (!opts?.onPayment) throw new Error("Missing payment handler");
79
+ const { getEncodedToken } = await import("@cashu/cashu-ts");
80
+ const { getPaymentRequestFromHeaders } = await import("../helpers/cashu.js");
81
+ const request = getPaymentRequestFromHeaders(firstTry.headers);
82
+
83
+ const token = await opts.onPayment(server, sha256, blob, request);
84
+ const payment = getEncodedToken(token);
85
+
86
+ // Try upload with payment
87
+ upload = await fetch(url, {
88
+ signal: opts?.signal,
89
+ method: "PUT",
90
+ body: blob,
91
+ headers: { ...headers, "X-Cashu": payment },
92
+ });
93
+ break;
94
+ }
95
+ }
96
+
97
+ if (firstTry.status >= 500) throw new Error("Server error");
98
+
99
+ // check passed, upload
100
+ if (!upload)
101
+ upload = await fetch(url, {
102
+ signal: opts?.signal,
103
+ method: "PUT",
104
+ body: blob,
105
+ headers: { ...headers },
106
+ });
107
+
108
+ // handle errors
109
+ await HTTPError.handleErrorResponse(upload);
110
+
111
+ // return blob descriptor
112
+ return upload.json();
113
+ }