@sparkvault/sdk-js 12.0.3 → 12.0.5

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.mjs CHANGED
@@ -31,7 +31,8 @@ function isTransientHttpStatus(status) {
31
31
  * publication it is bound to (a content version, and the one an ingot row
32
32
  * names), Core's revocation of an upload's token, and the refusals of Core's
33
33
  * a transfer's answer names (the header, and the lock of a vault scheduled
34
- * for deletion).
34
+ * for deletion). Every client ends an upload it gives up by one rule here
35
+ * too: the upload id its delete is conditioned on (givenUpUploadId).
35
36
  *
36
37
  * Forge stamps UPLOAD_PUBLICATION_PROTOCOL on every upload session it creates
37
38
  * and on the final state it hands Core's activation (POST
@@ -50,6 +51,38 @@ function isTransientHttpStatus(status) {
50
51
  */
51
52
 
52
53
 
54
+ /**
55
+ * An upload's id as both services spell it: `tus_` and the 32 lowercase hex
56
+ * digits of 16 random bytes. An encrypt token that names one (`upload_id`)
57
+ * was staged by Core under it, and Forge keys the upload's session, its chunk
58
+ * prefix and its VAK wrapping by it, so Core finds and settles the upload by
59
+ * the session's id.
60
+ */
61
+ const UPLOAD_ID_PATTERN = /^tus_[0-9a-f]{32}$/;
62
+
63
+ /**
64
+ * The upload id under which a client that gives an upload up (its person
65
+ * cancelled it, or it failed for good) ends it with the file its create
66
+ * made: the `upload_id` that create answered, which Core's delete takes as
67
+ * its condition (`DELETE …/ingots/:ingot_id?upload_id=`), deleting the ingot
68
+ * only while it is still that upload's unfinished file and keeping (412) one
69
+ * the upload published, or a later upload took over. Null when the file is
70
+ * not the upload's to end: its create staged onto a row that already stood
71
+ * (`created` not true: another upload's unfinished file, or a published file
72
+ * the upload was replacing), or answered no upload id, without which the
73
+ * delete would take whatever file stands, one the upload published
74
+ * included. Every client sends a given-up upload's delete under this id
75
+ * alone, and sends none when it is null.
76
+ *
77
+ * @param {{ created?: boolean|null, uploadId?: string|null }} placement -
78
+ * What the upload's create answered: whether it made the file, and the
79
+ * upload it staged
80
+ * @returns {string|null}
81
+ */
82
+ function givenUpUploadId({ created, uploadId }) {
83
+ return created === true && typeof uploadId === 'string' && UPLOAD_ID_PATTERN.test(uploadId) ? uploadId : null;
84
+ }
85
+
53
86
  /**
54
87
  * The codes Core's activation refuses an upload with, which Forge's refusal
55
88
  * map reads (the status is Core's):
@@ -1872,14 +1905,14 @@ function defineEntropyLayout(fields) {
1872
1905
  }
1873
1906
  const names = new Set();
1874
1907
  let bytes = 0;
1875
- for (const [name, length] of fields) {
1876
- if (typeof name !== 'string' || name.length === 0 || names.has(name)) {
1877
- throw new TypeError(`Entropy layout field names must be unique non-empty strings (${String(name)})`);
1908
+ for (const [field, length] of fields) {
1909
+ if (typeof field !== 'string' || field.length === 0 || names.has(field)) {
1910
+ throw new TypeError(`Entropy layout field names must be unique non-empty strings (${String(field)})`);
1878
1911
  }
1879
1912
  if (!Number.isSafeInteger(length) || length <= 0) {
1880
- throw new TypeError(`Entropy layout field ${name} must be a positive whole number of bytes`);
1913
+ throw new TypeError(`Entropy layout field ${field} must be a positive whole number of bytes`);
1881
1914
  }
1882
- names.add(name);
1915
+ names.add(field);
1883
1916
  bytes += length;
1884
1917
  }
1885
1918
  if (bytes > MAX_DRAW_BYTES) {
@@ -3637,7 +3670,15 @@ class SparkLinkHandler {
3637
3670
  * alike.
3638
3671
  */
3639
3672
 
3640
- const LOCAL_PART = /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/;
3673
+ /**
3674
+ * The characters an RFC 5322 dot-atom local part holds, in its canonical
3675
+ * (lowercase) form, as the body of a character class: the one set the
3676
+ * grammar below accepts and the log mask (./pii-mask.js) reads an address in
3677
+ * text by.
3678
+ */
3679
+ const EMAIL_LOCAL_PART_CHARACTERS = "a-z0-9.!#$%&'*+/=?^_`{|}~-";
3680
+
3681
+ const LOCAL_PART = new RegExp(`^[${EMAIL_LOCAL_PART_CHARACTERS}]+$`);
3641
3682
  const DOMAIN_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
3642
3683
 
3643
3684
  /** RFC 5321 length limits, in characters. */
@@ -11970,6 +12011,38 @@ function waitUntilOnline(signal) {
11970
12011
  settle(resolve);
11971
12012
  });
11972
12013
  }
12014
+ /**
12015
+ * The failures a transfer met once the server held every byte of its upload,
12016
+ * which leave the upload's end to the server ({@link isReceivedUploadFailure}).
12017
+ */
12018
+ const receivedFailures = new WeakSet();
12019
+ /** The codes that end an upload whatever the server holds of it: its session gone, Core's refusal, the caller's cancel. */
12020
+ const UPLOAD_ENDING_CODES = new Set(['session_gone', 'upload_refused', 'cancelled']);
12021
+ /**
12022
+ * A failure of the receipt, which the transfer asks for only once the server
12023
+ * holds every byte: it leaves the upload's end to the server unless it ended
12024
+ * the upload itself (UPLOAD_ENDING_CODES) or named an earlier offset, bytes
12025
+ * the server lacks.
12026
+ */
12027
+ function receiptFailure(error) {
12028
+ if (error instanceof UploadApiError &&
12029
+ !UPLOAD_ENDING_CODES.has(error.code) &&
12030
+ error.verdict !== TRANSFER_VERDICT.RESYNC) {
12031
+ receivedFailures.add(error);
12032
+ }
12033
+ return error;
12034
+ }
12035
+ /**
12036
+ * Whether a transfer failed once the server held every byte of its upload,
12037
+ * short of the upload's own end: `upload_received_publishing`, and any other
12038
+ * failure of the receipt that confirms publication (one refused, or one that
12039
+ * went unanswered), never a gone session, Core's refusal or a cancel. The
12040
+ * server publishes such an upload, or ends it, on its own, so its caller
12041
+ * neither sends it again nor gives it up (`ingots.endUpload`).
12042
+ */
12043
+ function isReceivedUploadFailure(error) {
12044
+ return error instanceof UploadApiError && receivedFailures.has(error);
12045
+ }
11973
12046
  /** A failed request of this upload's transfer; anything else is rethrown as it is. */
11974
12047
  function transferFailure(error) {
11975
12048
  if (error instanceof UploadApiError)
@@ -12367,7 +12440,9 @@ class UploadApi extends SparkVaultApi {
12367
12440
  // the server (a chunk's 204, a HEAD, a 409), publication is confirmed
12368
12441
  // before the upload resolves.
12369
12442
  if (offset === file.size) {
12370
- const receipt = await this.confirmServerFinalized(transfer);
12443
+ const receipt = await this.confirmServerFinalized(transfer).catch((error) => {
12444
+ throw receiptFailure(error);
12445
+ });
12371
12446
  if (receipt.published)
12372
12447
  return;
12373
12448
  offset = receipt.resumeAt;
@@ -14217,6 +14292,11 @@ function formatBytes(bytes, decimals = 1) {
14217
14292
  * admin how to cancel the deletion, is the console's, never this page's.
14218
14293
  */
14219
14294
  const VAULT_NOT_ACCEPTING_MESSAGE = 'This vault isn\'t accepting files right now, so your file was not saved. Please contact the person who shared this upload page with you.';
14295
+ /**
14296
+ * What an uploader reads for a file of no bytes, which Core never stores: said
14297
+ * on the form, where another file can be chosen, as the size limit is.
14298
+ */
14299
+ const EMPTY_FILE_MESSAGE = 'This file is empty, so there is nothing to upload. Choose another file.';
14220
14300
  /**
14221
14301
  * Ceremony steps for the cryptographic visualization.
14222
14302
  */
@@ -14245,6 +14325,36 @@ function transferChannelLine(requestId) {
14245
14325
  ? ''
14246
14326
  : `<p class="svu-forging-line">Secure Transfer Channel: <span class="svu-mono">${escapeHtml(requestId)}</span></p>`;
14247
14327
  }
14328
+ /**
14329
+ * Refusals that say the vault takes no upload now, whichever file is chosen:
14330
+ * it is scheduled for deletion, its owner's plan lapsed, or its upload page is
14331
+ * gone or switched off. An error view after one offers no way on.
14332
+ */
14333
+ function vaultTakesNoUpload(error) {
14334
+ return error.code === VAULT_DELETION_SCHEDULED
14335
+ || error.details?.coreCode === VAULT_DELETION_SCHEDULED
14336
+ || error.code === 'UPLOAD_SOURCE_DISABLED'
14337
+ || error.statusCode === 402
14338
+ || (error.statusCode === 404 && error.code !== 'session_gone');
14339
+ }
14340
+ /**
14341
+ * The way on an error view offers after an upload of the chosen file failed:
14342
+ * nothing while the vault takes no upload ({@link vaultTakesNoUpload}); the
14343
+ * same file again after a failure that may pass (no answer, a fault, a rate
14344
+ * limit); another file after a refusal of this one, or after one received
14345
+ * whole, which the server finishes saving on its own.
14346
+ */
14347
+ function recoveryAfterUpload(error) {
14348
+ if (!(error instanceof UploadApiError))
14349
+ return { label: 'Try Again', keepFile: true };
14350
+ if (vaultTakesNoUpload(error))
14351
+ return null;
14352
+ if (error.code === RECEIVED_STILL_SAVING)
14353
+ return { label: 'Upload Another File', keepFile: false };
14354
+ const status = error.statusCode ?? 0;
14355
+ const mayPass = status === 0 || status === 429 || status >= 500;
14356
+ return mayPass ? { label: 'Try Again', keepFile: true } : { label: 'Choose Another File', keepFile: false };
14357
+ }
14248
14358
  /**
14249
14359
  * Whether an error represents a deliberate cancellation (user close,
14250
14360
  * programmatic close, or session abort) rather than a genuine failure.
@@ -14297,11 +14407,13 @@ class UploadRenderer {
14297
14407
  // (its own button, picker, or drop target) and hand the File to the SDK.
14298
14408
  if (this.options.file) {
14299
14409
  this.selectedFile = this.options.file;
14410
+ this.callbacks.onReady?.();
14300
14411
  await this.startUpload(config);
14301
14412
  return;
14302
14413
  }
14303
14414
  // Show form
14304
14415
  this.setState({ view: 'form', config });
14416
+ this.callbacks.onReady?.();
14305
14417
  }
14306
14418
  catch (error) {
14307
14419
  this.handleApiError(error);
@@ -14808,9 +14920,26 @@ class UploadRenderer {
14808
14920
  <span class="svu-error-code-value">${escapeHtml(state.code)}</span>
14809
14921
  </div>
14810
14922
  `;
14923
+ const { action } = state;
14924
+ if (action && this.config) {
14925
+ const config = this.config;
14926
+ const recover = document.createElement('button');
14927
+ recover.className = 'svu-btn svu-btn-primary';
14928
+ recover.textContent = action.label;
14929
+ recover.addEventListener('click', () => {
14930
+ if (!action.keepFile)
14931
+ this.selectedFile = null;
14932
+ this.setState({ view: 'form', config });
14933
+ });
14934
+ div.appendChild(recover);
14935
+ }
14811
14936
  return div;
14812
14937
  }
14813
14938
  handleFileSelect(file, config) {
14939
+ if (file.size === 0) {
14940
+ this.setState({ view: 'form', config, error: EMPTY_FILE_MESSAGE });
14941
+ return;
14942
+ }
14814
14943
  // Validate file size
14815
14944
  if (file.size > config.maxSizeBytes) {
14816
14945
  this.setState({
@@ -14935,7 +15064,9 @@ class UploadRenderer {
14935
15064
  this.callbacks.onSuccess(result);
14936
15065
  }
14937
15066
  catch (error) {
14938
- this.handleApiError(error);
15067
+ // A host that chose the file itself offers its own way on; the
15068
+ // widget's form is the way on only for a file chosen on it.
15069
+ this.handleApiError(error, this.options.file ? null : recoveryAfterUpload(error));
14939
15070
  }
14940
15071
  }
14941
15072
  async runCeremony(file, ingotId, requestId) {
@@ -14967,7 +15098,11 @@ class UploadRenderer {
14967
15098
  });
14968
15099
  await new Promise(resolve => setTimeout(resolve, 500));
14969
15100
  }
14970
- handleApiError(error) {
15101
+ /**
15102
+ * Show a failure in the error view, with the way on it offers (`action`:
15103
+ * none for a page that could not load), and tell the host through onError.
15104
+ */
15105
+ handleApiError(error, action = null) {
14971
15106
  // A closed renderer must not surface errors: cancelling mid-transfer
14972
15107
  // aborts the in-flight request, whose 'cancelled' rejection races the
14973
15108
  // teardown. The host has already received onCancel — onCancel and
@@ -14983,6 +15118,7 @@ class UploadRenderer {
14983
15118
  // points at the dashboard rather than the end user.
14984
15119
  this.setState({
14985
15120
  view: 'error',
15121
+ action,
14986
15122
  title: 'Upload Widget Not Enabled',
14987
15123
  message: 'This vault has not enabled the embedded upload widget. Enable it on the vault\'s settings page in the SparkVault dashboard to start accepting uploads here.',
14988
15124
  code: 'UPLOAD_SOURCE_DISABLED',
@@ -14996,6 +15132,7 @@ class UploadRenderer {
14996
15132
  // tells it never to upload the file again.
14997
15133
  this.setState({
14998
15134
  view: 'error',
15135
+ action,
14999
15136
  title: 'Upload Received',
15000
15137
  message: error.message,
15001
15138
  code: error.code,
@@ -15009,6 +15146,7 @@ class UploadRenderer {
15009
15146
  // uploader, told only that the vault takes no files now.
15010
15147
  this.setState({
15011
15148
  view: 'error',
15149
+ action,
15012
15150
  title: 'Uploads Paused',
15013
15151
  message: VAULT_NOT_ACCEPTING_MESSAGE,
15014
15152
  code: error.code,
@@ -15021,6 +15159,7 @@ class UploadRenderer {
15021
15159
  // sentence that never asks for the file again.
15022
15160
  this.setState({
15023
15161
  view: 'error',
15162
+ action,
15024
15163
  title: 'Upload Not Saved',
15025
15164
  message: error.message,
15026
15165
  code: error.code,
@@ -15032,6 +15171,7 @@ class UploadRenderer {
15032
15171
  // can answer 404 too, and its own sentence says what became of the file.
15033
15172
  this.setState({
15034
15173
  view: 'error',
15174
+ action,
15035
15175
  title: 'Upload Page Not Found',
15036
15176
  message: 'The requested upload endpoint could not be located. This may occur if the upload link has expired or was entered incorrectly.',
15037
15177
  code: 'NOT_FOUND',
@@ -15041,6 +15181,7 @@ class UploadRenderer {
15041
15181
  else if (error.statusCode === 402) {
15042
15182
  this.setState({
15043
15183
  view: 'error',
15184
+ action,
15044
15185
  title: 'Service Unavailable',
15045
15186
  message: 'This upload endpoint has been temporarily disabled due to an account billing issue. Please contact the organization\'s administrator.',
15046
15187
  code: 'PAYMENT_REQUIRED',
@@ -15050,6 +15191,7 @@ class UploadRenderer {
15050
15191
  else {
15051
15192
  this.setState({
15052
15193
  view: 'error',
15194
+ action,
15053
15195
  title: 'Upload Failed',
15054
15196
  message: error.message,
15055
15197
  code: error.code,
@@ -15061,6 +15203,7 @@ class UploadRenderer {
15061
15203
  else if (error instanceof Error) {
15062
15204
  this.setState({
15063
15205
  view: 'error',
15206
+ action,
15064
15207
  title: 'Upload Failed',
15065
15208
  message: error.message,
15066
15209
  code: 'UNKNOWN_ERROR',
@@ -15071,6 +15214,7 @@ class UploadRenderer {
15071
15214
  const err = new Error('An unexpected error occurred');
15072
15215
  this.setState({
15073
15216
  view: 'error',
15217
+ action,
15074
15218
  title: 'Upload Failed',
15075
15219
  message: err.message,
15076
15220
  code: 'UNKNOWN_ERROR',
@@ -15157,6 +15301,7 @@ class VaultUploadModule {
15157
15301
  reject(error);
15158
15302
  },
15159
15303
  onProgress: options.onProgress,
15304
+ onReady: options.onReady,
15160
15305
  });
15161
15306
  this.renderer.start().catch((error) => {
15162
15307
  options.onError?.(error);
@@ -15689,6 +15834,74 @@ function readIngotAccess(entry) {
15689
15834
  };
15690
15835
  }
15691
15836
 
15837
+ /**
15838
+ * SparkVault Debug Logger
15839
+ *
15840
+ * Conditional logging that respects debug mode setting.
15841
+ * When debug is enabled, logs detailed information to console.
15842
+ * When disabled (default), only fatal errors are logged.
15843
+ */
15844
+ let debugEnabled = false;
15845
+ /**
15846
+ * Enable or disable debug logging
15847
+ */
15848
+ function setDebugMode(enabled) {
15849
+ debugEnabled = enabled;
15850
+ if (enabled) {
15851
+ log('info', 'Debug mode enabled');
15852
+ }
15853
+ }
15854
+ /**
15855
+ * Internal log function
15856
+ */
15857
+ function log(level, message, ...args) {
15858
+ const prefix = '[SparkVault]';
15859
+ const timestamp = new Date().toISOString().split('T')[1].slice(0, -1);
15860
+ const formattedMessage = `${prefix} ${timestamp} ${message}`;
15861
+ switch (level) {
15862
+ case 'debug':
15863
+ if (debugEnabled) {
15864
+ console.debug(formattedMessage, ...args);
15865
+ }
15866
+ break;
15867
+ case 'info':
15868
+ if (debugEnabled) {
15869
+ console.log(formattedMessage, ...args);
15870
+ }
15871
+ break;
15872
+ case 'warn':
15873
+ if (debugEnabled) {
15874
+ console.warn(formattedMessage, ...args);
15875
+ }
15876
+ break;
15877
+ case 'error':
15878
+ // Always log errors (fatal)
15879
+ console.error(formattedMessage, ...args);
15880
+ break;
15881
+ }
15882
+ }
15883
+ /**
15884
+ * Logger object for convenient access
15885
+ */
15886
+ const logger = {
15887
+ /**
15888
+ * Debug level - verbose details for troubleshooting
15889
+ */
15890
+ debug: (message, ...args) => log('debug', message, ...args),
15891
+ /**
15892
+ * Info level - general information
15893
+ */
15894
+ info: (message, ...args) => log('info', message, ...args),
15895
+ /**
15896
+ * Warn level - warnings that don't prevent operation
15897
+ */
15898
+ warn: (message, ...args) => log('warn', message, ...args),
15899
+ /**
15900
+ * Error level - always logged regardless of debug mode
15901
+ */
15902
+ error: (message, ...args) => log('error', message, ...args),
15903
+ };
15904
+
15692
15905
  /**
15693
15906
  * The one browser transfer for a signed ingot download link: fetch it into a
15694
15907
  * Blob under liveness bounds, resuming from the bytes it holds when the caller
@@ -16332,8 +16545,10 @@ function mapFolder(wire) {
16332
16545
  * - `upsert` (the server default): the upload replaces the holder's content.
16333
16546
  * - `complete_pending`: a holder whose own upload never finalized is completed
16334
16547
  * (`created: false`); a published holder is refused with a 409 CONFLICT whose
16335
- * `details` are `{ reason: 'NAME_HELD', ingot_id, status, size_bytes }`, and
16336
- * is left untouched.
16548
+ * `details.reason` is `'NAME_HELD'`, and is left untouched. The details
16549
+ * describe the holder (`ingot_id`, `status`, `size_bytes`) unless another
16550
+ * app manages it or another request claimed the name first, when they carry
16551
+ * the reason alone.
16337
16552
  * - `refuse`: any holder, its upload finished or not, is refused with that
16338
16553
  * same 409 and left untouched; the create only ever mints.
16339
16554
  * - `new_name`: the holder is never touched; the ingot is minted under the
@@ -16368,7 +16583,9 @@ class IngotsModule {
16368
16583
  * transfer yourself; otherwise prefer {@link upload}. A create another
16369
16584
  * upload of the same file superseded before its token was issued rejects
16370
16585
  * with code `upload_refused` (`details.coreCode` UPLOAD_SUPERSEDED): the
16371
- * later upload is the one kept, so a new upload is no remedy.
16586
+ * later upload is the one kept, so a new upload is no remedy. An upload
16587
+ * you give up (you cancel its transfer, or it fails for good) ends with the
16588
+ * file its create made through {@link endUpload}, given this result.
16372
16589
  *
16373
16590
  * @example
16374
16591
  * const session = await sv.ingots.createUpload({
@@ -16397,15 +16614,65 @@ class IngotsModule {
16397
16614
  onNameConflict: options.onNameConflict,
16398
16615
  });
16399
16616
  return {
16400
- id: created.ingot_id,
16617
+ ...placementOf(created),
16401
16618
  name: created.name,
16402
16619
  contentType: created.content_type,
16403
16620
  size: created.size_bytes,
16404
16621
  uploadUrl: created.forge_url,
16405
16622
  expiresAt: created.expires_at,
16406
- created: created.created,
16407
16623
  };
16408
16624
  }
16625
+ /**
16626
+ * End an upload you give up (you cancelled its transfer, or it failed for
16627
+ * good) with the file its create made ({@link createUpload}'s result): the
16628
+ * server deletes the ingot only while it is still that upload's unfinished
16629
+ * file, ending the upload first, so a publication racing the end is decided
16630
+ * before anything goes. Never give up one the server received whole
16631
+ * ({@link isReceivedUploadFailure}): the server publishes or ends it on its
16632
+ * own. Resolves `deleted` once the vault holds the file no longer, deleted
16633
+ * now or already gone. Resolves `kept` when this end deleted nothing, which
16634
+ * {@link get} shows as it is now: the upload published the file, or a later
16635
+ * upload took it over, before the end reached the server, or, with no
16636
+ * request sent, the create did not make it (`created: false`) or names no
16637
+ * upload (`uploadId: null`), since a delete without its upload would take
16638
+ * whatever file stands. Any other failure rejects, the file left as it was.
16639
+ * {@link upload} ends an upload it cannot finish this way by itself.
16640
+ *
16641
+ * @example
16642
+ * const upload = await sv.ingots.createUpload({ vault: unsealed, name: file.name,
16643
+ * contentType: file.type, sizeBytes: file.size });
16644
+ * try {
16645
+ * await sv.ingots.sendUpload(upload.uploadUrl, file, { signal: controller.signal });
16646
+ * } catch (error) {
16647
+ * if (!isReceivedUploadFailure(error) &&
16648
+ * await sv.ingots.endUpload(unsealed, upload) === 'kept') {
16649
+ * // The end deleted nothing (the upload published the file, say): show it as it is.
16650
+ * showIngot(await sv.ingots.get(unsealed, upload.id));
16651
+ * }
16652
+ * throw error;
16653
+ * }
16654
+ */
16655
+ async endUpload(vault, upload) {
16656
+ const vaultId = requireVaultId(vault);
16657
+ const id = requireResourceId(upload.id, 'ingotId');
16658
+ const uploadId = givenUpUploadId(upload);
16659
+ if (uploadId === null)
16660
+ return 'kept';
16661
+ try {
16662
+ await this.http.delete(apiPath `/v1/vaults/${vaultId}/ingots/${id}`, {
16663
+ vat: vault.vatToken,
16664
+ query: { upload_id: uploadId },
16665
+ });
16666
+ return 'deleted';
16667
+ }
16668
+ catch (error) {
16669
+ if (error instanceof SparkVaultError && error.statusCode === 404)
16670
+ return 'deleted';
16671
+ if (error instanceof SparkVaultError && error.statusCode === 412)
16672
+ return 'kept';
16673
+ throw error;
16674
+ }
16675
+ }
16409
16676
  /**
16410
16677
  * Send a file's bytes to an upload session — the `uploadUrl` a
16411
16678
  * {@link createUpload} returned — over the resumable transfer every SDK
@@ -16513,7 +16780,11 @@ class IngotsModule {
16513
16780
  * server refused — another upload of it superseded this one, at its create
16514
16781
  * or while it streamed, the storage pool cannot take it, or its vault is
16515
16782
  * scheduled for deletion (a 409 `VAULT_DELETION_SCHEDULED`) — rejects with
16516
- * code `upload_refused`, as {@link sendUpload} does.
16783
+ * code `upload_refused`, as {@link sendUpload} does. An upload that rejects
16784
+ * any way but one the server received whole ({@link isReceivedUploadFailure}:
16785
+ * the server publishes or ends that one on its own) is given up: the end of
16786
+ * it with the file its create made ({@link endUpload}) starts as it
16787
+ * rejects, without holding up its own error.
16517
16788
  *
16518
16789
  * @example
16519
16790
  * const ingot = await sv.ingots.upload(unsealed, {
@@ -16535,7 +16806,29 @@ class IngotsModule {
16535
16806
  folderId: options.folderId,
16536
16807
  onNameConflict: options.onNameConflict,
16537
16808
  });
16538
- return this.transferAndFinalize(created, created.created, options.file, options.onProgress);
16809
+ try {
16810
+ return await this.transferAndFinalize(created, created.created, options.file, options.onProgress);
16811
+ }
16812
+ catch (error) {
16813
+ // The caller holds no session to continue this upload in, so a transfer
16814
+ // that ends any way but received whole is given up, its file with it.
16815
+ if (!isReceivedUploadFailure(error))
16816
+ this.endGivenUp(vault, placementOf(created));
16817
+ throw error;
16818
+ }
16819
+ }
16820
+ /**
16821
+ * End an upload this flow gave up ({@link endUpload}) without holding up
16822
+ * the error its caller is answered with: an end that fails leaves the file
16823
+ * to the server's expiry of abandoned uploads, and is logged.
16824
+ */
16825
+ endGivenUp(vault, upload) {
16826
+ this.endUpload(vault, upload).catch((error) => {
16827
+ logger.warn('A given-up upload could not be ended with its file; the server expires it', {
16828
+ ingotId: upload.id,
16829
+ code: error instanceof SparkVaultError ? error.code : undefined,
16830
+ });
16831
+ });
16539
16832
  }
16540
16833
  /**
16541
16834
  * Replace an existing ingot's content (high-level flow). Rejects as
@@ -16773,8 +17066,11 @@ class IngotsModule {
16773
17066
  return mapSharingConfig(response.data);
16774
17067
  }
16775
17068
  /**
16776
- * Invite an identity to a shared ingot. The identity type (email or phone)
16777
- * is inferred server-side from the identity value.
17069
+ * Invite an identity to an ingot's invite-only share, or share an ingot not
17070
+ * yet shared invite-only with it. A public or authenticated share refuses
17071
+ * it (a ValidationError) and changes nothing: set its visibility to
17072
+ * `invite_only` first. The identity type (email or phone) is inferred
17073
+ * server-side from the identity value.
16778
17074
  *
16779
17075
  * @example
16780
17076
  * await sv.ingots.addInvite(unsealed, 'ing_abc', 'user@example.com');
@@ -16786,7 +17082,7 @@ class IngotsModule {
16786
17082
  const vaultId = requireVaultId(vault);
16787
17083
  const id = requireResourceId(ingotId, 'ingotId');
16788
17084
  const response = await this.http.post(apiPath `/v1/vaults/${vaultId}/ingots/${id}/sharing/invite`, { identity }, { vat: vault.vatToken });
16789
- return mapInvite(response.data);
17085
+ return mapInvitation(response.data);
16790
17086
  }
16791
17087
  /**
16792
17088
  * Revoke an ingot sharing invite.
@@ -16872,6 +17168,8 @@ class IngotsModule {
16872
17168
  throw stagingRefusalOf(error);
16873
17169
  });
16874
17170
  if (!response.data.forge_url) {
17171
+ // No upload can start without its URL: the file the create made goes too.
17172
+ this.endGivenUp(vault, placementOf(response.data));
16875
17173
  throw new ValidationError('Upload endpoint did not return a Forge upload URL');
16876
17174
  }
16877
17175
  return response.data;
@@ -16902,6 +17200,14 @@ class IngotsModule {
16902
17200
  }
16903
17201
  }
16904
17202
  }
17203
+ /**
17204
+ * What a create answered about the file it placed: its id, whether the create
17205
+ * made it, and the upload it staged there, which {@link IngotsModule.endUpload}
17206
+ * ends it by.
17207
+ */
17208
+ function placementOf(created) {
17209
+ return { id: created.ingot_id, created: created.created, uploadId: created.upload_id ?? null };
17210
+ }
16905
17211
  function getBlobName(file) {
16906
17212
  if (typeof File !== 'undefined' && file instanceof File && file.name) {
16907
17213
  return file.name;
@@ -16951,7 +17257,12 @@ function mapIngotPage(response) {
16951
17257
  function mapSharingConfig(wire) {
16952
17258
  return {
16953
17259
  shared: wire.shared,
16954
- visibility: wire.visibility,
17260
+ visibility: wire.visibility ?? undefined,
17261
+ publicUrl: wire.public_url,
17262
+ linkCode: wire.link_code,
17263
+ sharingEnabled: wire.sharing_enabled,
17264
+ vaultAllIngotsPublic: wire.vault_all_ingots_public,
17265
+ sessionLengthSeconds: wire.session_length_seconds,
16955
17266
  invites: wire.invites?.map(mapInvite),
16956
17267
  };
16957
17268
  }
@@ -16960,6 +17271,14 @@ function mapInvite(wire) {
16960
17271
  id: wire.invite_id,
16961
17272
  identity: wire.identity,
16962
17273
  identityType: wire.identity_type,
17274
+ invitedAt: wire.created_at,
17275
+ };
17276
+ }
17277
+ function mapInvitation(wire) {
17278
+ return {
17279
+ ...mapInvite(wire),
17280
+ shareUrl: wire.share_url,
17281
+ delivered: wire.delivered,
16963
17282
  };
16964
17283
  }
16965
17284
 
@@ -17481,74 +17800,6 @@ class NotifyModule {
17481
17800
  }
17482
17801
  }
17483
17802
 
17484
- /**
17485
- * SparkVault Debug Logger
17486
- *
17487
- * Conditional logging that respects debug mode setting.
17488
- * When debug is enabled, logs detailed information to console.
17489
- * When disabled (default), only fatal errors are logged.
17490
- */
17491
- let debugEnabled = false;
17492
- /**
17493
- * Enable or disable debug logging
17494
- */
17495
- function setDebugMode(enabled) {
17496
- debugEnabled = enabled;
17497
- if (enabled) {
17498
- log('info', 'Debug mode enabled');
17499
- }
17500
- }
17501
- /**
17502
- * Internal log function
17503
- */
17504
- function log(level, message, ...args) {
17505
- const prefix = '[SparkVault]';
17506
- const timestamp = new Date().toISOString().split('T')[1].slice(0, -1);
17507
- const formattedMessage = `${prefix} ${timestamp} ${message}`;
17508
- switch (level) {
17509
- case 'debug':
17510
- if (debugEnabled) {
17511
- console.debug(formattedMessage, ...args);
17512
- }
17513
- break;
17514
- case 'info':
17515
- if (debugEnabled) {
17516
- console.log(formattedMessage, ...args);
17517
- }
17518
- break;
17519
- case 'warn':
17520
- if (debugEnabled) {
17521
- console.warn(formattedMessage, ...args);
17522
- }
17523
- break;
17524
- case 'error':
17525
- // Always log errors (fatal)
17526
- console.error(formattedMessage, ...args);
17527
- break;
17528
- }
17529
- }
17530
- /**
17531
- * Logger object for convenient access
17532
- */
17533
- const logger = {
17534
- /**
17535
- * Debug level - verbose details for troubleshooting
17536
- */
17537
- debug: (message, ...args) => log('debug', message, ...args),
17538
- /**
17539
- * Info level - general information
17540
- */
17541
- info: (message, ...args) => log('info', message, ...args),
17542
- /**
17543
- * Warn level - warnings that don't prevent operation
17544
- */
17545
- warn: (message, ...args) => log('warn', message, ...args),
17546
- /**
17547
- * Error level - always logged regardless of debug mode
17548
- */
17549
- error: (message, ...args) => log('error', message, ...args),
17550
- };
17551
-
17552
17803
  /**
17553
17804
  * SparkVault Auto-Initialization
17554
17805
  *
@@ -17683,7 +17934,7 @@ class SparkVault {
17683
17934
  }
17684
17935
  /** Get the SDK version */
17685
17936
  static get version() {
17686
- return '12.0.3';
17937
+ return '12.0.5';
17687
17938
  }
17688
17939
  }
17689
17940
  if (typeof window !== 'undefined') {
@@ -17693,5 +17944,5 @@ if (typeof window !== 'undefined') {
17693
17944
  window.SparkVault = instance ?? SparkVault;
17694
17945
  }
17695
17946
 
17696
- export { AuthenticationError, AuthorizationError, EntropyModule, FoldersModule, IdentityModule, IdentityProviderError, 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 };
17947
+ export { AuthenticationError, AuthorizationError, EntropyModule, FoldersModule, IdentityModule, IdentityProviderError, 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, isReceivedUploadFailure, logger, setDebugMode };
17697
17948
  //# sourceMappingURL=index.mjs.map