@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.cjs CHANGED
@@ -11567,6 +11567,27 @@ function resolveForgeSessionUrl(location, endpoint) {
11567
11567
  return SESSION_ID_PATTERN.test(session) ? `${origin}${base.path}/${session}` : null;
11568
11568
  }
11569
11569
 
11570
+ /**
11571
+ * Read a tus session URL a client kept to resume an upload: a session Forge
11572
+ * opened directly under the operation's endpoint on an allowed host, exactly
11573
+ * as resolveForgeSessionUrl placed it when the session was created. A resumed
11574
+ * session receives the ISTK and the file's bytes, so it is held to the rule a
11575
+ * created one was.
11576
+ *
11577
+ * @param {unknown} value
11578
+ * @param {Object} options
11579
+ * @param {'encrypt'|'decrypt'} options.operation - The transfer the session belongs to
11580
+ * @param {(hostname: string) => boolean} [options.isAllowedHost] - As for readForgeTransferUrl
11581
+ * @returns {{ ok: true, url: string } | { ok: false, reason: string }}
11582
+ */
11583
+ function readForgeSessionUrl(value, { operation, isAllowedHost = isForgeHost }) {
11584
+ const url = readHttpsUrl(value);
11585
+ if (!url.ok) return url;
11586
+ if (!isAllowedHost(url.hostname)) return refused(FORGE_URL_REFUSAL.HOST);
11587
+ const session = resolveForgeSessionUrl(value, `https://${url.hostname}/${operation}`);
11588
+ return session === null ? refused(FORGE_URL_REFUSAL.OPERATION) : { ok: true, url: session };
11589
+ }
11590
+
11570
11591
  /**
11571
11592
  * Cut an https URL into its host name, path and query by string rules alone.
11572
11593
  * @param {unknown} value
@@ -11695,6 +11716,13 @@ function parseChunkSizeHeader(raw) {
11695
11716
  const value = Number(raw);
11696
11717
  return Number.isSafeInteger(value) && value > 0 ? value : null;
11697
11718
  }
11719
+ /** Strict whole-number parse of a session's `Upload-Length`; anything else is `null`. */
11720
+ function parseLengthHeader(raw) {
11721
+ if (raw === null || !/^\d+$/.test(raw.trim()))
11722
+ return null;
11723
+ const value = Number(raw);
11724
+ return Number.isSafeInteger(value) ? value : null;
11725
+ }
11698
11726
  /**
11699
11727
  * Abort a stalled chunk PATCH after this long with no upload progress.
11700
11728
  * XHR's own `timeout` measures total request duration, which would abort a
@@ -11775,6 +11803,12 @@ function stagingRefusalOf(error) {
11775
11803
  function cancelledError() {
11776
11804
  return new UploadApiError('Upload cancelled', 'cancelled', 0);
11777
11805
  }
11806
+ /** Refuse a transfer where the browser's XMLHttpRequest is missing: a chunk's upload progress needs it. */
11807
+ function assertBrowserTransfer() {
11808
+ if (typeof XMLHttpRequest === 'undefined') {
11809
+ throw new UploadApiError('XMLHttpRequest is required for browser uploads', 'environment_unsupported', 0);
11810
+ }
11811
+ }
11778
11812
  /**
11779
11813
  * A delay that a cancel cuts short: resolves after `ms`, rejects with the
11780
11814
  * canonical cancelled error the moment the signal aborts.
@@ -12115,12 +12149,13 @@ class UploadApi extends SparkVaultApi {
12115
12149
  * Resolves only once the server has confirmed finalization
12116
12150
  * ({@link confirmServerFinalized}), so a caller that gets a resolved promise
12117
12151
  * is always looking at a published ingot; a publication the server still
12118
- * defers at the idle limit throws `upload_received_publishing`.
12152
+ * defers at the idle limit throws `upload_received_publishing`. The
12153
+ * session's URL goes to `onSessionCreated` once Forge opens it, before the
12154
+ * first byte, so the caller can continue the upload in it
12155
+ * ({@link resumeUploadToForge}) whatever becomes of this transfer.
12119
12156
  */
12120
- async uploadFileToForge(file, forgeUrl, onProgress) {
12121
- if (typeof XMLHttpRequest === 'undefined') {
12122
- throw new UploadApiError('XMLHttpRequest is required for browser uploads', 'environment_unsupported', 0);
12123
- }
12157
+ async uploadFileToForge(file, forgeUrl, onProgress, onSessionCreated) {
12158
+ assertBrowserTransfer();
12124
12159
  const target = readForgeTransferUrl(forgeUrl, {
12125
12160
  operation: 'encrypt',
12126
12161
  isAllowedHost: (hostname) => isAllowedTransferHost(this.config, hostname),
@@ -12139,13 +12174,66 @@ class UploadApi extends SparkVaultApi {
12139
12174
  if (!uploadUrl) {
12140
12175
  throw new UploadApiError('Upload session is outside the upload endpoint', 'tus_create_failed', 0);
12141
12176
  }
12142
- const transfer = {
12177
+ // Handed over before the first byte, so a caller can continue the upload
12178
+ // in this session whatever becomes of this transfer. It addresses the
12179
+ // upload itself, so it is never logged.
12180
+ onSessionCreated?.(uploadUrl);
12181
+ await this.sendFile(file, {
12143
12182
  uploadUrl,
12144
12183
  totalSize: file.size,
12145
12184
  chunkSize: session.chunkSize,
12146
12185
  budget,
12147
12186
  sessionSignal,
12187
+ }, 0, onProgress);
12188
+ }
12189
+ /**
12190
+ * Continue an upload in the session {@link uploadFileToForge} opened for
12191
+ * `file` (the session URL its `onSessionCreated` handed over), through the same
12192
+ * transfer: Forge is asked where the session stands (a HEAD, retried under
12193
+ * the transfer policy as any request of the upload is), only the bytes it
12194
+ * lacks are sent, and the upload resolves on the same receipt, so a
12195
+ * resolved promise is a published ingot. A session at its full offset sends
12196
+ * no byte and only takes the receipt: this is how a caller learns what
12197
+ * became of an upload whose publication was still deferred
12198
+ * (`upload_received_publishing`). It throws as an upload does: `session_gone`
12199
+ * once Forge no longer holds the session (cancelled, expired, or ended when
12200
+ * Core refused its publication), `upload_refused` for a refusal Core
12201
+ * decided, `upload_received_publishing` again for a publication still
12202
+ * deferred at the idle limit. A session URL that is not an upload session
12203
+ * on an allowed transfer host is refused (`invalid_forge_url`), and one
12204
+ * whose upload is not this file's length (`session_mismatch`), before any
12205
+ * byte is sent.
12206
+ */
12207
+ async resumeUploadToForge(file, sessionUrl, onProgress) {
12208
+ assertBrowserTransfer();
12209
+ const target = readForgeSessionUrl(sessionUrl, {
12210
+ operation: 'encrypt',
12211
+ isAllowedHost: (hostname) => isAllowedTransferHost(this.config, hostname),
12212
+ });
12213
+ if (!target.ok) {
12214
+ throw new UploadApiError('Forge upload session URL was refused', 'invalid_forge_url', 0, { reason: target.reason });
12215
+ }
12216
+ const sessionSignal = this.getAbortSignal();
12217
+ const budget = createTransferBudget();
12218
+ const standing = await this.readSessionStanding(target.url, budget, sessionSignal);
12219
+ if (standing.length !== file.size) {
12220
+ throw new UploadApiError('The upload session is for a file of another length', 'session_mismatch', 0, { sessionLength: standing.length, fileSize: file.size });
12221
+ }
12222
+ const transfer = {
12223
+ uploadUrl: target.url,
12224
+ totalSize: file.size,
12225
+ chunkSize: standing.chunkSize,
12226
+ budget,
12227
+ sessionSignal,
12148
12228
  };
12229
+ await this.sendFile(file, transfer, this.checkResumeOffset(standing.offset, transfer), onProgress);
12230
+ }
12231
+ /**
12232
+ * Send `file` into its session from `offset` (0 for a session just opened,
12233
+ * the server's own offset for a resumed one) until the receipt confirms
12234
+ * publication: the one loop every transfer runs.
12235
+ */
12236
+ async sendFile(file, transfer, offset, onProgress) {
12149
12237
  // Retries make raw progress non-monotonic (a chunk that streamed to 90%
12150
12238
  // then failed re-reports from its start on resend); callers get only the
12151
12239
  // high-water mark so a progress bar never runs backwards.
@@ -12158,9 +12246,10 @@ class UploadApi extends SparkVaultApi {
12158
12246
  }
12159
12247
  }
12160
12248
  : undefined;
12161
- let offset = 0;
12249
+ // A resumed session already holds its first bytes.
12250
+ monotonicProgress?.(offset, file.size);
12162
12251
  for (;;) {
12163
- if (sessionSignal.aborted) {
12252
+ if (transfer.sessionSignal.aborted) {
12164
12253
  throw cancelledError();
12165
12254
  }
12166
12255
  // One exit, one receipt: however the loop learned that every byte is on
@@ -12173,7 +12262,7 @@ class UploadApi extends SparkVaultApi {
12173
12262
  offset = receipt.resumeAt;
12174
12263
  continue;
12175
12264
  }
12176
- const chunkEnd = Math.min(offset + session.chunkSize, file.size);
12265
+ const chunkEnd = Math.min(offset + transfer.chunkSize, file.size);
12177
12266
  try {
12178
12267
  offset = await this.patchChunk(transfer, file.slice(offset, chunkEnd), offset, monotonicProgress);
12179
12268
  transfer.budget.progressed();
@@ -12299,6 +12388,36 @@ class UploadApi extends SparkVaultApi {
12299
12388
  }
12300
12389
  }
12301
12390
  }
12391
+ /**
12392
+ * Where a session a resume continues stands, from its HEAD: the bytes it
12393
+ * holds, the length of the upload it was opened for, and its chunk size
12394
+ * (Forge echoes `X-Chunk-Size` on a HEAD as on the create). A HEAD that
12395
+ * fails is asked again under the upload's budget as any request of it is;
12396
+ * a session the server no longer holds throws `session_gone`, and a refusal
12397
+ * Core decided its `upload_refused`.
12398
+ */
12399
+ async readSessionStanding(sessionUrl, budget, sessionSignal) {
12400
+ for (;;) {
12401
+ try {
12402
+ const { response, outcome } = await this.tusRequest(sessionUrl, { method: 'HEAD', headers: { 'Tus-Resumable': TUS_VERSION } }, RESUME_CHECK);
12403
+ const chunkSizeHeader = response.headers.get('X-Chunk-Size');
12404
+ const chunkSize = parseChunkSizeHeader(chunkSizeHeader);
12405
+ if (chunkSize === null) {
12406
+ throw new UploadApiError('Server did not return a valid X-Chunk-Size', RESUME_CHECK.code, response.status, { header: 'X-Chunk-Size', received: chunkSizeHeader });
12407
+ }
12408
+ // The session stands: the server confirmed it.
12409
+ budget.progressed();
12410
+ return { offset: outcome.offset, length: parseLengthHeader(response.headers.get('Upload-Length')), chunkSize };
12411
+ }
12412
+ catch (error) {
12413
+ const failure = transferFailure(error);
12414
+ if (failure.verdict === TRANSFER_VERDICT.GONE) {
12415
+ throw sessionGoneError(failure);
12416
+ }
12417
+ await waitToRetry(budget, failure, sessionUrl, sessionSignal);
12418
+ }
12419
+ }
12420
+ }
12302
12421
  /**
12303
12422
  * Read the offset a failed chunk should resume from, from the session's
12304
12423
  * HEAD. At the full offset it proves receipt only, published or not, so the
@@ -15621,6 +15740,16 @@ async function attemptDownload(link, state, options) {
15621
15740
  // next attempt what it needs to resume.
15622
15741
  state.held = held;
15623
15742
  await readBody(response, controller, state, held.total, onProgress);
15743
+ if (held.total > 0 && received.loaded !== held.total) {
15744
+ // A body that ended cleanly at any length but its declared one is not
15745
+ // the file: some hop reframed a cut transfer as a complete one. The
15746
+ // request counts as unanswered, so the next attempt resumes from the
15747
+ // bytes held, except after a body that ran past the declared length,
15748
+ // which no range can continue: it starts over.
15749
+ if (received.loaded > held.total)
15750
+ received.discard();
15751
+ return { ok: false, error: lengthMismatch(received.loaded, held.total), outcome: UNANSWERED };
15752
+ }
15624
15753
  delivered = true;
15625
15754
  return whole(held);
15626
15755
  }
@@ -15642,6 +15771,14 @@ async function attemptDownload(link, state, options) {
15642
15771
  signal?.removeEventListener('abort', abortFromCaller);
15643
15772
  }
15644
15773
  }
15774
+ /**
15775
+ * The failure of a body that ended at a length other than the one its
15776
+ * response declared: what the caller sees once the transfer can no longer
15777
+ * retry it (no link to mint, or the budget spent). Never a download.
15778
+ */
15779
+ function lengthMismatch(received, total) {
15780
+ return new SparkVaultError(`The download ended after ${received} of ${total} bytes`, 'download_failed', undefined, { reason: 'length_mismatch', received, total });
15781
+ }
15645
15782
  /** The resume point the bytes held allow, or null when the attempt fetches the whole file. */
15646
15783
  function resumePoint(state) {
15647
15784
  const { held, received } = state;
@@ -16049,11 +16186,15 @@ class IngotsModule {
16049
16186
  * `details.coreCode`: a new upload is no remedy. A publication the server
16050
16187
  * still defers at the transfer's idle limit rejects with code
16051
16188
  * `upload_received_publishing`: every byte is received, and the server
16052
- * finishes the publication on its own, so never upload the file again.
16189
+ * finishes the publication on its own, so never upload the file again; a
16190
+ * caller that kept the session (`onSessionCreated`) learns what became of
16191
+ * it with {@link resumeUpload}.
16053
16192
  *
16054
16193
  * @param options.signal - Cancels this transfer (it rejects with code
16055
16194
  * `cancelled`); other transfers carry on.
16056
16195
  * @param options.onProgress - Bytes sent so far and the file size; never runs backwards.
16196
+ * @param options.onSessionCreated - Hands over the upload's session once
16197
+ * Forge opens it, before the first byte is sent.
16057
16198
  *
16058
16199
  * @example
16059
16200
  * const session = await sv.ingots.createUpload({ vault: unsealed, name: file.name,
@@ -16062,17 +16203,60 @@ class IngotsModule {
16062
16203
  */
16063
16204
  async sendUpload(uploadUrl, file, options = {}) {
16064
16205
  this.validateFile(file);
16065
- const { signal, onProgress } = options;
16206
+ const { onProgress, onSessionCreated } = options;
16207
+ await this.runTransfer(options.signal, (transfer) => transfer.uploadFileToForge(file, uploadUrl, onProgress, onSessionCreated && ((sessionUrl) => onSessionCreated({ sessionUrl }))));
16208
+ }
16209
+ /**
16210
+ * Continue an upload in the session a {@link sendUpload} opened for the same
16211
+ * file (the `session` its `onSessionCreated` handed over): Forge is asked
16212
+ * where the session stands, only the bytes it lacks are sent, and the
16213
+ * promise resolves once the server confirms the ingot is published. A
16214
+ * session that already holds every byte sends none and only asks: this is
16215
+ * how a caller follows an upload that ended `upload_received_publishing`
16216
+ * until the server publishes it or ends it.
16217
+ *
16218
+ * It rejects as {@link sendUpload} does: `session_gone` once the server no
16219
+ * longer holds the session (it expired, was cancelled, or ended when the
16220
+ * server refused to publish it), `upload_refused` for an upload refused for
16221
+ * good, `upload_received_publishing` again for a publication the server
16222
+ * still defers at the transfer's idle limit, which leaves the session to
16223
+ * resume again later. A session URL that is not an upload session on an
16224
+ * allowed transfer host is refused (`invalid_forge_url`), and one whose
16225
+ * upload is not this file's length (`session_mismatch`), before a byte is
16226
+ * sent.
16227
+ *
16228
+ * @param options.signal - Cancels this transfer (it rejects with code
16229
+ * `cancelled`); the session stays as it stands.
16230
+ * @param options.onProgress - Bytes the session holds so far and the file size; never runs backwards.
16231
+ *
16232
+ * @example
16233
+ * let session;
16234
+ * try {
16235
+ * await sv.ingots.sendUpload(upload.uploadUrl, file, { onSessionCreated: (s) => { session = s; } });
16236
+ * } catch (error) {
16237
+ * if (error.code !== 'upload_received_publishing') throw error;
16238
+ * await sv.ingots.resumeUpload(session, file);
16239
+ * }
16240
+ */
16241
+ async resumeUpload(session, file, options = {}) {
16242
+ this.validateFile(file);
16243
+ const { onProgress } = options;
16244
+ await this.runTransfer(options.signal, (transfer) => transfer.resumeUploadToForge(file, session.sessionUrl, onProgress));
16245
+ }
16246
+ /**
16247
+ * Run one transfer on a transfer client of its own: its abort is scoped to
16248
+ * its own session, so cancelling one upload never touches another in
16249
+ * flight, and the caller's signal cancels it (code `cancelled`).
16250
+ */
16251
+ async runTransfer(signal, run) {
16066
16252
  if (signal?.aborted) {
16067
16253
  throw new UploadApiError('Upload cancelled', 'cancelled', 0);
16068
16254
  }
16069
- // One transfer client per call: its abort is scoped to its own session,
16070
- // so cancelling one upload never touches another in flight.
16071
16255
  const transfer = new UploadApi(this.config);
16072
16256
  const cancel = () => transfer.abort();
16073
16257
  signal?.addEventListener('abort', cancel, { once: true });
16074
16258
  try {
16075
- await transfer.uploadFileToForge(file, uploadUrl, onProgress);
16259
+ await run(transfer);
16076
16260
  }
16077
16261
  finally {
16078
16262
  signal?.removeEventListener('abort', cancel);
@@ -17200,7 +17384,7 @@ class SparkVault {
17200
17384
  }
17201
17385
  /** Get the SDK version */
17202
17386
  static get version() {
17203
- return '11.1.12';
17387
+ return '11.1.14';
17204
17388
  }
17205
17389
  }
17206
17390
  if (typeof window !== 'undefined') {