@abraca/dabra 2.72.0 → 2.73.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/dist/index.d.ts CHANGED
@@ -629,6 +629,22 @@ declare class AbracadabraClient {
629
629
  listUploads(docId: string): Promise<UploadInfo[]>;
630
630
  /** Download an upload as a Blob. */
631
631
  getUpload(docId: string, uploadId: string): Promise<Blob>;
632
+ /**
633
+ * Build the request path (with query string) for an upload's thumbnail.
634
+ * Also the canonical cache key suffix — the query string is deterministic
635
+ * in insertion order, so identical options map to the same URL and the
636
+ * same `FileBlobStore` cache entry.
637
+ */
638
+ thumbnailPath(docId: string, uploadId: string, opts?: ThumbnailOptions): string;
639
+ /**
640
+ * Download a generated thumbnail of an image upload as a Blob. The server
641
+ * renders + caches it on first request. Because a browser `<img>` can't
642
+ * send `Authorization`, callers render the returned Blob via an object URL
643
+ * (see `FileBlobStore.getThumbUrl`, which also caches it locally).
644
+ * Throws (with `.status = 415`) when the source isn't a thumbnailable
645
+ * raster image, or `422` for an out-of-allowlist size/format.
646
+ */
647
+ getThumbnail(docId: string, uploadId: string, opts?: ThumbnailOptions): Promise<Blob>;
632
648
  /** Delete an upload (requires uploader or document Owner). */
633
649
  deleteUpload(docId: string, uploadId: string): Promise<void>;
634
650
  /** Create an invite code (requires permission per server config). */
@@ -1796,6 +1812,26 @@ interface UploadInfo {
1796
1812
  filename: string;
1797
1813
  mime_type: string;
1798
1814
  size: number;
1815
+ /** Intrinsic pixel width of the image (captured server-side at upload).
1816
+ * Absent for non-images and older servers. */
1817
+ width?: number;
1818
+ /** Intrinsic pixel height of the image. */
1819
+ height?: number;
1820
+ /** True when the server can synthesise a thumbnail for this upload (a
1821
+ * supported raster image and the feature is enabled). Absent on older
1822
+ * servers — treat as `false`. */
1823
+ thumbnail?: boolean;
1824
+ }
1825
+ /** Query options for the on-demand thumbnail endpoint. `w`/`h` are the
1826
+ * bounding box (at least one required, each on the server's allowed_sizes);
1827
+ * `fit` defaults to `contain`, `format` to `auto`. */
1828
+ interface ThumbnailOptions {
1829
+ w?: number;
1830
+ h?: number;
1831
+ fit?: "cover" | "contain" | "inside";
1832
+ format?: "auto" | "jpeg" | "png";
1833
+ /** JPEG quality 1–100. */
1834
+ q?: number;
1799
1835
  }
1800
1836
  interface PublicKeyInfo {
1801
1837
  id: string;
@@ -3333,6 +3369,13 @@ declare class FileBlobStore extends EventEmitter {
3333
3369
  constructor(serverOrigin: string, client?: AbracadabraClient | null);
3334
3370
  private getDb;
3335
3371
  private blobKey;
3372
+ /**
3373
+ * Cache key for a thumbnail. Lives in the SAME IDB `blobs` store as
3374
+ * originals (no schema bump — the frozen cross-SDK IDB contract stays
3375
+ * intact) under a distinct `thumb:` namespace. The spec suffix is
3376
+ * deterministic so identical options collapse to one entry.
3377
+ */
3378
+ private thumbKey;
3336
3379
  /**
3337
3380
  * Return a local object URL for a file.
3338
3381
  * On first call the blob is downloaded from the server and cached in IDB.
@@ -3340,6 +3383,22 @@ declare class FileBlobStore extends EventEmitter {
3340
3383
  * URL.createObjectURL is unavailable (e.g. Node.js / SSR).
3341
3384
  */
3342
3385
  getBlobUrl(docId: string, uploadId: string): Promise<string | null>;
3386
+ /**
3387
+ * Return a local object URL for a **thumbnail** of an image upload.
3388
+ * On first call the server renders + caches it and this stores the bytes
3389
+ * in IDB (same offline-serving model as `getBlobUrl`). Returns null when
3390
+ * offline + uncached, on non-image sources (server 415 → treated like a
3391
+ * miss), or outside the browser. Options must match the server's
3392
+ * `allowed_sizes` / `allowed_formats` or the fetch 422s (→ null).
3393
+ */
3394
+ getThumbUrl(docId: string, uploadId: string, opts?: ThumbnailOptions): Promise<string | null>;
3395
+ /**
3396
+ * Shared read-through: in-memory object URL → IDB `blobs` cache (with a
3397
+ * one-shot reopen on `InvalidStateError`) → `download()` (when a client is
3398
+ * available), caching the result. `download === null` means "no network
3399
+ * source" (offline / no client) → cache-only. 404 is negative-cached.
3400
+ */
3401
+ private _objectUrlForKey;
3343
3402
  /**
3344
3403
  * Store a blob directly into the cache under the given (docId, uploadId) key
3345
3404
  * and return its object URL. Use this to pre-populate the cache for files
@@ -3370,6 +3429,11 @@ declare class FileBlobStore extends EventEmitter {
3370
3429
  * the object URL reference is stale.
3371
3430
  */
3372
3431
  invalidateUrl(docId: string, uploadId: string): void;
3432
+ /**
3433
+ * Thumbnail counterpart of {@link invalidateUrl}: revoke the in-memory
3434
+ * object URL for a specific thumbnail spec without touching its IDB cache.
3435
+ */
3436
+ invalidateThumbUrl(docId: string, uploadId: string, opts?: ThumbnailOptions): void;
3373
3437
  /**
3374
3438
  * Clear the 404 negative-cache entry for (docId, uploadId) so the next
3375
3439
  * getBlobUrl() re-fetches from the server instead of short-circuiting.
@@ -5861,4 +5925,4 @@ declare function collectMediaFileBlocks(root: Y.XmlFragment | Y.XmlElement): Med
5861
5925
  */
5862
5926
  declare function reconcileDocCover(treeMap: Y.Map<unknown>, docId: string, fragment: Y.XmlFragment | Y.XmlElement): void;
5863
5927
  //#endregion
5864
- export { AbracadabraBaseProvider, AbracadabraBaseProviderConfiguration, AbracadabraClient, AbracadabraClientConfig, AbracadabraOutgoingMessageArguments, AbracadabraProvider, AbracadabraProviderConfiguration, AbracadabraWS, AbracadabraWSConfiguration, AbracadabraWebRTC, type AbracadabraWebRTCConfiguration, AbracadabraWebSocketConn, AdminConfigField, AdminConfigOriginKind, AuditLogEntry, AuditQueryOpts, AuditVerifyResult, AuthFailureContext, AuthFailureReason, AuthMessageType, AuthorizedScope, AwarenessError, BackgroundSyncManager, type BackgroundSyncManagerOptions, BackgroundSyncPersistence, BroadcastChannelSync, CHANNEL_NAMES, ChannelKeyResolver, type ChatChannel, ChatClient, type ChatClientTransport, type MarkReadInput as ChatMarkReadInput, type ChatMessage, type ChatReadCursor, type ChatReadReceipt, type ChatTypingEvent, type ChildrenPage, CloseEvent, CompleteAbracadabraBaseProviderConfiguration, CompleteAbracadabraWSConfiguration, CompleteHocuspocusProviderConfiguration, CompleteHocuspocusProviderWebsocketConfiguration, type ConnectPolicyResult, ConnectionTimeout, Constructable, ConstructableOutgoingMessage, ContentManager, type CreateNotificationInput, CryptoIdentity, CryptoIdentityKeystore, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS, DataChannelRouter, type DeleteMessageInput, DevicePairingChannel, type DevicePairingConfig, DeviceRegistrationService, type DeviceServerStatus, type DeviceSessionRecord, type DeviceSessionStorage, type DeviceTier, type DocEncryptionInfo, DocKeyManager, DocSearchHit, type DocSyncState, type DocSyncStatus, type DocumentBlock, DocumentCache, type DocumentCacheOptions, type DocumentContent, DocumentManager, type DocumentManagerConfig, DocumentMeta, type DocumentMetaInfo, type DocumentMetaWire, E2EAbracadabraProvider, E2EEChannel, type E2EEIdentity, E2EOfflineStore, type EditMessageInput, EffectivePermissionEntry, EffectivePermissionsResponse, EffectiveRole, EncryptedChatClient, EncryptedYMap, EncryptedYText, EnvSnapshotExtension, EnvSnapshotItem, EnvSnapshotResponse, type FetchInboxInput, type FetchNotificationsInput, FileBlobStore, FileTransferChannel, FileTransferHandle, type FileTransferMeta, type FileTransferStatus, type FoldedMessage, Forbidden, GEO_TYPE_META_SCHEMAS, type GetChatHistoryInput, HealthStatus, HocusPocusWebSocket, HocuspocusProvider, HocuspocusProviderConfiguration, HocuspocusProviderWebsocket, HocuspocusProviderWebsocketConfiguration, HocuspocusWebSocket, type IdentityDeviceEntry, type IdentityDocConfiguration, IdentityDocProvider, type IdentityProfile, type IdentityServerEntry, type IdentitySpaceEntry, type InboxEntry, type MarkReadInput$1 as InboxMarkReadInput, InviteRow, KEY_EXCHANGE_CHANNEL, type KeyAuthClient, Kind, type LoadKeyFileOptions, LocalStorageDeviceSessionStorage, type LoginOrRegisterOptions, ManualSignaling, type ManualSignalingBlob, type MediaFileBlock, type MessageRecord, MessageTooBig, MessageType, MetaFieldType, MetaManager, MetaValidationError, type NodeKeypair, type NotificationReadUpdate, type NotificationRecord, NotificationsClient, OfflineStore, OutgoingMessageArguments, OutgoingMessageInterface, PAGE_TYPES, PageMeta, PageTypeInfo, PageTypeMetaField, type PairingRequest, type PairingResult, PeerConnection, type PeerInfo, type PeerState, PendingSubdoc, PermissionEntry, type PolicyAuthClient, PublicKeyInfo, QUERY_PREFIX, QueryClient, QueryError, type QueryFrame, type QueryKind, type QuerySpec, type QuerySubscriptionHandle, type QuerySubscriptionHandlers, type QueryTransport, RPC_PREFIX, ReadyzStatus, ResetConnection, type RpcCallHandle, type RpcCallOptions, RpcClient, RpcError, type RpcErrorCode, type RpcErrorPayload, type RpcFrame, type RpcHandler, type RpcHandlerContext, type RpcKind, type RpcTarget, type RpcTransport, SERVER_ROOT_ID, type SchemaDocTypeName, type SchemaMetaOf, type SchemaRegistryLike, type SchemaValidatorLike, SearchIndex, SearchResult, type SendChatMessageInput, type SendMessageInput, type SendMessageResult, ServerInfo, type ServerProfile, type ServerRegistry, type SignalingIncoming, type SignalingOutgoing, SignalingSocket, SnapshotCreateResult, SnapshotData, SnapshotFileEntry, SnapshotForkResult, SnapshotMeta, SnapshotRestoreResult, StatesArray, SubdocMessage, SubdocRegisteredEvent, TYPE_ALIASES, TokenManager, type TokenManagerOptions, TreeEntry, TreeManager, TreeNode, TreeSearchResult, TypedDocTypeMismatchError, type TypedDocsClient, type TypedTreeEntry, Unauthorized, UploadInfo, UploadMeta, UploadQueueEntry, UploadQueueStatus, UserMetaField, UserProfile, WebSocketStatus, WsReadyStates, YjsDataChannel, addServer, attachUpdatedAtObserver, awarenessStatesToArray, wordlist as bip39Wordlist, buildBlockquoteElement, buildBlocksFromMarkdown, buildBulletListElement, buildCodeBlockElement, buildHeadingElement, buildHorizontalRuleElement, buildOrderedListElement, buildParagraphElement, buildTaskListElement, collectMediaFileBlocks, decryptChatContent, decryptField, defaultKeyFileFor, deriveIdentityDocId, deriveSeedWrappingKey, deterministicKeypair, encryptChatContent, encryptField, filenameToLabel, foldRecords, generateMnemonic, isEncryptedContent, isPlaceholderLabel, loadOrCreateKeyFile, loadServerRegistry, loginOrRegisterWithKey, loginOrRegisterWithPolicy, makeChallengeSigner, makeEncryptedYMap, makeEncryptedYText, makeEntryMap, migrateLegacyDefault, mnemonicToEd25519Seed, mnemonicToKeyPair, normalizeRootId, onAuthenticatedParameters, onAuthenticationFailedParameters, onAwarenessChangeParameters, onAwarenessUpdateParameters, onCloseParameters, onCompactedParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onReconnectedParameters, onServerErrorParameters, onStatelessParameters, onStatusParameters, onSubdocLoadedParameters, onSubdocRegisteredParameters, onSyncedParameters, onUnsyncedChangesParameters, openSyncedProvider, parseFrontmatter, patchEntry, pickEntrySpace, populateYDocFromMarkdown, readAuthMessage, readBlocksFromFragment, readEntries, reconcileDocCover, recordFromYAny, removeServer, resolvePageType, resolveServer, saveServerRegistry, serverRegistryPath, setDefault, signChallengeWithSeed, toPlain, unwrapSeed, validateMnemonic, waitForSync, withTimeout, wrapSeed, writeAuthenticated, writeAuthentication, writePermissionDenied, writeTokenSyncRequest, yjsToMarkdown };
5928
+ export { AbracadabraBaseProvider, AbracadabraBaseProviderConfiguration, AbracadabraClient, AbracadabraClientConfig, AbracadabraOutgoingMessageArguments, AbracadabraProvider, AbracadabraProviderConfiguration, AbracadabraWS, AbracadabraWSConfiguration, AbracadabraWebRTC, type AbracadabraWebRTCConfiguration, AbracadabraWebSocketConn, AdminConfigField, AdminConfigOriginKind, AuditLogEntry, AuditQueryOpts, AuditVerifyResult, AuthFailureContext, AuthFailureReason, AuthMessageType, AuthorizedScope, AwarenessError, BackgroundSyncManager, type BackgroundSyncManagerOptions, BackgroundSyncPersistence, BroadcastChannelSync, CHANNEL_NAMES, ChannelKeyResolver, type ChatChannel, ChatClient, type ChatClientTransport, type MarkReadInput as ChatMarkReadInput, type ChatMessage, type ChatReadCursor, type ChatReadReceipt, type ChatTypingEvent, type ChildrenPage, CloseEvent, CompleteAbracadabraBaseProviderConfiguration, CompleteAbracadabraWSConfiguration, CompleteHocuspocusProviderConfiguration, CompleteHocuspocusProviderWebsocketConfiguration, type ConnectPolicyResult, ConnectionTimeout, Constructable, ConstructableOutgoingMessage, ContentManager, type CreateNotificationInput, CryptoIdentity, CryptoIdentityKeystore, DEFAULT_FILE_CHUNK_SIZE, DEFAULT_ICE_SERVERS, DataChannelRouter, type DeleteMessageInput, DevicePairingChannel, type DevicePairingConfig, DeviceRegistrationService, type DeviceServerStatus, type DeviceSessionRecord, type DeviceSessionStorage, type DeviceTier, type DocEncryptionInfo, DocKeyManager, DocSearchHit, type DocSyncState, type DocSyncStatus, type DocumentBlock, DocumentCache, type DocumentCacheOptions, type DocumentContent, DocumentManager, type DocumentManagerConfig, DocumentMeta, type DocumentMetaInfo, type DocumentMetaWire, E2EAbracadabraProvider, E2EEChannel, type E2EEIdentity, E2EOfflineStore, type EditMessageInput, EffectivePermissionEntry, EffectivePermissionsResponse, EffectiveRole, EncryptedChatClient, EncryptedYMap, EncryptedYText, EnvSnapshotExtension, EnvSnapshotItem, EnvSnapshotResponse, type FetchInboxInput, type FetchNotificationsInput, FileBlobStore, FileTransferChannel, FileTransferHandle, type FileTransferMeta, type FileTransferStatus, type FoldedMessage, Forbidden, GEO_TYPE_META_SCHEMAS, type GetChatHistoryInput, HealthStatus, HocusPocusWebSocket, HocuspocusProvider, HocuspocusProviderConfiguration, HocuspocusProviderWebsocket, HocuspocusProviderWebsocketConfiguration, HocuspocusWebSocket, type IdentityDeviceEntry, type IdentityDocConfiguration, IdentityDocProvider, type IdentityProfile, type IdentityServerEntry, type IdentitySpaceEntry, type InboxEntry, type MarkReadInput$1 as InboxMarkReadInput, InviteRow, KEY_EXCHANGE_CHANNEL, type KeyAuthClient, Kind, type LoadKeyFileOptions, LocalStorageDeviceSessionStorage, type LoginOrRegisterOptions, ManualSignaling, type ManualSignalingBlob, type MediaFileBlock, type MessageRecord, MessageTooBig, MessageType, MetaFieldType, MetaManager, MetaValidationError, type NodeKeypair, type NotificationReadUpdate, type NotificationRecord, NotificationsClient, OfflineStore, OutgoingMessageArguments, OutgoingMessageInterface, PAGE_TYPES, PageMeta, PageTypeInfo, PageTypeMetaField, type PairingRequest, type PairingResult, PeerConnection, type PeerInfo, type PeerState, PendingSubdoc, PermissionEntry, type PolicyAuthClient, PublicKeyInfo, QUERY_PREFIX, QueryClient, QueryError, type QueryFrame, type QueryKind, type QuerySpec, type QuerySubscriptionHandle, type QuerySubscriptionHandlers, type QueryTransport, RPC_PREFIX, ReadyzStatus, ResetConnection, type RpcCallHandle, type RpcCallOptions, RpcClient, RpcError, type RpcErrorCode, type RpcErrorPayload, type RpcFrame, type RpcHandler, type RpcHandlerContext, type RpcKind, type RpcTarget, type RpcTransport, SERVER_ROOT_ID, type SchemaDocTypeName, type SchemaMetaOf, type SchemaRegistryLike, type SchemaValidatorLike, SearchIndex, SearchResult, type SendChatMessageInput, type SendMessageInput, type SendMessageResult, ServerInfo, type ServerProfile, type ServerRegistry, type SignalingIncoming, type SignalingOutgoing, SignalingSocket, SnapshotCreateResult, SnapshotData, SnapshotFileEntry, SnapshotForkResult, SnapshotMeta, SnapshotRestoreResult, StatesArray, SubdocMessage, SubdocRegisteredEvent, TYPE_ALIASES, ThumbnailOptions, TokenManager, type TokenManagerOptions, TreeEntry, TreeManager, TreeNode, TreeSearchResult, TypedDocTypeMismatchError, type TypedDocsClient, type TypedTreeEntry, Unauthorized, UploadInfo, UploadMeta, UploadQueueEntry, UploadQueueStatus, UserMetaField, UserProfile, WebSocketStatus, WsReadyStates, YjsDataChannel, addServer, attachUpdatedAtObserver, awarenessStatesToArray, wordlist as bip39Wordlist, buildBlockquoteElement, buildBlocksFromMarkdown, buildBulletListElement, buildCodeBlockElement, buildHeadingElement, buildHorizontalRuleElement, buildOrderedListElement, buildParagraphElement, buildTaskListElement, collectMediaFileBlocks, decryptChatContent, decryptField, defaultKeyFileFor, deriveIdentityDocId, deriveSeedWrappingKey, deterministicKeypair, encryptChatContent, encryptField, filenameToLabel, foldRecords, generateMnemonic, isEncryptedContent, isPlaceholderLabel, loadOrCreateKeyFile, loadServerRegistry, loginOrRegisterWithKey, loginOrRegisterWithPolicy, makeChallengeSigner, makeEncryptedYMap, makeEncryptedYText, makeEntryMap, migrateLegacyDefault, mnemonicToEd25519Seed, mnemonicToKeyPair, normalizeRootId, onAuthenticatedParameters, onAuthenticationFailedParameters, onAwarenessChangeParameters, onAwarenessUpdateParameters, onCloseParameters, onCompactedParameters, onDisconnectParameters, onMessageParameters, onOpenParameters, onOutgoingMessageParameters, onReconnectedParameters, onServerErrorParameters, onStatelessParameters, onStatusParameters, onSubdocLoadedParameters, onSubdocRegisteredParameters, onSyncedParameters, onUnsyncedChangesParameters, openSyncedProvider, parseFrontmatter, patchEntry, pickEntrySpace, populateYDocFromMarkdown, readAuthMessage, readBlocksFromFragment, readEntries, reconcileDocCover, recordFromYAny, removeServer, resolvePageType, resolveServer, saveServerRegistry, serverRegistryPath, setDefault, signChallengeWithSeed, toPlain, unwrapSeed, validateMnemonic, waitForSync, withTimeout, wrapSeed, writeAuthenticated, writeAuthentication, writePermissionDenied, writeTokenSyncRequest, yjsToMarkdown };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@abraca/dabra",
3
- "version": "2.72.0",
3
+ "version": "2.73.0",
4
4
  "description": "abracadabra provider",
5
5
  "keywords": [
6
6
  "abracadabra",
@@ -41,7 +41,7 @@
41
41
  "yjs": "^13.6.8"
42
42
  },
43
43
  "devDependencies": {
44
- "@abraca/schema": "2.72.0"
44
+ "@abraca/schema": "2.73.0"
45
45
  },
46
46
  "scripts": {
47
47
  "test": "node --no-warnings --conditions=source --experimental-transform-types --test 'tests/*.test.ts'"
@@ -3,6 +3,7 @@ import type {
3
3
  DocumentMeta,
4
4
  UploadMeta,
5
5
  UploadInfo,
6
+ ThumbnailOptions,
6
7
  PublicKeyInfo,
7
8
  PermissionEntry,
8
9
  EffectivePermissionsResponse,
@@ -883,6 +884,51 @@ export class AbracadabraClient {
883
884
  return res.blob();
884
885
  }
885
886
 
887
+ /**
888
+ * Build the request path (with query string) for an upload's thumbnail.
889
+ * Also the canonical cache key suffix — the query string is deterministic
890
+ * in insertion order, so identical options map to the same URL and the
891
+ * same `FileBlobStore` cache entry.
892
+ */
893
+ thumbnailPath(docId: string, uploadId: string, opts: ThumbnailOptions = {}): string {
894
+ const p = new URLSearchParams();
895
+ if (opts.w != null) p.set("w", String(opts.w));
896
+ if (opts.h != null) p.set("h", String(opts.h));
897
+ if (opts.fit) p.set("fit", opts.fit);
898
+ if (opts.format) p.set("format", opts.format);
899
+ if (opts.q != null) p.set("q", String(opts.q));
900
+ const qs = p.toString();
901
+ return `/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}/thumbnail${qs ? `?${qs}` : ""}`;
902
+ }
903
+
904
+ /**
905
+ * Download a generated thumbnail of an image upload as a Blob. The server
906
+ * renders + caches it on first request. Because a browser `<img>` can't
907
+ * send `Authorization`, callers render the returned Blob via an object URL
908
+ * (see `FileBlobStore.getThumbUrl`, which also caches it locally).
909
+ * Throws (with `.status = 415`) when the source isn't a thumbnailable
910
+ * raster image, or `422` for an out-of-allowlist size/format.
911
+ */
912
+ async getThumbnail(
913
+ docId: string,
914
+ uploadId: string,
915
+ opts: ThumbnailOptions = {},
916
+ ): Promise<Blob> {
917
+ const headers: Record<string, string> = {};
918
+ if (this._token) {
919
+ headers["Authorization"] = `Bearer ${this._token}`;
920
+ }
921
+
922
+ const res = await this._fetch(
923
+ `${this.baseUrl}${this.thumbnailPath(docId, uploadId, opts)}`,
924
+ { method: "GET", headers },
925
+ );
926
+ if (!res.ok) {
927
+ throw await this.toError(res);
928
+ }
929
+ return res.blob();
930
+ }
931
+
886
932
  /** Delete an upload (requires uploader or document Owner). */
887
933
  async deleteUpload(docId: string, uploadId: string): Promise<void> {
888
934
  await this.request(
@@ -18,7 +18,7 @@
18
18
  * Falls back to a silent no-op when IndexedDB is unavailable (SSR / Node.js).
19
19
  */
20
20
 
21
- import type { UploadQueueEntry } from "./types.ts";
21
+ import type { UploadQueueEntry, ThumbnailOptions } from "./types.ts";
22
22
  import type { AbracadabraClient } from "./AbracadabraClient.ts";
23
23
  import EventEmitter from "./EventEmitter.ts";
24
24
 
@@ -118,6 +118,25 @@ export class FileBlobStore extends EventEmitter {
118
118
  return `${docId}/${uploadId}`;
119
119
  }
120
120
 
121
+ /**
122
+ * Cache key for a thumbnail. Lives in the SAME IDB `blobs` store as
123
+ * originals (no schema bump — the frozen cross-SDK IDB contract stays
124
+ * intact) under a distinct `thumb:` namespace. The spec suffix is
125
+ * deterministic so identical options collapse to one entry.
126
+ */
127
+ private thumbKey(docId: string, uploadId: string, opts: ThumbnailOptions): string {
128
+ const spec = [
129
+ opts.w != null ? `w${opts.w}` : "",
130
+ opts.h != null ? `h${opts.h}` : "",
131
+ opts.fit ? `f${opts.fit}` : "",
132
+ opts.format ? `m${opts.format}` : "",
133
+ opts.q != null ? `q${opts.q}` : "",
134
+ ]
135
+ .filter(Boolean)
136
+ .join("-");
137
+ return `thumb:${docId}/${uploadId}/${spec}`;
138
+ }
139
+
121
140
  // ── Blob cache ────────────────────────────────────────────────────────────
122
141
 
123
142
  /**
@@ -127,11 +146,47 @@ export class FileBlobStore extends EventEmitter {
127
146
  * URL.createObjectURL is unavailable (e.g. Node.js / SSR).
128
147
  */
129
148
  async getBlobUrl(docId: string, uploadId: string): Promise<string | null> {
149
+ return this._objectUrlForKey(
150
+ this.blobKey(docId, uploadId),
151
+ uploadId,
152
+ this.client ? () => this.client!.getUpload(docId, uploadId) : null,
153
+ );
154
+ }
155
+
156
+ /**
157
+ * Return a local object URL for a **thumbnail** of an image upload.
158
+ * On first call the server renders + caches it and this stores the bytes
159
+ * in IDB (same offline-serving model as `getBlobUrl`). Returns null when
160
+ * offline + uncached, on non-image sources (server 415 → treated like a
161
+ * miss), or outside the browser. Options must match the server's
162
+ * `allowed_sizes` / `allowed_formats` or the fetch 422s (→ null).
163
+ */
164
+ async getThumbUrl(
165
+ docId: string,
166
+ uploadId: string,
167
+ opts: ThumbnailOptions = {},
168
+ ): Promise<string | null> {
169
+ return this._objectUrlForKey(
170
+ this.thumbKey(docId, uploadId, opts),
171
+ uploadId,
172
+ this.client ? () => this.client!.getThumbnail(docId, uploadId, opts) : null,
173
+ );
174
+ }
175
+
176
+ /**
177
+ * Shared read-through: in-memory object URL → IDB `blobs` cache (with a
178
+ * one-shot reopen on `InvalidStateError`) → `download()` (when a client is
179
+ * available), caching the result. `download === null` means "no network
180
+ * source" (offline / no client) → cache-only. 404 is negative-cached.
181
+ */
182
+ private async _objectUrlForKey(
183
+ key: string,
184
+ filename: string,
185
+ download: (() => Promise<Blob>) | null,
186
+ ): Promise<string | null> {
130
187
  // Object URLs are only meaningful in browser environments.
131
188
  if (typeof window === "undefined") return null;
132
189
 
133
- const key = this.blobKey(docId, uploadId);
134
-
135
190
  // Reuse existing in-memory object URL if available
136
191
  const existing = this.objectUrls.get(key);
137
192
  if (existing) return existing;
@@ -172,7 +227,7 @@ export class FileBlobStore extends EventEmitter {
172
227
  }
173
228
 
174
229
  // Not cached — try downloading from server (requires a client)
175
- if (!this.client) return null;
230
+ if (!download) return null;
176
231
 
177
232
  // Skip if we recently got a 404 for this key
178
233
  const nfTime = this._notFound.get(key);
@@ -182,7 +237,7 @@ export class FileBlobStore extends EventEmitter {
182
237
 
183
238
  let blob: Blob;
184
239
  try {
185
- blob = await this.client.getUpload(docId, uploadId);
240
+ blob = await download();
186
241
  } catch (err: unknown) {
187
242
  const status = (err as any)?.status;
188
243
  if (status === 404) {
@@ -196,7 +251,7 @@ export class FileBlobStore extends EventEmitter {
196
251
  const entry: BlobCacheEntry = {
197
252
  blob,
198
253
  mime_type: blob.type,
199
- filename: uploadId,
254
+ filename,
200
255
  cachedAt: Date.now(),
201
256
  };
202
257
  const tx = db.transaction("blobs", "readwrite");
@@ -319,6 +374,19 @@ export class FileBlobStore extends EventEmitter {
319
374
  }
320
375
  }
321
376
 
377
+ /**
378
+ * Thumbnail counterpart of {@link invalidateUrl}: revoke the in-memory
379
+ * object URL for a specific thumbnail spec without touching its IDB cache.
380
+ */
381
+ invalidateThumbUrl(docId: string, uploadId: string, opts: ThumbnailOptions = {}): void {
382
+ const key = this.thumbKey(docId, uploadId, opts);
383
+ const url = this.objectUrls.get(key);
384
+ if (url) {
385
+ URL.revokeObjectURL(url);
386
+ this.objectUrls.delete(key);
387
+ }
388
+ }
389
+
322
390
  /**
323
391
  * Clear the 404 negative-cache entry for (docId, uploadId) so the next
324
392
  * getBlobUrl() re-fetches from the server instead of short-circuiting.
package/src/types.ts CHANGED
@@ -269,6 +269,27 @@ export interface UploadInfo {
269
269
  filename: string;
270
270
  mime_type: string;
271
271
  size: number;
272
+ /** Intrinsic pixel width of the image (captured server-side at upload).
273
+ * Absent for non-images and older servers. */
274
+ width?: number;
275
+ /** Intrinsic pixel height of the image. */
276
+ height?: number;
277
+ /** True when the server can synthesise a thumbnail for this upload (a
278
+ * supported raster image and the feature is enabled). Absent on older
279
+ * servers — treat as `false`. */
280
+ thumbnail?: boolean;
281
+ }
282
+
283
+ /** Query options for the on-demand thumbnail endpoint. `w`/`h` are the
284
+ * bounding box (at least one required, each on the server's allowed_sizes);
285
+ * `fit` defaults to `contain`, `format` to `auto`. */
286
+ export interface ThumbnailOptions {
287
+ w?: number;
288
+ h?: number;
289
+ fit?: "cover" | "contain" | "inside";
290
+ format?: "auto" | "jpeg" | "png";
291
+ /** JPEG quality 1–100. */
292
+ q?: number;
272
293
  }
273
294
 
274
295
  export interface PublicKeyInfo {