@sparkvault/sdk-js 11.1.12 → 11.1.14

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
@@ -2362,13 +2362,33 @@ interface UploadIngotOptions {
2362
2362
  /** Progress callback for the Forge/TUS transfer */
2363
2363
  onProgress?: (bytesUploaded: number, bytesTotal: number) => void;
2364
2364
  }
2365
+ /**
2366
+ * The upload session a file's bytes go to, which `sendUpload` hands over once
2367
+ * Forge opens it (`onSessionCreated`): what `resumeUpload` continues the
2368
+ * upload in. Its URL addresses the upload itself (a request to it can end the
2369
+ * upload), so keep it in memory, never in a log or a URL a person shares.
2370
+ */
2371
+ interface UploadSession {
2372
+ /** The session's URL on Forge. */
2373
+ readonly sessionUrl: string;
2374
+ }
2365
2375
  /** Options for sendUpload. */
2366
2376
  interface SendUploadOptions {
2367
2377
  /** Cancels the transfer. */
2368
2378
  signal?: AbortSignal;
2369
2379
  /** Bytes sent so far and the file size; never runs backwards. */
2370
2380
  onProgress?: (bytesUploaded: number, bytesTotal: number) => void;
2381
+ /**
2382
+ * Hands over the upload's session once Forge opens it, before the first
2383
+ * byte is sent, so the caller can `resumeUpload` the upload in it later:
2384
+ * after `upload_received_publishing`, to learn whether the server published
2385
+ * it, or after a failure, to send only the bytes the server lacks. A throw
2386
+ * here ends the transfer with that error.
2387
+ */
2388
+ onSessionCreated?: (session: UploadSession) => void;
2371
2389
  }
2390
+ /** Options for resumeUpload. */
2391
+ type ResumeUploadOptions = Omit<SendUploadOptions, 'onSessionCreated'>;
2372
2392
  /** Options for replacing an existing ingot's content. */
2373
2393
  interface ReplaceIngotOptions {
2374
2394
  /** File or Blob to upload as the new content */
@@ -2631,11 +2651,15 @@ declare class IngotsModule {
2631
2651
  * `details.coreCode`: a new upload is no remedy. A publication the server
2632
2652
  * still defers at the transfer's idle limit rejects with code
2633
2653
  * `upload_received_publishing`: every byte is received, and the server
2634
- * finishes the publication on its own, so never upload the file again.
2654
+ * finishes the publication on its own, so never upload the file again; a
2655
+ * caller that kept the session (`onSessionCreated`) learns what became of
2656
+ * it with {@link resumeUpload}.
2635
2657
  *
2636
2658
  * @param options.signal - Cancels this transfer (it rejects with code
2637
2659
  * `cancelled`); other transfers carry on.
2638
2660
  * @param options.onProgress - Bytes sent so far and the file size; never runs backwards.
2661
+ * @param options.onSessionCreated - Hands over the upload's session once
2662
+ * Forge opens it, before the first byte is sent.
2639
2663
  *
2640
2664
  * @example
2641
2665
  * const session = await sv.ingots.createUpload({ vault: unsealed, name: file.name,
@@ -2643,6 +2667,45 @@ declare class IngotsModule {
2643
2667
  * await sv.ingots.sendUpload(session.uploadUrl, file, { signal: controller.signal });
2644
2668
  */
2645
2669
  sendUpload(uploadUrl: string, file: File | Blob, options?: SendUploadOptions): Promise<void>;
2670
+ /**
2671
+ * Continue an upload in the session a {@link sendUpload} opened for the same
2672
+ * file (the `session` its `onSessionCreated` handed over): Forge is asked
2673
+ * where the session stands, only the bytes it lacks are sent, and the
2674
+ * promise resolves once the server confirms the ingot is published. A
2675
+ * session that already holds every byte sends none and only asks: this is
2676
+ * how a caller follows an upload that ended `upload_received_publishing`
2677
+ * until the server publishes it or ends it.
2678
+ *
2679
+ * It rejects as {@link sendUpload} does: `session_gone` once the server no
2680
+ * longer holds the session (it expired, was cancelled, or ended when the
2681
+ * server refused to publish it), `upload_refused` for an upload refused for
2682
+ * good, `upload_received_publishing` again for a publication the server
2683
+ * still defers at the transfer's idle limit, which leaves the session to
2684
+ * resume again later. A session URL that is not an upload session on an
2685
+ * allowed transfer host is refused (`invalid_forge_url`), and one whose
2686
+ * upload is not this file's length (`session_mismatch`), before a byte is
2687
+ * sent.
2688
+ *
2689
+ * @param options.signal - Cancels this transfer (it rejects with code
2690
+ * `cancelled`); the session stays as it stands.
2691
+ * @param options.onProgress - Bytes the session holds so far and the file size; never runs backwards.
2692
+ *
2693
+ * @example
2694
+ * let session;
2695
+ * try {
2696
+ * await sv.ingots.sendUpload(upload.uploadUrl, file, { onSessionCreated: (s) => { session = s; } });
2697
+ * } catch (error) {
2698
+ * if (error.code !== 'upload_received_publishing') throw error;
2699
+ * await sv.ingots.resumeUpload(session, file);
2700
+ * }
2701
+ */
2702
+ resumeUpload(session: UploadSession, file: File | Blob, options?: ResumeUploadOptions): Promise<void>;
2703
+ /**
2704
+ * Run one transfer on a transfer client of its own: its abort is scoped to
2705
+ * its own session, so cancelling one upload never touches another in
2706
+ * flight, and the caller's signal cancels it (code `cancelled`).
2707
+ */
2708
+ private runTransfer;
2646
2709
  /**
2647
2710
  * Upload a file as a new ingot (high-level flow).
2648
2711
  *
@@ -3444,4 +3507,4 @@ declare global {
3444
3507
  }
3445
3508
 
3446
3509
  export { AuthenticationError, AuthorizationError, EntropyModule, FoldersModule, IdentityModule, IngotsModule, NAME_CONFLICT_POLICIES, NOTIFY_PRESETS, NetworkError, NotifyModule, NotifyProductModule, NotifySubscriptionRequiredError, PlanRequiredError, PopupBlockedError, ProductsModule, QuotaExceededError, SparkVault, SparkVaultError, SparksModule, TimeoutError, UserCancelledError, ValidationError, VaultsModule, buildNotifyPresetSend, SparkVault as default, fetchDownload, logger, setDebugMode };
3447
- export type { AccessLogRetention, AccessLogsOptions, CreateFolderOptions, CreateNotifySendOptions, CreateSparkOptions, CreateUploadOptions, CreateVaultOptions, CreatedIngot, CreatedSpark, EntropyFormat, EntropyResult, FetchDownloadOptions, FetchedDownload, Folder, FolderBreadcrumbItem, FolderContents, GenerateEntropyOptions, HealthCheckOptions, HealthCheckResult, AttachOptions as IdentityAttachOptions, Ingot, IngotAccessLog, IngotAccessLogPage, IngotDownloadLink, IngotInvite, IngotPage, IngotSharingConfig, IngotUpload, ListContentsOptions, ListIngotsOptions, ListNotificationsOptions, ListNotificationsResponse, ListNotifyInboxOptions, ListNotifyInboxResponse, ListNotifyReceiptsOptions, ListNotifyReceiptsResponse, ListNotifySendsOptions, ListNotifySendsResponse, ListSparksOptions, MarkAllNotificationsStateOptions, MarkAllNotificationsStateResponse, MarkAllReadResult, MarkNotificationStateOptions, MarkNotificationStateResponse, MarkNotifyInboxAllOptions, MarkNotifyInboxAllResponse, MarkNotifyInboxStateOptions, MarkNotifyInboxStateResponse, NameConflictPolicy, NotificationBulkMarkState, NotificationInboxState, NotificationMarkState, NotificationRow, NotifyCategory, NotifyChannel, NotifyConfig, NotifyConfigCategory, NotifyConfigDelivery, NotifyConfigEvents, NotifyConfigEventsRead, NotifyConfigHistory, NotifyConfigOverrides, NotifyConfigPatch, NotifyConfigRealtimeFallbackDelay, NotifyConfigReliability, NotifyConfigResponse, NotifyConfigSecurity, NotifyDeliveryMode, NotifyEscalation, NotifyInboxBulkMarkState, NotifyInboxMarkState, NotifyInboxRow, NotifyInboxView, NotifyIngotRef, NotifyInteraction, NotifyPreset, NotifyPresetCategory, NotifyPresetName, NotifyPresetSendOptions, NotifyRecallMode, NotifyReceipt, NotifyReceiptEventType, NotifyRecipient, NotifyRecipientRef, NotifySendContent, NotifySendPolicy, NotifySendReceipt, NotifySendReceiptsResponse, NotifySendResult, NotifySendState, NotifySendStatus, NotifySendStatusCounts, NotifySendStatusRecipient, NotifySendSummary, NotifyVerificationLevel, QuotaResource, RecallNotifySendOptions, RecallNotifySendResponse, RegisterWebPushResponse, ReplaceIngotOptions, SearchIngotsOptions, SendUploadOptions, ShareSparkOptions, Spark, SparkPage, SparkShare, SparkSummary, SparkVaultConfig, SparkVisibility, SubscribeWebPushOptions, SubscribeWebPushResult, SubscribeWebPushStatus, TokenClaims, UnreadCountResponse, UnsealedVault, UnsubscribeWebPushResponse, UpdateFolderOptions, UpdateIngotSharingOptions, UpdateVaultUploadOptions, UpdatedVault, UploadAttachOptions, UploadBranding, UploadIngotOptions, UploadOptions, UploadProgress, UploadResult, Vault, VaultDetail, VaultSharingConfig, VaultSharingOptions, VaultSummary, VaultUploadConfig, VaultUploadSettings, VerifyOptions, VerifyResult, WebPushKeyResponse, WebPushSubscriptionInput };
3510
+ export type { AccessLogRetention, AccessLogsOptions, CreateFolderOptions, CreateNotifySendOptions, CreateSparkOptions, CreateUploadOptions, CreateVaultOptions, CreatedIngot, CreatedSpark, EntropyFormat, EntropyResult, FetchDownloadOptions, FetchedDownload, Folder, FolderBreadcrumbItem, FolderContents, GenerateEntropyOptions, HealthCheckOptions, HealthCheckResult, AttachOptions as IdentityAttachOptions, Ingot, IngotAccessLog, IngotAccessLogPage, IngotDownloadLink, IngotInvite, IngotPage, IngotSharingConfig, IngotUpload, ListContentsOptions, ListIngotsOptions, ListNotificationsOptions, ListNotificationsResponse, ListNotifyInboxOptions, ListNotifyInboxResponse, ListNotifyReceiptsOptions, ListNotifyReceiptsResponse, ListNotifySendsOptions, ListNotifySendsResponse, ListSparksOptions, MarkAllNotificationsStateOptions, MarkAllNotificationsStateResponse, MarkAllReadResult, MarkNotificationStateOptions, MarkNotificationStateResponse, MarkNotifyInboxAllOptions, MarkNotifyInboxAllResponse, MarkNotifyInboxStateOptions, MarkNotifyInboxStateResponse, NameConflictPolicy, NotificationBulkMarkState, NotificationInboxState, NotificationMarkState, NotificationRow, NotifyCategory, NotifyChannel, NotifyConfig, NotifyConfigCategory, NotifyConfigDelivery, NotifyConfigEvents, NotifyConfigEventsRead, NotifyConfigHistory, NotifyConfigOverrides, NotifyConfigPatch, NotifyConfigRealtimeFallbackDelay, NotifyConfigReliability, NotifyConfigResponse, NotifyConfigSecurity, NotifyDeliveryMode, NotifyEscalation, NotifyInboxBulkMarkState, NotifyInboxMarkState, NotifyInboxRow, NotifyInboxView, NotifyIngotRef, NotifyInteraction, NotifyPreset, NotifyPresetCategory, NotifyPresetName, NotifyPresetSendOptions, NotifyRecallMode, NotifyReceipt, NotifyReceiptEventType, NotifyRecipient, NotifyRecipientRef, NotifySendContent, NotifySendPolicy, NotifySendReceipt, NotifySendReceiptsResponse, NotifySendResult, NotifySendState, NotifySendStatus, NotifySendStatusCounts, NotifySendStatusRecipient, NotifySendSummary, NotifyVerificationLevel, QuotaResource, RecallNotifySendOptions, RecallNotifySendResponse, RegisterWebPushResponse, ReplaceIngotOptions, ResumeUploadOptions, SearchIngotsOptions, SendUploadOptions, ShareSparkOptions, Spark, SparkPage, SparkShare, SparkSummary, SparkVaultConfig, SparkVisibility, SubscribeWebPushOptions, SubscribeWebPushResult, SubscribeWebPushStatus, TokenClaims, UnreadCountResponse, UnsealedVault, UnsubscribeWebPushResponse, UpdateFolderOptions, UpdateIngotSharingOptions, UpdateVaultUploadOptions, UpdatedVault, UploadAttachOptions, UploadBranding, UploadIngotOptions, UploadOptions, UploadProgress, UploadResult, UploadSession, Vault, VaultDetail, VaultSharingConfig, VaultSharingOptions, VaultSummary, VaultUploadConfig, VaultUploadSettings, VerifyOptions, VerifyResult, WebPushKeyResponse, WebPushSubscriptionInput };
package/dist/index.mjs CHANGED
@@ -11563,6 +11563,27 @@ function resolveForgeSessionUrl(location, endpoint) {
11563
11563
  return SESSION_ID_PATTERN.test(session) ? `${origin}${base.path}/${session}` : null;
11564
11564
  }
11565
11565
 
11566
+ /**
11567
+ * Read a tus session URL a client kept to resume an upload: a session Forge
11568
+ * opened directly under the operation's endpoint on an allowed host, exactly
11569
+ * as resolveForgeSessionUrl placed it when the session was created. A resumed
11570
+ * session receives the ISTK and the file's bytes, so it is held to the rule a
11571
+ * created one was.
11572
+ *
11573
+ * @param {unknown} value
11574
+ * @param {Object} options
11575
+ * @param {'encrypt'|'decrypt'} options.operation - The transfer the session belongs to
11576
+ * @param {(hostname: string) => boolean} [options.isAllowedHost] - As for readForgeTransferUrl
11577
+ * @returns {{ ok: true, url: string } | { ok: false, reason: string }}
11578
+ */
11579
+ function readForgeSessionUrl(value, { operation, isAllowedHost = isForgeHost }) {
11580
+ const url = readHttpsUrl(value);
11581
+ if (!url.ok) return url;
11582
+ if (!isAllowedHost(url.hostname)) return refused(FORGE_URL_REFUSAL.HOST);
11583
+ const session = resolveForgeSessionUrl(value, `https://${url.hostname}/${operation}`);
11584
+ return session === null ? refused(FORGE_URL_REFUSAL.OPERATION) : { ok: true, url: session };
11585
+ }
11586
+
11566
11587
  /**
11567
11588
  * Cut an https URL into its host name, path and query by string rules alone.
11568
11589
  * @param {unknown} value
@@ -11691,6 +11712,13 @@ function parseChunkSizeHeader(raw) {
11691
11712
  const value = Number(raw);
11692
11713
  return Number.isSafeInteger(value) && value > 0 ? value : null;
11693
11714
  }
11715
+ /** Strict whole-number parse of a session's `Upload-Length`; anything else is `null`. */
11716
+ function parseLengthHeader(raw) {
11717
+ if (raw === null || !/^\d+$/.test(raw.trim()))
11718
+ return null;
11719
+ const value = Number(raw);
11720
+ return Number.isSafeInteger(value) ? value : null;
11721
+ }
11694
11722
  /**
11695
11723
  * Abort a stalled chunk PATCH after this long with no upload progress.
11696
11724
  * XHR's own `timeout` measures total request duration, which would abort a
@@ -11771,6 +11799,12 @@ function stagingRefusalOf(error) {
11771
11799
  function cancelledError() {
11772
11800
  return new UploadApiError('Upload cancelled', 'cancelled', 0);
11773
11801
  }
11802
+ /** Refuse a transfer where the browser's XMLHttpRequest is missing: a chunk's upload progress needs it. */
11803
+ function assertBrowserTransfer() {
11804
+ if (typeof XMLHttpRequest === 'undefined') {
11805
+ throw new UploadApiError('XMLHttpRequest is required for browser uploads', 'environment_unsupported', 0);
11806
+ }
11807
+ }
11774
11808
  /**
11775
11809
  * A delay that a cancel cuts short: resolves after `ms`, rejects with the
11776
11810
  * canonical cancelled error the moment the signal aborts.
@@ -12111,12 +12145,13 @@ class UploadApi extends SparkVaultApi {
12111
12145
  * Resolves only once the server has confirmed finalization
12112
12146
  * ({@link confirmServerFinalized}), so a caller that gets a resolved promise
12113
12147
  * is always looking at a published ingot; a publication the server still
12114
- * defers at the idle limit throws `upload_received_publishing`.
12148
+ * defers at the idle limit throws `upload_received_publishing`. The
12149
+ * session's URL goes to `onSessionCreated` once Forge opens it, before the
12150
+ * first byte, so the caller can continue the upload in it
12151
+ * ({@link resumeUploadToForge}) whatever becomes of this transfer.
12115
12152
  */
12116
- async uploadFileToForge(file, forgeUrl, onProgress) {
12117
- if (typeof XMLHttpRequest === 'undefined') {
12118
- throw new UploadApiError('XMLHttpRequest is required for browser uploads', 'environment_unsupported', 0);
12119
- }
12153
+ async uploadFileToForge(file, forgeUrl, onProgress, onSessionCreated) {
12154
+ assertBrowserTransfer();
12120
12155
  const target = readForgeTransferUrl(forgeUrl, {
12121
12156
  operation: 'encrypt',
12122
12157
  isAllowedHost: (hostname) => isAllowedTransferHost(this.config, hostname),
@@ -12135,13 +12170,66 @@ class UploadApi extends SparkVaultApi {
12135
12170
  if (!uploadUrl) {
12136
12171
  throw new UploadApiError('Upload session is outside the upload endpoint', 'tus_create_failed', 0);
12137
12172
  }
12138
- const transfer = {
12173
+ // Handed over before the first byte, so a caller can continue the upload
12174
+ // in this session whatever becomes of this transfer. It addresses the
12175
+ // upload itself, so it is never logged.
12176
+ onSessionCreated?.(uploadUrl);
12177
+ await this.sendFile(file, {
12139
12178
  uploadUrl,
12140
12179
  totalSize: file.size,
12141
12180
  chunkSize: session.chunkSize,
12142
12181
  budget,
12143
12182
  sessionSignal,
12183
+ }, 0, onProgress);
12184
+ }
12185
+ /**
12186
+ * Continue an upload in the session {@link uploadFileToForge} opened for
12187
+ * `file` (the session URL its `onSessionCreated` handed over), through the same
12188
+ * transfer: Forge is asked where the session stands (a HEAD, retried under
12189
+ * the transfer policy as any request of the upload is), only the bytes it
12190
+ * lacks are sent, and the upload resolves on the same receipt, so a
12191
+ * resolved promise is a published ingot. A session at its full offset sends
12192
+ * no byte and only takes the receipt: this is how a caller learns what
12193
+ * became of an upload whose publication was still deferred
12194
+ * (`upload_received_publishing`). It throws as an upload does: `session_gone`
12195
+ * once Forge no longer holds the session (cancelled, expired, or ended when
12196
+ * Core refused its publication), `upload_refused` for a refusal Core
12197
+ * decided, `upload_received_publishing` again for a publication still
12198
+ * deferred at the idle limit. A session URL that is not an upload session
12199
+ * on an allowed transfer host is refused (`invalid_forge_url`), and one
12200
+ * whose upload is not this file's length (`session_mismatch`), before any
12201
+ * byte is sent.
12202
+ */
12203
+ async resumeUploadToForge(file, sessionUrl, onProgress) {
12204
+ assertBrowserTransfer();
12205
+ const target = readForgeSessionUrl(sessionUrl, {
12206
+ operation: 'encrypt',
12207
+ isAllowedHost: (hostname) => isAllowedTransferHost(this.config, hostname),
12208
+ });
12209
+ if (!target.ok) {
12210
+ throw new UploadApiError('Forge upload session URL was refused', 'invalid_forge_url', 0, { reason: target.reason });
12211
+ }
12212
+ const sessionSignal = this.getAbortSignal();
12213
+ const budget = createTransferBudget();
12214
+ const standing = await this.readSessionStanding(target.url, budget, sessionSignal);
12215
+ if (standing.length !== file.size) {
12216
+ throw new UploadApiError('The upload session is for a file of another length', 'session_mismatch', 0, { sessionLength: standing.length, fileSize: file.size });
12217
+ }
12218
+ const transfer = {
12219
+ uploadUrl: target.url,
12220
+ totalSize: file.size,
12221
+ chunkSize: standing.chunkSize,
12222
+ budget,
12223
+ sessionSignal,
12144
12224
  };
12225
+ await this.sendFile(file, transfer, this.checkResumeOffset(standing.offset, transfer), onProgress);
12226
+ }
12227
+ /**
12228
+ * Send `file` into its session from `offset` (0 for a session just opened,
12229
+ * the server's own offset for a resumed one) until the receipt confirms
12230
+ * publication: the one loop every transfer runs.
12231
+ */
12232
+ async sendFile(file, transfer, offset, onProgress) {
12145
12233
  // Retries make raw progress non-monotonic (a chunk that streamed to 90%
12146
12234
  // then failed re-reports from its start on resend); callers get only the
12147
12235
  // high-water mark so a progress bar never runs backwards.
@@ -12154,9 +12242,10 @@ class UploadApi extends SparkVaultApi {
12154
12242
  }
12155
12243
  }
12156
12244
  : undefined;
12157
- let offset = 0;
12245
+ // A resumed session already holds its first bytes.
12246
+ monotonicProgress?.(offset, file.size);
12158
12247
  for (;;) {
12159
- if (sessionSignal.aborted) {
12248
+ if (transfer.sessionSignal.aborted) {
12160
12249
  throw cancelledError();
12161
12250
  }
12162
12251
  // One exit, one receipt: however the loop learned that every byte is on
@@ -12169,7 +12258,7 @@ class UploadApi extends SparkVaultApi {
12169
12258
  offset = receipt.resumeAt;
12170
12259
  continue;
12171
12260
  }
12172
- const chunkEnd = Math.min(offset + session.chunkSize, file.size);
12261
+ const chunkEnd = Math.min(offset + transfer.chunkSize, file.size);
12173
12262
  try {
12174
12263
  offset = await this.patchChunk(transfer, file.slice(offset, chunkEnd), offset, monotonicProgress);
12175
12264
  transfer.budget.progressed();
@@ -12295,6 +12384,36 @@ class UploadApi extends SparkVaultApi {
12295
12384
  }
12296
12385
  }
12297
12386
  }
12387
+ /**
12388
+ * Where a session a resume continues stands, from its HEAD: the bytes it
12389
+ * holds, the length of the upload it was opened for, and its chunk size
12390
+ * (Forge echoes `X-Chunk-Size` on a HEAD as on the create). A HEAD that
12391
+ * fails is asked again under the upload's budget as any request of it is;
12392
+ * a session the server no longer holds throws `session_gone`, and a refusal
12393
+ * Core decided its `upload_refused`.
12394
+ */
12395
+ async readSessionStanding(sessionUrl, budget, sessionSignal) {
12396
+ for (;;) {
12397
+ try {
12398
+ const { response, outcome } = await this.tusRequest(sessionUrl, { method: 'HEAD', headers: { 'Tus-Resumable': TUS_VERSION } }, RESUME_CHECK);
12399
+ const chunkSizeHeader = response.headers.get('X-Chunk-Size');
12400
+ const chunkSize = parseChunkSizeHeader(chunkSizeHeader);
12401
+ if (chunkSize === null) {
12402
+ throw new UploadApiError('Server did not return a valid X-Chunk-Size', RESUME_CHECK.code, response.status, { header: 'X-Chunk-Size', received: chunkSizeHeader });
12403
+ }
12404
+ // The session stands: the server confirmed it.
12405
+ budget.progressed();
12406
+ return { offset: outcome.offset, length: parseLengthHeader(response.headers.get('Upload-Length')), chunkSize };
12407
+ }
12408
+ catch (error) {
12409
+ const failure = transferFailure(error);
12410
+ if (failure.verdict === TRANSFER_VERDICT.GONE) {
12411
+ throw sessionGoneError(failure);
12412
+ }
12413
+ await waitToRetry(budget, failure, sessionUrl, sessionSignal);
12414
+ }
12415
+ }
12416
+ }
12298
12417
  /**
12299
12418
  * Read the offset a failed chunk should resume from, from the session's
12300
12419
  * HEAD. At the full offset it proves receipt only, published or not, so the
@@ -15617,6 +15736,16 @@ async function attemptDownload(link, state, options) {
15617
15736
  // next attempt what it needs to resume.
15618
15737
  state.held = held;
15619
15738
  await readBody(response, controller, state, held.total, onProgress);
15739
+ if (held.total > 0 && received.loaded !== held.total) {
15740
+ // A body that ended cleanly at any length but its declared one is not
15741
+ // the file: some hop reframed a cut transfer as a complete one. The
15742
+ // request counts as unanswered, so the next attempt resumes from the
15743
+ // bytes held, except after a body that ran past the declared length,
15744
+ // which no range can continue: it starts over.
15745
+ if (received.loaded > held.total)
15746
+ received.discard();
15747
+ return { ok: false, error: lengthMismatch(received.loaded, held.total), outcome: UNANSWERED };
15748
+ }
15620
15749
  delivered = true;
15621
15750
  return whole(held);
15622
15751
  }
@@ -15638,6 +15767,14 @@ async function attemptDownload(link, state, options) {
15638
15767
  signal?.removeEventListener('abort', abortFromCaller);
15639
15768
  }
15640
15769
  }
15770
+ /**
15771
+ * The failure of a body that ended at a length other than the one its
15772
+ * response declared: what the caller sees once the transfer can no longer
15773
+ * retry it (no link to mint, or the budget spent). Never a download.
15774
+ */
15775
+ function lengthMismatch(received, total) {
15776
+ return new SparkVaultError(`The download ended after ${received} of ${total} bytes`, 'download_failed', undefined, { reason: 'length_mismatch', received, total });
15777
+ }
15641
15778
  /** The resume point the bytes held allow, or null when the attempt fetches the whole file. */
15642
15779
  function resumePoint(state) {
15643
15780
  const { held, received } = state;
@@ -16045,11 +16182,15 @@ class IngotsModule {
16045
16182
  * `details.coreCode`: a new upload is no remedy. A publication the server
16046
16183
  * still defers at the transfer's idle limit rejects with code
16047
16184
  * `upload_received_publishing`: every byte is received, and the server
16048
- * finishes the publication on its own, so never upload the file again.
16185
+ * finishes the publication on its own, so never upload the file again; a
16186
+ * caller that kept the session (`onSessionCreated`) learns what became of
16187
+ * it with {@link resumeUpload}.
16049
16188
  *
16050
16189
  * @param options.signal - Cancels this transfer (it rejects with code
16051
16190
  * `cancelled`); other transfers carry on.
16052
16191
  * @param options.onProgress - Bytes sent so far and the file size; never runs backwards.
16192
+ * @param options.onSessionCreated - Hands over the upload's session once
16193
+ * Forge opens it, before the first byte is sent.
16053
16194
  *
16054
16195
  * @example
16055
16196
  * const session = await sv.ingots.createUpload({ vault: unsealed, name: file.name,
@@ -16058,17 +16199,60 @@ class IngotsModule {
16058
16199
  */
16059
16200
  async sendUpload(uploadUrl, file, options = {}) {
16060
16201
  this.validateFile(file);
16061
- const { signal, onProgress } = options;
16202
+ const { onProgress, onSessionCreated } = options;
16203
+ await this.runTransfer(options.signal, (transfer) => transfer.uploadFileToForge(file, uploadUrl, onProgress, onSessionCreated && ((sessionUrl) => onSessionCreated({ sessionUrl }))));
16204
+ }
16205
+ /**
16206
+ * Continue an upload in the session a {@link sendUpload} opened for the same
16207
+ * file (the `session` its `onSessionCreated` handed over): Forge is asked
16208
+ * where the session stands, only the bytes it lacks are sent, and the
16209
+ * promise resolves once the server confirms the ingot is published. A
16210
+ * session that already holds every byte sends none and only asks: this is
16211
+ * how a caller follows an upload that ended `upload_received_publishing`
16212
+ * until the server publishes it or ends it.
16213
+ *
16214
+ * It rejects as {@link sendUpload} does: `session_gone` once the server no
16215
+ * longer holds the session (it expired, was cancelled, or ended when the
16216
+ * server refused to publish it), `upload_refused` for an upload refused for
16217
+ * good, `upload_received_publishing` again for a publication the server
16218
+ * still defers at the transfer's idle limit, which leaves the session to
16219
+ * resume again later. A session URL that is not an upload session on an
16220
+ * allowed transfer host is refused (`invalid_forge_url`), and one whose
16221
+ * upload is not this file's length (`session_mismatch`), before a byte is
16222
+ * sent.
16223
+ *
16224
+ * @param options.signal - Cancels this transfer (it rejects with code
16225
+ * `cancelled`); the session stays as it stands.
16226
+ * @param options.onProgress - Bytes the session holds so far and the file size; never runs backwards.
16227
+ *
16228
+ * @example
16229
+ * let session;
16230
+ * try {
16231
+ * await sv.ingots.sendUpload(upload.uploadUrl, file, { onSessionCreated: (s) => { session = s; } });
16232
+ * } catch (error) {
16233
+ * if (error.code !== 'upload_received_publishing') throw error;
16234
+ * await sv.ingots.resumeUpload(session, file);
16235
+ * }
16236
+ */
16237
+ async resumeUpload(session, file, options = {}) {
16238
+ this.validateFile(file);
16239
+ const { onProgress } = options;
16240
+ await this.runTransfer(options.signal, (transfer) => transfer.resumeUploadToForge(file, session.sessionUrl, onProgress));
16241
+ }
16242
+ /**
16243
+ * Run one transfer on a transfer client of its own: its abort is scoped to
16244
+ * its own session, so cancelling one upload never touches another in
16245
+ * flight, and the caller's signal cancels it (code `cancelled`).
16246
+ */
16247
+ async runTransfer(signal, run) {
16062
16248
  if (signal?.aborted) {
16063
16249
  throw new UploadApiError('Upload cancelled', 'cancelled', 0);
16064
16250
  }
16065
- // One transfer client per call: its abort is scoped to its own session,
16066
- // so cancelling one upload never touches another in flight.
16067
16251
  const transfer = new UploadApi(this.config);
16068
16252
  const cancel = () => transfer.abort();
16069
16253
  signal?.addEventListener('abort', cancel, { once: true });
16070
16254
  try {
16071
- await transfer.uploadFileToForge(file, uploadUrl, onProgress);
16255
+ await run(transfer);
16072
16256
  }
16073
16257
  finally {
16074
16258
  signal?.removeEventListener('abort', cancel);
@@ -17196,7 +17380,7 @@ class SparkVault {
17196
17380
  }
17197
17381
  /** Get the SDK version */
17198
17382
  static get version() {
17199
- return '11.1.12';
17383
+ return '11.1.14';
17200
17384
  }
17201
17385
  }
17202
17386
  if (typeof window !== 'undefined') {