@sparkvault/sdk-js 11.1.13 → 11.2.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.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
@@ -15075,6 +15194,7 @@ class VaultsModule {
15075
15194
  createdAt: v.created_at,
15076
15195
  ingotCount: v.ingot_count,
15077
15196
  storageBytes: v.storage_bytes,
15197
+ ...mapLifecycle(v),
15078
15198
  })),
15079
15199
  nextCursor: response.data.next_cursor,
15080
15200
  };
@@ -15089,18 +15209,7 @@ class VaultsModule {
15089
15209
  async get(vaultId) {
15090
15210
  const id = requireResourceId(vaultId, 'vaultId');
15091
15211
  const response = await this.http.get(apiPath `/v1/vaults/${id}`);
15092
- const v = response.data;
15093
- return {
15094
- id: v.vault_id,
15095
- name: v.name,
15096
- description: v.description ?? null,
15097
- status: v.status,
15098
- ingotCount: v.ingot_count ?? 0,
15099
- storageBytes: v.storage_bytes ?? 0,
15100
- createdAt: v.created_at,
15101
- lastUnsealedAt: v.last_unsealed_at ?? null,
15102
- unsealCount: v.unseal_count ?? 0,
15103
- };
15212
+ return mapVaultDetail(response.data);
15104
15213
  }
15105
15214
  /**
15106
15215
  * Rename a vault.
@@ -15135,7 +15244,8 @@ class VaultsModule {
15135
15244
  await this.http.post(apiPath `/v1/vaults/${id}/seal`);
15136
15245
  }
15137
15246
  /**
15138
- * Delete a vault and all its ingots. This action is irreversible!
15247
+ * Schedule permanent deletion in seven days and immediately lock all vault access.
15248
+ * Company admins only; cancelDeletion can abort this schedule before its deadline.
15139
15249
  *
15140
15250
  * Requires the vault's exact name as confirmation, matched case-sensitively.
15141
15251
  * The name is sent base64(UTF-8) as the `X-Confirm-Name-B64` header so a vault
@@ -15150,9 +15260,32 @@ class VaultsModule {
15150
15260
  if (!name) {
15151
15261
  throw new ValidationError('Vault name is required to confirm deletion');
15152
15262
  }
15153
- await this.http.delete(apiPath `/v1/vaults/${id}`, {
15154
- headers: { 'X-Confirm-Name-B64': base64EncodeUtf8(name) },
15263
+ const response = await this.http.delete(apiPath `/v1/vaults/${id}`, {
15264
+ headers: {
15265
+ 'X-Confirm-Name-B64': base64EncodeUtf8(name),
15266
+ 'X-Vault-Deletion-Mode': 'schedule',
15267
+ },
15268
+ });
15269
+ const scheduled = response.data;
15270
+ return {
15271
+ id: scheduled.vault_id,
15272
+ status: scheduled.status,
15273
+ deletionRequestedAt: scheduled.deletion_requested_at,
15274
+ deletionScheduledFor: scheduled.deletion_scheduled_for,
15275
+ deletionRequestedBy: scheduled.deletion_requested_by,
15276
+ deletionScheduleId: scheduled.deletion_schedule_id,
15277
+ };
15278
+ }
15279
+ /** Cancel this exact deletion schedule before its deadline; company admins only. */
15280
+ async cancelDeletion(vaultId, deletionScheduleId) {
15281
+ const id = requireResourceId(vaultId, 'vaultId');
15282
+ if (!deletionScheduleId?.trim()) {
15283
+ throw new ValidationError('Deletion schedule is required to cancel deletion');
15284
+ }
15285
+ const response = await this.http.post(apiPath `/v1/vaults/${id}/deletion/cancel`, {
15286
+ deletion_schedule_id: deletionScheduleId,
15155
15287
  });
15288
+ return mapVaultDetail(response.data);
15156
15289
  }
15157
15290
  /**
15158
15291
  * Get a vault's public-sharing configuration.
@@ -15333,6 +15466,28 @@ class VaultsModule {
15333
15466
  }
15334
15467
  }
15335
15468
  }
15469
+ function mapLifecycle(v) {
15470
+ return {
15471
+ status: v.status,
15472
+ deletionRequestedAt: v.deletion_requested_at,
15473
+ deletionScheduledFor: v.deletion_scheduled_for,
15474
+ deletionRequestedBy: v.deletion_requested_by,
15475
+ deletionScheduleId: v.deletion_schedule_id,
15476
+ };
15477
+ }
15478
+ function mapVaultDetail(v) {
15479
+ return {
15480
+ id: v.vault_id,
15481
+ name: v.name,
15482
+ description: v.description ?? null,
15483
+ ...mapLifecycle(v),
15484
+ ingotCount: v.ingot_count ?? 0,
15485
+ storageBytes: v.storage_bytes ?? 0,
15486
+ createdAt: v.created_at,
15487
+ lastUnsealedAt: v.last_unsealed_at ?? null,
15488
+ unsealCount: v.unseal_count ?? 0,
15489
+ };
15490
+ }
15336
15491
  function mapSharingConfig$1(wire) {
15337
15492
  return {
15338
15493
  vaultId: wire.vault_id,
@@ -15621,6 +15776,16 @@ async function attemptDownload(link, state, options) {
15621
15776
  // next attempt what it needs to resume.
15622
15777
  state.held = held;
15623
15778
  await readBody(response, controller, state, held.total, onProgress);
15779
+ if (held.total > 0 && received.loaded !== held.total) {
15780
+ // A body that ended cleanly at any length but its declared one is not
15781
+ // the file: some hop reframed a cut transfer as a complete one. The
15782
+ // request counts as unanswered, so the next attempt resumes from the
15783
+ // bytes held, except after a body that ran past the declared length,
15784
+ // which no range can continue: it starts over.
15785
+ if (received.loaded > held.total)
15786
+ received.discard();
15787
+ return { ok: false, error: lengthMismatch(received.loaded, held.total), outcome: UNANSWERED };
15788
+ }
15624
15789
  delivered = true;
15625
15790
  return whole(held);
15626
15791
  }
@@ -15642,6 +15807,14 @@ async function attemptDownload(link, state, options) {
15642
15807
  signal?.removeEventListener('abort', abortFromCaller);
15643
15808
  }
15644
15809
  }
15810
+ /**
15811
+ * The failure of a body that ended at a length other than the one its
15812
+ * response declared: what the caller sees once the transfer can no longer
15813
+ * retry it (no link to mint, or the budget spent). Never a download.
15814
+ */
15815
+ function lengthMismatch(received, total) {
15816
+ return new SparkVaultError(`The download ended after ${received} of ${total} bytes`, 'download_failed', undefined, { reason: 'length_mismatch', received, total });
15817
+ }
15645
15818
  /** The resume point the bytes held allow, or null when the attempt fetches the whole file. */
15646
15819
  function resumePoint(state) {
15647
15820
  const { held, received } = state;
@@ -16049,11 +16222,15 @@ class IngotsModule {
16049
16222
  * `details.coreCode`: a new upload is no remedy. A publication the server
16050
16223
  * still defers at the transfer's idle limit rejects with code
16051
16224
  * `upload_received_publishing`: every byte is received, and the server
16052
- * finishes the publication on its own, so never upload the file again.
16225
+ * finishes the publication on its own, so never upload the file again; a
16226
+ * caller that kept the session (`onSessionCreated`) learns what became of
16227
+ * it with {@link resumeUpload}.
16053
16228
  *
16054
16229
  * @param options.signal - Cancels this transfer (it rejects with code
16055
16230
  * `cancelled`); other transfers carry on.
16056
16231
  * @param options.onProgress - Bytes sent so far and the file size; never runs backwards.
16232
+ * @param options.onSessionCreated - Hands over the upload's session once
16233
+ * Forge opens it, before the first byte is sent.
16057
16234
  *
16058
16235
  * @example
16059
16236
  * const session = await sv.ingots.createUpload({ vault: unsealed, name: file.name,
@@ -16062,17 +16239,60 @@ class IngotsModule {
16062
16239
  */
16063
16240
  async sendUpload(uploadUrl, file, options = {}) {
16064
16241
  this.validateFile(file);
16065
- const { signal, onProgress } = options;
16242
+ const { onProgress, onSessionCreated } = options;
16243
+ await this.runTransfer(options.signal, (transfer) => transfer.uploadFileToForge(file, uploadUrl, onProgress, onSessionCreated && ((sessionUrl) => onSessionCreated({ sessionUrl }))));
16244
+ }
16245
+ /**
16246
+ * Continue an upload in the session a {@link sendUpload} opened for the same
16247
+ * file (the `session` its `onSessionCreated` handed over): Forge is asked
16248
+ * where the session stands, only the bytes it lacks are sent, and the
16249
+ * promise resolves once the server confirms the ingot is published. A
16250
+ * session that already holds every byte sends none and only asks: this is
16251
+ * how a caller follows an upload that ended `upload_received_publishing`
16252
+ * until the server publishes it or ends it.
16253
+ *
16254
+ * It rejects as {@link sendUpload} does: `session_gone` once the server no
16255
+ * longer holds the session (it expired, was cancelled, or ended when the
16256
+ * server refused to publish it), `upload_refused` for an upload refused for
16257
+ * good, `upload_received_publishing` again for a publication the server
16258
+ * still defers at the transfer's idle limit, which leaves the session to
16259
+ * resume again later. A session URL that is not an upload session on an
16260
+ * allowed transfer host is refused (`invalid_forge_url`), and one whose
16261
+ * upload is not this file's length (`session_mismatch`), before a byte is
16262
+ * sent.
16263
+ *
16264
+ * @param options.signal - Cancels this transfer (it rejects with code
16265
+ * `cancelled`); the session stays as it stands.
16266
+ * @param options.onProgress - Bytes the session holds so far and the file size; never runs backwards.
16267
+ *
16268
+ * @example
16269
+ * let session;
16270
+ * try {
16271
+ * await sv.ingots.sendUpload(upload.uploadUrl, file, { onSessionCreated: (s) => { session = s; } });
16272
+ * } catch (error) {
16273
+ * if (error.code !== 'upload_received_publishing') throw error;
16274
+ * await sv.ingots.resumeUpload(session, file);
16275
+ * }
16276
+ */
16277
+ async resumeUpload(session, file, options = {}) {
16278
+ this.validateFile(file);
16279
+ const { onProgress } = options;
16280
+ await this.runTransfer(options.signal, (transfer) => transfer.resumeUploadToForge(file, session.sessionUrl, onProgress));
16281
+ }
16282
+ /**
16283
+ * Run one transfer on a transfer client of its own: its abort is scoped to
16284
+ * its own session, so cancelling one upload never touches another in
16285
+ * flight, and the caller's signal cancels it (code `cancelled`).
16286
+ */
16287
+ async runTransfer(signal, run) {
16066
16288
  if (signal?.aborted) {
16067
16289
  throw new UploadApiError('Upload cancelled', 'cancelled', 0);
16068
16290
  }
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
16291
  const transfer = new UploadApi(this.config);
16072
16292
  const cancel = () => transfer.abort();
16073
16293
  signal?.addEventListener('abort', cancel, { once: true });
16074
16294
  try {
16075
- await transfer.uploadFileToForge(file, uploadUrl, onProgress);
16295
+ await run(transfer);
16076
16296
  }
16077
16297
  finally {
16078
16298
  signal?.removeEventListener('abort', cancel);
@@ -17200,7 +17420,7 @@ class SparkVault {
17200
17420
  }
17201
17421
  /** Get the SDK version */
17202
17422
  static get version() {
17203
- return '11.1.13';
17423
+ return '11.2.0';
17204
17424
  }
17205
17425
  }
17206
17426
  if (typeof window !== 'undefined') {