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/hls.js ADDED
@@ -0,0 +1,182 @@
1
+ const DEFAULT_PENALIZE_MS = 30_000;
2
+ function createEmptyStats() {
3
+ return {
4
+ aborted: false,
5
+ loaded: 0,
6
+ retry: 0,
7
+ total: 0,
8
+ chunkCount: 0,
9
+ bwEstimate: 0,
10
+ loading: { start: 0, first: 0, end: 0 },
11
+ parsing: { start: 0, end: 0 },
12
+ buffering: { start: 0, first: 0, end: 0 },
13
+ };
14
+ }
15
+ function normalizeServer(server) {
16
+ if (server instanceof URL)
17
+ return server.origin;
18
+ if (!server.includes("://"))
19
+ return `https://${server}`;
20
+ try {
21
+ return new URL(server).origin;
22
+ }
23
+ catch {
24
+ return `https://${server}`;
25
+ }
26
+ }
27
+ function replaceUrlOrigin(url, origin) {
28
+ const next = new URL(url);
29
+ const base = new URL(origin);
30
+ next.protocol = base.protocol;
31
+ next.host = base.host;
32
+ return next.toString();
33
+ }
34
+ function shouldRetry(code, isTimeout, retryStatuses) {
35
+ return isTimeout || code === 0 || code >= 500 || retryStatuses.has(code);
36
+ }
37
+ export function createBlossomHlsLoaders(options = {}) {
38
+ const fallbackServers = options.fallbackServers?.map(normalizeServer) ?? [];
39
+ const stickyFailover = options.stickyFailover ?? false;
40
+ const penalizeMs = options.penalizeMs ?? DEFAULT_PENALIZE_MS;
41
+ const retryStatuses = new Set(options.retryStatuses ?? [404]);
42
+ const penalties = new Map();
43
+ function clearExpiredPenalties() {
44
+ const now = Date.now();
45
+ for (const [origin, expiry] of penalties) {
46
+ if (expiry <= now)
47
+ penalties.delete(origin);
48
+ }
49
+ }
50
+ function penalize(origin) {
51
+ if (!stickyFailover)
52
+ return;
53
+ penalties.set(origin, Date.now() + penalizeMs);
54
+ }
55
+ function reward(origin) {
56
+ if (!stickyFailover)
57
+ return;
58
+ penalties.delete(origin);
59
+ }
60
+ function getCandidateOrigins(url) {
61
+ clearExpiredPenalties();
62
+ const originalOrigin = new URL(url).origin;
63
+ const seen = new Set();
64
+ const ordered = [originalOrigin, ...fallbackServers].filter((origin) => {
65
+ if (seen.has(origin))
66
+ return false;
67
+ seen.add(origin);
68
+ return true;
69
+ });
70
+ if (!stickyFailover)
71
+ return ordered;
72
+ const healthy = ordered.filter((origin) => !penalties.has(origin));
73
+ const penalizedOrigins = ordered.filter((origin) => penalties.has(origin));
74
+ return healthy.length > 0 ? [...healthy, ...penalizedOrigins] : ordered;
75
+ }
76
+ function createLoaderClass(kind) {
77
+ return class BlossomHlsLoader {
78
+ config;
79
+ context = null;
80
+ stats = createEmptyStats();
81
+ activeLoader = null;
82
+ destroyed = false;
83
+ aborted = false;
84
+ constructor(config) {
85
+ this.config = config;
86
+ }
87
+ destroy() {
88
+ this.destroyed = true;
89
+ this.activeLoader?.destroy();
90
+ this.activeLoader = null;
91
+ this.context = null;
92
+ }
93
+ abort() {
94
+ this.aborted = true;
95
+ this.activeLoader?.abort();
96
+ }
97
+ getCacheAge() {
98
+ return this.activeLoader?.getCacheAge?.() ?? null;
99
+ }
100
+ getResponseHeader(name) {
101
+ return this.activeLoader?.getResponseHeader?.(name) ?? null;
102
+ }
103
+ load(context, loaderConfig, callbacks) {
104
+ this.destroyed = false;
105
+ this.aborted = false;
106
+ const origins = getCandidateOrigins(context.url);
107
+ const BaseLoader = this.config.loader;
108
+ let attempt = 0;
109
+ const startAttempt = () => {
110
+ if (this.destroyed || this.aborted)
111
+ return;
112
+ const origin = origins[attempt];
113
+ const attemptUrl = replaceUrlOrigin(context.url, origin);
114
+ const attemptContext = { ...context, url: attemptUrl };
115
+ const loader = new BaseLoader(this.config);
116
+ this.activeLoader = loader;
117
+ this.context = attemptContext;
118
+ this.stats = loader.stats;
119
+ loader.load(attemptContext, loaderConfig, {
120
+ onSuccess: (response, stats, successContext, networkDetails) => {
121
+ this.stats = stats;
122
+ this.context = successContext;
123
+ reward(new URL(successContext.url).origin);
124
+ callbacks.onSuccess(response, stats, successContext, networkDetails);
125
+ },
126
+ onProgress: callbacks.onProgress,
127
+ onAbort: callbacks.onAbort,
128
+ onError: (error, errorContext, networkDetails, stats) => {
129
+ this.stats = stats;
130
+ this.context = errorContext;
131
+ if (attempt < origins.length - 1 && shouldRetry(error.code, false, retryStatuses)) {
132
+ const failedOrigin = new URL(errorContext.url).origin;
133
+ const nextOrigin = origins[attempt + 1];
134
+ penalize(failedOrigin);
135
+ this.activeLoader?.destroy();
136
+ this.activeLoader = null;
137
+ options.onFallback?.({
138
+ kind,
139
+ from: failedOrigin,
140
+ to: nextOrigin,
141
+ url: errorContext.url,
142
+ attempt: attempt + 1,
143
+ });
144
+ attempt += 1;
145
+ startAttempt();
146
+ return;
147
+ }
148
+ callbacks.onError(error, errorContext, networkDetails, stats);
149
+ },
150
+ onTimeout: (stats, timeoutContext, networkDetails) => {
151
+ this.stats = stats;
152
+ this.context = timeoutContext;
153
+ if (attempt < origins.length - 1 && shouldRetry(0, true, retryStatuses)) {
154
+ const failedOrigin = new URL(timeoutContext.url).origin;
155
+ const nextOrigin = origins[attempt + 1];
156
+ penalize(failedOrigin);
157
+ this.activeLoader?.destroy();
158
+ this.activeLoader = null;
159
+ options.onFallback?.({
160
+ kind,
161
+ from: failedOrigin,
162
+ to: nextOrigin,
163
+ url: timeoutContext.url,
164
+ attempt: attempt + 1,
165
+ });
166
+ attempt += 1;
167
+ startAttempt();
168
+ return;
169
+ }
170
+ callbacks.onTimeout(stats, timeoutContext, networkDetails);
171
+ },
172
+ });
173
+ };
174
+ startAttempt();
175
+ }
176
+ };
177
+ }
178
+ return {
179
+ pLoader: createLoaderClass("playlist"),
180
+ fLoader: createLoaderClass("fragment"),
181
+ };
182
+ }
package/lib/index.d.ts CHANGED
@@ -1,8 +1,7 @@
1
1
  export * from "./const.js";
2
2
  export * from "./auth.js";
3
- export * from "./client.js";
4
3
  export * from "./helpers/index.js";
5
- export * from "./image.js";
4
+ export * from "./media.js";
6
5
  export * from "./nostr.js";
7
6
  export * from "./error.js";
8
7
  export * from "./types.js";
package/lib/index.js CHANGED
@@ -1,8 +1,7 @@
1
1
  export * from "./const.js";
2
2
  export * from "./auth.js";
3
- export * from "./client.js";
4
3
  export * from "./helpers/index.js";
5
- export * from "./image.js";
4
+ export * from "./media.js";
6
5
  export * from "./nostr.js";
7
6
  export * from "./error.js";
8
7
  export * from "./types.js";
package/lib/media.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ type MediaElement = HTMLImageElement | HTMLVideoElement | HTMLAudioElement;
2
+ type GetServersMethod = (pubkey?: string) => Promise<(string | URL)[] | undefined> | undefined;
3
+ /**
4
+ * Attaches an "error" event listener to a media element (img, video, audio) to handle server fallbacks.
5
+ *
6
+ * Supports two modes:
7
+ * - **Blossom URIs**: If the element's `src` is a `blossom:` URI, parses it and resolves server URLs
8
+ * from xs hints, author hints (via getServers), and builds a fallback chain automatically.
9
+ * - **HTTP URLs**: Extracts the blob hash from the URL, walks the DOM for a `data-pubkey` attribute,
10
+ * and uses the getServers callback to find alternative servers.
11
+ *
12
+ * @param element The media element (img, video, or audio)
13
+ * @param getServers An async method to get an ordered list of servers for a pubkey
14
+ * @param overridePubkey An optional pubkey to use instead of walking the DOM
15
+ * @returns A method to remove the "error" event listener
16
+ */
17
+ export declare function handleMediaFallbacks(element: MediaElement, getServers: GetServersMethod, overridePubkey?: string): () => void;
18
+ /**
19
+ * Watch for any broken media elements (img, video, audio) in the DOM tree and attempt to fix them
20
+ * by trying alternative blossom servers. Supports both regular HTTP blob URLs and blossom: URIs.
21
+ *
22
+ * @param root The root element to observe
23
+ * @param getServers A method used to get a list of servers for a specific pubkey
24
+ * @returns A cleanup function that disconnects the observer and removes all error listeners
25
+ */
26
+ export declare function handleBrokenMedia(root: HTMLElement, getServers: GetServersMethod): () => void;
27
+ /**
28
+ * Creates an array of HTMLSourceElement elements from a list of URLs.
29
+ * Useful for providing native browser fallback for video and audio elements,
30
+ * where the browser automatically tries the next <source> when one fails.
31
+ *
32
+ * @param urls Ordered list of blob URLs to try
33
+ * @param type Optional MIME type to set on each source element (e.g. "video/mp4", "audio/ogg")
34
+ * @returns Array of HTMLSourceElement elements
35
+ */
36
+ export declare function createSourceElements(urls: (string | URL)[], type?: string): HTMLSourceElement[];
37
+ export {};
package/lib/media.js ADDED
@@ -0,0 +1,179 @@
1
+ import { getHashFromURL } from "./helpers/url.js";
2
+ import { parseBlossomURI } from "./helpers/blossom-uri.js";
3
+ import { getBlobUrls } from "./actions/resolve.js";
4
+ /**
5
+ * Attaches an "error" event listener to a media element (img, video, audio) to handle server fallbacks.
6
+ *
7
+ * Supports two modes:
8
+ * - **Blossom URIs**: If the element's `src` is a `blossom:` URI, parses it and resolves server URLs
9
+ * from xs hints, author hints (via getServers), and builds a fallback chain automatically.
10
+ * - **HTTP URLs**: Extracts the blob hash from the URL, walks the DOM for a `data-pubkey` attribute,
11
+ * and uses the getServers callback to find alternative servers.
12
+ *
13
+ * @param element The media element (img, video, or audio)
14
+ * @param getServers An async method to get an ordered list of servers for a pubkey
15
+ * @param overridePubkey An optional pubkey to use instead of walking the DOM
16
+ * @returns A method to remove the "error" event listener
17
+ */
18
+ export function handleMediaFallbacks(element, getServers, overridePubkey) {
19
+ let urls;
20
+ let urlIndex = 0;
21
+ /** Resolve a blossom: URI into an ordered list of HTTP URLs */
22
+ const resolveBlossomUri = async (src) => {
23
+ const parsed = parseBlossomURI(src);
24
+ return getBlobUrls(parsed, {
25
+ getServers: getServers
26
+ ? async (pubkey) => (await getServers(pubkey)) ?? undefined
27
+ : undefined,
28
+ });
29
+ };
30
+ /** Resolve an HTTP blob URL into fallback URLs via pubkey server lookup */
31
+ const resolveHttpUrl = async () => {
32
+ const hash = getHashFromURL(element.src);
33
+ if (!hash)
34
+ return undefined;
35
+ const url = new URL(element.src);
36
+ const ext = url.pathname.match(/\.\w+$/i);
37
+ let pubkey = overridePubkey;
38
+ // walk up the tree looking for pubkey
39
+ let el = element;
40
+ while (!pubkey && el.parentElement) {
41
+ if (el.dataset.pubkey)
42
+ pubkey = el.dataset.pubkey;
43
+ else
44
+ el = el.parentElement;
45
+ }
46
+ if (!pubkey) {
47
+ console.warn("Failed to find pubkey for broken media element", element);
48
+ return undefined;
49
+ }
50
+ const servers = (await getServers(pubkey))?.map((s) => (s instanceof URL ? s : new URL(s)));
51
+ if (!servers)
52
+ return undefined;
53
+ return servers
54
+ .filter((s) => s.hostname !== url.hostname)
55
+ .map((s) => {
56
+ const u = new URL(url);
57
+ u.hostname = s.hostname;
58
+ u.protocol = s.protocol;
59
+ u.pathname = "/" + hash + (ext?.[0] ?? "");
60
+ return u.toString();
61
+ });
62
+ };
63
+ const onError = async () => {
64
+ // Already resolved — try the next URL in the list
65
+ if (urls) {
66
+ if (urlIndex < urls.length) {
67
+ element.src = urls[urlIndex++];
68
+ }
69
+ else {
70
+ element.removeEventListener("error", onError);
71
+ }
72
+ return;
73
+ }
74
+ // First error — resolve URLs based on src type
75
+ const rawSrc = element.getAttribute("src") || "";
76
+ if (rawSrc.startsWith("blossom:")) {
77
+ urls = await resolveBlossomUri(rawSrc);
78
+ }
79
+ else {
80
+ urls = (await resolveHttpUrl()) ?? [];
81
+ }
82
+ urlIndex = 0;
83
+ if (urls.length > 0) {
84
+ element.src = urls[urlIndex++];
85
+ }
86
+ else {
87
+ element.removeEventListener("error", onError);
88
+ }
89
+ };
90
+ element.addEventListener("error", onError);
91
+ return () => element.removeEventListener("error", onError);
92
+ }
93
+ const MEDIA_SELECTOR = "img[src], video[src], audio[src]";
94
+ function isMediaElement(node) {
95
+ return node instanceof HTMLImageElement || node instanceof HTMLVideoElement || node instanceof HTMLAudioElement;
96
+ }
97
+ /**
98
+ * Watch for any broken media elements (img, video, audio) in the DOM tree and attempt to fix them
99
+ * by trying alternative blossom servers. Supports both regular HTTP blob URLs and blossom: URIs.
100
+ *
101
+ * @param root The root element to observe
102
+ * @param getServers A method used to get a list of servers for a specific pubkey
103
+ * @returns A cleanup function that disconnects the observer and removes all error listeners
104
+ */
105
+ export function handleBrokenMedia(root, getServers) {
106
+ const listeners = new Map();
107
+ const attachFallback = (element) => {
108
+ if (!listeners.has(element)) {
109
+ const listener = handleMediaFallbacks(element, getServers);
110
+ listeners.set(element, listener);
111
+ }
112
+ };
113
+ const detachFallback = (element) => {
114
+ const listener = listeners.get(element);
115
+ if (listener) {
116
+ listener();
117
+ listeners.delete(element);
118
+ }
119
+ };
120
+ const observer = new MutationObserver((changes) => {
121
+ for (const change of changes) {
122
+ if (change.type === "childList") {
123
+ // Process added nodes and their children for media elements
124
+ change.addedNodes.forEach((node) => {
125
+ if (!(node instanceof HTMLElement))
126
+ return;
127
+ const children = Array.from(node.querySelectorAll(MEDIA_SELECTOR));
128
+ const elements = isMediaElement(node) ? [node, ...children] : children;
129
+ for (const element of elements) {
130
+ if (isMediaElement(element))
131
+ attachFallback(element);
132
+ }
133
+ });
134
+ // cleanup removed nodes
135
+ change.removedNodes.forEach((node) => {
136
+ if (!(node instanceof HTMLElement))
137
+ return;
138
+ const children = Array.from(node.querySelectorAll(MEDIA_SELECTOR));
139
+ const elements = isMediaElement(node) ? [node, ...children] : children;
140
+ for (const element of elements) {
141
+ if (isMediaElement(element))
142
+ detachFallback(element);
143
+ }
144
+ });
145
+ }
146
+ }
147
+ });
148
+ // start watching root
149
+ observer.observe(root, { subtree: true, childList: true });
150
+ // find all existing media elements and attach error handler
151
+ root.querySelectorAll(MEDIA_SELECTOR).forEach((element) => {
152
+ if (isMediaElement(element))
153
+ attachFallback(element);
154
+ });
155
+ return () => {
156
+ observer.disconnect();
157
+ for (const element of listeners.keys()) {
158
+ detachFallback(element);
159
+ }
160
+ };
161
+ }
162
+ /**
163
+ * Creates an array of HTMLSourceElement elements from a list of URLs.
164
+ * Useful for providing native browser fallback for video and audio elements,
165
+ * where the browser automatically tries the next <source> when one fails.
166
+ *
167
+ * @param urls Ordered list of blob URLs to try
168
+ * @param type Optional MIME type to set on each source element (e.g. "video/mp4", "audio/ogg")
169
+ * @returns Array of HTMLSourceElement elements
170
+ */
171
+ export function createSourceElements(urls, type) {
172
+ return urls.map((url) => {
173
+ const source = document.createElement("source");
174
+ source.src = url.toString();
175
+ if (type)
176
+ source.type = type;
177
+ return source;
178
+ });
179
+ }
package/lib/types.d.ts CHANGED
@@ -3,7 +3,8 @@ import { DownloadOptions } from "./actions/download.js";
3
3
  import { ListOptions } from "./actions/list.js";
4
4
  import { MirrorOptions } from "./actions/mirror.js";
5
5
  import { UploadOptions } from "./actions/upload.js";
6
- import { ServerType, UploadType } from "./client.js";
6
+ export type ServerType = string | URL;
7
+ export type UploadType = Blob | File | Buffer;
7
8
  import { type PaymentRequest as CashuPaymentRequest } from "@cashu/cashu-ts";
8
9
  export type EventTemplate = {
9
10
  created_at: number;
@@ -34,6 +35,7 @@ export type BlobDescriptor = {
34
35
  url: string;
35
36
  };
36
37
  export type PaymentRequest = CashuPaymentRequest;
38
+ export type RejectionAction = "skip" | "cancel";
37
39
  type SerializedDLEQ = {
38
40
  s: string;
39
41
  e: string;
@@ -0,0 +1,13 @@
1
+ import { BlobDescriptor, ServerType, SignedEvent, Signer, UploadType } from "./client.js";
2
+ /**
3
+ * Creates an AsyncGenerator that can be used to upload a blob to multiple servers
4
+ * @param servers A Set or Array of servers to upload to
5
+ * @param file The blob to be uploaded
6
+ * @param signer An async function used for signing nostr events
7
+ * @returns The BlobDescriptor if successful
8
+ */
9
+ export declare function multiServerUpload(servers: Iterable<ServerType>, file: UploadType, signer: Signer, auth?: SignedEvent): AsyncGenerator<{
10
+ blob: BlobDescriptor;
11
+ progress: number;
12
+ server: ServerType;
13
+ }, BlobDescriptor | undefined, unknown>;
package/lib/upload.js ADDED
@@ -0,0 +1,37 @@
1
+ import { BlossomClient } from "./client.js";
2
+ /**
3
+ * Creates an AsyncGenerator that can be used to upload a blob to multiple servers
4
+ * @param servers A Set or Array of servers to upload to
5
+ * @param file The blob to be uploaded
6
+ * @param signer An async function used for signing nostr events
7
+ * @returns The BlobDescriptor if successful
8
+ */
9
+ export async function* multiServerUpload(servers, file, signer, auth) {
10
+ auth = auth || (await BlossomClient.getUploadAuth(file, signer));
11
+ let blob = undefined;
12
+ let total = Array.from(servers).length;
13
+ let uploaded = 0;
14
+ for (const server of servers) {
15
+ if (blob) {
16
+ // mirror blob to server
17
+ try {
18
+ let b = await BlossomClient.mirrorBlob(server, blob.url, auth);
19
+ uploaded++;
20
+ yield { blob: b, progress: uploaded / total, server };
21
+ }
22
+ catch (error) {
23
+ // not all servers support mirroring, attempt to upload
24
+ let b = await BlossomClient.uploadBlob(server, file, auth);
25
+ uploaded++;
26
+ yield { blob: b, progress: uploaded / total, server };
27
+ }
28
+ }
29
+ else {
30
+ // attempt initial upload
31
+ blob = await BlossomClient.uploadBlob(server, file, auth);
32
+ uploaded++;
33
+ yield { blob, progress: uploaded / total, server };
34
+ }
35
+ }
36
+ return blob;
37
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "blossom-client-sdk",
3
- "version": "4.0.0",
3
+ "version": "5.0.0-0",
4
4
  "description": "Client SDK for talking to blossom servers",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -17,13 +17,13 @@
17
17
  "import": "./lib/index.js",
18
18
  "types": "./lib/index.d.ts"
19
19
  },
20
- "./client": {
21
- "import": "./lib/client.js",
22
- "types": "./lib/client.d.ts"
20
+ "./media": {
21
+ "import": "./lib/media.js",
22
+ "types": "./lib/media.d.ts"
23
23
  },
24
- "./image": {
25
- "import": "./lib/image.js",
26
- "types": "./lib/image.d.ts"
24
+ "./hls": {
25
+ "import": "./lib/hls.js",
26
+ "types": "./lib/hls.d.ts"
27
27
  },
28
28
  "./helpers": {
29
29
  "import": "./lib/helpers/index.js",
@@ -57,12 +57,21 @@
57
57
  "@cashu/cashu-ts": "^2.4.3",
58
58
  "@noble/hashes": "^1.8.0"
59
59
  },
60
+ "peerDependencies": {
61
+ "hls.js": "^1.6.16"
62
+ },
63
+ "peerDependenciesMeta": {
64
+ "hls.js": {
65
+ "optional": true
66
+ }
67
+ },
60
68
  "devDependencies": {
61
69
  "@changesets/cli": "^2.29.3",
62
70
  "@testing-library/dom": "^10.4.0",
63
71
  "@types/node": "^22.15.14",
64
72
  "@vitest/browser": "^3.1.3",
65
73
  "@vitest/coverage-v8": "^3.1.3",
74
+ "hls.js": "^1.6.16",
66
75
  "nostr-tools": "^2.12.0",
67
76
  "playwright": "^1.52.0",
68
77
  "prettier": "^3.5.3",
@@ -1,5 +1,5 @@
1
- import { encodeAuthorizationHeader } from "../auth.js";
2
- import { ServerType } from "../client.js";
1
+ import { encodeAuthorizationHeader, getReusableAuthEvent, storeAuthEvent } from "../auth.js";
2
+ import { ServerType } from "../types.js";
3
3
  import HTTPError from "../error.js";
4
4
  import { fetchWithTimeout } from "../helpers/fetch.js";
5
5
  import { PaymentRequest, PaymentToken, SignedEvent } from "../types.js";
@@ -7,8 +7,10 @@ import { PaymentRequest, PaymentToken, SignedEvent } from "../types.js";
7
7
  export type DeleteOptions<S extends ServerType> = {
8
8
  /** AbortSignal to cancel the action */
9
9
  signal?: AbortSignal;
10
- /** Override auth event to use */
11
- auth?: SignedEvent;
10
+ /** Override authorization event, or true to always use authorization, false to disable authorization */
11
+ auth?: SignedEvent | boolean;
12
+ /** Shared auth event store used to reuse non-expired auth events between requests */
13
+ authEvents?: Set<SignedEvent>;
12
14
  /** Request timeout */
13
15
  timeout?: number;
14
16
  /**
@@ -29,11 +31,29 @@ export type DeleteOptions<S extends ServerType> = {
29
31
  /** Deletes a blob to a server */
30
32
  export async function deleteBlob<S extends ServerType>(server: S, hash: string, opts?: DeleteOptions<S>) {
31
33
  const url = new URL("/" + hash, server);
34
+ const resolveAuth = async (preset: boolean = false) => {
35
+ const reused = opts?.authEvents
36
+ ? await getReusableAuthEvent(opts.authEvents, { server, type: "delete", blob: hash })
37
+ : undefined;
38
+ if (reused) return reused;
39
+
40
+ const auth = await opts?.onAuth?.(server, hash);
41
+ if (!auth) throw new Error(preset ? "Missing onAuth handler" : "Missing auth handler");
42
+
43
+ if (opts?.authEvents) storeAuthEvent(opts.authEvents, auth);
44
+ return auth;
45
+ };
32
46
 
33
47
  const headers: HeadersInit = {};
34
48
 
35
- // attach the auth if its already set
36
- if (opts?.auth) headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
49
+ // attach the authorization if its already set
50
+ if (opts?.auth) {
51
+ if (typeof opts.auth === "boolean") {
52
+ headers["Authorization"] = encodeAuthorizationHeader(await resolveAuth(true));
53
+ } else {
54
+ headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
55
+ }
56
+ }
37
57
 
38
58
  let res = await fetchWithTimeout(url, {
39
59
  method: "DELETE",
@@ -45,8 +65,11 @@ export async function deleteBlob<S extends ServerType>(server: S, hash: string,
45
65
  // handle auth and payment
46
66
  switch (res.status) {
47
67
  case 401: {
48
- const auth = opts?.auth || (await opts?.onAuth?.(server, hash));
49
- if (!auth) throw new Error("Missing auth handler");
68
+ // throw an error if authorization is required but disabled
69
+ if (opts?.auth === false) throw new Error("Authorization disabled");
70
+
71
+ // request authorization for this request
72
+ const auth = await resolveAuth();
50
73
 
51
74
  // Try delete with auth
52
75
  res = await fetchWithTimeout(url, {
@@ -1,14 +1,16 @@
1
- import { ServerType } from "../client.js";
1
+ import { ServerType } from "../types.js";
2
2
  import { PaymentRequest, PaymentToken, SignedEvent } from "../types.js";
3
3
  import HTTPError from "../error.js";
4
- import { encodeAuthorizationHeader } from "../auth.js";
4
+ import { encodeAuthorizationHeader, getReusableAuthEvent, storeAuthEvent } from "../auth.js";
5
5
  import { fetchWithTimeout } from "../helpers/index.js";
6
6
 
7
7
  export type DownloadOptions<S extends ServerType> = {
8
8
  /** AbortSignal to cancel the action */
9
9
  signal?: AbortSignal;
10
- /** Override auth event to use */
11
- auth?: SignedEvent;
10
+ /** Override authorization event, or true to always use authorization, false to disable authorization */
11
+ auth?: SignedEvent | boolean;
12
+ /** Shared auth event store used to reuse non-expired auth events between requests */
13
+ authEvents?: Set<SignedEvent>;
12
14
  /** Request timeout */
13
15
  timeout?: number;
14
16
  /**
@@ -29,11 +31,29 @@ export type DownloadOptions<S extends ServerType> = {
29
31
  /** Downloads a blob from a server and returns the Response */
30
32
  export async function downloadBlob<S extends ServerType>(server: S, hash: string, opts?: DownloadOptions<S>) {
31
33
  const url = new URL("/" + hash, server);
34
+ const resolveAuth = async (preset: boolean = false) => {
35
+ const reused = opts?.authEvents
36
+ ? await getReusableAuthEvent(opts.authEvents, { server, type: "get", blob: hash })
37
+ : undefined;
38
+ if (reused) return reused;
39
+
40
+ const auth = await opts?.onAuth?.(server, hash);
41
+ if (!auth) throw new Error(preset ? "Missing onAuth handler" : "Missing auth handler");
42
+
43
+ if (opts?.authEvents) storeAuthEvent(opts.authEvents, auth);
44
+ return auth;
45
+ };
32
46
 
33
47
  const headers: HeadersInit = {};
34
48
 
35
- // attach the auth if its already set
36
- if (opts?.auth) headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
49
+ // attach the authorization if its already set
50
+ if (opts?.auth) {
51
+ if (typeof opts.auth === "boolean") {
52
+ headers["Authorization"] = encodeAuthorizationHeader(await resolveAuth(true));
53
+ } else {
54
+ headers["Authorization"] = encodeAuthorizationHeader(opts.auth);
55
+ }
56
+ }
37
57
 
38
58
  let download = await fetchWithTimeout(url, {
39
59
  headers,
@@ -44,8 +64,11 @@ export async function downloadBlob<S extends ServerType>(server: S, hash: string
44
64
  // handle auth and payment
45
65
  switch (download.status) {
46
66
  case 401: {
47
- const auth = opts?.auth || (await opts?.onAuth?.(server, hash));
48
- if (!auth) throw new Error("Missing auth handler");
67
+ // throw an error if auth is requested and disabled
68
+ if (opts?.auth === false) throw new Error("Authorization disabled");
69
+
70
+ // Request authorization for this request
71
+ const auth = await resolveAuth();
49
72
 
50
73
  // Try download with auth
51
74
  download = await fetchWithTimeout(url, {