@abraca/dabra 2.76.0 → 2.77.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/abracadabra-provider.cjs +73 -0
- package/dist/abracadabra-provider.cjs.map +1 -1
- package/dist/abracadabra-provider.esm.js +73 -0
- package/dist/abracadabra-provider.esm.js.map +1 -1
- package/dist/index.d.ts +52 -1
- package/package.json +2 -2
- package/src/AbracadabraClient.ts +81 -0
- package/src/FileBlobStore.ts +23 -0
- package/src/types.ts +12 -0
package/dist/index.d.ts
CHANGED
|
@@ -297,6 +297,13 @@ declare class AbracadabraClient {
|
|
|
297
297
|
* a busy server, and a connect burst fires several identical ones.
|
|
298
298
|
* Keyed by the kind filter; cleared when the request settles. */
|
|
299
299
|
private readonly rootListInflight;
|
|
300
|
+
/** Cached media-stream grants (`getStreamUrl`), keyed `docId/uploadId`.
|
|
301
|
+
* Re-minted just before expiry and dropped whenever the session token
|
|
302
|
+
* changes — a stream token inherits the identity that minted it. */
|
|
303
|
+
private readonly streamTokens;
|
|
304
|
+
/** In-flight mints, keyed like `streamTokens` — collapses the burst a page
|
|
305
|
+
* of media blocks produces into one request per upload. */
|
|
306
|
+
private readonly streamTokenInflight;
|
|
300
307
|
constructor(config: AbracadabraClientConfig);
|
|
301
308
|
get token(): string | null;
|
|
302
309
|
set token(value: string | null);
|
|
@@ -643,6 +650,27 @@ declare class AbracadabraClient {
|
|
|
643
650
|
listUploads(docId: string): Promise<UploadInfo[]>;
|
|
644
651
|
/** Download an upload as a Blob. */
|
|
645
652
|
getUpload(docId: string, uploadId: string): Promise<Blob>;
|
|
653
|
+
/**
|
|
654
|
+
* Mint a short-lived, read-only token bound to this one upload.
|
|
655
|
+
* Prefer `getStreamUrl`, which caches and reuses the grant.
|
|
656
|
+
*/
|
|
657
|
+
createStreamToken(docId: string, uploadId: string): Promise<StreamTokenInfo>;
|
|
658
|
+
/**
|
|
659
|
+
* Absolute URL that streams an upload straight from the server, safe to
|
|
660
|
+
* hand to `<video src>` / `<audio src>`.
|
|
661
|
+
*
|
|
662
|
+
* Unlike `FileBlobStore.getBlobUrl` (which downloads the whole blob into
|
|
663
|
+
* IndexedDB and hands back an object URL), this keeps the bytes on the
|
|
664
|
+
* server so the browser can seek natively over HTTP Range — the difference
|
|
665
|
+
* between "wait for 400 MB" and "scrub instantly". It needs the network,
|
|
666
|
+
* so callers should fall back to `getBlobUrl` when offline.
|
|
667
|
+
*
|
|
668
|
+
* Grants are cached per upload and re-minted shortly before they expire.
|
|
669
|
+
* Throws on servers older than the `stream-token` endpoint (404).
|
|
670
|
+
*/
|
|
671
|
+
getStreamUrl(docId: string, uploadId: string): Promise<string>;
|
|
672
|
+
/** Drop any cached stream grant for an upload (or all of them). */
|
|
673
|
+
clearStreamUrl(docId?: string, uploadId?: string): void;
|
|
646
674
|
/**
|
|
647
675
|
* Build the request path (with query string) for an upload's thumbnail.
|
|
648
676
|
* Also the canonical cache key suffix — the query string is deterministic
|
|
@@ -1847,6 +1875,17 @@ interface ThumbnailOptions {
|
|
|
1847
1875
|
/** JPEG quality 1–100. */
|
|
1848
1876
|
q?: number;
|
|
1849
1877
|
}
|
|
1878
|
+
/** Response of `POST /docs/:docId/uploads/:uploadId/stream-token` — a
|
|
1879
|
+
* short-lived grant that reads exactly one upload and travels in the query
|
|
1880
|
+
* string, so a `<video src>` can Range-seek it without an Authorization
|
|
1881
|
+
* header. `url` is server-relative. */
|
|
1882
|
+
interface StreamTokenInfo {
|
|
1883
|
+
token: string;
|
|
1884
|
+
/** Lifetime in seconds, from the moment the server minted it. */
|
|
1885
|
+
expires_in: number;
|
|
1886
|
+
/** `/docs/<docId>/uploads/<uploadId>?token=…` */
|
|
1887
|
+
url: string;
|
|
1888
|
+
}
|
|
1850
1889
|
interface PublicKeyInfo {
|
|
1851
1890
|
id: string;
|
|
1852
1891
|
publicKey: string;
|
|
@@ -3397,6 +3436,18 @@ declare class FileBlobStore extends EventEmitter {
|
|
|
3397
3436
|
* URL.createObjectURL is unavailable (e.g. Node.js / SSR).
|
|
3398
3437
|
*/
|
|
3399
3438
|
getBlobUrl(docId: string, uploadId: string): Promise<string | null>;
|
|
3439
|
+
/**
|
|
3440
|
+
* Return a **server** URL that streams an upload with HTTP Range support —
|
|
3441
|
+
* for `<video src>` / `<audio src>`, where `getBlobUrl` would first pull
|
|
3442
|
+
* the entire file into IndexedDB and seeking would stall until it landed.
|
|
3443
|
+
*
|
|
3444
|
+
* Requires a client and the network (the URL points at the server, and
|
|
3445
|
+
* minting its token is a request). Returns `null` when either is missing,
|
|
3446
|
+
* when the server predates the `stream-token` endpoint, or when we're
|
|
3447
|
+
* already known to be offline — callers fall back to `getBlobUrl` for the
|
|
3448
|
+
* cached copy.
|
|
3449
|
+
*/
|
|
3450
|
+
getStreamUrl(docId: string, uploadId: string): Promise<string | null>;
|
|
3400
3451
|
/**
|
|
3401
3452
|
* Return a local object URL for a **thumbnail** of an image upload.
|
|
3402
3453
|
* On first call the server renders + caches it and this stores the bytes
|
|
@@ -5951,4 +6002,4 @@ declare function collectMediaFileBlocks(root: Y.XmlFragment | Y.XmlElement): Med
|
|
|
5951
6002
|
*/
|
|
5952
6003
|
declare function reconcileDocCover(treeMap: Y.Map<unknown>, docId: string, fragment: Y.XmlFragment | Y.XmlElement): void;
|
|
5953
6004
|
//#endregion
|
|
5954
|
-
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, deriveDmDocId, 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 };
|
|
6005
|
+
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, StreamTokenInfo, 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, deriveDmDocId, 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.
|
|
3
|
+
"version": "2.77.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.
|
|
44
|
+
"@abraca/schema": "2.77.0"
|
|
45
45
|
},
|
|
46
46
|
"scripts": {
|
|
47
47
|
"test": "node --no-warnings --conditions=source --experimental-transform-types --test 'tests/*.test.ts'"
|
package/src/AbracadabraClient.ts
CHANGED
|
@@ -4,6 +4,7 @@ import type {
|
|
|
4
4
|
UploadMeta,
|
|
5
5
|
UploadInfo,
|
|
6
6
|
ThumbnailOptions,
|
|
7
|
+
StreamTokenInfo,
|
|
7
8
|
PublicKeyInfo,
|
|
8
9
|
PermissionEntry,
|
|
9
10
|
EffectivePermissionsResponse,
|
|
@@ -119,6 +120,16 @@ export class AbracadabraClient {
|
|
|
119
120
|
string,
|
|
120
121
|
Promise<DocumentMeta[]>
|
|
121
122
|
>();
|
|
123
|
+
/** Cached media-stream grants (`getStreamUrl`), keyed `docId/uploadId`.
|
|
124
|
+
* Re-minted just before expiry and dropped whenever the session token
|
|
125
|
+
* changes — a stream token inherits the identity that minted it. */
|
|
126
|
+
private readonly streamTokens = new Map<
|
|
127
|
+
string,
|
|
128
|
+
{ url: string; expiresAt: number }
|
|
129
|
+
>();
|
|
130
|
+
/** In-flight mints, keyed like `streamTokens` — collapses the burst a page
|
|
131
|
+
* of media blocks produces into one request per upload. */
|
|
132
|
+
private readonly streamTokenInflight = new Map<string, Promise<string>>();
|
|
122
133
|
|
|
123
134
|
constructor(config: AbracadabraClientConfig) {
|
|
124
135
|
this.baseUrl = config.url.replace(/\/+$/, "");
|
|
@@ -140,6 +151,10 @@ export class AbracadabraClient {
|
|
|
140
151
|
|
|
141
152
|
set token(value: string | null) {
|
|
142
153
|
this._token = value;
|
|
154
|
+
// Stream grants carry the old identity (and die with it on
|
|
155
|
+
// logout-all) — never serve one across a session change.
|
|
156
|
+
this.streamTokens.clear();
|
|
157
|
+
this.streamTokenInflight.clear();
|
|
143
158
|
if (this.persistAuth) {
|
|
144
159
|
if (value) {
|
|
145
160
|
this.persistToken(value);
|
|
@@ -900,6 +915,72 @@ export class AbracadabraClient {
|
|
|
900
915
|
return res.blob();
|
|
901
916
|
}
|
|
902
917
|
|
|
918
|
+
/**
|
|
919
|
+
* Mint a short-lived, read-only token bound to this one upload.
|
|
920
|
+
* Prefer `getStreamUrl`, which caches and reuses the grant.
|
|
921
|
+
*/
|
|
922
|
+
async createStreamToken(
|
|
923
|
+
docId: string,
|
|
924
|
+
uploadId: string,
|
|
925
|
+
): Promise<StreamTokenInfo> {
|
|
926
|
+
return this.request<StreamTokenInfo>(
|
|
927
|
+
"POST",
|
|
928
|
+
`/docs/${encodeURIComponent(docId)}/uploads/${encodeURIComponent(uploadId)}/stream-token`,
|
|
929
|
+
);
|
|
930
|
+
}
|
|
931
|
+
|
|
932
|
+
/**
|
|
933
|
+
* Absolute URL that streams an upload straight from the server, safe to
|
|
934
|
+
* hand to `<video src>` / `<audio src>`.
|
|
935
|
+
*
|
|
936
|
+
* Unlike `FileBlobStore.getBlobUrl` (which downloads the whole blob into
|
|
937
|
+
* IndexedDB and hands back an object URL), this keeps the bytes on the
|
|
938
|
+
* server so the browser can seek natively over HTTP Range — the difference
|
|
939
|
+
* between "wait for 400 MB" and "scrub instantly". It needs the network,
|
|
940
|
+
* so callers should fall back to `getBlobUrl` when offline.
|
|
941
|
+
*
|
|
942
|
+
* Grants are cached per upload and re-minted shortly before they expire.
|
|
943
|
+
* Throws on servers older than the `stream-token` endpoint (404).
|
|
944
|
+
*/
|
|
945
|
+
async getStreamUrl(docId: string, uploadId: string): Promise<string> {
|
|
946
|
+
const key = `${docId}/${uploadId}`;
|
|
947
|
+
const cached = this.streamTokens.get(key);
|
|
948
|
+
// Re-mint a minute early so a URL handed to a media element doesn't
|
|
949
|
+
// expire mid-request.
|
|
950
|
+
if (cached && cached.expiresAt - 60_000 > Date.now()) return cached.url;
|
|
951
|
+
|
|
952
|
+
// Single-flight: a page full of media blocks resolves the same upload
|
|
953
|
+
// from several components at once, and each mint is a round trip.
|
|
954
|
+
const inflight = this.streamTokenInflight.get(key);
|
|
955
|
+
if (inflight) return inflight;
|
|
956
|
+
|
|
957
|
+
const pending = this.createStreamToken(docId, uploadId)
|
|
958
|
+
.then((info) => {
|
|
959
|
+
const url = `${this.baseUrl}${info.url}`;
|
|
960
|
+
this.streamTokens.set(key, {
|
|
961
|
+
url,
|
|
962
|
+
expiresAt: Date.now() + info.expires_in * 1000,
|
|
963
|
+
});
|
|
964
|
+
return url;
|
|
965
|
+
})
|
|
966
|
+
.finally(() => {
|
|
967
|
+
this.streamTokenInflight.delete(key);
|
|
968
|
+
});
|
|
969
|
+
this.streamTokenInflight.set(key, pending);
|
|
970
|
+
return pending;
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
/** Drop any cached stream grant for an upload (or all of them). */
|
|
974
|
+
clearStreamUrl(docId?: string, uploadId?: string): void {
|
|
975
|
+
if (docId && uploadId) {
|
|
976
|
+
this.streamTokens.delete(`${docId}/${uploadId}`);
|
|
977
|
+
this.streamTokenInflight.delete(`${docId}/${uploadId}`);
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
this.streamTokens.clear();
|
|
981
|
+
this.streamTokenInflight.clear();
|
|
982
|
+
}
|
|
983
|
+
|
|
903
984
|
/**
|
|
904
985
|
* Build the request path (with query string) for an upload's thumbnail.
|
|
905
986
|
* Also the canonical cache key suffix — the query string is deterministic
|
package/src/FileBlobStore.ts
CHANGED
|
@@ -153,6 +153,29 @@ export class FileBlobStore extends EventEmitter {
|
|
|
153
153
|
);
|
|
154
154
|
}
|
|
155
155
|
|
|
156
|
+
/**
|
|
157
|
+
* Return a **server** URL that streams an upload with HTTP Range support —
|
|
158
|
+
* for `<video src>` / `<audio src>`, where `getBlobUrl` would first pull
|
|
159
|
+
* the entire file into IndexedDB and seeking would stall until it landed.
|
|
160
|
+
*
|
|
161
|
+
* Requires a client and the network (the URL points at the server, and
|
|
162
|
+
* minting its token is a request). Returns `null` when either is missing,
|
|
163
|
+
* when the server predates the `stream-token` endpoint, or when we're
|
|
164
|
+
* already known to be offline — callers fall back to `getBlobUrl` for the
|
|
165
|
+
* cached copy.
|
|
166
|
+
*/
|
|
167
|
+
async getStreamUrl(docId: string, uploadId: string): Promise<string | null> {
|
|
168
|
+
if (!this.client) return null;
|
|
169
|
+
if (typeof navigator !== "undefined" && navigator.onLine === false) {
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
return await this.client.getStreamUrl(docId, uploadId);
|
|
174
|
+
} catch {
|
|
175
|
+
return null;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
156
179
|
/**
|
|
157
180
|
* Return a local object URL for a **thumbnail** of an image upload.
|
|
158
181
|
* On first call the server renders + caches it and this stores the bytes
|
package/src/types.ts
CHANGED
|
@@ -292,6 +292,18 @@ export interface ThumbnailOptions {
|
|
|
292
292
|
q?: number;
|
|
293
293
|
}
|
|
294
294
|
|
|
295
|
+
/** Response of `POST /docs/:docId/uploads/:uploadId/stream-token` — a
|
|
296
|
+
* short-lived grant that reads exactly one upload and travels in the query
|
|
297
|
+
* string, so a `<video src>` can Range-seek it without an Authorization
|
|
298
|
+
* header. `url` is server-relative. */
|
|
299
|
+
export interface StreamTokenInfo {
|
|
300
|
+
token: string;
|
|
301
|
+
/** Lifetime in seconds, from the moment the server minted it. */
|
|
302
|
+
expires_in: number;
|
|
303
|
+
/** `/docs/<docId>/uploads/<uploadId>?token=…` */
|
|
304
|
+
url: string;
|
|
305
|
+
}
|
|
306
|
+
|
|
295
307
|
export interface PublicKeyInfo {
|
|
296
308
|
id: string;
|
|
297
309
|
publicKey: string;
|