@sparkvault/sdk-mobile 8.0.4 → 8.0.6

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.
@@ -24,7 +24,15 @@
24
24
  * alike.
25
25
  */
26
26
 
27
- const LOCAL_PART = /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/;
27
+ /**
28
+ * The characters an RFC 5322 dot-atom local part holds, in its canonical
29
+ * (lowercase) form, as the body of a character class: the one set the
30
+ * grammar below accepts and the log mask (./pii-mask.js) reads an address in
31
+ * text by.
32
+ */
33
+ export const EMAIL_LOCAL_PART_CHARACTERS = "a-z0-9.!#$%&'*+/=?^_`{|}~-";
34
+
35
+ const LOCAL_PART = new RegExp(`^[${EMAIL_LOCAL_PART_CHARACTERS}]+$`);
28
36
  const DOMAIN_LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
29
37
 
30
38
  /** RFC 5321 length limits, in characters. */
@@ -8,7 +8,8 @@
8
8
  * publication it is bound to (a content version, and the one an ingot row
9
9
  * names), Core's revocation of an upload's token, and the refusals of Core's
10
10
  * a transfer's answer names (the header, and the lock of a vault scheduled
11
- * for deletion).
11
+ * for deletion). Every client ends an upload it gives up by one rule here
12
+ * too: the upload id its delete is conditioned on (givenUpUploadId).
12
13
  *
13
14
  * Forge stamps UPLOAD_PUBLICATION_PROTOCOL on every upload session it creates
14
15
  * and on the final state it hands Core's activation (POST
@@ -37,6 +38,29 @@ export const UPLOAD_PUBLICATION_PROTOCOL = 2;
37
38
  */
38
39
  export const UPLOAD_ID_PATTERN = /^tus_[0-9a-f]{32}$/;
39
40
 
41
+ /**
42
+ * The upload id under which a client that gives an upload up (its person
43
+ * cancelled it, or it failed for good) ends it with the file its create
44
+ * made: the `upload_id` that create answered, which Core's delete takes as
45
+ * its condition (`DELETE …/ingots/:ingot_id?upload_id=`), deleting the ingot
46
+ * only while it is still that upload's unfinished file and keeping (412) one
47
+ * the upload published, or a later upload took over. Null when the file is
48
+ * not the upload's to end: its create staged onto a row that already stood
49
+ * (`created` not true: another upload's unfinished file, or a published file
50
+ * the upload was replacing), or answered no upload id, without which the
51
+ * delete would take whatever file stands, one the upload published
52
+ * included. Every client sends a given-up upload's delete under this id
53
+ * alone, and sends none when it is null.
54
+ *
55
+ * @param {{ created?: boolean|null, uploadId?: string|null }} placement -
56
+ * What the upload's create answered: whether it made the file, and the
57
+ * upload it staged
58
+ * @returns {string|null}
59
+ */
60
+ export function givenUpUploadId({ created, uploadId }) {
61
+ return created === true && typeof uploadId === 'string' && UPLOAD_ID_PATTERN.test(uploadId) ? uploadId : null;
62
+ }
63
+
40
64
  /**
41
65
  * Whether a value is a content version: the identity of one publication of an
42
66
  * ingot (a non-empty string, the upload id its activation stamped), or null
package/src/errors.ts CHANGED
@@ -148,12 +148,14 @@ export interface IngotNameHolder {
148
148
 
149
149
  /**
150
150
  * Thrown when a create is refused because an ingot already holds the name in
151
- * the target folder (409 `details.reason === 'NAME_HELD'`): with
152
- * `onNameConflict: 'complete_pending'` a published holder, with `'refuse'` any
153
- * holder. The server decided before writing anything, so the holder is
154
- * untouched; `holder` is the row it read, which lets the caller act on it
155
- * (send its bytes into its own row by id, adopt it, or try another name)
156
- * without a second read.
151
+ * the target folder (409 `details.reason === 'NAME_HELD'`) and the refusal
152
+ * describes that ingot: with `onNameConflict: 'complete_pending'` a published
153
+ * holder, with `'refuse'` any holder. The server decided before writing
154
+ * anything, so the holder is untouched; `holder` is the row it read, which
155
+ * lets the caller act on it (send its bytes into its own row by id, adopt it,
156
+ * or try another name) without a second read. A NAME_HELD that describes no
157
+ * holder (one another app manages, or a name another request claimed first)
158
+ * is a plain `SparkVaultMobileError`.
157
159
  */
158
160
  export class IngotNameHeldError extends SparkVaultMobileError {
159
161
  readonly holder: IngotNameHolder;
package/src/index.ts CHANGED
@@ -41,6 +41,8 @@ export type {
41
41
  ResumeUploadOptions,
42
42
  CreateUploadOptions,
43
43
  CreateUploadResult,
44
+ EndUploadOptions,
45
+ UploadEnd,
44
46
  CreateDownloadLinkOptions,
45
47
  CreateDownloadLinkResult,
46
48
  } from './ingots.js';
package/src/ingots.ts CHANGED
@@ -1,16 +1,19 @@
1
+ import { CONTENT_CONFLICT_REASONS } from './app-sdk/content-conflict.js';
1
2
  import { readForgeTransferUrl } from './app-sdk/forge-url.js';
2
3
  import { INGOT_ACCESS_EVENT_TYPES, readIngotAccess } from './app-sdk/ingot-access-log.js';
4
+ import { givenUpUploadId } from './app-sdk/upload-publication.js';
3
5
  import type { ResolvedMobileConfig } from './config.js';
4
6
  import {
5
7
  IngotNameHeldError,
6
8
  IngotNotReadyError,
9
+ isNotFoundError,
7
10
  isRetryableDownloadError,
8
11
  SparkVaultMobileError,
9
12
  SparkVaultValidationError,
10
13
  TusUploadError,
11
14
  } from './errors.js';
12
15
  import type { MobileHttpClient } from './http.js';
13
- import { allowsHost, MobileTusUploader, type TusSessionProbe } from './tus.js';
16
+ import { allowsHost, isCancelledTransfer, MobileTusUploader, type TusSessionProbe } from './tus.js';
14
17
  import type {
15
18
  DebugLogger,
16
19
  HashCheckResponse,
@@ -89,6 +92,8 @@ export interface PlacedIngot {
89
92
  name: string;
90
93
  /** Absent only when the server did not say and the upload sent none. */
91
94
  contentType?: string;
95
+ /** The upload the create staged (see `CreateUploadResult.uploadId`); absent when the server did not say. */
96
+ uploadId?: string;
92
97
  }
93
98
 
94
99
  export interface UploadFromUriOptions extends UploadOptions {
@@ -101,11 +106,14 @@ export interface UploadFromUriOptions extends UploadOptions {
101
106
  * session exists: `created` is true when it minted the ingot and false when
102
107
  * it staged the upload onto the row holding the name (as `onNameConflict`
103
108
  * allowed), `name` is the name the ingot is stored under (the server's
104
- * numbered name under `new_name`), and `contentType` the MIME type it is
105
- * stored under (see `CreateUploadResult.contentType`). The placement has
106
- * already been written by then, so this hook observes; a caller that must
107
- * not replace content says so through `onNameConflict`. A throw here still
108
- * stops the upload before a byte moves and propagates as-is.
109
+ * numbered name under `new_name`), `contentType` the MIME type it is
110
+ * stored under (see `CreateUploadResult.contentType`), and `uploadId` the
111
+ * upload the create staged, through which a caller that gives the upload
112
+ * up ends it with its file (`endUpload`). The placement has already been
113
+ * written by then, so this hook observes; a caller that must not replace
114
+ * content says so through `onNameConflict`. A throw here still stops the
115
+ * upload before a byte moves and propagates as-is, the placement left the
116
+ * caller's to end.
109
117
  */
110
118
  onIngotCreated?: (ingot: PlacedIngot) => void;
111
119
  /**
@@ -131,13 +139,15 @@ export interface UploadFromUriOptions extends UploadOptions {
131
139
  */
132
140
  sourceAssetId?: string;
133
141
  /**
134
- * What an abort does to the Forge session; see `UploadAbortBehavior`.
135
- * Default `terminate` (a user cancel: Forge drops the chunks). `keep`
136
- * (a pause) leaves the session on Forge so the caller can `resumeUpload`
137
- * the one it was handed via `onSessionCreated` from the server offset;
138
- * the caller then owns that session and is expected to resume or
139
- * terminate it. The error is the same either way: the pre-flight
140
- * `upload_cancelled` or the tus `cancelled`-phase `TusUploadError`.
142
+ * What an abort does to the upload; see `UploadAbortBehavior`. Default
143
+ * `terminate` (a user cancel): the upload is given up, Forge drops the
144
+ * chunks, and the file the create made is deleted with it (`endUpload`).
145
+ * `keep` (a pause) leaves the session on Forge so the caller can
146
+ * `resumeUpload` the one it was handed via `onSessionCreated` from the
147
+ * server offset; the caller then owns that session and is expected to
148
+ * resume or terminate it. The error is the same either way: the
149
+ * pre-flight `upload_cancelled` or the tus `cancelled`-phase
150
+ * `TusUploadError`.
141
151
  */
142
152
  abortBehavior?: UploadAbortBehavior;
143
153
  debug?: DebugLogger;
@@ -295,6 +305,32 @@ export interface CreateUploadResult {
295
305
  * the row already holding the name (false). Absent when the server did not say.
296
306
  */
297
307
  created?: boolean;
308
+ /**
309
+ * The upload the create staged onto the ingot (Core's `upload_id`): the id
310
+ * Forge keys the upload's session by, and the `content_version` the ingot
311
+ * reads once the upload publishes. Giving the upload up ends it with the
312
+ * file the create made through this id (`endUpload`). Absent when the
313
+ * server did not say.
314
+ */
315
+ uploadId?: string;
316
+ }
317
+
318
+ /**
319
+ * What became of a given-up upload's file (`endUpload`): `deleted`, the
320
+ * vault holds it no longer (this end deleted it, or it was already gone);
321
+ * `kept`, this end deleted nothing, and a read of it by id shows the file as
322
+ * it is now.
323
+ */
324
+ export type UploadEnd = 'deleted' | 'kept';
325
+
326
+ export interface EndUploadOptions {
327
+ vaultId: string;
328
+ vat: string;
329
+ /**
330
+ * The upload as its create answered it: `onIngotCreated`'s placement, or
331
+ * `createUpload`'s result.
332
+ */
333
+ upload: Pick<CreateUploadResult, 'ingotId' | 'created' | 'uploadId'>;
298
334
  }
299
335
 
300
336
  export interface CreateDownloadLinkOptions {
@@ -316,6 +352,7 @@ interface IngotUploadInitResponse {
316
352
  content_type?: string;
317
353
  size_bytes?: number;
318
354
  created?: boolean;
355
+ upload_id?: string;
319
356
  }
320
357
 
321
358
  /** An ingot audit entry in the server's public shape. */
@@ -361,13 +398,18 @@ function toTypedDownloadError(err: unknown): unknown {
361
398
 
362
399
  /**
363
400
  * A create refused over its holder (`complete_pending` over a published one,
364
- * `refuse` over any) answers 409 CONFLICT with `details.reason === 'NAME_HELD'`
365
- * and the holder the server read. Every other 409 on the create (a folder
366
- * being deleted, a cross-manager name) carries no holder and stays a plain
401
+ * `refuse` over any) answers 409 CONFLICT with `details.reason` NAME_HELD and
402
+ * the holder the server read. A NAME_HELD that describes no holder (one
403
+ * another app manages, or a name another request claimed first) and every
404
+ * other 409 on the create (a folder being deleted) stay a plain
367
405
  * `SparkVaultMobileError`.
368
406
  */
369
407
  function toTypedCreateError(err: unknown): unknown {
370
- if (!(err instanceof SparkVaultMobileError) || err.statusCode !== 409 || err.details?.reason !== 'NAME_HELD') {
408
+ if (
409
+ !(err instanceof SparkVaultMobileError) ||
410
+ err.statusCode !== 409 ||
411
+ err.details?.reason !== CONTENT_CONFLICT_REASONS.NAME_HELD
412
+ ) {
371
413
  return err;
372
414
  }
373
415
  const { ingot_id: ingotId, status, size_bytes: sizeBytes } = err.details;
@@ -454,31 +496,45 @@ export class MobileIngotsClient {
454
496
  contentHmac: options.contentHmac,
455
497
  onNameConflict: options.onNameConflict,
456
498
  });
457
- const created = init.created ?? true;
499
+ // Only the create's own word proves the upload made the row: what a
500
+ // given-up upload's end deletes, and what tells a caller "mine to discard"
501
+ // from "someone else's live row".
502
+ const created = init.created === true;
458
503
  const name = init.name ?? options.name;
459
504
  const contentType = init.contentType ?? options.contentType;
460
505
 
461
506
  // The placement is written but no Forge session exists yet: a throw from
462
507
  // the hook stops the upload before a byte moves and reaches the caller
463
508
  // untouched.
464
- options.onIngotCreated?.({ ingotId: init.ingotId, created, name, contentType });
465
-
466
- await this.tus.uploadFromUri({
467
- fileUri: options.fileUri,
468
- fileSize: options.fileSize,
469
- filename: name,
470
- forgeUrl: init.forgeUrl,
471
- onSessionCreated: session =>
472
- options.onSessionCreated?.({ ...session, ingotId: init.ingotId, created, uploadId: uploadIdOf(session.uploadUrl) }),
473
- onSessionExpiry: options.onSessionExpiry,
474
- transport: options.transport,
475
- transferPolicy: options.transferPolicy,
476
- sourceAssetId: options.sourceAssetId,
477
- onProgress: options.onProgress,
478
- abortSignal: options.abortSignal,
479
- abortBehavior: options.abortBehavior,
480
- debug: options.debug,
481
- });
509
+ options.onIngotCreated?.({ ingotId: init.ingotId, created, name, contentType, uploadId: init.uploadId });
510
+
511
+ try {
512
+ await this.tus.uploadFromUri({
513
+ fileUri: options.fileUri,
514
+ fileSize: options.fileSize,
515
+ filename: name,
516
+ forgeUrl: init.forgeUrl,
517
+ onSessionCreated: session =>
518
+ options.onSessionCreated?.({ ...session, ingotId: init.ingotId, created, uploadId: uploadIdOf(session.uploadUrl) }),
519
+ onSessionExpiry: options.onSessionExpiry,
520
+ transport: options.transport,
521
+ transferPolicy: options.transferPolicy,
522
+ sourceAssetId: options.sourceAssetId,
523
+ onProgress: options.onProgress,
524
+ abortSignal: options.abortSignal,
525
+ abortBehavior: options.abortBehavior,
526
+ debug: options.debug,
527
+ });
528
+ } catch (err) {
529
+ // A cancel gives the upload up, so the file its create made goes with
530
+ // it rather than staying listed as uploading until Core's expiry; a
531
+ // pause keeps both for the resume. Any other failure leaves the upload
532
+ // the caller's to resume or end.
533
+ if (options.abortBehavior !== 'keep' && isCancelledTransfer(err, options.abortSignal)) {
534
+ this.endGivenUp({ vaultId: options.vaultId, vat: options.vat, upload: { ingotId: init.ingotId, created, uploadId: init.uploadId } });
535
+ }
536
+ throw err;
537
+ }
482
538
 
483
539
  const ingot = await this.verifyIngotActive(
484
540
  { vaultId: options.vaultId, ingotId: init.ingotId, vat: options.vat },
@@ -490,8 +546,6 @@ export class MobileIngotsClient {
490
546
  ingot_id: init.ingotId,
491
547
  name,
492
548
  size_bytes: init.sizeBytes ?? options.fileSize,
493
- // A server that does not report it minted the row (the upsert is the
494
- // only other outcome, and it always says so).
495
549
  created,
496
550
  status: ingot.status,
497
551
  ...publicationOf(ingot),
@@ -576,6 +630,52 @@ export class MobileIngotsClient {
576
630
  return this.tus.terminateSession(session);
577
631
  }
578
632
 
633
+ /**
634
+ * End an upload the caller gives up (cancelled, or failed for good) with
635
+ * the file its create made: Core deletes the ingot only while it is still
636
+ * that upload's unfinished file, ending the upload first, so a publication
637
+ * racing the end is decided before anything goes (`DELETE` naming the
638
+ * upload, `?upload_id=`). Resolves `deleted` once the vault holds the file
639
+ * no longer, deleted now or already gone. Resolves `kept` when this end
640
+ * deleted nothing, the file a read by id shows as it is now: the
641
+ * upload published the file, or a later upload took it over, before the
642
+ * end reached Core (Core's 412), or, sending nothing, the create did not
643
+ * make it (it staged onto a row that already stood, or did not say it made
644
+ * one) or names no upload, since a delete without its upload would take
645
+ * whatever file stands. Any other failure rejects, the file left as it
646
+ * was. `uploadFromUri` ends an upload its caller cancels this way by
647
+ * itself.
648
+ */
649
+ async endUpload(options: EndUploadOptions): Promise<UploadEnd> {
650
+ const { vaultId, vat, upload } = options;
651
+ validateVaultId(vaultId);
652
+ validateIngotId(upload.ingotId);
653
+ const uploadId = givenUpUploadId(upload);
654
+ if (uploadId === null) return 'kept';
655
+ try {
656
+ await this.http.delete(apiPath`/vaults/${vaultId}/ingots/${upload.ingotId}`, { vat, query: { upload_id: uploadId } });
657
+ return 'deleted';
658
+ } catch (err) {
659
+ if (isNotFoundError(err)) return 'deleted';
660
+ if (err instanceof SparkVaultMobileError && err.statusCode === 412) return 'kept';
661
+ throw err;
662
+ }
663
+ }
664
+
665
+ /**
666
+ * End an upload this client gave up (endUpload) without holding up the
667
+ * error the caller is answered with: an end that fails leaves the file to
668
+ * Core's expiry of abandoned uploads, and says so to the client's logger.
669
+ */
670
+ private endGivenUp(options: EndUploadOptions): void {
671
+ this.endUpload(options).catch((err: unknown) => {
672
+ this.config.logger.warn('A given-up upload could not be ended with its file; Core expires it', {
673
+ ingotId: options.upload.ingotId,
674
+ error: err instanceof Error ? err.message : String(err),
675
+ });
676
+ });
677
+ }
678
+
579
679
  /**
580
680
  * Initialize an ingot record and obtain the Forge resumable-upload endpoint
581
681
  * (with its upload-session token). The canonical first step of every upload;
@@ -608,18 +708,21 @@ export class MobileIngotsClient {
608
708
  throw toTypedCreateError(err);
609
709
  });
610
710
 
611
- if (!response.data.ingot_id || !response.data.forge_url) {
612
- throw new SparkVaultMobileError('Server returned invalid response for ingot creation');
613
- }
614
-
615
- return {
711
+ const placed: CreateUploadResult = {
616
712
  ingotId: response.data.ingot_id,
617
713
  forgeUrl: response.data.forge_url,
618
714
  name: response.data.name,
619
715
  contentType: response.data.content_type,
620
716
  sizeBytes: response.data.size_bytes,
621
717
  created: typeof response.data.created === 'boolean' ? response.data.created : undefined,
718
+ uploadId: typeof response.data.upload_id === 'string' ? response.data.upload_id : undefined,
622
719
  };
720
+ if (!placed.ingotId || !placed.forgeUrl) {
721
+ // No upload can start without its URL: the file the create made goes too.
722
+ if (placed.ingotId) this.endGivenUp({ vaultId: options.vaultId, vat: options.vat, upload: placed });
723
+ throw new SparkVaultMobileError('Server returned invalid response for ingot creation');
724
+ }
725
+ return placed;
623
726
  }
624
727
 
625
728
  async replaceFromUri(options: ReplaceFromUriOptions): Promise<UploadResult> {
package/src/tus.ts CHANGED
@@ -248,6 +248,15 @@ function ensureNotAborted(signal?: AbortSignal): void {
248
248
  }
249
249
  }
250
250
 
251
+ /**
252
+ * Whether a transfer that threw `err` ended because its caller cancelled it:
253
+ * its abort signal fired, whatever the error, or the transfer reports its
254
+ * cancelled phase.
255
+ */
256
+ export function isCancelledTransfer(err: unknown, signal: AbortSignal | undefined): boolean {
257
+ return signal?.aborted === true || (err instanceof TusUploadError && err.phase === 'cancelled');
258
+ }
259
+
251
260
  /**
252
261
  * A file chunk kept in the base64 form the native file read produced. The bytes
253
262
  * are NEVER materialized in JS: React Native's networking accepts a
@@ -1283,10 +1292,7 @@ export class MobileTusUploader {
1283
1292
  // reclaims them. Unless the caller asked to keep it: a pause is not a
1284
1293
  // cancel, and the bytes Forge holds are exactly what a later resume
1285
1294
  // avoids re-sending.
1286
- const cancelled =
1287
- options.abortSignal?.aborted === true ||
1288
- (err instanceof TusUploadError && err.phase === 'cancelled');
1289
- if (cancelled && uploadUrl) {
1295
+ if (isCancelledTransfer(err, options.abortSignal) && uploadUrl) {
1290
1296
  if (options.abortBehavior === 'keep') {
1291
1297
  debug?.log(`TUS session for ${options.filename} kept on Forge for resume`);
1292
1298
  } else {
package/src/types.ts CHANGED
@@ -846,6 +846,7 @@ export interface IngotInvite {
846
846
  invite_id: string;
847
847
  identity: string;
848
848
  identity_type: 'email' | 'phone';
849
+ /** When this identity was invited (Unix seconds), each invitee's own. */
849
850
  created_at: number;
850
851
  }
851
852
 
@@ -1063,16 +1064,17 @@ export interface UploadTransferPolicy {
1063
1064
  }
1064
1065
 
1065
1066
  /**
1066
- * What happens to the Forge tus session when an upload's `abortSignal` fires
1067
- * mid-transfer. `terminate` (the default) sends a tus DELETE so Forge drops
1068
- * the chunks it already holds: right for a user cancel, where the bytes will
1069
- * never be wanted again. `keep` leaves the session untouched on Forge, so a
1070
- * PAUSE (WiFi lost, low battery, app going to background) can stop the
1071
- * transfer now and `ingots.resumeUpload` it later from the server offset
1072
- * instead of re-sending the file. The caller owns a kept session: it is
1073
- * expected to persist it (`onSessionCreated`) and resume or terminate it,
1074
- * otherwise it only goes away when Forge's abandoned-session TTL reaps it.
1075
- * The cancellation error is identical either way.
1067
+ * What happens to an upload when its `abortSignal` fires mid-transfer.
1068
+ * `terminate` (the default) gives it up: a tus DELETE has Forge drop the
1069
+ * chunks it already holds, and `uploadFromUri` deletes the file its create
1070
+ * made with it (`MobileIngotsClient.endUpload`), right for a user cancel,
1071
+ * where the bytes will never be wanted again. `keep` leaves the session
1072
+ * untouched on Forge, so a PAUSE (WiFi lost, low battery, app going to
1073
+ * background) can stop the transfer now and `ingots.resumeUpload` it later
1074
+ * from the server offset instead of re-sending the file. The caller owns a
1075
+ * kept session: it is expected to persist it (`onSessionCreated`) and resume
1076
+ * or terminate it, otherwise it only goes away when Forge's abandoned-session
1077
+ * TTL reaps it. The cancellation error is identical either way.
1076
1078
  */
1077
1079
  export type UploadAbortBehavior = 'terminate' | 'keep';
1078
1080