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.
- package/lib/actions/delete.d.ts +4 -5
- package/lib/actions/delete.js +18 -6
- package/lib/actions/download.d.ts +4 -5
- package/lib/actions/download.js +18 -5
- package/lib/actions/list.d.ts +4 -5
- package/lib/actions/list.js +22 -5
- package/lib/actions/media.js +18 -5
- package/lib/actions/mirror.d.ts +4 -5
- package/lib/actions/mirror.js +19 -6
- package/lib/actions/multi-server.js +15 -4
- package/lib/actions/upload.d.ts +4 -5
- package/lib/actions/upload.js +19 -6
- package/lib/auth.d.ts +4 -1
- package/lib/auth.js +18 -8
- package/lib/helpers/blob.d.ts +2 -0
- package/lib/helpers/blob.js +8 -5
- package/lib/helpers/cashu.js +14 -0
- package/lib/helpers/index.d.ts +1 -1
- package/lib/helpers/index.js +1 -1
- package/lib/helpers/signal.js +1 -1
- package/lib/image.js +25 -11
- package/lib/types.d.ts +20 -4
- package/package.json +18 -17
- package/src/actions/delete.ts +96 -0
- package/src/actions/download.ts +95 -0
- package/src/actions/index.ts +7 -0
- package/src/actions/list.ts +95 -0
- package/src/actions/media.ts +113 -0
- package/src/actions/mirror.ts +110 -0
- package/src/actions/multi-server.ts +218 -0
- package/src/actions/upload.ts +140 -0
- package/src/auth.ts +145 -0
- package/src/client.ts +221 -0
- package/src/const.ts +1 -0
- package/src/error.ts +23 -0
- package/src/helpers/blob.ts +62 -0
- package/src/helpers/cashu.ts +21 -0
- package/src/helpers/fetch.ts +16 -0
- package/src/helpers/index.ts +5 -0
- package/src/helpers/signal.ts +20 -0
- package/src/helpers/url.ts +16 -0
- package/src/image.ts +122 -0
- package/src/index.ts +9 -0
- package/src/nostr.ts +17 -0
- package/src/types.ts +63 -0
- package/lib/helpers/cachu.js +0 -6
- /package/lib/helpers/{cachu.d.ts → cashu.d.ts} +0 -0
package/src/client.ts
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { getBlobSha256 } from "./helpers/blob.js";
|
|
2
|
+
import {
|
|
3
|
+
createDeleteAuth,
|
|
4
|
+
createDownloadAuth,
|
|
5
|
+
createListAuth,
|
|
6
|
+
createMirrorAuth,
|
|
7
|
+
createUploadAuth,
|
|
8
|
+
DeleteAuthOptions,
|
|
9
|
+
DownloadAuthOptions,
|
|
10
|
+
encodeAuthorizationHeader,
|
|
11
|
+
ListAuthOptions,
|
|
12
|
+
MirrorAuthOptions,
|
|
13
|
+
UploadAuthOptions,
|
|
14
|
+
} from "./auth.js";
|
|
15
|
+
import { BlobDescriptor, PaymentHandlers as PaymentHandler, SignedEvent, Signer } from "./types.js";
|
|
16
|
+
import { mirrorBlob, MirrorOptions } from "./actions/mirror.js";
|
|
17
|
+
import { uploadBlob, UploadOptions } from "./actions/upload.js";
|
|
18
|
+
import { listBlobs, ListOptions } from "./actions/list.js";
|
|
19
|
+
import { downloadBlob, DownloadOptions } from "./actions/download.js";
|
|
20
|
+
import { deleteBlob, DeleteOptions } from "./actions/delete.js";
|
|
21
|
+
import { uploadMedia, UploadMediaOptions } from "./actions/media.js";
|
|
22
|
+
|
|
23
|
+
export type ServerType = string | URL;
|
|
24
|
+
export type UploadType = Blob | File | Buffer;
|
|
25
|
+
|
|
26
|
+
export class BlossomClient {
|
|
27
|
+
server: URL;
|
|
28
|
+
signer?: Signer;
|
|
29
|
+
payment?: PaymentHandler<URL>;
|
|
30
|
+
|
|
31
|
+
constructor(server: string | URL, signer?: Signer) {
|
|
32
|
+
this.server = new URL("/", server);
|
|
33
|
+
this.signer = signer;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// moved to helpers.ts
|
|
37
|
+
static getFileSha256 = getBlobSha256;
|
|
38
|
+
|
|
39
|
+
// static auth methods moved to auth.ts
|
|
40
|
+
static createGetAuth = createDownloadAuth;
|
|
41
|
+
static createUploadAuth = createUploadAuth;
|
|
42
|
+
static createListAuth = createListAuth;
|
|
43
|
+
static createDeleteAuth = createDeleteAuth;
|
|
44
|
+
|
|
45
|
+
// util
|
|
46
|
+
static encodeAuthorizationHeader = encodeAuthorizationHeader;
|
|
47
|
+
|
|
48
|
+
// static blob methods moved to actions
|
|
49
|
+
static mirrorBlob = mirrorBlob;
|
|
50
|
+
static uploadBlob = uploadBlob;
|
|
51
|
+
static listBlobs = listBlobs;
|
|
52
|
+
static downloadBlob = downloadBlob;
|
|
53
|
+
static deleteBlob = deleteBlob;
|
|
54
|
+
static uploadMedia = uploadMedia;
|
|
55
|
+
|
|
56
|
+
// download blob
|
|
57
|
+
async createDownloadAuth(hash: string, options?: DownloadAuthOptions) {
|
|
58
|
+
if (!this.signer) throw new Error("Missing signer");
|
|
59
|
+
return await createDownloadAuth(this.signer, hash, options);
|
|
60
|
+
}
|
|
61
|
+
async downloadBlob(
|
|
62
|
+
hash: string,
|
|
63
|
+
opts?: Omit<DownloadOptions<URL>, "onAuth" | "onPayment" | "auth"> & {
|
|
64
|
+
auth?: SignedEvent | boolean;
|
|
65
|
+
payment?: boolean;
|
|
66
|
+
},
|
|
67
|
+
) {
|
|
68
|
+
const options: DownloadOptions<URL> = { signal: opts?.signal };
|
|
69
|
+
|
|
70
|
+
// attach auth
|
|
71
|
+
if (opts?.auth !== false) {
|
|
72
|
+
if (this.signer)
|
|
73
|
+
options.onAuth = (_server, sha256) => this.createDownloadAuth(sha256, { message: `Download ${sha256}` });
|
|
74
|
+
if (typeof opts?.auth === "object") options.auth = opts.auth;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// attach payment
|
|
78
|
+
if (opts?.payment !== false && this.payment) options.onPayment = this.payment.download;
|
|
79
|
+
|
|
80
|
+
const download = await downloadBlob(this.server, hash, options);
|
|
81
|
+
return download.blob();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// upload blob
|
|
85
|
+
async createUploadAuth(blob: string | UploadType, options?: UploadAuthOptions) {
|
|
86
|
+
if (!this.signer) throw new Error("Missing signer");
|
|
87
|
+
return await createUploadAuth(this.signer, blob, options);
|
|
88
|
+
}
|
|
89
|
+
async uploadBlob<B extends UploadType>(
|
|
90
|
+
blob: B,
|
|
91
|
+
opts?: Omit<UploadOptions<URL, B>, "onAuth" | "onPayment" | "auth"> & {
|
|
92
|
+
auth?: SignedEvent | boolean;
|
|
93
|
+
payment?: boolean;
|
|
94
|
+
},
|
|
95
|
+
) {
|
|
96
|
+
const options: UploadOptions<URL, B> = { signal: opts?.signal };
|
|
97
|
+
|
|
98
|
+
// attach auth
|
|
99
|
+
if (opts?.auth !== false) {
|
|
100
|
+
if (this.signer) options.onAuth = (_server, sha256, type) => this.createUploadAuth(sha256, { type });
|
|
101
|
+
if (typeof opts?.auth === "object") options.auth = opts.auth;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// attach payment
|
|
105
|
+
if (opts?.payment !== false && this.payment) options.onPayment = this.payment.upload;
|
|
106
|
+
|
|
107
|
+
return uploadBlob(this.server, blob, options);
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// mirror blob
|
|
111
|
+
async createMirrorAuth(blob: string | BlobDescriptor, options?: MirrorAuthOptions) {
|
|
112
|
+
if (!this.signer) throw new Error("Missing signer");
|
|
113
|
+
return await createMirrorAuth(this.signer, typeof blob === "string" ? blob : blob.sha256, options);
|
|
114
|
+
}
|
|
115
|
+
async mirrorBlob(
|
|
116
|
+
blob: BlobDescriptor,
|
|
117
|
+
opts?: Omit<MirrorOptions<URL>, "onAuth" | "onPayment" | "auth"> & {
|
|
118
|
+
auth?: SignedEvent | boolean;
|
|
119
|
+
payment?: boolean;
|
|
120
|
+
},
|
|
121
|
+
) {
|
|
122
|
+
const options: MirrorOptions<URL> = { signal: opts?.signal };
|
|
123
|
+
|
|
124
|
+
// attach auth
|
|
125
|
+
if (opts?.auth !== false) {
|
|
126
|
+
if (this.signer) options.onAuth = (_server, sha256) => this.createMirrorAuth(sha256);
|
|
127
|
+
if (typeof opts?.auth === "object") options.auth = opts.auth;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// attach payment
|
|
131
|
+
if (opts?.payment !== false && this.payment) options.onPayment = this.payment.mirror;
|
|
132
|
+
|
|
133
|
+
return mirrorBlob(this.server, blob, options);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// upload media
|
|
137
|
+
async createMediaAuth(blob: string | UploadType, options?: Omit<UploadAuthOptions, "type">) {
|
|
138
|
+
return await this.createUploadAuth(blob, { ...options, type: "media" });
|
|
139
|
+
}
|
|
140
|
+
async uploadMedia<B extends UploadType>(
|
|
141
|
+
blob: B,
|
|
142
|
+
opts?: Omit<UploadMediaOptions<URL, B>, "onAuth" | "onPayment" | "auth"> & {
|
|
143
|
+
auth?: SignedEvent | boolean;
|
|
144
|
+
payment?: boolean;
|
|
145
|
+
},
|
|
146
|
+
) {
|
|
147
|
+
const options: UploadMediaOptions<URL, B> = { signal: opts?.signal };
|
|
148
|
+
|
|
149
|
+
// attach auth
|
|
150
|
+
if (opts?.auth !== false) {
|
|
151
|
+
if (this.signer) options.onAuth = (_server, sha256, type) => this.createUploadAuth(sha256, { type });
|
|
152
|
+
if (typeof opts?.auth === "object") options.auth = opts.auth;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// attach payment
|
|
156
|
+
if (opts?.payment !== false && this.payment) options.onPayment = this.payment.upload;
|
|
157
|
+
|
|
158
|
+
return uploadMedia(this.server, blob, options);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// has blob
|
|
162
|
+
static async hasBlob(server: ServerType, hash: string) {
|
|
163
|
+
const res = await fetch(new URL(`/` + hash, server), { method: "HEAD" });
|
|
164
|
+
return res.status !== 404;
|
|
165
|
+
}
|
|
166
|
+
async hasBlob(hash: string) {
|
|
167
|
+
return BlossomClient.hasBlob(this.server, hash);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// list blobs
|
|
171
|
+
async createListAuth(options?: ListAuthOptions) {
|
|
172
|
+
if (!this.signer) throw new Error("Missing signer");
|
|
173
|
+
return await createListAuth(this.signer, options);
|
|
174
|
+
}
|
|
175
|
+
async listBlobs(
|
|
176
|
+
pubkey: string,
|
|
177
|
+
opts?: Omit<ListOptions<URL>, "onAuth" | "onPayment" | "auth"> & {
|
|
178
|
+
auth?: SignedEvent | boolean;
|
|
179
|
+
payment?: boolean;
|
|
180
|
+
},
|
|
181
|
+
) {
|
|
182
|
+
const options: ListOptions<URL> = { signal: opts?.signal };
|
|
183
|
+
|
|
184
|
+
// attach auth
|
|
185
|
+
if (opts?.auth !== false) {
|
|
186
|
+
if (this.signer) options.onAuth = (_server) => this.createListAuth();
|
|
187
|
+
if (typeof opts?.auth === "object") options.auth = opts.auth;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// attach payment
|
|
191
|
+
if (opts?.payment !== false && this.payment) options.onPayment = this.payment.list;
|
|
192
|
+
|
|
193
|
+
return listBlobs(this.server, pubkey, options);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// delete blob
|
|
197
|
+
async createDeleteAuth(blob: string | UploadType, options?: DeleteAuthOptions) {
|
|
198
|
+
if (!this.signer) throw new Error("Missing signer");
|
|
199
|
+
return await createDeleteAuth(this.signer, blob, options);
|
|
200
|
+
}
|
|
201
|
+
async deleteBlob(
|
|
202
|
+
hash: string,
|
|
203
|
+
opts?: Omit<DeleteOptions<URL>, "onAuth" | "onPayment" | "auth"> & {
|
|
204
|
+
auth?: SignedEvent | boolean;
|
|
205
|
+
payment?: boolean;
|
|
206
|
+
},
|
|
207
|
+
) {
|
|
208
|
+
const options: DeleteOptions<URL> = { signal: opts?.signal };
|
|
209
|
+
|
|
210
|
+
// attach auth
|
|
211
|
+
if (opts?.auth !== false) {
|
|
212
|
+
if (this.signer) options.onAuth = (_server, sha256) => this.createDeleteAuth(sha256);
|
|
213
|
+
if (typeof opts?.auth === "object") options.auth = opts.auth;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// attach payment
|
|
217
|
+
if (opts?.payment !== false && this.payment) options.onPayment = this.payment.delete;
|
|
218
|
+
|
|
219
|
+
return BlossomClient.deleteBlob(this.server, hash, options);
|
|
220
|
+
}
|
|
221
|
+
}
|
package/src/const.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const AUTH_EVENT_KIND = 24242;
|
package/src/error.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export default class HTTPError extends Error {
|
|
2
|
+
response: Response;
|
|
3
|
+
status: number;
|
|
4
|
+
body?: { message: string };
|
|
5
|
+
|
|
6
|
+
constructor(response: Response, body: { message: string } | string) {
|
|
7
|
+
super(typeof body === "string" ? body : body.message);
|
|
8
|
+
this.response = response;
|
|
9
|
+
this.status = response.status;
|
|
10
|
+
|
|
11
|
+
if (typeof body == "object") this.body = body;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
static async handleErrorResponse(res: Response) {
|
|
15
|
+
if (!res.ok) {
|
|
16
|
+
try {
|
|
17
|
+
throw new HTTPError(res, res.headers.get("x-reason") || "Something went wrong");
|
|
18
|
+
} catch (e) {
|
|
19
|
+
throw e;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { bytesToHex } from "@noble/hashes/utils";
|
|
2
|
+
import { UploadType } from "../client.js";
|
|
3
|
+
|
|
4
|
+
/** Checks if a string is a 64 length hex string */
|
|
5
|
+
export function isSha256(str: string) {
|
|
6
|
+
return str.match(/^[0-9a-f]{64}$/);
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** A symbol use to store the sha256 hash of a blob on a Blob instance */
|
|
10
|
+
export const BlobHashSymbol = Symbol.for("sha256");
|
|
11
|
+
|
|
12
|
+
/** gets or calculates the sha2456 of a Blob */
|
|
13
|
+
export function getBlobSha256(blob: UploadType) {
|
|
14
|
+
if (Reflect.has(blob, BlobHashSymbol)) return Reflect.get(blob, BlobHashSymbol) as string;
|
|
15
|
+
|
|
16
|
+
return computeBlobSha256(blob).then((hash) => {
|
|
17
|
+
Reflect.set(blob, BlobHashSymbol, hash);
|
|
18
|
+
return hash;
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Calculates the sha2456 of a Blob */
|
|
23
|
+
export async function computeBlobSha256(blob: UploadType) {
|
|
24
|
+
let buffer: ArrayBuffer | Buffer;
|
|
25
|
+
|
|
26
|
+
// NOTE: use typeof File !== "undefined" to check if File is supported (required to support node 18)
|
|
27
|
+
if ((typeof File !== "undefined" && blob instanceof File) || blob instanceof Blob) {
|
|
28
|
+
buffer = await blob.arrayBuffer();
|
|
29
|
+
} else {
|
|
30
|
+
// nodejs Buffer
|
|
31
|
+
buffer = blob;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
let hash: Uint8Array;
|
|
35
|
+
if (typeof crypto !== "undefined" && crypto.subtle) {
|
|
36
|
+
const hashBuffer = await crypto.subtle.digest("SHA-256", buffer);
|
|
37
|
+
hash = new Uint8Array(hashBuffer);
|
|
38
|
+
} else {
|
|
39
|
+
const { sha256 } = await import("@noble/hashes/sha2");
|
|
40
|
+
hash = sha256.create().update(new Uint8Array(buffer)).digest();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return bytesToHex(hash);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Returns the size of the blob in bytes */
|
|
47
|
+
export function getBlobSize(blob: UploadType) {
|
|
48
|
+
if ((typeof File !== "undefined" && blob instanceof File) || blob instanceof Blob) {
|
|
49
|
+
return blob.size;
|
|
50
|
+
} else {
|
|
51
|
+
// nodejs Buffer
|
|
52
|
+
return blob.length;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Returns the mime type of the blob */
|
|
57
|
+
export function getBlobType(blob: UploadType) {
|
|
58
|
+
if ((typeof File !== "undefined" && blob instanceof File) || blob instanceof Blob) {
|
|
59
|
+
return blob.type;
|
|
60
|
+
}
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { decodePaymentRequest } from "@cashu/cashu-ts";
|
|
2
|
+
import { PaymentRequest } from "../types.js";
|
|
3
|
+
|
|
4
|
+
/** Extracts a cashu-ts PaymentRequest from Headers */
|
|
5
|
+
export function getPaymentRequestFromHeaders(headers: Headers): PaymentRequest;
|
|
6
|
+
export function getPaymentRequestFromHeaders(headers: Headers, quite: false): PaymentRequest;
|
|
7
|
+
export function getPaymentRequestFromHeaders(headers: Headers, quite: true): PaymentRequest | undefined;
|
|
8
|
+
export function getPaymentRequestFromHeaders(headers: Headers, quite = false) {
|
|
9
|
+
const header = headers.get("X-Cashu");
|
|
10
|
+
if (!header) {
|
|
11
|
+
if (!quite) throw new Error("Missing cashu header");
|
|
12
|
+
else return undefined;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const request = decodePaymentRequest(header);
|
|
16
|
+
|
|
17
|
+
// Clear the transport, since NUT-23 is only in-band payments
|
|
18
|
+
request.transport = [];
|
|
19
|
+
|
|
20
|
+
return request;
|
|
21
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { wrapSignalWithTimeout } from "./signal.js";
|
|
2
|
+
|
|
3
|
+
export type RequestInitWithTimeout = RequestInit & { timeout?: number; timeoutMessage?: string };
|
|
4
|
+
|
|
5
|
+
/** Make a fetch request with a timeout */
|
|
6
|
+
export function fetchWithTimeout(url: string | URL, init?: RequestInitWithTimeout): ReturnType<typeof fetch> {
|
|
7
|
+
if (init?.timeout) {
|
|
8
|
+
const { cancel, signal } = wrapSignalWithTimeout(
|
|
9
|
+
init.timeout,
|
|
10
|
+
init.timeoutMessage ?? "Timeout",
|
|
11
|
+
init.signal ?? undefined,
|
|
12
|
+
);
|
|
13
|
+
|
|
14
|
+
return fetch(url, { ...init, signal }).finally(cancel);
|
|
15
|
+
} else return fetch(url, init);
|
|
16
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export class TimeoutError extends Error {}
|
|
2
|
+
|
|
3
|
+
/** Creates and optionally wraps an AbortSignal with a timeout */
|
|
4
|
+
export function wrapSignalWithTimeout(
|
|
5
|
+
timeout: number,
|
|
6
|
+
message: string,
|
|
7
|
+
signal: AbortSignal | undefined,
|
|
8
|
+
): { cancel: () => void; signal: AbortSignal } {
|
|
9
|
+
const controller = new AbortController();
|
|
10
|
+
|
|
11
|
+
if (signal) signal.addEventListener("abort", (err) => controller.abort(err), { once: true });
|
|
12
|
+
|
|
13
|
+
const t = setTimeout(() => {
|
|
14
|
+
controller.abort(new TimeoutError(message));
|
|
15
|
+
}, timeout);
|
|
16
|
+
|
|
17
|
+
const cancel = () => clearTimeout(t);
|
|
18
|
+
|
|
19
|
+
return { cancel, signal: controller.signal };
|
|
20
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Check if two servers are the same */
|
|
2
|
+
export function areServersEqual(a: string | URL, b: string | URL) {
|
|
3
|
+
const hostnameA = a instanceof URL ? a.hostname : new URL(a).hostname;
|
|
4
|
+
const hostnameB = b instanceof URL ? b.hostname : new URL(b).hostname;
|
|
5
|
+
return hostnameA === hostnameB;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/** returns the last sha256 in a URL */
|
|
9
|
+
export function getHashFromURL(url: string | URL) {
|
|
10
|
+
if (typeof url === "string") url = new URL(url);
|
|
11
|
+
|
|
12
|
+
const hashes = Array.from(url.pathname.matchAll(/[0-9a-f]{64}/gi));
|
|
13
|
+
if (hashes.length > 0) return hashes[hashes.length - 1][0];
|
|
14
|
+
|
|
15
|
+
return null;
|
|
16
|
+
}
|
package/src/image.ts
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { getHashFromURL } from "./helpers/url.js";
|
|
2
|
+
|
|
3
|
+
type GetServersMethod = (pubkey?: string) => Promise<(string | URL)[] | undefined> | undefined;
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* attaches an "error" event listener to a HTMLImageElement element to handle server fallbacks
|
|
7
|
+
* @param image The image element
|
|
8
|
+
* @param getServers A async method to get an ordered list of servers for a pubkey
|
|
9
|
+
* @param overridePubkey An optional pubkey to set the `data-pubkey` attr on the image
|
|
10
|
+
* @returns returns a method to remove the "error" event listener
|
|
11
|
+
*/
|
|
12
|
+
export function handleImageFallbacks(image: HTMLImageElement, getServers: GetServersMethod, overridePubkey?: string) {
|
|
13
|
+
let tried: string[] = [];
|
|
14
|
+
let servers: URL[] | undefined = undefined;
|
|
15
|
+
|
|
16
|
+
const onError = async () => {
|
|
17
|
+
const hash = getHashFromURL(image.src);
|
|
18
|
+
if (!hash) return;
|
|
19
|
+
|
|
20
|
+
const url = new URL(image.src);
|
|
21
|
+
const ext = url.pathname.match(/\.\w+$/i);
|
|
22
|
+
tried.push(url.hostname);
|
|
23
|
+
|
|
24
|
+
let pubkey = overridePubkey;
|
|
25
|
+
|
|
26
|
+
// walk up the tree looking for pubkey
|
|
27
|
+
let el: HTMLElement | null = image;
|
|
28
|
+
while (!pubkey && el.parentElement) {
|
|
29
|
+
if (el.dataset.pubkey) pubkey = el.dataset.pubkey;
|
|
30
|
+
else el = el.parentElement;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
if (!pubkey) {
|
|
34
|
+
console.warn("Failed to find pubkey for broken image", image);
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (!servers) servers = (await getServers(pubkey))?.map((s) => (s instanceof URL ? s : new URL(s)));
|
|
39
|
+
if (servers) {
|
|
40
|
+
const server = servers.find((s) => !tried.includes(s.hostname));
|
|
41
|
+
|
|
42
|
+
if (server) {
|
|
43
|
+
url.hostname = server.hostname;
|
|
44
|
+
url.pathname = "/" + hash + ext;
|
|
45
|
+
url.protocol = server.protocol;
|
|
46
|
+
|
|
47
|
+
image.src = url.toString();
|
|
48
|
+
} else {
|
|
49
|
+
// ran out of servers, stop listening for errors
|
|
50
|
+
image.removeEventListener("error", onError);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
image.addEventListener("error", onError);
|
|
56
|
+
|
|
57
|
+
return () => image.removeEventListener("error", onError);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Watch for any broken <img> elements in the tree and attempt to fix them
|
|
62
|
+
* @param root The root element to observe
|
|
63
|
+
* @param getServers A method used to get a list of servers for a specific pubkey
|
|
64
|
+
* @returns A MutationObserver that is observing the root element
|
|
65
|
+
*/
|
|
66
|
+
export function handleBrokenImages(root: HTMLElement, getServers: GetServersMethod) {
|
|
67
|
+
const listeners = new WeakMap<HTMLImageElement, () => void>();
|
|
68
|
+
|
|
69
|
+
const observer = new MutationObserver((changes) => {
|
|
70
|
+
for (const change of changes) {
|
|
71
|
+
if (change.type === "childList") {
|
|
72
|
+
// Process added nodes and their children for images
|
|
73
|
+
change.addedNodes.forEach((node) => {
|
|
74
|
+
if (!(node instanceof HTMLElement)) return;
|
|
75
|
+
|
|
76
|
+
// Find all img elements in the added node and its children
|
|
77
|
+
const children = Array.from(node.querySelectorAll("img[src]"));
|
|
78
|
+
const images = node instanceof HTMLImageElement ? [node, ...children] : children;
|
|
79
|
+
|
|
80
|
+
for (const image of images) {
|
|
81
|
+
if (image instanceof HTMLImageElement && !listeners.has(image)) {
|
|
82
|
+
const listener = handleImageFallbacks(image, getServers);
|
|
83
|
+
listeners.set(image, listener);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
// cleanup removed nodes
|
|
89
|
+
change.removedNodes.forEach((node) => {
|
|
90
|
+
if (!(node instanceof HTMLElement)) return;
|
|
91
|
+
|
|
92
|
+
// Find all img elements in the removed node and its children
|
|
93
|
+
const children = Array.from(node.querySelectorAll("img[src]"));
|
|
94
|
+
const images = node instanceof HTMLImageElement ? [node, ...children] : children;
|
|
95
|
+
for (const image of images) {
|
|
96
|
+
if (image instanceof HTMLImageElement) {
|
|
97
|
+
const listener = listeners.get(image);
|
|
98
|
+
if (listener) {
|
|
99
|
+
listener();
|
|
100
|
+
listeners.delete(image);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
// start watching root
|
|
110
|
+
observer.observe(root, { subtree: true, childList: true });
|
|
111
|
+
|
|
112
|
+
// find all existing images and attach error handler
|
|
113
|
+
const images = root.querySelectorAll("img[src]");
|
|
114
|
+
images.forEach((image) => {
|
|
115
|
+
if (image instanceof HTMLImageElement) {
|
|
116
|
+
const listener = handleImageFallbacks(image, getServers);
|
|
117
|
+
listeners.set(image, listener);
|
|
118
|
+
}
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
return observer;
|
|
122
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export * from "./const.js";
|
|
2
|
+
export * from "./auth.js";
|
|
3
|
+
export * from "./client.js";
|
|
4
|
+
export * from "./helpers/index.js";
|
|
5
|
+
export * from "./image.js";
|
|
6
|
+
export * from "./nostr.js";
|
|
7
|
+
export * from "./error.js";
|
|
8
|
+
export * from "./types.js";
|
|
9
|
+
export * as Actions from "./actions/index.js";
|
package/src/nostr.ts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export const USER_BLOSSOM_SERVER_LIST_KIND = 10063;
|
|
2
|
+
|
|
3
|
+
/** Returns an ordered array of servers found in a server list event (10063) */
|
|
4
|
+
export function getServersFromServerListEvent(event: { tags: string[][] }) {
|
|
5
|
+
const servers: URL[] = [];
|
|
6
|
+
for (const tag of event.tags) {
|
|
7
|
+
if (tag[0] === "server" && tag[1]) {
|
|
8
|
+
try {
|
|
9
|
+
const url = new URL(tag[1]);
|
|
10
|
+
url.pathname = "/";
|
|
11
|
+
|
|
12
|
+
servers.push(url);
|
|
13
|
+
} catch (e) {}
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return servers;
|
|
17
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { DeleteOptions } from "./actions/delete.js";
|
|
2
|
+
import { DownloadOptions } from "./actions/download.js";
|
|
3
|
+
import { ListOptions } from "./actions/list.js";
|
|
4
|
+
import { MirrorOptions } from "./actions/mirror.js";
|
|
5
|
+
import { UploadOptions } from "./actions/upload.js";
|
|
6
|
+
import { ServerType, UploadType } from "./client.js";
|
|
7
|
+
import { type PaymentRequest as CashuPaymentRequest } from "@cashu/cashu-ts";
|
|
8
|
+
|
|
9
|
+
export type EventTemplate = {
|
|
10
|
+
created_at: number;
|
|
11
|
+
kind: number;
|
|
12
|
+
content: string;
|
|
13
|
+
tags: string[][];
|
|
14
|
+
};
|
|
15
|
+
export type SignedEvent = EventTemplate & {
|
|
16
|
+
id: string;
|
|
17
|
+
sig: string;
|
|
18
|
+
pubkey: string;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
/** An async method used to sign nostr events */
|
|
22
|
+
export type Signer = (draft: EventTemplate) => Promise<SignedEvent>;
|
|
23
|
+
|
|
24
|
+
/** interface for handling payment requests */
|
|
25
|
+
export interface PaymentHandlers<S extends ServerType = ServerType> {
|
|
26
|
+
upload?: UploadOptions<S, UploadType>["onPayment"];
|
|
27
|
+
download?: DownloadOptions<S>["onPayment"];
|
|
28
|
+
list?: ListOptions<S>["onPayment"];
|
|
29
|
+
mirror?: MirrorOptions<S>["onPayment"];
|
|
30
|
+
delete?: DeleteOptions<S>["onPayment"];
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export type BlobDescriptor = {
|
|
34
|
+
uploaded: number;
|
|
35
|
+
type?: string;
|
|
36
|
+
sha256: string;
|
|
37
|
+
size: number;
|
|
38
|
+
url: string;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export type PaymentRequest = CashuPaymentRequest;
|
|
42
|
+
|
|
43
|
+
// NOTE: hack for Token type not being exported from cashu-ts
|
|
44
|
+
type SerializedDLEQ = {
|
|
45
|
+
s: string;
|
|
46
|
+
e: string;
|
|
47
|
+
r?: string;
|
|
48
|
+
};
|
|
49
|
+
type Proof = {
|
|
50
|
+
id: string;
|
|
51
|
+
amount: number;
|
|
52
|
+
secret: string;
|
|
53
|
+
C: string;
|
|
54
|
+
dleq?: SerializedDLEQ;
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/** Copy of the Token type from cashu-ts */
|
|
58
|
+
export type PaymentToken = {
|
|
59
|
+
mint: string;
|
|
60
|
+
proofs: Array<Proof>;
|
|
61
|
+
memo?: string;
|
|
62
|
+
unit?: string;
|
|
63
|
+
};
|
package/lib/helpers/cachu.js
DELETED
|
File without changes
|