blossom-client-sdk 1.1.1 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/client.d.ts CHANGED
@@ -1,88 +1,54 @@
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
- }
1
+ import { getBlobSha256 } from "./helpers.js";
2
+ import { createDeleteAuth, createDownloadAuth, createListAuth, createUploadAuth, encodeAuthorizationHeader } from "./auth.js";
3
+ import { BlobDescriptor, PaymentHandlers as PaymentHandler, SignedEvent, Signer } from "./types.js";
4
+ import { mirrorBlob, MirrorOptions } from "./actions/mirror.js";
5
+ import { uploadBlob, UploadOptions } from "./actions/upload.js";
6
+ import { listBlobs, ListOptions } from "./actions/list.js";
7
+ import { downloadBlob, DownloadOptions } from "./actions/download.js";
8
+ import { deleteBlob, DeleteOptions } from "./actions/delete.js";
35
9
  export type ServerType = string | URL;
36
10
  export type UploadType = Blob | File | Buffer;
37
11
  export declare class BlossomClient {
38
12
  server: URL;
39
13
  signer?: Signer;
14
+ payment?: PaymentHandler<URL>;
40
15
  constructor(server: string | URL, signer?: Signer);
41
- static getFileSha256(file: UploadType): Promise<string>;
42
- static encodeAuthorizationHeader(event: SignedEvent): string;
43
- /**
44
- * Creates a get auth event
45
- * @param signer the signer to use for signing the event
46
- * @param message A human readable explanation of what the auth token will be used for
47
- * @param serverOrHash A server URL or one or many blob hashes
48
- * @param expiration The expiration time in seconds
49
- * @returns {Promise<SignedEvent>}
50
- */
51
- static getGetAuth(signer: Signer, message: string, serverOrHash: string | string[], expiration?: number): Promise<SignedEvent>;
52
- static getBlob(server: ServerType, hash: string, auth?: SignedEvent): Promise<Blob>;
53
- /**
54
- * Creates an upload auth event
55
- * @param sha256 one or an array of sha256 hashes
56
- * @param signer the signer to use for signing the event
57
- * @param message A human readable explanation of what the auth token will be used for
58
- * @param expiration The expiration time in seconds
59
- * @returns {Promise<SignedEvent>}
60
- */
61
- static createUploadAuth(sha256: string | string[], signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
62
- /** Creates a one-off upload auth event for a file */
63
- static getUploadAuth(file: UploadType, signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
64
- static uploadBlob(server: ServerType, file: UploadType, auth?: SignedEvent): Promise<BlobDescriptor>;
65
- static mirrorBlob(server: ServerType, url: string | URL, auth?: SignedEvent): Promise<BlobDescriptor>;
66
- static getListAuth(signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
67
- static listBlobs(server: ServerType, pubkey: string, opts?: {
68
- since?: number;
69
- until?: number;
70
- }, auth?: SignedEvent): Promise<BlobDescriptor[]>;
71
- static getDeleteAuth(hash: string | string[], signer: Signer, message?: string, expiration?: number): Promise<SignedEvent>;
72
- static deleteBlob(server: ServerType, hash: string, auth?: SignedEvent): Promise<string>;
73
- getGetAuth(message: string, serverOrHash: string, expiration?: number): Promise<SignedEvent>;
74
- getBlob(hash: string, auth?: SignedEvent | boolean): Promise<Blob>;
75
- getUploadAuth(file: UploadType, message?: string, expiration?: number): Promise<SignedEvent>;
76
- uploadBlob(file: UploadType, auth?: SignedEvent | boolean): Promise<BlobDescriptor>;
77
- getMirrorAuth(sha256: string, message?: string, expiration?: number): Promise<SignedEvent>;
78
- mirrorBlob(sha256: string, url: string | URL, auth?: SignedEvent | boolean): Promise<BlobDescriptor>;
16
+ static getFileSha256: typeof getBlobSha256;
17
+ static createGetAuth: typeof createDownloadAuth;
18
+ static createUploadAuth: typeof createUploadAuth;
19
+ static createListAuth: typeof createListAuth;
20
+ static createDeleteAuth: typeof createDeleteAuth;
21
+ static encodeAuthorizationHeader: typeof encodeAuthorizationHeader;
22
+ static mirrorBlob: typeof mirrorBlob;
23
+ static uploadBlob: typeof uploadBlob;
24
+ static listBlobs: typeof listBlobs;
25
+ static downloadBlob: typeof downloadBlob;
26
+ static deleteBlob: typeof deleteBlob;
27
+ createDownloadAuth(message: string, hash: string, expiration?: number): Promise<SignedEvent>;
28
+ downloadBlob(hash: string, opts?: Omit<DownloadOptions<URL>, "onAuth" | "onPayment" | "auth"> & {
29
+ auth?: SignedEvent | boolean;
30
+ payment?: boolean;
31
+ }): Promise<Blob>;
32
+ createUploadAuth(blob: UploadType, message?: string, expiration?: number): Promise<SignedEvent>;
33
+ uploadBlob<B extends UploadType>(blob: B, opts?: Omit<UploadOptions<URL, B>, "onAuth" | "onPayment" | "auth"> & {
34
+ auth?: SignedEvent | boolean;
35
+ payment?: boolean;
36
+ }): Promise<BlobDescriptor>;
37
+ createMirrorAuth(blob: string | BlobDescriptor, message?: string, expiration?: number): Promise<SignedEvent>;
38
+ mirrorBlob(blob: BlobDescriptor, opts?: Omit<MirrorOptions<URL>, "onAuth" | "onPayment" | "auth"> & {
39
+ auth?: SignedEvent | boolean;
40
+ payment?: boolean;
41
+ }): Promise<BlobDescriptor>;
79
42
  static hasBlob(server: ServerType, hash: string): Promise<boolean>;
80
43
  hasBlob(hash: string): Promise<boolean>;
81
- getListAuth(message?: string, expiration?: number): Promise<SignedEvent>;
82
- listBlobs(pubkey: string, opts?: {
83
- since?: number;
84
- until?: number;
85
- }, auth?: SignedEvent | boolean): Promise<BlobDescriptor[]>;
86
- getDeleteAuth(hash: string, message?: string, expiration?: number): Promise<SignedEvent>;
87
- deleteBlob(hash: string, auth?: SignedEvent | boolean): Promise<string>;
44
+ createListAuth(message?: string, expiration?: number): Promise<SignedEvent>;
45
+ listBlobs(pubkey: string, opts?: Omit<ListOptions<URL>, "onAuth" | "onPayment" | "auth"> & {
46
+ auth?: SignedEvent | boolean;
47
+ payment?: boolean;
48
+ }): Promise<BlobDescriptor[]>;
49
+ createDeleteAuth(hash: string, message?: string, expiration?: number): Promise<SignedEvent>;
50
+ deleteBlob(hash: string, opts?: Omit<DeleteOptions<URL>, "onAuth" | "onPayment" | "auth"> & {
51
+ auth?: SignedEvent | boolean;
52
+ payment?: boolean;
53
+ }): Promise<boolean>;
88
54
  }
package/lib/client.js CHANGED
@@ -1,260 +1,141 @@
1
- import { bytesToHex } from "@noble/hashes/utils";
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
- response;
7
- status;
8
- body;
9
- constructor(response, body) {
10
- super(typeof body === "string" ? body : body.message);
11
- this.response = response;
12
- this.status = response.status;
13
- if (typeof body == "object")
14
- this.body = body;
15
- }
16
- static async handleErrorResponse(res) {
17
- if (!res.ok) {
18
- try {
19
- throw new HTTPError(res, await res.json());
20
- }
21
- catch (e) {
22
- if (e instanceof Error)
23
- throw new HTTPError(res, e.message);
24
- }
25
- }
26
- }
27
- }
1
+ import { getBlobSha256 } from "./helpers.js";
2
+ import { createDeleteAuth, createDownloadAuth, createListAuth, createUploadAuth, encodeAuthorizationHeader, } from "./auth.js";
3
+ import { mirrorBlob } from "./actions/mirror.js";
4
+ import { uploadBlob } from "./actions/upload.js";
5
+ import { listBlobs } from "./actions/list.js";
6
+ import { downloadBlob } from "./actions/download.js";
7
+ import { deleteBlob } from "./actions/delete.js";
28
8
  export class BlossomClient {
29
9
  server;
30
10
  signer;
11
+ payment;
31
12
  constructor(server, signer) {
32
13
  this.server = new URL("/", server);
33
14
  this.signer = signer;
34
15
  }
35
- static async getFileSha256(file) {
36
- let buffer;
37
- if (file instanceof File || file instanceof Blob) {
38
- buffer = await file.arrayBuffer();
39
- }
40
- else {
41
- // nodejs Buffer
42
- buffer = file;
43
- }
44
- let hash;
45
- if (crypto.subtle) {
46
- const hashBuffer = await crypto.subtle.digest("SHA-256", buffer);
47
- hash = new Uint8Array(hashBuffer);
48
- }
49
- else {
50
- const { sha256 } = await import("@noble/hashes/sha256");
51
- hash = sha256.create().update(new Uint8Array(buffer)).digest();
52
- }
53
- return bytesToHex(hash);
54
- }
55
- static encodeAuthorizationHeader(event) {
56
- return "Nostr " + btoa(JSON.stringify(event));
57
- }
58
- /**
59
- * Creates a get auth event
60
- * @param signer the signer to use for signing the event
61
- * @param message A human readable explanation of what the auth token will be used for
62
- * @param serverOrHash A server URL or one or many blob hashes
63
- * @param expiration The expiration time in seconds
64
- * @returns {Promise<SignedEvent>}
65
- */
66
- static async getGetAuth(signer, message, serverOrHash, expiration = oneHour()) {
67
- const draft = {
68
- created_at: now(),
69
- kind: AUTH_EVENT_KIND,
70
- content: message,
71
- tags: [
72
- ["t", "get"],
73
- ["expiration", String(expiration)],
74
- ],
75
- };
76
- if (Array.isArray(serverOrHash)) {
77
- for (const sha256 of serverOrHash)
78
- draft.tags.push(["x", sha256]);
79
- }
80
- else if (serverOrHash.match(/^[0-9a-f]{64}$/)) {
81
- draft.tags.push(["x", serverOrHash]);
82
- }
83
- else {
84
- draft.tags.push(["server", new URL("/", serverOrHash).toString()]);
85
- }
86
- return await signer(draft);
87
- }
88
- static async getBlob(server, hash, auth) {
89
- const res = await fetch(new URL(hash, server), {
90
- headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
91
- });
92
- await HTTPError.handleErrorResponse(res);
93
- return await res.blob();
94
- }
95
- /**
96
- * Creates an upload auth event
97
- * @param sha256 one or an array of sha256 hashes
98
- * @param signer the signer to use for signing the event
99
- * @param message A human readable explanation of what the auth token will be used for
100
- * @param expiration The expiration time in seconds
101
- * @returns {Promise<SignedEvent>}
102
- */
103
- static async createUploadAuth(sha256, signer, message = "Upload Blob", expiration = oneHour()) {
104
- const draft = {
105
- kind: AUTH_EVENT_KIND,
106
- content: message,
107
- created_at: now(),
108
- tags: [
109
- ["t", "upload"],
110
- ["expiration", String(expiration)],
111
- ],
112
- };
113
- if (Array.isArray(sha256)) {
114
- for (const hash of sha256)
115
- draft.tags.push(["x", hash]);
116
- }
117
- else
118
- draft.tags.push(["x", sha256]);
119
- return await signer(draft);
120
- }
121
- /** Creates a one-off upload auth event for a file */
122
- static async getUploadAuth(file, signer, message = "Upload Blob", expiration = oneHour()) {
123
- const sha256 = await BlossomClient.getFileSha256(file);
124
- return await BlossomClient.createUploadAuth(sha256, signer, message, expiration);
125
- }
126
- static async uploadBlob(server, file, auth) {
127
- const res = await fetch(new URL("/upload", server), {
128
- method: "PUT",
129
- body: file,
130
- headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
131
- });
132
- await HTTPError.handleErrorResponse(res);
133
- return (await res.json());
134
- }
135
- // static mirror blob
136
- static async mirrorBlob(server, url, auth) {
137
- const res = await fetch(new URL("/mirror", server), {
138
- method: "PUT",
139
- body: JSON.stringify({ url: url.toString() }),
140
- headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
141
- });
142
- await HTTPError.handleErrorResponse(res);
143
- return (await res.json());
144
- }
145
- // static list blobs
146
- static async getListAuth(signer, message = "List Blobs", expiration = oneHour()) {
147
- return await signer({
148
- created_at: now(),
149
- kind: AUTH_EVENT_KIND,
150
- content: message,
151
- tags: [
152
- ["t", "list"],
153
- ["expiration", String(expiration)],
154
- ],
155
- });
156
- }
157
- static async listBlobs(server, pubkey, opts, auth) {
158
- const url = new URL(`/list/` + pubkey, server);
159
- if (opts?.since)
160
- url.searchParams.append("since", String(opts.since));
161
- if (opts?.until)
162
- url.searchParams.append("until", String(opts.until));
163
- const res = await fetch(url, {
164
- headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
165
- });
166
- await HTTPError.handleErrorResponse(res);
167
- return (await res.json());
168
- }
169
- // static delete blob
170
- static async getDeleteAuth(hash, signer, message = "Delete Blob", expiration = oneHour()) {
171
- const draft = {
172
- created_at: now(),
173
- kind: AUTH_EVENT_KIND,
174
- content: message,
175
- tags: [
176
- ["t", "delete"],
177
- ["expiration", String(expiration)],
178
- ],
179
- };
180
- if (Array.isArray(hash)) {
181
- for (const x of hash)
182
- draft.tags.push(["x", x]);
183
- }
184
- else
185
- draft.tags.push(["x", hash]);
186
- return await signer(draft);
187
- }
188
- static async deleteBlob(server, hash, auth) {
189
- const res = await fetch(new URL("/" + hash, server), {
190
- method: "DELETE",
191
- headers: auth ? { authorization: BlossomClient.encodeAuthorizationHeader(auth) } : {},
192
- });
193
- await HTTPError.handleErrorResponse(res);
194
- return await res.text();
195
- }
196
- // get blob
197
- async getGetAuth(message, serverOrHash, expiration) {
16
+ // moved to helpers.ts
17
+ static getFileSha256 = getBlobSha256;
18
+ // static auth methods moved to auth.ts
19
+ static createGetAuth = createDownloadAuth;
20
+ static createUploadAuth = createUploadAuth;
21
+ static createListAuth = createListAuth;
22
+ static createDeleteAuth = createDeleteAuth;
23
+ // util
24
+ static encodeAuthorizationHeader = encodeAuthorizationHeader;
25
+ // static blob methods moved to actions
26
+ static mirrorBlob = mirrorBlob;
27
+ static uploadBlob = uploadBlob;
28
+ static listBlobs = listBlobs;
29
+ static downloadBlob = downloadBlob;
30
+ static deleteBlob = deleteBlob;
31
+ // download blob
32
+ async createDownloadAuth(message, hash, expiration) {
198
33
  if (!this.signer)
199
34
  throw new Error("Missing signer");
200
- return await BlossomClient.getGetAuth(this.signer, message, serverOrHash, expiration);
201
- }
202
- async getBlob(hash, auth = false) {
203
- if (typeof auth === "boolean" && auth)
204
- auth = await this.getGetAuth("Get Blob", hash);
205
- return BlossomClient.getBlob(this.server, hash, auth ? auth : undefined);
35
+ return await createDownloadAuth(this.signer, hash, message, expiration);
36
+ }
37
+ async downloadBlob(hash, opts) {
38
+ const options = { signal: opts?.signal };
39
+ // attach auth
40
+ if (opts?.auth !== false) {
41
+ if (typeof opts?.auth === "object")
42
+ options.auth = opts.auth;
43
+ if (this.signer)
44
+ options.auth = await this.createDownloadAuth(`Download ${hash}`, hash);
45
+ }
46
+ // attach payment
47
+ if (opts?.payment !== false && this.payment)
48
+ options.onPayment = this.payment.download;
49
+ const download = await downloadBlob(this.server, hash, options);
50
+ return download.blob();
206
51
  }
207
52
  // upload blob
208
- async getUploadAuth(file, message, expiration) {
53
+ async createUploadAuth(blob, message, expiration) {
209
54
  if (!this.signer)
210
55
  throw new Error("Missing signer");
211
- return await BlossomClient.getUploadAuth(file, this.signer, message, expiration);
212
- }
213
- async uploadBlob(file, auth = true) {
214
- if (typeof auth === "boolean" && auth)
215
- auth = await this.getUploadAuth(file);
216
- return BlossomClient.uploadBlob(this.server, file, auth ? auth : undefined);
56
+ const hash = await getBlobSha256(blob);
57
+ return await createUploadAuth(this.signer, hash, message, expiration);
58
+ }
59
+ async uploadBlob(blob, opts) {
60
+ const options = { signal: opts?.signal };
61
+ // attach auth
62
+ if (opts?.auth !== false) {
63
+ if (typeof opts?.auth === "object")
64
+ options.auth = opts.auth;
65
+ if (this.signer)
66
+ options.auth = await this.createUploadAuth(blob);
67
+ }
68
+ // attach payment
69
+ if (opts?.payment !== false && this.payment)
70
+ options.onPayment = this.payment.upload;
71
+ return uploadBlob(this.server, blob, options);
217
72
  }
218
73
  // mirror blob
219
- async getMirrorAuth(sha256, message, expiration) {
74
+ async createMirrorAuth(blob, message, expiration) {
220
75
  if (!this.signer)
221
76
  throw new Error("Missing signer");
222
- return await BlossomClient.createUploadAuth(sha256, this.signer, message, expiration);
223
- }
224
- async mirrorBlob(sha256, url, auth = true) {
225
- if (typeof auth === "boolean" && auth)
226
- auth = await this.getMirrorAuth(sha256);
227
- return BlossomClient.mirrorBlob(this.server, url, auth ? auth : undefined);
77
+ return await createUploadAuth(this.signer, typeof blob === "string" ? blob : blob.sha256, message, expiration);
78
+ }
79
+ async mirrorBlob(blob, opts) {
80
+ const options = { signal: opts?.signal };
81
+ // attach auth
82
+ if (opts?.auth !== false) {
83
+ if (typeof opts?.auth === "object")
84
+ options.auth = opts.auth;
85
+ if (this.signer)
86
+ options.auth = await this.createMirrorAuth(blob);
87
+ }
88
+ // attach payment
89
+ if (opts?.payment !== false && this.payment)
90
+ options.onPayment = this.payment.mirror;
91
+ return mirrorBlob(this.server, blob, options);
228
92
  }
229
93
  // has blob
230
94
  static async hasBlob(server, hash) {
231
95
  const res = await fetch(new URL(`/` + hash, server), { method: "HEAD" });
232
- await HTTPError.handleErrorResponse(res);
233
- return res.ok;
96
+ return res.status !== 404;
234
97
  }
235
98
  async hasBlob(hash) {
236
99
  return BlossomClient.hasBlob(this.server, hash);
237
100
  }
238
101
  // list blobs
239
- async getListAuth(message, expiration) {
102
+ async createListAuth(message, expiration) {
240
103
  if (!this.signer)
241
104
  throw new Error("Missing signer");
242
- return await BlossomClient.getListAuth(this.signer, message, expiration);
243
- }
244
- async listBlobs(pubkey, opts, auth = false) {
245
- if (typeof auth === "boolean" && auth)
246
- auth = await this.getListAuth();
247
- return BlossomClient.listBlobs(this.server, pubkey, opts, auth ? auth : undefined);
105
+ return await createListAuth(this.signer, message, expiration);
106
+ }
107
+ async listBlobs(pubkey, opts) {
108
+ const options = { signal: opts?.signal };
109
+ // attach auth
110
+ if (opts?.auth !== false) {
111
+ if (typeof opts?.auth === "object")
112
+ options.auth = opts.auth;
113
+ if (this.signer)
114
+ options.auth = await this.createListAuth();
115
+ }
116
+ // attach payment
117
+ if (opts?.payment !== false && this.payment)
118
+ options.onPayment = this.payment.list;
119
+ return listBlobs(this.server, pubkey, options);
248
120
  }
249
121
  // delete blob
250
- async getDeleteAuth(hash, message, expiration) {
122
+ async createDeleteAuth(hash, message, expiration) {
251
123
  if (!this.signer)
252
124
  throw new Error("Missing signer");
253
- return await BlossomClient.getDeleteAuth(hash, this.signer, message, expiration);
254
- }
255
- async deleteBlob(hash, auth = true) {
256
- if (typeof auth === "boolean" && auth)
257
- auth = await this.getDeleteAuth(hash);
258
- return BlossomClient.deleteBlob(this.server, hash, auth ? auth : undefined);
125
+ return await createDeleteAuth(this.signer, hash, message, expiration);
126
+ }
127
+ async deleteBlob(hash, opts) {
128
+ const options = { signal: opts?.signal };
129
+ // attach auth
130
+ if (opts?.auth !== false) {
131
+ if (typeof opts?.auth === "object")
132
+ options.auth = opts.auth;
133
+ if (this.signer)
134
+ options.auth = await this.createListAuth();
135
+ }
136
+ // attach payment
137
+ if (opts?.payment !== false && this.payment)
138
+ options.onPayment = this.payment.delete;
139
+ return BlossomClient.deleteBlob(this.server, hash, options);
259
140
  }
260
141
  }
package/lib/const.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare const AUTH_EVENT_KIND = 24242;
package/lib/const.js ADDED
@@ -0,0 +1 @@
1
+ export const AUTH_EVENT_KIND = 24242;
package/lib/error.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ export default class HTTPError extends Error {
2
+ response: Response;
3
+ status: number;
4
+ body?: {
5
+ message: string;
6
+ };
7
+ constructor(response: Response, body: {
8
+ message: string;
9
+ } | string);
10
+ static handleErrorResponse(res: Response): Promise<void>;
11
+ }
package/lib/error.js ADDED
@@ -0,0 +1,22 @@
1
+ export default class HTTPError extends Error {
2
+ response;
3
+ status;
4
+ body;
5
+ constructor(response, body) {
6
+ super(typeof body === "string" ? body : body.message);
7
+ this.response = response;
8
+ this.status = response.status;
9
+ if (typeof body == "object")
10
+ this.body = body;
11
+ }
12
+ static async handleErrorResponse(res) {
13
+ if (!res.ok) {
14
+ try {
15
+ throw new HTTPError(res, res.headers.get("x-reason") || "Something went wrong");
16
+ }
17
+ catch (e) {
18
+ throw e;
19
+ }
20
+ }
21
+ }
22
+ }
package/lib/helpers.d.ts CHANGED
@@ -1,2 +1,19 @@
1
+ import { type UploadType } from "./client.js";
2
+ import { PaymentRequest } from "./types.js";
1
3
  /** returns the last sha256 in a URL */
2
4
  export declare function getHashFromURL(url: string | URL): string | null;
5
+ export declare const BlobHashSymbol: unique symbol;
6
+ /** gets or calculates the sha2456 of a Blob */
7
+ export declare function getBlobSha256(blob: UploadType): string | Promise<string>;
8
+ /** Calculates the sha2456 of a Blob */
9
+ export declare function computeBlobSha256(blob: UploadType): Promise<string>;
10
+ /** Returns the size of the blob in bytes */
11
+ export declare function getBlobSize(blob: UploadType): number;
12
+ /** Returns the mimt type of the blob */
13
+ export declare function getBlobType(blob: UploadType): string | undefined;
14
+ /** Check if two servers are the same */
15
+ export declare function areServersEqual(a: string | URL, b: string | URL): boolean;
16
+ /** Extracts a cashu-ts PaymentRequest from Headers */
17
+ export declare function getPaymentRequestFromHeaders(headers: Headers): PaymentRequest;
18
+ export declare function getPaymentRequestFromHeaders(headers: Headers, quite: false): PaymentRequest;
19
+ export declare function getPaymentRequestFromHeaders(headers: Headers, quite: true): PaymentRequest | undefined;
package/lib/helpers.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { bytesToHex } from "@noble/hashes/utils";
1
2
  /** returns the last sha256 in a URL */
2
3
  export function getHashFromURL(url) {
3
4
  if (typeof url === "string")
@@ -7,3 +8,63 @@ export function getHashFromURL(url) {
7
8
  return hashes[hashes.length - 1][0];
8
9
  return null;
9
10
  }
11
+ export const BlobHashSymbol = Symbol.for("sha256");
12
+ /** gets or calculates the sha2456 of a Blob */
13
+ export function getBlobSha256(blob) {
14
+ if (Reflect.has(blob, BlobHashSymbol))
15
+ return Reflect.get(blob, BlobHashSymbol);
16
+ return computeBlobSha256(blob).then((hash) => {
17
+ Reflect.set(blob, BlobHashSymbol, hash);
18
+ return hash;
19
+ });
20
+ }
21
+ /** Calculates the sha2456 of a Blob */
22
+ export async function computeBlobSha256(blob) {
23
+ let buffer;
24
+ if (blob instanceof File || blob instanceof Blob) {
25
+ buffer = await blob.arrayBuffer();
26
+ }
27
+ else {
28
+ // nodejs Buffer
29
+ buffer = blob;
30
+ }
31
+ let hash;
32
+ if (crypto.subtle) {
33
+ const hashBuffer = await crypto.subtle.digest("SHA-256", buffer);
34
+ hash = new Uint8Array(hashBuffer);
35
+ }
36
+ else {
37
+ const { sha256 } = await import("@noble/hashes/sha256");
38
+ hash = sha256.create().update(new Uint8Array(buffer)).digest();
39
+ }
40
+ return bytesToHex(hash);
41
+ }
42
+ /** Returns the size of the blob in bytes */
43
+ export function getBlobSize(blob) {
44
+ if (blob instanceof File || blob instanceof Blob) {
45
+ return blob.size;
46
+ }
47
+ else {
48
+ // nodejs Buffer
49
+ return blob.length;
50
+ }
51
+ }
52
+ /** Returns the mimt type of the blob */
53
+ export function getBlobType(blob) {
54
+ if (blob instanceof File || blob instanceof Blob) {
55
+ return blob.type;
56
+ }
57
+ return undefined;
58
+ }
59
+ /** Check if two servers are the same */
60
+ export function areServersEqual(a, b) {
61
+ const hostnameA = a instanceof URL ? a.hostname : new URL(a).hostname;
62
+ const hostnameB = b instanceof URL ? b.hostname : new URL(b).hostname;
63
+ return hostnameA === hostnameB;
64
+ }
65
+ export function getPaymentRequestFromHeaders(headers, quite = false) {
66
+ const header = headers.get("X-Cashu");
67
+ if (!header && !quite)
68
+ throw new Error("Missing cashu header");
69
+ return header ? JSON.parse(atob(header)) : undefined;
70
+ }
package/lib/index.d.ts CHANGED
@@ -1,5 +1,8 @@
1
+ export * from "./const.js";
2
+ export * from "./auth.js";
1
3
  export * from "./client.js";
2
4
  export * from "./helpers.js";
3
5
  export * from "./image.js";
4
6
  export * from "./nostr.js";
5
- export * from "./upload.js";
7
+ export * from "./error.js";
8
+ export * from "./types.js";
package/lib/index.js CHANGED
@@ -1,5 +1,8 @@
1
+ export * from "./const.js";
2
+ export * from "./auth.js";
1
3
  export * from "./client.js";
2
4
  export * from "./helpers.js";
3
5
  export * from "./image.js";
4
6
  export * from "./nostr.js";
5
- export * from "./upload.js";
7
+ export * from "./error.js";
8
+ export * from "./types.js";