blossom-client-sdk 0.5.1 → 0.6.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/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # blossom-client-sdk
2
+
3
+ ## 0.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - e2e93f5: Add `handleImageFallbacks` method
package/README.md CHANGED
@@ -4,10 +4,12 @@ A client for manage blobs on blossom servers
4
4
 
5
5
  [Documentation](https://hzrd149.github.io/blossom-client-sdk/classes/BlossomClient)
6
6
 
7
- ## Using the static methods
7
+ ## Using the client
8
+
9
+ ### Using the static methods
8
10
 
9
11
  ```js
10
- import { BlossomClient } from "blossom-client-sdk";
12
+ import { BlossomClient } from "blossom-client-sdk/client";
11
13
 
12
14
  async function signer(event) {
13
15
  return await window.nostr.signEvent(event);
@@ -35,7 +37,7 @@ if (res.ok) {
35
37
  }
36
38
  ```
37
39
 
38
- ## Using the class
40
+ ### Using the class
39
41
 
40
42
  The `BlossomClient` class can be used to talk to a single server
41
43
 
@@ -53,7 +55,86 @@ const blobs = await client.listBlobs(pubkey, undefined, true);
53
55
  // passing true as the last argument will make it send an auth event with the list request
54
56
  ```
55
57
 
56
- ## Examples
58
+ ### Using with NDK
59
+
60
+ The `BlossomClient` class and methods optionally take a `signer` method that is used to sign the upload auth events
61
+
62
+ If your using NDK in your app you can use this method
63
+
64
+ ```ts
65
+ const signer = async (draft: EventTemplate) => {
66
+ // add the pubkey to the draft event
67
+ const event: UnsignedEvent = { ...draft, pubkey: user.pubkey };
68
+ // get the signature
69
+ const sig = await ndk.signer!.sign(event);
70
+
71
+ // return the event + id + sig
72
+ return { ...event, sig, id: getEventHash(event) };
73
+ };
74
+ ```
75
+
76
+ ## Helper Methods
77
+
78
+ ### Getting the hash from a URL
79
+
80
+ The `getHashFromURL` method will return the last SHA256 hash it finds in a URL
81
+
82
+ ```js
83
+ import { getHashFromURL } from "blossom-client-sdk";
84
+
85
+ // blossom compatible URLs
86
+ console.log(
87
+ getHashFromURL("https://cdn.example.com/b1674191a88ec5cdd733e4240a81803105dc412d6c6708d53ab94fc248f4f553.pdf"),
88
+ );
89
+ // -> b1674191a88ec5cdd733e4240a81803105dc412d6c6708d53ab94fc248f4f553
90
+
91
+ // non-blossom URLs
92
+ console.log(
93
+ getHashFromURL(
94
+ "https://cdn.example.com/266815e0c9210dfa324c6cba3573b14bee49da4209a9456f9484e5106cd408a5/media/b1674191a88ec5cdd733e4240a81803105dc412d6c6708d53ab94fc248f4f553.pdf",
95
+ ),
96
+ );
97
+ // -> b1674191a88ec5cdd733e4240a81803105dc412d6c6708d53ab94fc248f4f553
98
+
99
+ // returns null when no hash is found
100
+ console.log(getHashFromURL("https://example.com/index.html"));
101
+ // -> null
102
+ ```
103
+
104
+ ### Handling broken images
105
+
106
+ This package also exports a few helper methods for handling broken images
107
+
108
+ The `handleImageFallbacks(image, getServers)` method listen for an `error` event on an `<img/>` element and if the element has a `data-pubkey` attribute. it will call `getServers` to ask for a list of blossom servers for the pubkey
109
+
110
+ ```js
111
+ import { handleImageFallbacks, USER_BLOSSOM_SERVER_LIST_KIND, getServersFromServerListEvent } from "blossom-client-sdk";
112
+
113
+ const image = new Image();
114
+ image.src = "https://cdn.censorship.com/72cb99b689b4cfe1a9fb6937f779f3f9c65094bf0e6ac72a8f8261efa96653f5.png";
115
+
116
+ // set the pubkey from the kind 1 event this image was found it
117
+ image.dataset.pubkey = event.pubkey;
118
+
119
+ // this is called when
120
+ async function getServers(pubkey) {
121
+ if (pubkey) {
122
+ // use NDK to find the users blossom server list event (k:10063)
123
+ const event = await ndk.fetchEvent({ kinds: [USER_BLOSSOM_SERVER_LIST_KIND], authors: [pubkey] });
124
+
125
+ // if its found return a list of blossom servers
126
+ if (event) return getServersFromServerListEvent(event);
127
+ }
128
+ return undefined;
129
+ }
130
+
131
+ // listen for "error" events
132
+ handleImageFallbacks(image, getServers);
133
+
134
+ document.body.appendChild(image);
135
+ ```
136
+
137
+ ## Other Examples
57
138
 
58
139
  ### List all blobs on a server
59
140
 
@@ -0,0 +1,64 @@
1
+ export type EventTemplate = {
2
+ created_at: number;
3
+ kind: number;
4
+ content: string;
5
+ tags: string[][];
6
+ };
7
+ export type SignedEvent = EventTemplate & {
8
+ id: string;
9
+ sig: string;
10
+ pubkey: string;
11
+ };
12
+ /** An async method used to sign nostr events */
13
+ export type Signer = (draft: EventTemplate) => Promise<SignedEvent>;
14
+ export declare const AUTH_EVENT_KIND = 24242;
15
+ export type BlobDescriptor = {
16
+ /** @deprecated use uploaded instead */
17
+ created?: number;
18
+ uploaded: number;
19
+ type?: string;
20
+ sha256: string;
21
+ size: number;
22
+ url: string;
23
+ };
24
+ export declare class HTTPError extends Error {
25
+ response: Response;
26
+ status: number;
27
+ body?: {
28
+ message: string;
29
+ };
30
+ constructor(response: Response, body: {
31
+ message: string;
32
+ } | string);
33
+ static handleErrorResponse(res: Response): Promise<void>;
34
+ }
35
+ export declare class BlossomClient {
36
+ server: string;
37
+ signer?: Signer;
38
+ constructor(server: string, signer?: Signer);
39
+ static getGetAuth(signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
40
+ static getUploadAuth(file: File, signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
41
+ static getDeleteAuth(hash: string, signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
42
+ static getListAuth(signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
43
+ getGetAuth(message?: string, expiration?: number): Promise<SignedEvent>;
44
+ getUploadAuth(file: File, message?: string, expiration?: number): Promise<SignedEvent>;
45
+ getDeleteAuth(hash: string, message?: string, expiration?: number): Promise<SignedEvent>;
46
+ getListAuth(message?: string, expiration?: number): Promise<SignedEvent>;
47
+ static encodeAuthorizationHeader(event: SignedEvent): string;
48
+ static getBlob(server: string, hash: string, auth?: SignedEvent): Promise<Blob>;
49
+ getBlob(hash: string, auth?: SignedEvent | boolean): Promise<Blob>;
50
+ static hasBlob(server: string, hash: string): Promise<boolean>;
51
+ hasBlob(hash: string): Promise<boolean>;
52
+ static listBlobs(server: string, pubkey: string, opts?: {
53
+ since?: number;
54
+ until?: number;
55
+ }, auth?: SignedEvent): Promise<BlobDescriptor[]>;
56
+ listBlobs(pubkey: string, opts?: {
57
+ since?: number;
58
+ until?: number;
59
+ }, auth?: SignedEvent | boolean): Promise<BlobDescriptor[]>;
60
+ static deleteBlob(server: string, hash: string, auth?: SignedEvent): Promise<string>;
61
+ deleteBlob(hash: string, auth?: SignedEvent | boolean): Promise<string>;
62
+ static uploadBlob(server: string, file: File, auth?: SignedEvent): Promise<BlobDescriptor>;
63
+ uploadBlob(file: File, auth?: SignedEvent | boolean): Promise<BlobDescriptor>;
64
+ }
package/lib/client.js ADDED
@@ -0,0 +1,164 @@
1
+ import fetch from "cross-fetch";
2
+ const now = () => Math.floor(new Date().valueOf() / 1000);
3
+ const oneHour = () => now() + 60 * 60;
4
+ export const AUTH_EVENT_KIND = 24242;
5
+ export class HTTPError extends Error {
6
+ constructor(response, body) {
7
+ super(typeof body === "string" ? body : body.message);
8
+ this.response = response;
9
+ this.status = response.status;
10
+ if (typeof body == "object")
11
+ this.body = body;
12
+ }
13
+ static async handleErrorResponse(res) {
14
+ if (!res.ok) {
15
+ try {
16
+ throw new HTTPError(res, await res.json());
17
+ }
18
+ catch (e) {
19
+ if (e instanceof Error)
20
+ throw new HTTPError(res, e.message);
21
+ }
22
+ }
23
+ }
24
+ }
25
+ export class BlossomClient {
26
+ constructor(server, signer) {
27
+ this.server = new URL("/", server).toString();
28
+ this.signer = signer;
29
+ }
30
+ static async getGetAuth(signer, message = "Get Blobs", expiration = oneHour()) {
31
+ return await signer({
32
+ created_at: now(),
33
+ kind: AUTH_EVENT_KIND,
34
+ content: message,
35
+ tags: [
36
+ ["t", "get"],
37
+ ["expiration", String(expiration)],
38
+ ],
39
+ });
40
+ }
41
+ static async getUploadAuth(file, signer, message = "Upload Blob", expiration = oneHour()) {
42
+ return await signer({
43
+ created_at: now(),
44
+ kind: AUTH_EVENT_KIND,
45
+ content: message,
46
+ tags: [
47
+ ["t", "upload"],
48
+ ["name", file.name],
49
+ ["size", String(file.size)],
50
+ ["expiration", String(expiration)],
51
+ ],
52
+ });
53
+ }
54
+ static async getDeleteAuth(hash, signer, message = "Delete Blob", expiration = oneHour()) {
55
+ return await signer({
56
+ created_at: now(),
57
+ kind: AUTH_EVENT_KIND,
58
+ content: message,
59
+ tags: [
60
+ ["t", "delete"],
61
+ ["x", hash],
62
+ ["expiration", String(expiration)],
63
+ ],
64
+ });
65
+ }
66
+ static async getListAuth(signer, message = "List Blobs", expiration = oneHour()) {
67
+ return await signer({
68
+ created_at: now(),
69
+ kind: AUTH_EVENT_KIND,
70
+ content: message,
71
+ tags: [
72
+ ["t", "list"],
73
+ ["expiration", String(expiration)],
74
+ ],
75
+ });
76
+ }
77
+ async getGetAuth(message, expiration) {
78
+ if (!this.signer)
79
+ throw new Error("Missing signer");
80
+ return await BlossomClient.getGetAuth(this.signer, message, expiration);
81
+ }
82
+ async getUploadAuth(file, message, expiration) {
83
+ if (!this.signer)
84
+ throw new Error("Missing signer");
85
+ return await BlossomClient.getUploadAuth(file, this.signer, message, expiration);
86
+ }
87
+ async getDeleteAuth(hash, message, expiration) {
88
+ if (!this.signer)
89
+ throw new Error("Missing signer");
90
+ return await BlossomClient.getDeleteAuth(hash, this.signer, message, expiration);
91
+ }
92
+ async getListAuth(message, expiration) {
93
+ if (!this.signer)
94
+ throw new Error("Missing signer");
95
+ return await BlossomClient.getListAuth(this.signer, message, expiration);
96
+ }
97
+ static encodeAuthorizationHeader(event) {
98
+ return "Nostr " + btoa(JSON.stringify(event));
99
+ }
100
+ static async getBlob(server, hash, auth) {
101
+ const res = await fetch(new URL(hash, server), {
102
+ headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
103
+ });
104
+ await HTTPError.handleErrorResponse(res);
105
+ return await res.blob();
106
+ }
107
+ async getBlob(hash, auth = false) {
108
+ if (typeof auth === "boolean" && auth)
109
+ auth = await this.getGetAuth();
110
+ return BlossomClient.getBlob(this.server, hash, auth ? auth : undefined);
111
+ }
112
+ static async hasBlob(server, hash) {
113
+ const res = await fetch(new URL(`/` + hash, server), { method: "HEAD" });
114
+ await HTTPError.handleErrorResponse(res);
115
+ return res.ok;
116
+ }
117
+ async hasBlob(hash) {
118
+ return BlossomClient.hasBlob(this.server, hash);
119
+ }
120
+ static async listBlobs(server, pubkey, opts, auth) {
121
+ const url = new URL(`/list/` + pubkey, server);
122
+ if (opts?.since)
123
+ url.searchParams.append("since", String(opts.since));
124
+ if (opts?.until)
125
+ url.searchParams.append("until", String(opts.until));
126
+ const res = await fetch(url, {
127
+ headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
128
+ });
129
+ await HTTPError.handleErrorResponse(res);
130
+ return (await res.json());
131
+ }
132
+ async listBlobs(pubkey, opts, auth = false) {
133
+ if (typeof auth === "boolean" && auth)
134
+ auth = await this.getListAuth();
135
+ return BlossomClient.listBlobs(this.server, pubkey, opts, auth ? auth : undefined);
136
+ }
137
+ static async deleteBlob(server, hash, auth) {
138
+ const res = await fetch(new URL("/" + hash, server), {
139
+ method: "DELETE",
140
+ headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
141
+ });
142
+ await HTTPError.handleErrorResponse(res);
143
+ return await res.text();
144
+ }
145
+ async deleteBlob(hash, auth = true) {
146
+ if (typeof auth === "boolean" && auth)
147
+ auth = await this.getDeleteAuth(hash);
148
+ return BlossomClient.deleteBlob(this.server, hash, auth ? auth : undefined);
149
+ }
150
+ static async uploadBlob(server, file, auth) {
151
+ const res = await fetch(new URL("/upload", server), {
152
+ method: "PUT",
153
+ body: file,
154
+ headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
155
+ });
156
+ await HTTPError.handleErrorResponse(res);
157
+ return (await res.json());
158
+ }
159
+ async uploadBlob(file, auth = true) {
160
+ if (typeof auth === "boolean" && auth)
161
+ auth = await this.getUploadAuth(file);
162
+ return BlossomClient.uploadBlob(this.server, file, auth ? auth : undefined);
163
+ }
164
+ }
@@ -0,0 +1,2 @@
1
+ /** returns the last sha256 in a URL */
2
+ export declare function getHashFromURL(url: string | URL): string | null;
package/lib/helpers.js ADDED
@@ -0,0 +1,9 @@
1
+ /** returns the last sha256 in a URL */
2
+ export function getHashFromURL(url) {
3
+ if (typeof url === "string")
4
+ url = new URL(url);
5
+ const hashes = Array.from(url.pathname.matchAll(/[0-9a-f]{64}/gi));
6
+ if (hashes.length > 0)
7
+ return hashes[hashes.length - 1][0];
8
+ return null;
9
+ }
package/lib/image.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * attaches an "error" event listener to a HTMLImageElement element to handle server fallbacks
3
+ * @param image The image element
4
+ * @param getServers A async method to get an ordered list of servers for a pubkey
5
+ * @param pubkey An optional pubkey to set the `data-pubkey` attr on the image
6
+ */
7
+ export declare function handleImageFallbacks(image: HTMLImageElement, getServers: (pubkey?: string) => Promise<(string | URL)[] | undefined> | undefined, pubkey?: string): void;
package/lib/image.js ADDED
@@ -0,0 +1,38 @@
1
+ import { getHashFromURL } from "./helpers.js";
2
+ /**
3
+ * attaches an "error" event listener to a HTMLImageElement element to handle server fallbacks
4
+ * @param image The image element
5
+ * @param getServers A async method to get an ordered list of servers for a pubkey
6
+ * @param pubkey An optional pubkey to set the `data-pubkey` attr on the image
7
+ */
8
+ export function handleImageFallbacks(image, getServers, pubkey) {
9
+ const original = new URL(image.src);
10
+ const hash = getHashFromURL(original);
11
+ if (!hash)
12
+ return;
13
+ if (pubkey)
14
+ image.dataset.pubkey = pubkey;
15
+ let tried = [original.hostname];
16
+ let servers = undefined;
17
+ const onError = async () => {
18
+ const url = new URL(image.src);
19
+ const ext = url.pathname.match(/\.\w+$/i);
20
+ if (!servers)
21
+ servers = (await getServers(image.dataset.pubkey))?.map((s) => (s instanceof URL ? s : new URL(s)));
22
+ if (servers) {
23
+ const server = servers.find((s) => !tried.includes(s.hostname));
24
+ if (server) {
25
+ url.hostname = server.hostname;
26
+ url.pathname = "/" + hash + ext;
27
+ url.protocol = server.protocol;
28
+ image.src = url.toString();
29
+ tried.push(url.hostname);
30
+ }
31
+ else {
32
+ // ran out of servers, stop listening for errors
33
+ image.removeEventListener("error", onError);
34
+ }
35
+ }
36
+ };
37
+ image.addEventListener("error", onError);
38
+ }
package/lib/index.d.ts CHANGED
@@ -1,64 +1,4 @@
1
- export type EventTemplate = {
2
- created_at: number;
3
- kind: number;
4
- content: string;
5
- tags: string[][];
6
- };
7
- export type SignedEvent = EventTemplate & {
8
- id: string;
9
- sig: string;
10
- pubkey: string;
11
- };
12
- /** An async method used to sign nostr events */
13
- export type Signer = (draft: EventTemplate) => Promise<SignedEvent>;
14
- export declare const AUTH_EVENT_KIND = 24242;
15
- export type BlobDescriptor = {
16
- /** @deprecated use uploaded instead */
17
- created?: number;
18
- uploaded: number;
19
- type?: string;
20
- sha256: string;
21
- size: number;
22
- url: string;
23
- };
24
- export declare class HTTPError extends Error {
25
- response: Response;
26
- status: number;
27
- body?: {
28
- message: string;
29
- };
30
- constructor(response: Response, body: {
31
- message: string;
32
- } | string);
33
- static handleErrorResponse(res: Response): Promise<void>;
34
- }
35
- export declare class BlossomClient {
36
- server: string;
37
- signer?: Signer;
38
- constructor(server: string, signer?: Signer);
39
- static getGetAuth(signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
40
- static getUploadAuth(file: File, signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
41
- static getDeleteAuth(hash: string, signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
42
- static getListAuth(signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
43
- getGetAuth(message?: string, expiration?: number): Promise<SignedEvent>;
44
- getUploadAuth(file: File, message?: string, expiration?: number): Promise<SignedEvent>;
45
- getDeleteAuth(hash: string, message?: string, expiration?: number): Promise<SignedEvent>;
46
- getListAuth(message?: string, expiration?: number): Promise<SignedEvent>;
47
- static encodeAuthorizationHeader(event: SignedEvent): string;
48
- static getBlob(server: string, hash: string, auth?: SignedEvent): Promise<Blob>;
49
- getBlob(hash: string, auth?: SignedEvent | boolean): Promise<Blob>;
50
- static hasBlob(server: string, hash: string): Promise<boolean>;
51
- hasBlob(hash: string): Promise<boolean>;
52
- static listBlobs(server: string, pubkey: string, opts?: {
53
- since?: number;
54
- until?: number;
55
- }, auth?: SignedEvent): Promise<BlobDescriptor[]>;
56
- listBlobs(pubkey: string, opts?: {
57
- since?: number;
58
- until?: number;
59
- }, auth?: SignedEvent | boolean): Promise<BlobDescriptor[]>;
60
- static deleteBlob(server: string, hash: string, auth?: SignedEvent): Promise<string>;
61
- deleteBlob(hash: string, auth?: SignedEvent | boolean): Promise<string>;
62
- static uploadBlob(server: string, file: File, auth?: SignedEvent): Promise<BlobDescriptor>;
63
- uploadBlob(file: File, auth?: SignedEvent | boolean): Promise<BlobDescriptor>;
64
- }
1
+ export * from "./client.js";
2
+ export * from "./helpers.js";
3
+ export * from "./image.js";
4
+ export * from "./nostr.js";
package/lib/index.js CHANGED
@@ -1,164 +1,4 @@
1
- import fetch from "cross-fetch";
2
- const now = () => Math.floor(new Date().valueOf() / 1000);
3
- const oneHour = () => now() + 60 * 60;
4
- export const AUTH_EVENT_KIND = 24242;
5
- export class HTTPError extends Error {
6
- constructor(response, body) {
7
- super(typeof body === "string" ? body : body.message);
8
- this.response = response;
9
- this.status = response.status;
10
- if (typeof body == "object")
11
- this.body = body;
12
- }
13
- static async handleErrorResponse(res) {
14
- if (!res.ok) {
15
- try {
16
- throw new HTTPError(res, await res.json());
17
- }
18
- catch (e) {
19
- if (e instanceof Error)
20
- throw new HTTPError(res, e.message);
21
- }
22
- }
23
- }
24
- }
25
- export class BlossomClient {
26
- constructor(server, signer) {
27
- this.server = new URL("/", server).toString();
28
- this.signer = signer;
29
- }
30
- static async getGetAuth(signer, message = "Get Blobs", expiration = oneHour()) {
31
- return await signer({
32
- created_at: now(),
33
- kind: AUTH_EVENT_KIND,
34
- content: message,
35
- tags: [
36
- ["t", "get"],
37
- ["expiration", String(expiration)],
38
- ],
39
- });
40
- }
41
- static async getUploadAuth(file, signer, message = "Upload Blob", expiration = oneHour()) {
42
- return await signer({
43
- created_at: now(),
44
- kind: AUTH_EVENT_KIND,
45
- content: message,
46
- tags: [
47
- ["t", "upload"],
48
- ["name", file.name],
49
- ["size", String(file.size)],
50
- ["expiration", String(expiration)],
51
- ],
52
- });
53
- }
54
- static async getDeleteAuth(hash, signer, message = "Delete Blob", expiration = oneHour()) {
55
- return await signer({
56
- created_at: now(),
57
- kind: AUTH_EVENT_KIND,
58
- content: message,
59
- tags: [
60
- ["t", "delete"],
61
- ["x", hash],
62
- ["expiration", String(expiration)],
63
- ],
64
- });
65
- }
66
- static async getListAuth(signer, message = "List Blobs", expiration = oneHour()) {
67
- return await signer({
68
- created_at: now(),
69
- kind: AUTH_EVENT_KIND,
70
- content: message,
71
- tags: [
72
- ["t", "list"],
73
- ["expiration", String(expiration)],
74
- ],
75
- });
76
- }
77
- async getGetAuth(message, expiration) {
78
- if (!this.signer)
79
- throw new Error("Missing signer");
80
- return await BlossomClient.getGetAuth(this.signer, message, expiration);
81
- }
82
- async getUploadAuth(file, message, expiration) {
83
- if (!this.signer)
84
- throw new Error("Missing signer");
85
- return await BlossomClient.getUploadAuth(file, this.signer, message, expiration);
86
- }
87
- async getDeleteAuth(hash, message, expiration) {
88
- if (!this.signer)
89
- throw new Error("Missing signer");
90
- return await BlossomClient.getDeleteAuth(hash, this.signer, message, expiration);
91
- }
92
- async getListAuth(message, expiration) {
93
- if (!this.signer)
94
- throw new Error("Missing signer");
95
- return await BlossomClient.getListAuth(this.signer, message, expiration);
96
- }
97
- static encodeAuthorizationHeader(event) {
98
- return "Nostr " + btoa(JSON.stringify(event));
99
- }
100
- static async getBlob(server, hash, auth) {
101
- const res = await fetch(new URL(hash, server), {
102
- headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
103
- });
104
- await HTTPError.handleErrorResponse(res);
105
- return await res.blob();
106
- }
107
- async getBlob(hash, auth = false) {
108
- if (typeof auth === "boolean" && auth)
109
- auth = await this.getGetAuth();
110
- return BlossomClient.getBlob(this.server, hash, auth ? auth : undefined);
111
- }
112
- static async hasBlob(server, hash) {
113
- const res = await fetch(new URL(`/` + hash, server), { method: "HEAD" });
114
- await HTTPError.handleErrorResponse(res);
115
- return res.ok;
116
- }
117
- async hasBlob(hash) {
118
- return BlossomClient.hasBlob(this.server, hash);
119
- }
120
- static async listBlobs(server, pubkey, opts, auth) {
121
- const url = new URL(`/list/` + pubkey, server);
122
- if (opts?.since)
123
- url.searchParams.append("since", String(opts.since));
124
- if (opts?.until)
125
- url.searchParams.append("until", String(opts.until));
126
- const res = await fetch(url, {
127
- headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
128
- });
129
- await HTTPError.handleErrorResponse(res);
130
- return (await res.json());
131
- }
132
- async listBlobs(pubkey, opts, auth = false) {
133
- if (typeof auth === "boolean" && auth)
134
- auth = await this.getListAuth();
135
- return BlossomClient.listBlobs(this.server, pubkey, opts, auth ? auth : undefined);
136
- }
137
- static async deleteBlob(server, hash, auth) {
138
- const res = await fetch(new URL("/" + hash, server), {
139
- method: "DELETE",
140
- headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
141
- });
142
- await HTTPError.handleErrorResponse(res);
143
- return await res.text();
144
- }
145
- async deleteBlob(hash, auth = true) {
146
- if (typeof auth === "boolean" && auth)
147
- auth = await this.getDeleteAuth(hash);
148
- return BlossomClient.deleteBlob(this.server, hash, auth ? auth : undefined);
149
- }
150
- static async uploadBlob(server, file, auth) {
151
- const res = await fetch(new URL("/upload", server), {
152
- method: "PUT",
153
- body: file,
154
- headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
155
- });
156
- await HTTPError.handleErrorResponse(res);
157
- return (await res.json());
158
- }
159
- async uploadBlob(file, auth = true) {
160
- if (typeof auth === "boolean" && auth)
161
- auth = await this.getUploadAuth(file);
162
- return BlossomClient.uploadBlob(this.server, file, auth ? auth : undefined);
163
- }
164
- }
1
+ export * from "./client.js";
2
+ export * from "./helpers.js";
3
+ export * from "./image.js";
4
+ export * from "./nostr.js";
package/lib/nostr.d.ts ADDED
@@ -0,0 +1,8 @@
1
+ type NostrEvent = {
2
+ tags: string[][];
3
+ };
4
+ export declare const USER_BLOSSOM_SERVER_LIST_KIND = 10063;
5
+ export declare function areServersEqual(a: string | URL, b: string | URL): boolean;
6
+ /** Returns an ordered array of servers found in a server list event (10063) */
7
+ export declare function getServersFromServerListEvent(event: NostrEvent): URL[];
8
+ export {};
package/lib/nostr.js ADDED
@@ -0,0 +1,21 @@
1
+ export const USER_BLOSSOM_SERVER_LIST_KIND = 10063;
2
+ export function areServersEqual(a, b) {
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
+ /** Returns an ordered array of servers found in a server list event (10063) */
8
+ export function getServersFromServerListEvent(event) {
9
+ const servers = [];
10
+ for (const tag of event.tags) {
11
+ if (tag[0] === "server" && tag[1]) {
12
+ try {
13
+ const url = new URL(tag[1]);
14
+ url.pathname = "/";
15
+ servers.push(url);
16
+ }
17
+ catch (e) { }
18
+ }
19
+ }
20
+ return servers;
21
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blossom-client-sdk",
3
- "version": "0.5.1",
3
+ "version": "0.6.0",
4
4
  "description": "A simple client for manage blobs on blossom servers",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -10,15 +10,39 @@
10
10
  "scripts": {
11
11
  "build": "tsc",
12
12
  "prepublish": "npm run build",
13
- "format": "prettier -w ."
13
+ "format": "prettier -w .",
14
+ "docs": "typedoc src/index.ts"
14
15
  },
15
16
  "files": [
16
17
  "lib"
17
18
  ],
19
+ "exports": {
20
+ ".": {
21
+ "import": "./lib/index.js",
22
+ "types": "./lib/index.d.ts"
23
+ },
24
+ "./client": {
25
+ "import": "./lib/client.js",
26
+ "types": "./lib/client.d.ts"
27
+ },
28
+ "./image": {
29
+ "import": "./lib/image.js",
30
+ "types": "./lib/image.d.ts"
31
+ },
32
+ "./helpers": {
33
+ "import": "./lib/helpers.js",
34
+ "types": "./lib/helpers.d.ts"
35
+ },
36
+ "./nostr": {
37
+ "import": "./lib/nostr.js",
38
+ "types": "./lib/nostr.d.ts"
39
+ }
40
+ },
18
41
  "dependencies": {
19
42
  "cross-fetch": "^4.0.0"
20
43
  },
21
44
  "devDependencies": {
45
+ "@changesets/cli": "^2.27.1",
22
46
  "prettier": "^3.2.5",
23
47
  "typedoc": "^0.25.12",
24
48
  "typescript": "^5.3.3"