blossom-client-sdk 4.0.0 → 5.0.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.
Files changed (75) hide show
  1. package/README.md +246 -92
  2. package/lib/actions/delete.d.ts +5 -3
  3. package/lib/actions/delete.js +28 -7
  4. package/lib/actions/download.d.ts +5 -3
  5. package/lib/actions/download.js +28 -7
  6. package/lib/actions/has.d.ts +9 -0
  7. package/lib/actions/has.js +10 -0
  8. package/lib/actions/index.d.ts +3 -0
  9. package/lib/actions/index.js +3 -0
  10. package/lib/actions/list.d.ts +10 -4
  11. package/lib/actions/list.js +45 -7
  12. package/lib/actions/media.d.ts +1 -1
  13. package/lib/actions/media.js +29 -7
  14. package/lib/actions/mirror.d.ts +5 -3
  15. package/lib/actions/mirror.js +28 -7
  16. package/lib/actions/multi-server.d.ts +63 -43
  17. package/lib/actions/multi-server.js +208 -88
  18. package/lib/actions/report.d.ts +11 -0
  19. package/lib/actions/report.js +35 -0
  20. package/lib/actions/resolve.d.ts +27 -0
  21. package/lib/actions/resolve.js +129 -0
  22. package/lib/actions/upload.d.ts +5 -3
  23. package/lib/actions/upload.js +28 -7
  24. package/lib/auth.d.ts +23 -2
  25. package/lib/auth.js +82 -22
  26. package/lib/error.d.ts +5 -0
  27. package/lib/error.js +11 -0
  28. package/lib/helpers/blob.d.ts +1 -1
  29. package/lib/helpers/blossom-uri.d.ts +20 -0
  30. package/lib/helpers/blossom-uri.js +77 -0
  31. package/lib/helpers/cachu.d.ts +5 -0
  32. package/lib/helpers/cachu.js +14 -0
  33. package/lib/helpers/index.d.ts +1 -0
  34. package/lib/helpers/index.js +1 -0
  35. package/lib/helpers/url.d.ts +2 -0
  36. package/lib/helpers/url.js +9 -3
  37. package/lib/helpers.d.ts +20 -0
  38. package/lib/helpers.js +73 -0
  39. package/lib/hls.d.ts +20 -0
  40. package/lib/hls.js +182 -0
  41. package/lib/index.d.ts +1 -2
  42. package/lib/index.js +1 -2
  43. package/lib/media.d.ts +37 -0
  44. package/lib/media.js +179 -0
  45. package/lib/types.d.ts +3 -1
  46. package/lib/upload.d.ts +13 -0
  47. package/lib/upload.js +37 -0
  48. package/package.json +16 -7
  49. package/src/actions/delete.ts +31 -8
  50. package/src/actions/download.ts +31 -8
  51. package/src/actions/has.ts +19 -0
  52. package/src/actions/index.ts +3 -0
  53. package/src/actions/list.ts +55 -8
  54. package/src/actions/media.ts +29 -6
  55. package/src/actions/mirror.ts +31 -8
  56. package/src/actions/multi-server.ts +268 -111
  57. package/src/actions/report.ts +54 -0
  58. package/src/actions/resolve.ts +159 -0
  59. package/src/actions/upload.ts +31 -8
  60. package/src/auth.ts +105 -19
  61. package/src/error.ts +15 -0
  62. package/src/helpers/blob.ts +1 -1
  63. package/src/helpers/blossom-uri.ts +99 -0
  64. package/src/helpers/index.ts +1 -0
  65. package/src/helpers/url.ts +10 -3
  66. package/src/hls.ts +255 -0
  67. package/src/index.ts +1 -2
  68. package/src/media.ts +200 -0
  69. package/src/types.ts +4 -1
  70. package/lib/client.d.ts +0 -61
  71. package/lib/client.js +0 -160
  72. package/lib/image.d.ts +0 -17
  73. package/lib/image.js +0 -107
  74. package/src/client.ts +0 -221
  75. package/src/image.ts +0 -122
package/lib/auth.d.ts CHANGED
@@ -1,11 +1,32 @@
1
- import { ServerType, UploadType } from "./client.js";
1
+ import { ServerType, UploadType } from "./types.js";
2
2
  import { SignedEvent, Signer } from "./types.js";
3
3
  export declare const now: () => number;
4
4
  export declare const oneHour: () => number;
5
+ export type AuthRequest = {
6
+ server: ServerType;
7
+ type: AuthType;
8
+ blob?: string | UploadType;
9
+ };
5
10
  /** Encodes an auth event into a nostr authorization header */
6
11
  export declare function encodeAuthorizationHeader(event: SignedEvent): string;
7
12
  /** Checks if an auth event matches a server / blob upload */
8
- export declare function doseAuthMatchUpload(auth: SignedEvent, server: ServerType, blob: string | UploadType): Promise<boolean>;
13
+ export declare function doseAuthMatchBlob(auth: SignedEvent, server: ServerType, blob: string | UploadType, type?: string): Promise<boolean>;
14
+ /** Returns all tag values for a specific tag name */
15
+ export declare function getAuthTagValues(auth: SignedEvent, tagName: string): string[];
16
+ /** Returns the auth event expiration timestamp if one exists */
17
+ export declare function getAuthExpiration(auth: SignedEvent): number | undefined;
18
+ /** Returns true if an auth event has expired */
19
+ export declare function isAuthExpired(auth: SignedEvent, timestamp?: number): boolean;
20
+ /** Normalizes a server tag value to a lowercase hostname */
21
+ export declare function normalizeServerTag(server: string | URL): string;
22
+ /** Checks if an auth event can be reused for a request */
23
+ export declare function doesAuthMatchRequest(auth: SignedEvent, request: AuthRequest): Promise<boolean>;
24
+ /** Finds a reusable auth event in a store and prunes expired events */
25
+ export declare function getReusableAuthEvent(authEvents: Set<SignedEvent>, request: AuthRequest): Promise<SignedEvent | undefined>;
26
+ /** Stores a new auth event in the shared store */
27
+ export declare function storeAuthEvent(authEvents: Set<SignedEvent>, auth: SignedEvent): SignedEvent;
28
+ /** @deprecated Use `doseAuthMatchBlob` instead */
29
+ export declare const doseAuthMatchUpload: typeof doseAuthMatchBlob;
9
30
  export type AuthType = "upload" | "list" | "delete" | "get" | "media";
10
31
  export type AuthEventOptions = {
11
32
  blobs?: string | string[] | UploadType | UploadType[];
package/lib/auth.js CHANGED
@@ -1,35 +1,98 @@
1
1
  import { AUTH_EVENT_KIND } from "./const.js";
2
2
  import { getBlobSha256, isSha256 } from "./helpers/blob.js";
3
- import { areServersEqual } from "./helpers/url.js";
3
+ import { areServersEqual, getServerHostname } from "./helpers/url.js";
4
4
  export const now = () => Math.floor(new Date().valueOf() / 1000);
5
5
  export const oneHour = () => now() + 60 * 60;
6
6
  /** Encodes an auth event into a nostr authorization header */
7
7
  export function encodeAuthorizationHeader(event) {
8
- return "Nostr " + btoa(JSON.stringify(event));
8
+ const json = JSON.stringify(event);
9
+ const bytes = new TextEncoder().encode(json);
10
+ let binary = "";
11
+ for (const byte of bytes)
12
+ binary += String.fromCharCode(byte);
13
+ return "Nostr " + btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
9
14
  }
10
15
  /** Checks if an auth event matches a server / blob upload */
11
- export async function doseAuthMatchUpload(auth, server, blob) {
12
- const type = auth.tags.find((t) => t[0] === "t")?.[1];
16
+ export async function doseAuthMatchBlob(auth, server, blob, type = "upload") {
13
17
  if (type !== "upload" && type !== "media")
14
18
  return false;
15
- const sha256 = typeof blob === "string" ? blob : await getBlobSha256(blob);
16
- for (const tag of auth.tags) {
17
- switch (tag[0]) {
18
- case "x":
19
- if (tag[1] === sha256)
20
- return true;
21
- break;
22
- case "server":
23
- if (areServersEqual(tag[1], server))
24
- return true;
25
- break;
19
+ return doesAuthMatchRequest(auth, { server, type, blob });
20
+ }
21
+ /** Returns all tag values for a specific tag name */
22
+ export function getAuthTagValues(auth, tagName) {
23
+ return auth.tags.filter((tag) => tag[0] === tagName).map((tag) => tag[1]);
24
+ }
25
+ /** Returns the auth event expiration timestamp if one exists */
26
+ export function getAuthExpiration(auth) {
27
+ const expiration = auth.tags.find((tag) => tag[0] === "expiration")?.[1];
28
+ if (!expiration)
29
+ return undefined;
30
+ const timestamp = Number(expiration);
31
+ if (!Number.isFinite(timestamp))
32
+ return undefined;
33
+ return timestamp;
34
+ }
35
+ /** Returns true if an auth event has expired */
36
+ export function isAuthExpired(auth, timestamp = now()) {
37
+ const expiration = getAuthExpiration(auth);
38
+ return expiration !== undefined && expiration <= timestamp;
39
+ }
40
+ /** Normalizes a server tag value to a lowercase hostname */
41
+ export function normalizeServerTag(server) {
42
+ return getServerHostname(server);
43
+ }
44
+ function requestRequiresHashTag(type) {
45
+ return type === "upload" || type === "media" || type === "delete";
46
+ }
47
+ /** Checks if an auth event can be reused for a request */
48
+ export async function doesAuthMatchRequest(auth, request) {
49
+ if (isAuthExpired(auth))
50
+ return false;
51
+ const authType = auth.tags.find((tag) => tag[0] === "t")?.[1];
52
+ if (authType !== request.type)
53
+ return false;
54
+ const serverTags = getAuthTagValues(auth, "server");
55
+ if (serverTags.length > 0 && !serverTags.some((server) => areServersEqual(server, request.server)))
56
+ return false;
57
+ if (request.type === "list")
58
+ return true;
59
+ const blobTags = getAuthTagValues(auth, "x");
60
+ if (!request.blob)
61
+ return false;
62
+ const sha256 = typeof request.blob === "string" ? request.blob : await getBlobSha256(request.blob);
63
+ if (blobTags.length === 0)
64
+ return !requestRequiresHashTag(request.type);
65
+ return blobTags.includes(sha256);
66
+ }
67
+ /** Finds a reusable auth event in a store and prunes expired events */
68
+ export async function getReusableAuthEvent(authEvents, request) {
69
+ for (const auth of authEvents) {
70
+ if (isAuthExpired(auth)) {
71
+ authEvents.delete(auth);
72
+ continue;
26
73
  }
74
+ if (await doesAuthMatchRequest(auth, request))
75
+ return auth;
27
76
  }
28
- return false;
77
+ return undefined;
78
+ }
79
+ /** Stores a new auth event in the shared store */
80
+ export function storeAuthEvent(authEvents, auth) {
81
+ authEvents.add(auth);
82
+ return auth;
29
83
  }
84
+ /** @deprecated Use `doseAuthMatchBlob` instead */
85
+ export const doseAuthMatchUpload = doseAuthMatchBlob;
30
86
  async function normalizeToHash(blob) {
31
87
  return typeof blob === "string" ? blob : getBlobSha256(blob);
32
88
  }
89
+ function normalizeServers(servers) {
90
+ const values = Array.isArray(servers) ? servers : [servers];
91
+ return [...new Set(values.map((server) => normalizeServerTag(server)))];
92
+ }
93
+ function isDomainName(value) {
94
+ return /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(value);
95
+ }
33
96
  /** Generic auth event builder */
34
97
  export async function createAuthEvent(signer, type, options) {
35
98
  const draft = {
@@ -59,11 +122,8 @@ export async function createAuthEvent(signer, type, options) {
59
122
  }
60
123
  // add server tags
61
124
  if (options?.servers) {
62
- if (Array.isArray(options.servers))
63
- for (const server of new Set(options.servers))
64
- draft.tags.push(["server", server]);
65
- else
66
- draft.tags.push(["server", options.servers]);
125
+ for (const server of normalizeServers(options.servers))
126
+ draft.tags.push(["server", server]);
67
127
  }
68
128
  return await signer(draft);
69
129
  }
@@ -75,7 +135,7 @@ export async function createDownloadAuth(signer, serverOrHash, options) {
75
135
  message: "Download Blob",
76
136
  ...options,
77
137
  blobs: serverOrHash.filter((s) => (typeof s === "string" ? isSha256(s) : true)),
78
- servers: serverOrHash.filter((s) => typeof s === "string" && !isSha256(s) && URL.canParse(s)),
138
+ servers: serverOrHash.filter((s) => typeof s === "string" && !isSha256(s) && (URL.canParse(s) || isDomainName(s))),
79
139
  });
80
140
  }
81
141
  /** Creates an upload or media upload auth event */
package/lib/error.d.ts CHANGED
@@ -1,11 +1,16 @@
1
+ export type RejectionCode = "conflict" | "too_large" | "unsupported_type" | "unprocessable";
1
2
  export default class HTTPError extends Error {
2
3
  response: Response;
3
4
  status: number;
4
5
  body?: {
5
6
  message: string;
6
7
  };
8
+ code?: RejectionCode;
7
9
  constructor(response: Response, body: {
8
10
  message: string;
9
11
  } | string);
12
+ static isRejection(error: unknown): error is HTTPError & {
13
+ code: RejectionCode;
14
+ };
10
15
  static handleErrorResponse(res: Response): Promise<void>;
11
16
  }
package/lib/error.js CHANGED
@@ -1,14 +1,25 @@
1
+ const REJECTION_CODES = {
2
+ 409: "conflict",
3
+ 413: "too_large",
4
+ 415: "unsupported_type",
5
+ 422: "unprocessable",
6
+ };
1
7
  export default class HTTPError extends Error {
2
8
  response;
3
9
  status;
4
10
  body;
11
+ code;
5
12
  constructor(response, body) {
6
13
  super(typeof body === "string" ? body : body.message);
7
14
  this.response = response;
8
15
  this.status = response.status;
16
+ this.code = REJECTION_CODES[response.status];
9
17
  if (typeof body == "object")
10
18
  this.body = body;
11
19
  }
20
+ static isRejection(error) {
21
+ return error instanceof HTTPError && error.code !== undefined;
22
+ }
12
23
  static async handleErrorResponse(res) {
13
24
  if (!res.ok) {
14
25
  try {
@@ -1,4 +1,4 @@
1
- import { UploadType } from "../client.js";
1
+ import { UploadType } from "../types.js";
2
2
  /** Checks if a string is a 64 length hex string */
3
3
  export declare function isSha256(str: string): RegExpMatchArray | null;
4
4
  /** A symbol use to store the sha256 hash of a blob on a Blob instance */
@@ -0,0 +1,20 @@
1
+ export type BlossomURI = {
2
+ /** SHA-256 hash of the blob */
3
+ sha256: string;
4
+ /** File extension (e.g. "png", "pdf") */
5
+ ext: string;
6
+ /** Server hints from xs params */
7
+ servers: string[];
8
+ /** Author pubkey hints from as params */
9
+ authors: string[];
10
+ /** Expected blob size in bytes from sz param */
11
+ size?: number;
12
+ };
13
+ /** Parses a blossom: URI string into its components */
14
+ export declare function parseBlossomURI(uri: string): BlossomURI;
15
+ /** Builds a blossom: URI string from components */
16
+ export declare function buildBlossomURI(options: BlossomURI): string;
17
+ /** Converts a BlossomURI to a native URL object */
18
+ export declare function blossomURIToURL(uri: string | BlossomURI): URL;
19
+ /** Parses a blossom: URL object into its components */
20
+ export declare function blossomURIFromURL(url: URL): BlossomURI;
@@ -0,0 +1,77 @@
1
+ import { isSha256 } from "./blob.js";
2
+ /** Parses a blossom: URI string into its components */
3
+ export function parseBlossomURI(uri) {
4
+ if (!uri.startsWith("blossom:"))
5
+ throw new Error("Invalid blossom URI: missing blossom: scheme");
6
+ const body = uri.slice("blossom:".length);
7
+ // split hash.ext from query params
8
+ const queryIndex = body.indexOf("?");
9
+ const path = queryIndex === -1 ? body : body.slice(0, queryIndex);
10
+ const query = queryIndex === -1 ? "" : body.slice(queryIndex + 1);
11
+ // extract sha256 and extension
12
+ const dotIndex = path.indexOf(".");
13
+ if (dotIndex === -1)
14
+ throw new Error("Invalid blossom URI: missing file extension");
15
+ const sha256 = path.slice(0, dotIndex);
16
+ const ext = path.slice(dotIndex + 1);
17
+ if (!isSha256(sha256))
18
+ throw new Error("Invalid blossom URI: invalid sha256 hash");
19
+ if (!ext)
20
+ throw new Error("Invalid blossom URI: empty file extension");
21
+ // parse query params
22
+ const params = new URLSearchParams(query);
23
+ const servers = params.getAll("xs");
24
+ const authors = params.getAll("as");
25
+ const szValue = params.get("sz");
26
+ let size;
27
+ if (szValue !== null) {
28
+ size = Number(szValue);
29
+ if (!Number.isFinite(size) || size <= 0 || Math.floor(size) !== size) {
30
+ throw new Error("Invalid blossom URI: sz must be a positive integer");
31
+ }
32
+ }
33
+ return { sha256, ext, servers, authors, size };
34
+ }
35
+ /** Builds a blossom: URI string from components */
36
+ export function buildBlossomURI(options) {
37
+ const params = new URLSearchParams();
38
+ for (const server of options.servers)
39
+ params.append("xs", server);
40
+ for (const author of options.authors)
41
+ params.append("as", author);
42
+ if (options.size !== undefined)
43
+ params.append("sz", String(options.size));
44
+ const query = params.toString();
45
+ return `blossom:${options.sha256}.${options.ext}${query ? "?" + query : ""}`;
46
+ }
47
+ /** Converts a BlossomURI to a native URL object */
48
+ export function blossomURIToURL(uri) {
49
+ const str = typeof uri === "string" ? uri : buildBlossomURI(uri);
50
+ return new URL(str);
51
+ }
52
+ /** Parses a blossom: URL object into its components */
53
+ export function blossomURIFromURL(url) {
54
+ if (url.protocol !== "blossom:")
55
+ throw new Error("Invalid blossom URL: expected blossom: protocol");
56
+ const path = url.pathname;
57
+ const dotIndex = path.indexOf(".");
58
+ if (dotIndex === -1)
59
+ throw new Error("Invalid blossom URL: missing file extension");
60
+ const sha256 = path.slice(0, dotIndex);
61
+ const ext = path.slice(dotIndex + 1);
62
+ if (!isSha256(sha256))
63
+ throw new Error("Invalid blossom URL: invalid sha256 hash");
64
+ if (!ext)
65
+ throw new Error("Invalid blossom URL: empty file extension");
66
+ const servers = url.searchParams.getAll("xs");
67
+ const authors = url.searchParams.getAll("as");
68
+ const szValue = url.searchParams.get("sz");
69
+ let size;
70
+ if (szValue !== null) {
71
+ size = Number(szValue);
72
+ if (!Number.isFinite(size) || size <= 0 || Math.floor(size) !== size) {
73
+ throw new Error("Invalid blossom URL: sz must be a positive integer");
74
+ }
75
+ }
76
+ return { sha256, ext, servers, authors, size };
77
+ }
@@ -0,0 +1,5 @@
1
+ import { PaymentRequest } from "../types.js";
2
+ /** Extracts a cashu-ts PaymentRequest from Headers */
3
+ export declare function getPaymentRequestFromHeaders(headers: Headers): PaymentRequest;
4
+ export declare function getPaymentRequestFromHeaders(headers: Headers, quite: false): PaymentRequest;
5
+ export declare function getPaymentRequestFromHeaders(headers: Headers, quite: true): PaymentRequest | undefined;
@@ -0,0 +1,14 @@
1
+ import { decodePaymentRequest } from "@cashu/cashu-ts";
2
+ export function getPaymentRequestFromHeaders(headers, quite = false) {
3
+ const header = headers.get("X-Cashu");
4
+ if (!header) {
5
+ if (!quite)
6
+ throw new Error("Missing cashu header");
7
+ else
8
+ return undefined;
9
+ }
10
+ const request = decodePaymentRequest(header);
11
+ // Clear the transport, since NUT-23 is only in-band payments
12
+ request.transport = [];
13
+ return request;
14
+ }
@@ -1,4 +1,5 @@
1
1
  export * from "./blob.js";
2
+ export * from "./blossom-uri.js";
2
3
  export * from "./cashu.js";
3
4
  export * from "./fetch.js";
4
5
  export * from "./signal.js";
@@ -1,4 +1,5 @@
1
1
  export * from "./blob.js";
2
+ export * from "./blossom-uri.js";
2
3
  export * from "./cashu.js";
3
4
  export * from "./fetch.js";
4
5
  export * from "./signal.js";
@@ -1,3 +1,5 @@
1
+ /** Normalizes a server reference to a lowercase hostname */
2
+ export declare function getServerHostname(server: string | URL): string;
1
3
  /** Check if two servers are the same */
2
4
  export declare function areServersEqual(a: string | URL, b: string | URL): boolean;
3
5
  /** returns the last sha256 in a URL */
@@ -1,8 +1,14 @@
1
+ /** Normalizes a server reference to a lowercase hostname */
2
+ export function getServerHostname(server) {
3
+ if (server instanceof URL)
4
+ return server.hostname.toLowerCase();
5
+ if (URL.canParse(server))
6
+ return new URL(server).hostname.toLowerCase();
7
+ return server.toLowerCase();
8
+ }
1
9
  /** Check if two servers are the same */
2
10
  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;
11
+ return getServerHostname(a) === getServerHostname(b);
6
12
  }
7
13
  /** returns the last sha256 in a URL */
8
14
  export function getHashFromURL(url) {
@@ -0,0 +1,20 @@
1
+ import { type UploadType } from "./client.js";
2
+ import { PaymentRequest } from "./types.js";
3
+ export declare function isSha256(str: string): RegExpMatchArray | null;
4
+ /** returns the last sha256 in a URL */
5
+ export declare function getHashFromURL(url: string | URL): string | null;
6
+ export declare const BlobHashSymbol: unique symbol;
7
+ /** gets or calculates the sha2456 of a Blob */
8
+ export declare function getBlobSha256(blob: UploadType): string | Promise<string>;
9
+ /** Calculates the sha2456 of a Blob */
10
+ export declare function computeBlobSha256(blob: UploadType): Promise<string>;
11
+ /** Returns the size of the blob in bytes */
12
+ export declare function getBlobSize(blob: UploadType): number;
13
+ /** Returns the mime type of the blob */
14
+ export declare function getBlobType(blob: UploadType): string | undefined;
15
+ /** Check if two servers are the same */
16
+ export declare function areServersEqual(a: string | URL, b: string | URL): boolean;
17
+ /** Extracts a cashu-ts PaymentRequest from Headers */
18
+ export declare function getPaymentRequestFromHeaders(headers: Headers): PaymentRequest;
19
+ export declare function getPaymentRequestFromHeaders(headers: Headers, quite: false): PaymentRequest;
20
+ export declare function getPaymentRequestFromHeaders(headers: Headers, quite: true): PaymentRequest | undefined;
package/lib/helpers.js ADDED
@@ -0,0 +1,73 @@
1
+ import { bytesToHex } from "@noble/hashes/utils";
2
+ export function isSha256(str) {
3
+ return str.match(/^[0-9a-f]{64}$/);
4
+ }
5
+ /** returns the last sha256 in a URL */
6
+ export function getHashFromURL(url) {
7
+ if (typeof url === "string")
8
+ url = new URL(url);
9
+ const hashes = Array.from(url.pathname.matchAll(/[0-9a-f]{64}/gi));
10
+ if (hashes.length > 0)
11
+ return hashes[hashes.length - 1][0];
12
+ return null;
13
+ }
14
+ export const BlobHashSymbol = Symbol.for("sha256");
15
+ /** gets or calculates the sha2456 of a Blob */
16
+ export function getBlobSha256(blob) {
17
+ if (Reflect.has(blob, BlobHashSymbol))
18
+ return Reflect.get(blob, BlobHashSymbol);
19
+ return computeBlobSha256(blob).then((hash) => {
20
+ Reflect.set(blob, BlobHashSymbol, hash);
21
+ return hash;
22
+ });
23
+ }
24
+ /** Calculates the sha2456 of a Blob */
25
+ export async function computeBlobSha256(blob) {
26
+ let buffer;
27
+ if (blob instanceof File || blob instanceof Blob) {
28
+ buffer = await blob.arrayBuffer();
29
+ }
30
+ else {
31
+ // nodejs Buffer
32
+ buffer = blob;
33
+ }
34
+ let hash;
35
+ if (crypto.subtle) {
36
+ const hashBuffer = await crypto.subtle.digest("SHA-256", buffer);
37
+ hash = new Uint8Array(hashBuffer);
38
+ }
39
+ else {
40
+ const { sha256 } = await import("@noble/hashes/sha256");
41
+ hash = sha256.create().update(new Uint8Array(buffer)).digest();
42
+ }
43
+ return bytesToHex(hash);
44
+ }
45
+ /** Returns the size of the blob in bytes */
46
+ export function getBlobSize(blob) {
47
+ if (blob instanceof File || blob instanceof Blob) {
48
+ return blob.size;
49
+ }
50
+ else {
51
+ // nodejs Buffer
52
+ return blob.length;
53
+ }
54
+ }
55
+ /** Returns the mime type of the blob */
56
+ export function getBlobType(blob) {
57
+ if (blob instanceof File || blob instanceof Blob) {
58
+ return blob.type;
59
+ }
60
+ return undefined;
61
+ }
62
+ /** Check if two servers are the same */
63
+ export function areServersEqual(a, b) {
64
+ const hostnameA = a instanceof URL ? a.hostname : new URL(a).hostname;
65
+ const hostnameB = b instanceof URL ? b.hostname : new URL(b).hostname;
66
+ return hostnameA === hostnameB;
67
+ }
68
+ export function getPaymentRequestFromHeaders(headers, quite = false) {
69
+ const header = headers.get("X-Cashu");
70
+ if (!header && !quite)
71
+ throw new Error("Missing cashu header");
72
+ return header ? JSON.parse(atob(header)) : undefined;
73
+ }
package/lib/hls.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ import type { FragmentLoaderConstructor, FragmentLoaderContext as HlsFragmentLoaderContext, HlsConfig as HlsLoaderConfig, Loader as HlsLoader, LoaderCallbacks as HlsLoaderCallbacks, LoaderConfiguration as HlsLoaderConfiguration, LoaderContext as HlsLoaderContext, LoaderResponse as HlsLoaderResponse, LoaderStats as HlsLoaderStats, PlaylistLoaderConstructor, PlaylistLoaderContext as HlsPlaylistLoaderContext } from "hls.js";
2
+ export type { HlsFragmentLoaderContext, HlsLoader, HlsLoaderCallbacks, HlsLoaderConfig, HlsLoaderConfiguration, HlsLoaderContext, HlsLoaderResponse, HlsLoaderStats, HlsPlaylistLoaderContext, };
3
+ export type BlossomHlsFallbackInfo = {
4
+ kind: "playlist" | "fragment";
5
+ from: string;
6
+ to: string;
7
+ url: string;
8
+ attempt: number;
9
+ };
10
+ export type BlossomHlsLoaderOptions = {
11
+ fallbackServers?: (string | URL)[];
12
+ stickyFailover?: boolean;
13
+ penalizeMs?: number;
14
+ retryStatuses?: number[];
15
+ onFallback?: (info: BlossomHlsFallbackInfo) => void;
16
+ };
17
+ export declare function createBlossomHlsLoaders(options?: BlossomHlsLoaderOptions): {
18
+ pLoader: PlaylistLoaderConstructor;
19
+ fLoader: FragmentLoaderConstructor;
20
+ };