@sparkvault/sdk-js 11.0.1 → 11.0.3

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
@@ -1,33 +1,696 @@
1
+ /**
2
+ * Whether sending the SAME request again can succeed, read from its HTTP
3
+ * status: the one retry rule every client and every provider adapter applies.
4
+ *
5
+ * A retry rule restated beside every client drifts, and the copy that drifted
6
+ * decides whether a deliverable message is retried or abandoned, or whether a
7
+ * download is tried again. Each caller keeps its provider's own extras on top of
8
+ * this rule (a success body, a dead-token reason, a vendor error name).
9
+ *
10
+ * Browser-safe and import-free: sdk-js bundles it and sdk-mobile mirrors it.
11
+ */
12
+
13
+ /**
14
+ * Is this HTTP status one a retry of the same request can turn into a success?
15
+ *
16
+ * RFC 9110: 408 means the server never received the whole request, 429 that it
17
+ * throttled it, and a 5xx that it failed; every other status is the server's
18
+ * verdict on this exact request. A caller that got no response at all (a network
19
+ * error, a timeout) has no status to pass and decides that case itself.
20
+ *
21
+ * @param {number} status
22
+ * @returns {boolean}
23
+ */
24
+ function isTransientHttpStatus(status) {
25
+ return status === 408 || status === 429 || status >= 500;
26
+ }
27
+
28
+ /**
29
+ * The upload publication contract between Forge and Core's activation, and
30
+ * the facts of a transfer token both services spell: its shape, and Core's
31
+ * revocation of an upload's token.
32
+ *
33
+ * Forge stamps UPLOAD_PUBLICATION_PROTOCOL on every upload session it creates
34
+ * and on the final state it hands Core's activation (POST
35
+ * /v1/vaults/:vault_id/ingots/:ingot_id/activate); activation refuses any
36
+ * other version. The two services deploy separately, so a change to what
37
+ * either side sends or expects moves this number: a session or a finalize
38
+ * from the other side's contract then fails closed ("restart the upload")
39
+ * instead of publishing under a contract the other side does not hold.
40
+ *
41
+ * Version 2: an upload's own metadata (content type, original file name,
42
+ * uploader, content HMAC) travels on its upload token and its session, and
43
+ * activation publishes it from the session; the final state Forge sends
44
+ * carries only the storage facts Forge owns.
45
+ *
46
+ * Isomorphic: no Node imports.
47
+ */
48
+
49
+
50
+ /**
51
+ * The codes Core's activation refuses an upload with, which Forge's refusal
52
+ * map reads (the status is Core's):
53
+ * - UPLOAD_CONTRACT_MISMATCH (409): a finalize or session from another
54
+ * publication contract than Core's, a mixed deployment that converges — the
55
+ * upload is kept and its finalize tried again.
56
+ * - UPLOAD_PROTOCOL_RETIRED (410): a session from a contract Core no longer
57
+ * publishes, which never can be.
58
+ * - UPLOAD_SUPERSEDED (410): a session a later staging of its ingot
59
+ * superseded, which never can be.
60
+ * - UPLOAD_POOL_FULL (402): an upload the owner's storage pool cannot take at
61
+ * publication, which is final.
62
+ */
63
+ const UPLOAD_REFUSAL_CODES = Object.freeze({
64
+ UPLOAD_CONTRACT_MISMATCH: 'UPLOAD_CONTRACT_MISMATCH',
65
+ UPLOAD_PROTOCOL_RETIRED: 'UPLOAD_PROTOCOL_RETIRED',
66
+ UPLOAD_SUPERSEDED: 'UPLOAD_SUPERSEDED',
67
+ UPLOAD_POOL_FULL: 'UPLOAD_POOL_FULL'
68
+ });
69
+
70
+ /**
71
+ * The refusals of Core's that a new upload of the same file cannot remedy:
72
+ * the owner's storage pool cannot take it (UPLOAD_POOL_FULL), or a later
73
+ * upload of its ingot replaced it (UPLOAD_SUPERSEDED). Any other code Core
74
+ * ends an upload with ends its session alone, which a new upload starts
75
+ * over. Every client reads a terminal answer's code by it
76
+ * (transfer-retry.js): one of these is a refusal it reports in Core's words,
77
+ * any other a gone session.
78
+ */
79
+ const UPLOAD_FINAL_REFUSAL_CODES = Object.freeze([
80
+ UPLOAD_REFUSAL_CODES.UPLOAD_POOL_FULL,
81
+ UPLOAD_REFUSAL_CODES.UPLOAD_SUPERSEDED
82
+ ]);
83
+
84
+ /**
85
+ * Core's revocation of an upload's encrypt token: the `status` it writes on
86
+ * the token's forge-transactions record, and the `revoked_reason` beside it,
87
+ * written by the write that ends the upload's staging. Each reason is the
88
+ * refusal every reader of the token answers the upload with from then on,
89
+ * as Core's activation refuses such an upload: Core's mint of a token it
90
+ * revoked before issuing it, and Forge on every request the token, or a
91
+ * session it opened, makes.
92
+ *
93
+ * - UPLOAD_SUPERSEDED: a later staging of its ingot superseded the upload
94
+ * (410 UPLOAD_SUPERSEDED, in UPLOAD_SUPERSEDED_MESSAGE's words), which no
95
+ * new upload remedies;
96
+ * - INGOT_DELETED: the ingot it was staged onto was deleted, by a delete or
97
+ * the cascade of its folder, vault or account (a 404 naming the ingot, as
98
+ * activation answers an upload whose ingot is gone), which ends the upload
99
+ * alone: a new upload can store the file again.
100
+ */
101
+ const UPLOAD_TOKEN_REVOCATION = Object.freeze({
102
+ status: 'revoked',
103
+ reasons: Object.freeze({
104
+ UPLOAD_SUPERSEDED: UPLOAD_REFUSAL_CODES.UPLOAD_SUPERSEDED,
105
+ INGOT_DELETED: 'INGOT_DELETED'
106
+ })
107
+ });
108
+
109
+ Object.values(UPLOAD_TOKEN_REVOCATION.reasons);
110
+
111
+ /**
112
+ * The response header that names the code Core refused an upload with for
113
+ * good: Forge sends it on every terminal answer to a tus request, a HEAD's
114
+ * (which has no body) included, so a client tells an upload the owner's pool
115
+ * cannot take from one a later upload superseded without reading a body.
116
+ */
117
+ const UPLOAD_REFUSAL_HEADER = 'X-Upload-Refusal';
118
+
119
+ /**
120
+ * The transfer retry policy: what every first-party client does with the
121
+ * answer to a Forge transfer request (a tus chunk PATCH, an offset HEAD, the
122
+ * receipt PATCH at the final offset), in one place, so the Node uploader
123
+ * (forge-tus), the browser SDK (sdk-js bundles this module) and the mobile SDK
124
+ * (sdk-mobile carries a generated copy) read every answer the same way.
125
+ *
126
+ * It encodes what Google Drive, Google Cloud Storage, OneDrive, Dropbox and
127
+ * AWS document for resumable transfers:
128
+ * - only a request that got no answer, 408, 425, 429 or a 5xx is retried;
129
+ * every other 4xx is the server's verdict on the request;
130
+ * - `Retry-After` is a floor, never a ceiling;
131
+ * - retries back off exponentially, capped, with jitter;
132
+ * - before a chunk is sent again the server is asked for the offset it
133
+ * committed, because a request whose answer was lost may have landed;
134
+ * - a session that is gone (404, 410) is never resumed: only a new upload
135
+ * from byte 0 can succeed;
136
+ * - a transfer's retries are bounded in time and in failures in a row, and
137
+ * both bounds start over whenever the server confirms progress.
138
+ *
139
+ * Forge's own answers beyond the general rule:
140
+ * - the 409, in two kinds: one carrying `Upload-Offset` names where the
141
+ * session stands (continue from there), and one without it means another
142
+ * request holds the session's write lease, a chunk or the finalization
143
+ * (retry after its `Retry-After`);
144
+ * - a terminal answer (a 404, 410 or 412) names the code Core ended the
145
+ * upload with: its error envelope in `error.details.coreCode` for the
146
+ * refusals it words itself, and every one of them in `X-Upload-Refusal`,
147
+ * which is all a HEAD's answer, having no body, can carry; the body's code
148
+ * wins when both name one. The code decides the verdict: a full storage
149
+ * pool or a later upload that replaced this one is a refusal no new upload
150
+ * of the same file remedies, and any other code (the file the upload was
151
+ * for gone, a retired contract, a replacement base that moved on, a code
152
+ * this policy does not know) ends the session, which a new upload can
153
+ * start over;
154
+ * - a 503 carrying `Retry-After` to the receipt (the PATCH at the final
155
+ * offset) is a deferral: Forge holds every byte and is still publishing,
156
+ * and finishes without the client, so it is asked again, each time after a
157
+ * longer backoff, for as long as the idle limit allows, and never counts as
158
+ * a failure. Forge's deferral always names when to ask again; a 503 that
159
+ * does not is an ordinary failure.
160
+ *
161
+ * Isomorphic: no Node imports, no host APIs, no randomness. The jitter only
162
+ * has to spread retries, so it hashes the transfer and the attempt
163
+ * (docs/CONVENTIONS.md → Randomness).
164
+ */
165
+
166
+
167
+ /** What a client does after a transfer request, read from its answer. */
168
+ const TRANSFER_VERDICT = Object.freeze({
169
+ /** 2xx: the request did what it asked. */
170
+ OK: 'ok',
171
+ /**
172
+ * No answer (a reset, a timeout), 408, 425, 429, a 5xx, or a 409 without
173
+ * `Upload-Offset` (another request holds the session's lease): back off,
174
+ * never sooner than `Retry-After`, then ask the server's offset before
175
+ * sending a chunk again.
176
+ */
177
+ RETRY: 'retry',
178
+ /** 409 with `Upload-Offset`: the session stands elsewhere; continue from that offset at once. */
179
+ RESYNC: 'resync',
180
+ /**
181
+ * 503 with `Retry-After` to the receipt: every byte is received and the
182
+ * publication is still running. Ask again after a backoff that grows with
183
+ * each deferral, never sooner than `Retry-After`; only the idle limit ends
184
+ * the asking, never the failures in a row.
185
+ */
186
+ DEFERRED: 'deferred',
187
+ /**
188
+ * 404 or 410 naming no code, or a 404, 410 or 412 naming a code of Core's
189
+ * that is not a final refusal (`coreCode` carries it): the session no
190
+ * longer exists; only a new upload from byte 0 can succeed.
191
+ */
192
+ GONE: 'gone',
193
+ /**
194
+ * Any other status, or a 404, 410 or 412 naming a final refusal of Core's
195
+ * (`coreCode`: UPLOAD_POOL_FULL, UPLOAD_SUPERSEDED): the server's verdict on
196
+ * this request, which repeating it, or a new upload of the same file,
197
+ * earns again.
198
+ */
199
+ REFUSED: 'refused'
200
+ });
201
+
202
+ /** The failures a transfer recovers from by trying again: the verdicts a budget's `failed` records. */
203
+ const RETRYABLE_VERDICTS = new Set([TRANSFER_VERDICT.RETRY, TRANSFER_VERDICT.RESYNC]);
204
+
205
+ /** RFC 8470: the server refused a request sent in TLS early data; the same request succeeds once the handshake completes. */
206
+ const TOO_EARLY = 425;
207
+
208
+ /** Forge's answer to a receipt whose publication it deferred. */
209
+ const SERVICE_UNAVAILABLE = 503;
210
+
211
+ /**
212
+ * The statuses a terminal answer naming Core's code arrives with: Forge's 410
213
+ * (UPLOAD_GONE, or Core's own relayed), a relayed 404, and Core's own 412.
214
+ */
215
+ const TERMINAL_STATUSES = new Set([404, 410, 412]);
216
+
217
+ /** Core's error codes are upper-case words joined by underscores; anything else names no code. */
218
+ const CORE_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
219
+
220
+
221
+ const UPLOAD_OFFSET_HEADER = 'Upload-Offset';
222
+ const RETRY_AFTER_HEADER = 'Retry-After';
223
+
224
+ /**
225
+ * How long a client waits for the answer to an offset HEAD or a receipt
226
+ * PATCH, whatever its other requests get: on a received upload, Forge answers
227
+ * either only after its own call to Core (up to 30 s) has published the
228
+ * upload or deferred it, so each gets twice that.
229
+ */
230
+ const HEAD_AND_RECEIPT_TIMEOUT_MS = 60_000;
231
+
232
+ /** How a retry's delay spreads past its backoff: up to this much more. */
233
+ const JITTER_SPAN_MS = 1000;
234
+
235
+ /** How long a transfer may sit without progress or a sign of life by default. */
236
+ const DEFAULT_IDLE_LIMIT_MS = 10 * 60 * 1000;
237
+
238
+ /** How many failures in a row, without progress between them, end a transfer by default. */
239
+ const DEFAULT_MAX_CONSECUTIVE_FAILURES = 8;
240
+
241
+ /**
242
+ * @typedef {'ok'|'retry'|'resync'|'deferred'|'gone'|'refused'} TransferVerdict
243
+ */
244
+
245
+ /**
246
+ * The verdicts a transfer recovers from by trying again that count as
247
+ * failures: the ones a budget's `failed` records.
248
+ * @typedef {'retry'|'resync'} RetryableTransferVerdict
249
+ */
250
+
251
+ /**
252
+ * @typedef {Object} TransferOutcome
253
+ * @property {TransferVerdict} verdict - What the client does next
254
+ * @property {number|null} retryAfterMs - The answer's `Retry-After`, in ms from
255
+ * the answer (an HTTP-date already past reads as 0); null when absent or unreadable
256
+ * @property {number|null} offset - The answer's `Upload-Offset`; null when absent or unreadable
257
+ * @property {string|null} coreCode - The code Core ended the upload with, as a
258
+ * terminal answer named it (a 404, 410 or 412: its body's details or, those
259
+ * naming none, its `X-Upload-Refusal`): REFUSED for a final refusal
260
+ * (`UPLOAD_POOL_FULL`, `UPLOAD_SUPERSEDED`), GONE for any other code
261
+ * (`NOT_FOUND`, `UPLOAD_PROTOCOL_RETIRED`, a 412's, one this policy does not
262
+ * know); null when the answer names none
263
+ */
264
+
265
+ /**
266
+ * Read the answer to a transfer request the way the policy does.
267
+ *
268
+ * @param {Object} response
269
+ * @param {number} response.status - The HTTP status; 0 when the request got no answer
270
+ * @param {((name: string) => string|null)|null} [response.headers] - Reads a
271
+ * response header by name: a fetch `Headers`' `get` or an XHR's
272
+ * `getResponseHeader`, bound to its owner (`(name) => xhr.getResponseHeader(name)`)
273
+ * @param {unknown} [response.details] - The `details` of the error envelope the
274
+ * answer's body carries (`{ error: { code, message, details } }`), as the
275
+ * runtime's one reader of a failed answer parsed it from the whole body;
276
+ * where Forge names the refusal Core decided (`coreCode`), ahead of the
277
+ * answer's `X-Upload-Refusal`. Anything that is not an object names none.
278
+ * @param {boolean} [response.receipt] - The request was the receipt: the PATCH
279
+ * at the final offset, whose 503 carrying `Retry-After` is a deferral
280
+ * @param {number} [response.now] - When the answer arrived (epoch ms), which an
281
+ * HTTP-date `Retry-After` counts from
282
+ * @returns {TransferOutcome}
283
+ * @throws {TypeError} When the status is not a whole number, headers is not a
284
+ * function, or receipt is not a boolean
285
+ */
286
+ function classifyTransferResponse({ status, headers = null, details = null, receipt = false, now = Date.now() }) {
287
+ if (!Number.isSafeInteger(status) || status < 0) {
288
+ throw new TypeError(`A transfer answer's status is a whole number (0 for no answer), not ${status}`);
289
+ }
290
+ if (headers !== null && typeof headers !== 'function') {
291
+ throw new TypeError('A transfer answer\'s headers are read through a function from a header name to its value');
292
+ }
293
+ if (typeof receipt !== 'boolean') {
294
+ throw new TypeError(`Whether a transfer request was the receipt is a boolean, not ${receipt}`);
295
+ }
296
+ if (status === 0) {
297
+ return { verdict: TRANSFER_VERDICT.RETRY, retryAfterMs: null, offset: null, coreCode: null };
298
+ }
299
+ const header = (name) => (headers === null ? null : headers(name));
300
+ const offset = readCount(header(UPLOAD_OFFSET_HEADER));
301
+ const coreCode = TERMINAL_STATUSES.has(status)
302
+ ? coreCodeIn(details) ?? coreCodeOf(header(UPLOAD_REFUSAL_HEADER))
303
+ : null;
304
+ const retryAfterMs = readRetryAfterMs(header(RETRY_AFTER_HEADER), now);
305
+ return {
306
+ verdict: verdictFor(status, { offset, coreCode, deferral: receipt && retryAfterMs !== null }),
307
+ retryAfterMs,
308
+ offset,
309
+ coreCode
310
+ };
311
+ }
312
+
313
+ /**
314
+ * The verdict on a status that came with an answer: `offset` its readable
315
+ * `Upload-Offset`, `coreCode` the code of Core's a terminal answer names,
316
+ * `deferral` whether it answered the receipt with a readable `Retry-After`.
317
+ */
318
+ function verdictFor(status, { offset, coreCode, deferral }) {
319
+ if (status >= 200 && status < 300) return TRANSFER_VERDICT.OK;
320
+ if (status === 409) return offset === null ? TRANSFER_VERDICT.RETRY : TRANSFER_VERDICT.RESYNC;
321
+ if (coreCode !== null) return UPLOAD_FINAL_REFUSAL_CODES.includes(coreCode) ? TRANSFER_VERDICT.REFUSED : TRANSFER_VERDICT.GONE;
322
+ if (status === 404 || status === 410) return TRANSFER_VERDICT.GONE;
323
+ if (deferral && status === SERVICE_UNAVAILABLE) return TRANSFER_VERDICT.DEFERRED;
324
+ if (status === TOO_EARLY || isTransientHttpStatus(status)) return TRANSFER_VERDICT.RETRY;
325
+ return TRANSFER_VERDICT.REFUSED;
326
+ }
327
+
328
+ /** The code an error envelope's details name (`coreCode`), or null. */
329
+ function coreCodeIn(details) {
330
+ return details && typeof details === 'object' ? coreCodeOf(details.coreCode) : null;
331
+ }
332
+
333
+ /** A value that is one of Core's codes (surrounding whitespace allowed), or null. */
334
+ function coreCodeOf(value) {
335
+ if (typeof value !== 'string') return null;
336
+ const code = value.trim();
337
+ return CORE_CODE.test(code) ? code : null;
338
+ }
339
+
340
+ /** A header's non-negative whole number (surrounding whitespace allowed), or null. */
341
+ function readCount(value) {
342
+ if (typeof value !== 'string') return null;
343
+ const text = value.trim();
344
+ if (!/^\d+$/.test(text)) return null;
345
+ const count = Number(text);
346
+ return Number.isSafeInteger(count) ? count : null;
347
+ }
348
+
349
+ /** RFC 9110 §10.2.3: `Retry-After` is delay-seconds or an HTTP-date. */
350
+ function readRetryAfterMs(value, now) {
351
+ const seconds = readCount(value);
352
+ if (seconds !== null) {
353
+ const ms = seconds * 1000;
354
+ return Number.isSafeInteger(ms) ? ms : null;
355
+ }
356
+ const at = typeof value === 'string' ? parseHttpDate(value.trim(), now) : null;
357
+ return at === null ? null : Math.max(0, at - now);
358
+ }
359
+
360
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
361
+ const DAY_NAME = '(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)';
362
+ const LONG_DAY_NAME = '(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)';
363
+ const MONTH = `(${MONTHS.join('|')})`;
364
+ const TIME_OF_DAY = '(\\d{2}):(\\d{2}):(\\d{2})';
365
+
366
+ /** IMF-fixdate, what every current server sends: `Sun, 06 Nov 1994 08:49:37 GMT`. */
367
+ const IMF_FIXDATE = new RegExp(`^${DAY_NAME}, (\\d{2}) ${MONTH} (\\d{4}) ${TIME_OF_DAY} GMT$`);
368
+ /** The obsolete RFC 850 form a recipient still accepts: `Sunday, 06-Nov-94 08:49:37 GMT`. */
369
+ const RFC850_DATE = new RegExp(`^${LONG_DAY_NAME}, (\\d{2})-${MONTH}-(\\d{2}) ${TIME_OF_DAY} GMT$`);
370
+ /** The obsolete asctime form a recipient still accepts: `Sun Nov 6 08:49:37 1994`. */
371
+ const ASCTIME_DATE = new RegExp(`^${DAY_NAME} ${MONTH} ( \\d|\\d{2}) ${TIME_OF_DAY} (\\d{4})$`);
372
+
373
+ /**
374
+ * An HTTP-date (RFC 9110 §5.6.7, all three forms a recipient must accept) as
375
+ * epoch ms, or null when it is not one or names no real moment.
376
+ *
377
+ * @param {string} text
378
+ * @param {number} now - epoch ms, which places an RFC 850 two-digit year
379
+ * @returns {number|null}
380
+ */
381
+ function parseHttpDate(text, now) {
382
+ let match = IMF_FIXDATE.exec(text);
383
+ if (match) {
384
+ const [, day, month, year, hours, minutes, seconds] = match;
385
+ return utcMs(Number(year), month, Number(day), hours, minutes, seconds);
386
+ }
387
+ match = RFC850_DATE.exec(text);
388
+ if (match) {
389
+ const [, day, month, shortYear, hours, minutes, seconds] = match;
390
+ return utcMs(rfc850Year(Number(shortYear), now), month, Number(day), hours, minutes, seconds);
391
+ }
392
+ match = ASCTIME_DATE.exec(text);
393
+ if (match) {
394
+ const [, month, day, hours, minutes, seconds, year] = match;
395
+ return utcMs(Number(year), month, Number(day.trim()), hours, minutes, seconds);
396
+ }
397
+ return null;
398
+ }
399
+
400
+ /** RFC 9110: a two-digit year more than 50 years ahead is the latest past year with those digits. */
401
+ function rfc850Year(shortYear, now) {
402
+ const currentYear = new Date(now).getUTCFullYear();
403
+ const year = currentYear - (currentYear % 100) + shortYear;
404
+ return year > currentYear + 50 ? year - 100 : year;
405
+ }
406
+
407
+ /** The UTC instant of a calendar date and time of day, or null for a date or time that does not exist. */
408
+ function utcMs(year, monthName, day, hours, minutes, seconds) {
409
+ const monthIndex = MONTHS.indexOf(monthName);
410
+ const [h, m, s] = [Number(hours), Number(minutes), Number(seconds)];
411
+ // A leap second (60) is a real time of day; the instant rolls into the next minute.
412
+ if (h > 23 || m > 59 || s > 60) return null;
413
+ const date = new Date(0);
414
+ date.setUTCFullYear(year, monthIndex, day);
415
+ if (date.getUTCFullYear() !== year || date.getUTCMonth() !== monthIndex || date.getUTCDate() !== day) {
416
+ return null;
417
+ }
418
+ return date.getTime() + ((h * 60 + m) * 60 + s) * 1000;
419
+ }
420
+
421
+ const FNV_OFFSET_BASIS = 0x811c9dc5;
422
+ const FNV_PRIME = 0x01000193;
423
+
424
+ /**
425
+ * 32-bit FNV-1a over the text's UTF-8 bytes: the jitter's hash. A retry's
426
+ * delay only has to spread, so it hashes what identifies the retry and draws
427
+ * nothing (docs/CONVENTIONS.md → Randomness).
428
+ *
429
+ * @param {string} text
430
+ * @returns {number} An unsigned 32-bit integer
431
+ * @throws {TypeError} When the text is not a string
432
+ */
433
+ function fnv1a32(text) {
434
+ if (typeof text !== 'string') {
435
+ throw new TypeError(`fnv1a32 hashes a string, not ${typeof text}`);
436
+ }
437
+ let hash = FNV_OFFSET_BASIS;
438
+ const mix = (byte) => {
439
+ hash = Math.imul(hash ^ byte, FNV_PRIME) >>> 0;
440
+ };
441
+ for (const character of text) {
442
+ let point = character.codePointAt(0);
443
+ // A lone surrogate has no UTF-8 form; it encodes as U+FFFD, as TextEncoder does.
444
+ if (point >= 0xd800 && point <= 0xdfff) point = 0xfffd;
445
+ if (point < 0x80) {
446
+ mix(point);
447
+ } else if (point < 0x800) {
448
+ mix(0xc0 | (point >> 6));
449
+ mix(0x80 | (point & 0x3f));
450
+ } else if (point < 0x10000) {
451
+ mix(0xe0 | (point >> 12));
452
+ mix(0x80 | ((point >> 6) & 0x3f));
453
+ mix(0x80 | (point & 0x3f));
454
+ } else {
455
+ mix(0xf0 | (point >> 18));
456
+ mix(0x80 | ((point >> 12) & 0x3f));
457
+ mix(0x80 | ((point >> 6) & 0x3f));
458
+ mix(0x80 | (point & 0x3f));
459
+ }
460
+ }
461
+ return hash;
462
+ }
463
+
464
+ /** Transfers this runtime has keyed by `transferJitterKey`: with the start time, what tells them apart. */
465
+ let transfersKeyed = 0;
466
+
467
+ /**
468
+ * What a transfer's retries spread by when no session URL keys them yet (a
469
+ * session create) or ever (a download, whose link carries its token): the
470
+ * scope (the create endpoint, or the kind of transfer), when the transfer
471
+ * started, and this runtime's count of keyed transfers, which tell
472
+ * concurrent transfers apart. A transfer's token is a credential and never
473
+ * feeds anything observable such as a delay, so no part of the key derives
474
+ * from it (docs/CONVENTIONS.md → Randomness).
475
+ *
476
+ * @param {string} scope - The endpoint or the kind of transfer
477
+ * @returns {string} The key, for every retry of this one transfer
478
+ * @throws {TypeError} For a scope that is not a non-empty string
479
+ */
480
+ function transferJitterKey(scope) {
481
+ if (typeof scope !== 'string' || scope.length === 0) {
482
+ throw new TypeError('A transfer jitter key needs the scope its transfer runs in');
483
+ }
484
+ transfersKeyed += 1;
485
+ return `${scope}#${Date.now()}-${transfersKeyed}`;
486
+ }
487
+
488
+ /**
489
+ * How long to wait before retry `attempt` of a transfer: `baseMs` doubling per
490
+ * attempt, capped at `capMs`, plus a jitter in [0, 1000) ms hashed from the
491
+ * transfer and the attempt, and never less than the server's `Retry-After`.
492
+ * The same transfer and attempt always wait the same; different transfers
493
+ * failing together spread out.
494
+ *
495
+ * @param {Object} options
496
+ * @param {number} options.attempt - Which retry this is, from 1
497
+ * @param {number|null} [options.retryAfterMs] - The answer's `Retry-After`: a floor
498
+ * @param {number} [options.baseMs] - The first retry's backoff
499
+ * @param {number} [options.capMs] - The longest backoff, before jitter
500
+ * @param {string} options.jitterKey - What identifies the transfer (its session
501
+ * URL, or a `transferJitterKey`)
502
+ * @returns {number} ms
503
+ * @throws {TypeError} For an attempt that is not a whole number from 1, a
504
+ * missing jitter key, or a delay bound that is not a positive number of ms
505
+ */
506
+ function retryDelayMs({ attempt, retryAfterMs = null, baseMs = 1000, capMs = 32000, jitterKey }) {
507
+ if (!Number.isSafeInteger(attempt) || attempt < 1) {
508
+ throw new TypeError(`A retry's attempt is a whole number from 1, not ${attempt}`);
509
+ }
510
+ if (typeof jitterKey !== 'string' || jitterKey.length === 0) {
511
+ throw new TypeError('A retry delay needs the key its transfer spreads by');
512
+ }
513
+ if (!isDuration(baseMs) || baseMs === 0 || !isDuration(capMs) || capMs < baseMs) {
514
+ throw new TypeError(`A retry backs off from a positive base (${baseMs} ms) up to a cap no smaller (${capMs} ms)`);
515
+ }
516
+ if (retryAfterMs !== null && !isDuration(retryAfterMs)) {
517
+ throw new TypeError(`A Retry-After floor is a non-negative number of ms, not ${retryAfterMs}`);
518
+ }
519
+ const backoff = Math.min(capMs, baseMs * 2 ** (attempt - 1));
520
+ const jitter = Math.floor((fnv1a32(`${jitterKey}|${attempt}`) / 2 ** 32) * JITTER_SPAN_MS);
521
+ return Math.max(backoff + jitter, retryAfterMs ?? 0);
522
+ }
523
+
524
+ function isDuration(ms) {
525
+ return Number.isFinite(ms) && ms >= 0;
526
+ }
527
+
528
+ /**
529
+ * @typedef {Object} TransferBudget
530
+ * @property {() => void} progressed - The server confirmed progress (bytes
531
+ * landed, or the offset it names moved forward): the failures in a row and
532
+ * the idle clock start over
533
+ * @property {() => void} alive - A sign of life the server has not confirmed
534
+ * (bytes are leaving, or the device is back online): the idle clock starts
535
+ * over and the failures in a row stand, so attempts that die before the
536
+ * server confirms anything still end the transfer
537
+ * @property {(verdict: RetryableTransferVerdict, retryAfterMs?: number|null) => boolean} failed -
538
+ * Records a retryable answer (RETRY or RESYNC) and says whether another
539
+ * attempt is allowed: the failures in a row stay under the max, and the
540
+ * attempt `retryAfterMs` allows would start inside the idle limit, so a
541
+ * transfer never sleeps on a Retry-After longer than its budget. The limit
542
+ * bounds when a retry is decided; a retry decided inside it still waits its
543
+ * own backoff, so a transfer ends within one backoff of the limit.
544
+ * @property {(retryAfterMs?: number|null) => boolean} deferred - Records a
545
+ * DEFERRED answer and says whether to ask again: only the idle limit bounds
546
+ * it, as `failed` applies it, because a deferral is the server at work,
547
+ * never a failure, so the failures in a row stand
548
+ * @property {number} consecutiveFailures - Retryable failures since the last progress
549
+ * @property {number} attempt - Failures and deferrals since the last progress:
550
+ * the attempt the next wait's delay is computed for, so each deferral backs
551
+ * the next ask off as a failure does, sparing a Core that is struggling to
552
+ * publish
553
+ * @property {number} msSinceProgress - ms since the last progress or sign of life
554
+ */
555
+
556
+ /**
557
+ * The retry budget of one transfer: retries are bounded by failures in a row
558
+ * and by time without progress, deferrals by time alone, and both bounds
559
+ * start over whenever the server confirms progress, so a slow transfer that
560
+ * keeps landing bytes is never cut off while a dead one ends in bounded time.
561
+ *
562
+ * @param {Object} [options]
563
+ * @param {number} [options.idleLimitMs] - How long the transfer may go without
564
+ * progress or a sign of life
565
+ * @param {number} [options.maxConsecutiveFailures] - Failures in a row that end the transfer
566
+ * @param {() => number} [options.now] - The clock, epoch ms
567
+ * @returns {TransferBudget}
568
+ * @throws {TypeError} For a limit that is not a positive number, or a clock that is not a function
569
+ */
570
+ function createTransferBudget({
571
+ idleLimitMs = DEFAULT_IDLE_LIMIT_MS,
572
+ maxConsecutiveFailures = DEFAULT_MAX_CONSECUTIVE_FAILURES,
573
+ now = () => Date.now()
574
+ } = {}) {
575
+ if (!isDuration(idleLimitMs) || idleLimitMs === 0) {
576
+ throw new TypeError(`A transfer's idle limit is a positive number of ms, not ${idleLimitMs}`);
577
+ }
578
+ if (!Number.isSafeInteger(maxConsecutiveFailures) || maxConsecutiveFailures < 1) {
579
+ throw new TypeError(`A transfer's failure limit is a whole number from 1, not ${maxConsecutiveFailures}`);
580
+ }
581
+ if (typeof now !== 'function') {
582
+ throw new TypeError('A transfer budget reads time from a clock function');
583
+ }
584
+
585
+ let consecutiveFailures = 0;
586
+ let deferrals = 0;
587
+ let lastSignOfLifeAt = now();
588
+ const msIdle = () => now() - lastSignOfLifeAt;
589
+ const startsInsideIdleLimit = (retryAfterMs) => {
590
+ if (retryAfterMs !== null && !isDuration(retryAfterMs)) {
591
+ throw new TypeError(`A Retry-After floor is a non-negative number of ms, not ${retryAfterMs}`);
592
+ }
593
+ return msIdle() + (retryAfterMs ?? 0) < idleLimitMs;
594
+ };
595
+
596
+ return Object.freeze({
597
+ progressed() {
598
+ consecutiveFailures = 0;
599
+ deferrals = 0;
600
+ lastSignOfLifeAt = now();
601
+ },
602
+ alive() {
603
+ lastSignOfLifeAt = now();
604
+ },
605
+ failed(verdict, retryAfterMs = null) {
606
+ if (!RETRYABLE_VERDICTS.has(verdict)) {
607
+ throw new TypeError(`A transfer budget records retryable answers only, not '${verdict}'`);
608
+ }
609
+ const allowed = startsInsideIdleLimit(retryAfterMs);
610
+ consecutiveFailures += 1;
611
+ return allowed && consecutiveFailures < maxConsecutiveFailures;
612
+ },
613
+ deferred(retryAfterMs = null) {
614
+ const allowed = startsInsideIdleLimit(retryAfterMs);
615
+ deferrals += 1;
616
+ return allowed;
617
+ },
618
+ get consecutiveFailures() {
619
+ return consecutiveFailures;
620
+ },
621
+ get attempt() {
622
+ return consecutiveFailures + deferrals;
623
+ },
624
+ get msSinceProgress() {
625
+ return msIdle();
626
+ }
627
+ });
628
+ }
629
+
630
+ /** Why an offset the server names cannot be resumed from. */
631
+ const RESUME_OFFSET_PROBLEM = Object.freeze({
632
+ /** Not a non-negative whole number of bytes. */
633
+ INVALID: 'invalid',
634
+ /** Past the upload's length: resuming from it would report a partial upload complete. */
635
+ BEYOND_TOTAL: 'beyond_total',
636
+ /** Inside a chunk: a session commits whole chunks only, so the answer is corrupt. */
637
+ MISALIGNED: 'misaligned'
638
+ });
639
+
640
+ /**
641
+ * Why a session offset the server named (a HEAD's, or a 409's `Upload-Offset`)
642
+ * cannot be resumed from, or null when it can. Forge commits whole chunks, so
643
+ * a session stands at a multiple of its chunk size or at its total.
644
+ *
645
+ * @param {number|null} offset
646
+ * @param {Object} geometry
647
+ * @param {number} geometry.totalSize - The upload's length (a non-negative whole number)
648
+ * @param {number} geometry.chunkSize - The session's chunk size (a positive whole number)
649
+ * @returns {'invalid'|'beyond_total'|'misaligned'|null}
650
+ * @throws {TypeError} When the length is not a non-negative whole number or
651
+ * the chunk size not a positive one
652
+ */
653
+ function resumeOffsetProblem(offset, { totalSize, chunkSize }) {
654
+ if (!Number.isSafeInteger(totalSize) || totalSize < 0 || !Number.isSafeInteger(chunkSize) || chunkSize < 1) {
655
+ throw new TypeError(`An upload's geometry is a whole length and a positive chunk size, not ${totalSize} and ${chunkSize}`);
656
+ }
657
+ if (!Number.isSafeInteger(offset) || offset < 0) return RESUME_OFFSET_PROBLEM.INVALID;
658
+ if (offset > totalSize) return RESUME_OFFSET_PROBLEM.BEYOND_TOTAL;
659
+ if (offset !== totalSize && offset % chunkSize !== 0) return RESUME_OFFSET_PROBLEM.MISALIGNED;
660
+ return null;
661
+ }
662
+
1
663
  /**
2
664
  * SparkVault SDK Error Types
3
665
  */
4
666
  class SparkVaultError extends Error {
5
- constructor(message, code, statusCode, details) {
667
+ constructor(message, code, statusCode, details, retryAfterMs = null) {
6
668
  super(message);
7
669
  this.name = 'SparkVaultError';
8
670
  this.code = code;
9
671
  this.statusCode = statusCode;
10
672
  this.details = details;
673
+ this.retryAfterMs = retryAfterMs;
11
674
  Object.setPrototypeOf(this, SparkVaultError.prototype);
12
675
  }
13
676
  }
14
677
  class AuthenticationError extends SparkVaultError {
15
- constructor(message, details) {
16
- super(message, 'authentication_error', 401, details);
678
+ constructor(message, details, retryAfterMs = null) {
679
+ super(message, 'authentication_error', 401, details, retryAfterMs);
17
680
  this.name = 'AuthenticationError';
18
681
  Object.setPrototypeOf(this, AuthenticationError.prototype);
19
682
  }
20
683
  }
21
684
  class AuthorizationError extends SparkVaultError {
22
- constructor(message, details) {
23
- super(message, 'authorization_error', 403, details);
685
+ constructor(message, details, retryAfterMs = null) {
686
+ super(message, 'authorization_error', 403, details, retryAfterMs);
24
687
  this.name = 'AuthorizationError';
25
688
  Object.setPrototypeOf(this, AuthorizationError.prototype);
26
689
  }
27
690
  }
28
691
  class ValidationError extends SparkVaultError {
29
- constructor(message, details) {
30
- super(message, 'validation_error', 400, details);
692
+ constructor(message, details, retryAfterMs = null) {
693
+ super(message, 'validation_error', 400, details, retryAfterMs);
31
694
  this.name = 'ValidationError';
32
695
  Object.setPrototypeOf(this, ValidationError.prototype);
33
696
  }
@@ -38,8 +701,8 @@ class ValidationError extends SparkVaultError {
38
701
  * to admins, or "ask your account admin" to members.
39
702
  */
40
703
  class PlanRequiredError extends SparkVaultError {
41
- constructor(message, details) {
42
- super(message, 'PLAN_REQUIRED', 402, details);
704
+ constructor(message, details, retryAfterMs = null) {
705
+ super(message, 'PLAN_REQUIRED', 402, details, retryAfterMs);
43
706
  this.name = 'PlanRequiredError';
44
707
  Object.setPrototypeOf(this, PlanRequiredError.prototype);
45
708
  }
@@ -50,8 +713,8 @@ class PlanRequiredError extends SparkVaultError {
50
713
  * the right capacity block.
51
714
  */
52
715
  class QuotaExceededError extends SparkVaultError {
53
- constructor(message, details) {
54
- super(message, 'QUOTA_EXCEEDED', 402, details);
716
+ constructor(message, details, retryAfterMs = null) {
717
+ super(message, 'QUOTA_EXCEEDED', 402, details, retryAfterMs);
55
718
  this.name = 'QuotaExceededError';
56
719
  const resource = details?.resource;
57
720
  this.resource =
@@ -66,8 +729,8 @@ class QuotaExceededError extends SparkVaultError {
66
729
  * nothing, so surface a subscribe CTA rather than a sign-in prompt.
67
730
  */
68
731
  class NotifySubscriptionRequiredError extends SparkVaultError {
69
- constructor(message, details) {
70
- super(message, 'NOTIFY_SUBSCRIPTION_REQUIRED', 403, details);
732
+ constructor(message, details, retryAfterMs = null) {
733
+ super(message, 'NOTIFY_SUBSCRIPTION_REQUIRED', 403, details, retryAfterMs);
71
734
  this.name = 'NotifySubscriptionRequiredError';
72
735
  Object.setPrototypeOf(this, NotifySubscriptionRequiredError.prototype);
73
736
  }
@@ -123,24 +786,51 @@ function recordField(value) {
123
786
  ? value
124
787
  : undefined;
125
788
  }
789
+ function parseJson(text) {
790
+ try {
791
+ return JSON.parse(text);
792
+ }
793
+ catch {
794
+ return null;
795
+ }
796
+ }
126
797
  /**
127
- * Read a failed response's error body: the one reading every SDK transport
128
- * shares. SparkVault services answer `{ error: { code, message, details } }`;
129
- * a framework or gateway answers flat (`{ code, message }`, `{ message }`) or
130
- * with no JSON at all, so each field falls back to its flat form and then to a
131
- * default. The body is read leniently: a failure's status and class never
132
- * depend on the body being JSON.
798
+ * Read a failed answer from its parsed body: the one reading every SDK
799
+ * transport shares, so an error built from an answer carries the same of it
800
+ * whichever client made the request, and whether fetch or an XMLHttpRequest
801
+ * received it. SparkVault services answer `{ error: { code, message,
802
+ * details } }`; a framework or gateway answers flat (`{ code, message }`,
803
+ * `{ message }`) or with no JSON at all, so each field falls back to its flat
804
+ * form and then to a default. The body is read leniently: a failure's status
805
+ * and class never depend on the body being JSON. The `Retry-After` is read by
806
+ * the transfer policy's one parser (`@sparkvault/app-sdk/transfer-retry`),
807
+ * never a second one: the policy reads a whole answer at once, and only its
808
+ * header reading is kept here, because an API answer is the service's
809
+ * verdict, never a transfer answer the policy's verdict applies to.
133
810
  */
134
- async function readApiErrorBody(response) {
135
- const body = await response.json().catch(() => null);
811
+ function failureOf(status, body, header) {
136
812
  const root = recordField(body) ?? {};
137
813
  const nested = recordField(root.error);
138
814
  return {
815
+ status,
139
816
  message: stringField(nested?.message) ?? stringField(root.message) ?? stringField(root.error) ?? 'Request failed',
140
817
  code: stringField(nested?.code) ?? stringField(root.code) ?? 'api_error',
141
818
  details: recordField(nested?.details) ?? recordField(root.details),
819
+ retryAfterMs: classifyTransferResponse({ status, headers: header }).retryAfterMs,
142
820
  };
143
821
  }
822
+ /**
823
+ * Read a failed answer a transport holds as text (an XMLHttpRequest's
824
+ * `responseText`, a body it also keeps a snippet of), parsed whole, so
825
+ * nothing past any length is lost to the reading.
826
+ */
827
+ function apiFailureOf(answer) {
828
+ return failureOf(answer.status, parseJson(answer.body), answer.header);
829
+ }
830
+ /** Read a failed fetch response; a body that is not JSON, or cannot be read, reads as none. */
831
+ async function readApiFailure(response) {
832
+ return failureOf(response.status, await response.json().catch(() => null), (name) => response.headers.get(name));
833
+ }
144
834
 
145
835
  /**
146
836
  * SparkVault resource ids: the one grammar every surface reads an id by before
@@ -476,10 +1166,14 @@ class SparkVaultApi {
476
1166
  * here, when the request starts. resetSession() can swap the controller
477
1167
  * while the request is in flight, and reading the live one afterwards would
478
1168
  * misreport a genuine cancel as a timeout.
1169
+ *
1170
+ * @param timeoutMs - The deadline of a request whose server-side wait is
1171
+ * its own (a tus HEAD or receipt, which Forge answers only after its call
1172
+ * to Core); every other request takes the client's.
479
1173
  */
480
- send(url, init, copy, read) {
1174
+ send(url, init, copy, read, timeoutMs = this.timeoutMs) {
481
1175
  return exchange(url, init, {
482
- timeoutMs: this.timeoutMs,
1176
+ timeoutMs,
483
1177
  closeSignal: this.closeController.signal,
484
1178
  read,
485
1179
  fail: (failure, cause) => {
@@ -499,8 +1193,9 @@ class SparkVaultApi {
499
1193
  /**
500
1194
  * Issue a JSON API request. Returns the parsed JSON body (whatever shape it
501
1195
  * takes; null when the body is not JSON) plus the status code. A non-2xx
502
- * answer throws the subclass error carrying the server's code, message and
503
- * details, read by the one error-body reader every transport shares.
1196
+ * answer throws the subclass error carrying the server's code, message,
1197
+ * details and `Retry-After`, read by the one failed-answer reader every
1198
+ * transport shares.
504
1199
  */
505
1200
  rawRequest(url, options) {
506
1201
  // Only send Content-Type when there's actually a body — otherwise GETs
@@ -516,8 +1211,8 @@ class SparkVaultApi {
516
1211
  network: 'Unable to connect. Please check your connection and try again.',
517
1212
  }, async (response) => {
518
1213
  if (!response.ok) {
519
- const { message, code, details } = await readApiErrorBody(response);
520
- throw this.makeError(message, code, response.status, details);
1214
+ const { status, message, code, details, retryAfterMs } = await readApiFailure(response);
1215
+ throw this.makeError(message, code, status, details, retryAfterMs);
521
1216
  }
522
1217
  return { data: await readJsonBody(response), status: response.status };
523
1218
  });
@@ -645,7 +1340,7 @@ class HttpClient {
645
1340
  timeoutMs: timeout,
646
1341
  read: async (response) => {
647
1342
  if (!response.ok) {
648
- throw this.createErrorFromResponse(response.status, await readApiErrorBody(response));
1343
+ throw this.createErrorFromResponse(await readApiFailure(response));
649
1344
  }
650
1345
  const parsed = await this.parseResponse(response);
651
1346
  return {
@@ -683,26 +1378,34 @@ class HttpClient {
683
1378
  const text = await response.text();
684
1379
  throw new SparkVaultError(`Unexpected response format: expected JSON but received ${contentType ?? 'unknown content type'}`, 'invalid_response_format', response.status, { body: text.slice(0, 500) });
685
1380
  }
686
- createErrorFromResponse(status, { message, code, details }) {
1381
+ /**
1382
+ * The SDK error for a failed answer, typed by its status: the gates a host
1383
+ * page branches on get their own class, and every other answer is the base
1384
+ * error under the service's own code. Each carries the answer's
1385
+ * `Retry-After` (`retryAfterMs`), the floor for whoever retries it — the
1386
+ * SDK's own transfers when the answer is a download link's mint, and the
1387
+ * host page otherwise.
1388
+ */
1389
+ createErrorFromResponse({ status, message, code, details, retryAfterMs }) {
687
1390
  switch (status) {
688
1391
  case 400:
689
- return new ValidationError(message, details);
1392
+ return new ValidationError(message, details, retryAfterMs);
690
1393
  case 401:
691
- return new AuthenticationError(message, details);
1394
+ return new AuthenticationError(message, details, retryAfterMs);
692
1395
  case 402:
693
1396
  if (code === 'QUOTA_EXCEEDED')
694
- return new QuotaExceededError(message, details);
1397
+ return new QuotaExceededError(message, details, retryAfterMs);
695
1398
  // PLAN_REQUIRED is the canonical 402 gate; treat any other 402 as one too.
696
- return new PlanRequiredError(message, details);
1399
+ return new PlanRequiredError(message, details, retryAfterMs);
697
1400
  case 403:
698
1401
  // A Notify send refused for want of a subscription is a billing gate, not
699
1402
  // a credential problem — give it its own catchable type.
700
1403
  if (code === 'NOTIFY_SUBSCRIPTION_REQUIRED') {
701
- return new NotifySubscriptionRequiredError(message, details);
1404
+ return new NotifySubscriptionRequiredError(message, details, retryAfterMs);
702
1405
  }
703
- return new AuthorizationError(message, details);
1406
+ return new AuthorizationError(message, details, retryAfterMs);
704
1407
  default:
705
- return new SparkVaultError(message, code, status, details);
1408
+ return new SparkVaultError(message, code, status, details, retryAfterMs);
706
1409
  }
707
1410
  }
708
1411
  unwrapApiResponse(data) {
@@ -1498,8 +2201,8 @@ class IdentityApi extends SparkVaultApi {
1498
2201
  get baseUrl() {
1499
2202
  return `${this.config.identityBaseUrl}${apiPath `/${this.config.accountId}`}`;
1500
2203
  }
1501
- makeError(message, code, statusCode, details) {
1502
- return new IdentityApiError(message, code, statusCode, details);
2204
+ makeError(message, code, statusCode, details, retryAfterMs = null) {
2205
+ return new IdentityApiError(message, code, statusCode, details, retryAfterMs);
1503
2206
  }
1504
2207
  async request(method, endpoint, body, query) {
1505
2208
  const { data } = await this.rawRequest(`${this.baseUrl}${endpoint}${queryString(query)}`, {
@@ -1875,8 +2578,8 @@ function mapRecommendations(raw) {
1875
2578
  return result;
1876
2579
  }
1877
2580
  class IdentityApiError extends SparkVaultError {
1878
- constructor(message, code, statusCode, details) {
1879
- super(message, code, statusCode, details);
2581
+ constructor(message, code, statusCode, details, retryAfterMs = null) {
2582
+ super(message, code, statusCode, details, retryAfterMs);
1880
2583
  this.name = 'IdentityApiError';
1881
2584
  Object.setPrototypeOf(this, IdentityApiError.prototype);
1882
2585
  }
@@ -10984,11 +11687,21 @@ function refused(reason) {
10984
11687
  /**
10985
11688
  * Error class for upload API errors. Inherits `code` and `statusCode` from
10986
11689
  * SparkVaultError — no duplicate `httpStatus` field.
11690
+ *
11691
+ * A failed transfer request also carries what the transfer policy
11692
+ * (`@sparkvault/app-sdk/transfer-retry`) makes of its answer, read where the
11693
+ * answer arrived: its `verdict` and its `Upload-Offset` (`serverOffset`),
11694
+ * beside the `Retry-After` every SDK error carries (`retryAfterMs`). They are
11695
+ * the retry loop's bookkeeping, so they ride on the instance, never in
11696
+ * `details`. Every other failure (a cancel, a refused URL, a protocol
11697
+ * violation) is `refused`: nothing retries it.
10987
11698
  */
10988
11699
  class UploadApiError extends SparkVaultError {
10989
- constructor(message, code, statusCode, details) {
10990
- super(message, code, statusCode, details);
11700
+ constructor(message, code, statusCode, details, outcome) {
11701
+ super(message, code, statusCode, details, outcome?.retryAfterMs ?? null);
10991
11702
  this.name = 'UploadApiError';
11703
+ this.verdict = outcome?.verdict ?? TRANSFER_VERDICT.REFUSED;
11704
+ this.serverOffset = outcome?.offset ?? null;
10992
11705
  Object.setPrototypeOf(this, UploadApiError.prototype);
10993
11706
  }
10994
11707
  }
@@ -11051,51 +11764,91 @@ function parseChunkSizeHeader(raw) {
11051
11764
  */
11052
11765
  const CHUNK_INACTIVITY_TIMEOUT_MS = 60000;
11053
11766
  /**
11054
- * Per-chunk retry budget for the PATCH loop.
11767
+ * How many consecutive timeouts end the finalization receipt early.
11055
11768
  *
11056
- * Forge sessions are resumable, so a chunk that fails in transit is a blip to
11057
- * recover from rather than an upload to abandon — a multi-gigabyte transfer is
11058
- * otherwise one dropped packet away from starting over. The budget counts only
11059
- * failures that produced no server-side progress: a retry cycle that finds
11060
- * bytes actually landed earns the budget back, so a slow-but-alive transfer is
11061
- * never capped while a genuinely dead one still fails in bounded time.
11769
+ * A genuinely slow finalize shows up as ONE timeout — the PATCH that started
11770
+ * the re-drive — followed by 409s from the writer that is working on it.
11771
+ * Back-to-back timeouts mean nobody is answering at all, and spending the
11772
+ * whole retry budget on a black-holed socket would freeze the widget at 100%
11773
+ * for minutes with nothing for the user to act on.
11062
11774
  */
11063
- const CHUNK_MAX_ATTEMPTS = 3;
11064
- const CHUNK_RETRY_BASE_MS = 500;
11775
+ const FINALIZE_MAX_CONSECUTIVE_TIMEOUTS = 2;
11776
+ /** The copy a person reads when the session their upload ran in no longer exists. */
11777
+ const SESSION_GONE_MESSAGE = 'Upload could not be finished: the server has ended this upload session. Please upload the file again.';
11065
11778
  /**
11066
- * Retry budget for the finalization receipt.
11067
- *
11068
- * Forge answers the zero-length PATCH with a 409 while another writer is still
11069
- * inside the finalizer, so the confirmation has to out-wait a finalization
11070
- * already in flight rather than give up on it — a budget measured in seconds
11071
- * rather than in the sub-second blips a chunk retry recovers from.
11779
+ * The copy a person reads when the server kept deferring the publication
11780
+ * until the upload's idle limit: nothing failed, and nothing is left for
11781
+ * them to do.
11072
11782
  */
11073
- const FINALIZE_MAX_ATTEMPTS = 10;
11074
- const FINALIZE_RETRY_MS = 1000;
11783
+ const RECEIVED_PUBLISHING_MESSAGE = 'The server received every byte of this file and is still saving it. It finishes on its own.';
11075
11784
  /**
11076
- * How many consecutive timeouts end the confirmation early.
11077
- *
11078
- * A genuinely slow finalize shows up as ONE timeout — the PATCH that started
11079
- * the re-drive — followed by 409s from the writer that is working on it.
11080
- * Back-to-back timeouts mean nobody is answering at all, and spending the full
11081
- * budget on a black-holed socket would freeze the widget at 100% for minutes
11082
- * with nothing for the user to act on.
11785
+ * The copy a person reads for a final refusal whose answer carried no
11786
+ * sentence of Core's (a HEAD's, which has no body, naming Core's code in
11787
+ * `X-Upload-Refusal` alone): this SDK's own words for each code, none of them
11788
+ * asking for the file again.
11083
11789
  */
11084
- const FINALIZE_MAX_CONSECUTIVE_TIMEOUTS = 2;
11790
+ const REFUSAL_WORDING = new Map([
11791
+ [UPLOAD_REFUSAL_CODES.UPLOAD_POOL_FULL, 'This upload could not be saved: the owner\'s storage cannot take the file.'],
11792
+ [UPLOAD_REFUSAL_CODES.UPLOAD_SUPERSEDED, 'This upload was not saved: a newer upload of this file replaced it.'],
11793
+ ]);
11794
+ /** The copy for a final refusal of a code this SDK has no words of its own for. */
11795
+ const REFUSED_MESSAGE = 'This upload could not be saved: the server refused it.';
11796
+ /**
11797
+ * The error of an upload Core refused for good (UPLOAD_FINAL_REFUSAL_CODES):
11798
+ * `upload_refused` in Core's own sentence, this SDK's for an answer that
11799
+ * carried none (a HEAD's), Core's code in `details.coreCode`; never retried,
11800
+ * and no new upload of the same file remedies it. The one reading of that
11801
+ * verdict, whichever answer carries it: a transfer answer naming Core's code
11802
+ * ({@link readTransferAnswer}), or Core's own refusal of the request that
11803
+ * stages the upload ({@link stagingRefusal}).
11804
+ */
11805
+ function uploadRefusedError(coreCode, message, status, outcome) {
11806
+ return new UploadApiError(message ?? REFUSAL_WORDING.get(coreCode) ?? REFUSED_MESSAGE, 'upload_refused', status, { status, coreCode }, outcome);
11807
+ }
11808
+ /**
11809
+ * Core's refusal of a request that stages an upload — a create, a
11810
+ * replacement, the widget's initiation — read as the upload's verdict: a final
11811
+ * refusal of Core's (UPLOAD_FINAL_REFUSAL_CODES, the answer's own code: a
11812
+ * later staging of the same file superseded it before its token was minted,
11813
+ * 410 UPLOAD_SUPERSEDED) is the `upload_refused` a transfer answer naming it
11814
+ * throws ({@link uploadRefusedError}); null for any other refusal.
11815
+ */
11816
+ function stagingRefusal(code, message, status, retryAfterMs) {
11817
+ if (!UPLOAD_FINAL_REFUSAL_CODES.includes(code))
11818
+ return null;
11819
+ return uploadRefusedError(code, message, status, {
11820
+ verdict: TRANSFER_VERDICT.REFUSED,
11821
+ retryAfterMs,
11822
+ offset: null,
11823
+ coreCode: code,
11824
+ });
11825
+ }
11826
+ /**
11827
+ * The error a request that stages an upload throws, from the error Core's
11828
+ * answer made: its final refusal of the upload as `upload_refused`
11829
+ * ({@link stagingRefusal}), any other error as it is.
11830
+ */
11831
+ function stagingRefusalOf(error) {
11832
+ if (!(error instanceof SparkVaultError) || error instanceof UploadApiError || error.statusCode === undefined)
11833
+ return error;
11834
+ return stagingRefusal(error.code, error.message, error.statusCode, error.retryAfterMs) ?? error;
11835
+ }
11836
+ function cancelledError() {
11837
+ return new UploadApiError('Upload cancelled', 'cancelled', 0);
11838
+ }
11085
11839
  /**
11086
11840
  * A delay that a cancel cuts short: resolves after `ms`, rejects with the
11087
11841
  * canonical cancelled error the moment the signal aborts.
11088
11842
  */
11089
11843
  function abortableDelay(ms, signal) {
11090
11844
  return new Promise((resolve, reject) => {
11091
- const cancelled = () => new UploadApiError('Upload cancelled', 'cancelled', 0);
11092
11845
  if (signal.aborted) {
11093
- reject(cancelled());
11846
+ reject(cancelledError());
11094
11847
  return;
11095
11848
  }
11096
11849
  const onAbort = () => {
11097
11850
  clearTimeout(timer);
11098
- reject(cancelled());
11851
+ reject(cancelledError());
11099
11852
  };
11100
11853
  const timer = setTimeout(() => {
11101
11854
  signal.removeEventListener('abort', onAbort);
@@ -11104,63 +11857,162 @@ function abortableDelay(ms, signal) {
11104
11857
  signal.addEventListener('abort', onAbort, { once: true });
11105
11858
  });
11106
11859
  }
11860
+ /** Whether the browser knows it has no network: `onLine` false is definite, true is only a hope. */
11861
+ function isOffline() {
11862
+ return typeof navigator !== 'undefined' && navigator.onLine === false;
11863
+ }
11107
11864
  /**
11108
- * Whether a failed transfer request is worth another attempt. Every retrying
11109
- * stage of an upload asks this one question:
11110
- *
11111
- * - the chunk PATCH loop — may this chunk be re-sent?
11112
- * - the resume-HEAD loop — may the session's offset be re-read?
11113
- * - the finalization receipt — may publication be asked about again?
11114
- *
11115
- * A transport-level failure (status 0 — a dropped connection, a timeout, or
11116
- * the inactivity watchdog aborting a silent socket) says nothing about whether
11117
- * the request reached Forge, 409 is Forge's documented "another writer holds
11118
- * the session lease; re-check and retry" (on the receipt: a finalizer is
11119
- * running right now), and a 5xx is a server-side blip. Every other outcome is
11120
- * the server's considered answer about this exact request — a rejected offset,
11121
- * a bad ISTK, a vanished session, or a 2xx carrying a protocol-violating
11122
- * offset — and re-sending would only earn it again. A cancelled session is the
11123
- * user's decision, never a failure to retry.
11865
+ * Resolve once the browser is back online; reject with the canonical
11866
+ * cancelled error the moment the session closes, which is the only bound on
11867
+ * the wait.
11124
11868
  */
11125
- function isRetryableTransferFailure(error) {
11126
- if (!(error instanceof UploadApiError))
11127
- return false;
11128
- // Verdicts, not blips: a cancel is the user's decision, and an invalid or
11129
- // misaligned offset is a protocol violation the server would only repeat.
11130
- // The code exclusion is load-bearing for the statusCode-0 sites (the resume
11131
- // and misalignment guards); patchChunk's own invalid_offset rides a 2xx
11132
- // status the heuristic below would reject anyway.
11133
- if (error.code === 'cancelled' || error.code === 'invalid_offset')
11134
- return false;
11135
- const status = error.statusCode ?? 0;
11136
- return status === 0 || status === 409 || status >= 500;
11869
+ function waitUntilOnline(signal) {
11870
+ return new Promise((resolve, reject) => {
11871
+ if (signal.aborted) {
11872
+ reject(cancelledError());
11873
+ return;
11874
+ }
11875
+ const settle = (outcome) => {
11876
+ globalThis.removeEventListener('online', onOnline);
11877
+ signal.removeEventListener('abort', onAbort);
11878
+ outcome();
11879
+ };
11880
+ const onOnline = () => settle(resolve);
11881
+ const onAbort = () => settle(() => reject(cancelledError()));
11882
+ globalThis.addEventListener('online', onOnline);
11883
+ signal.addEventListener('abort', onAbort, { once: true });
11884
+ // The network may have come back between the caller's check and these
11885
+ // listeners, and its `online` event would then never arrive.
11886
+ if (!isOffline())
11887
+ settle(resolve);
11888
+ });
11889
+ }
11890
+ /** A failed request of this upload's transfer; anything else is rethrown as it is. */
11891
+ function transferFailure(error) {
11892
+ if (error instanceof UploadApiError)
11893
+ return error;
11894
+ throw error;
11895
+ }
11896
+ /**
11897
+ * The session the upload ran in is gone (cancelled, expired, or its file
11898
+ * removed): only a new upload from byte 0 can store the file, which the caller
11899
+ * starts (`ingots.upload` / `createUpload` again, or the widget's next upload).
11900
+ */
11901
+ function sessionGoneError(failure) {
11902
+ return new UploadApiError(SESSION_GONE_MESSAGE, 'session_gone', failure.statusCode ?? 0, { status: failure.statusCode, ...failure.details }, { verdict: TRANSFER_VERDICT.GONE, retryAfterMs: null, offset: null, coreCode: null });
11903
+ }
11904
+ /**
11905
+ * Wait out the backoff of a failed request, spending a retry of the upload's
11906
+ * budget, or of a deferred one, spending none for as long as the idle limit
11907
+ * allows; never shorter than the answer's `Retry-After`, and longer with
11908
+ * every failure and deferral since the last progress. Throws an answer no
11909
+ * retry follows as it is, and the last failure, or the deferral, once the
11910
+ * budget is spent. While the browser is offline a failure spends nothing: the
11911
+ * wait is for the network to come back (or the session to close), and the
11912
+ * idle clock starts over when it does.
11913
+ */
11914
+ async function waitToRetry(budget, failure, jitterKey, sessionSignal) {
11915
+ const { verdict, retryAfterMs } = failure;
11916
+ if (verdict === TRANSFER_VERDICT.DEFERRED) {
11917
+ if (!budget.deferred(retryAfterMs))
11918
+ throw failure;
11919
+ }
11920
+ else if (verdict !== TRANSFER_VERDICT.RETRY) {
11921
+ throw failure;
11922
+ }
11923
+ else if (isOffline()) {
11924
+ await waitUntilOnline(sessionSignal);
11925
+ budget.alive();
11926
+ return;
11927
+ }
11928
+ else if (!budget.failed(verdict, retryAfterMs)) {
11929
+ throw failure;
11930
+ }
11931
+ const delayMs = retryDelayMs({
11932
+ attempt: budget.attempt,
11933
+ retryAfterMs,
11934
+ jitterKey,
11935
+ });
11936
+ await abortableDelay(delayMs, sessionSignal);
11137
11937
  }
11138
11938
  /**
11139
11939
  * A server's error body, reduced to something safe to carry on an error:
11140
11940
  * whitespace collapsed and length clipped, so an HTML error page or a stack
11141
- * trace can never become the payload.
11941
+ * trace can never become the payload. The clip is only for what the error
11942
+ * carries: the body is read whole first ({@link readTransferAnswer}).
11142
11943
  */
11143
11944
  const ERROR_DETAIL_MAX_CHARS = 200;
11144
11945
  function summarizeErrorBody(body) {
11145
11946
  return body.replace(/\s+/g, ' ').trim().slice(0, ERROR_DETAIL_MAX_CHARS);
11146
11947
  }
11948
+ /**
11949
+ * What the transfer policy makes of a transfer request's answer, and the
11950
+ * error it throws when it is not a 2xx. A failed answer's body is read whole
11951
+ * by the SDK's one reader of a failed answer ({@link apiFailureOf}), so the
11952
+ * code Core ended the upload with reaches the policy however long Core's
11953
+ * sentence is, and an answer with no body (a HEAD's) names it in
11954
+ * `X-Upload-Refusal`: a final refusal throws `upload_refused` in Core's own
11955
+ * words (this SDK's for a HEAD's), Core's code in `details.coreCode`, and a
11956
+ * new upload is no remedy. The receipt's deferral throws
11957
+ * `upload_received_publishing`, which the upload only ever throws once the
11958
+ * idle limit ends the asking. Any other failure throws the request's own
11959
+ * copy, the server's detail and any other code of Core's in `details` (a gone
11960
+ * session's, which the upload reports as `session_gone`).
11961
+ *
11962
+ * @param answer - The status, the headers, and the body's whole text (empty for a 2xx)
11963
+ */
11964
+ function readTransferAnswer(answer, read) {
11965
+ const served = answer.body ? apiFailureOf(answer) : null;
11966
+ const outcome = classifyTransferResponse({
11967
+ status: answer.status,
11968
+ headers: answer.header,
11969
+ details: served?.details ?? null,
11970
+ receipt: read.receipt,
11971
+ });
11972
+ if (outcome.verdict === TRANSFER_VERDICT.OK)
11973
+ return { outcome, failure: null };
11974
+ const { status } = answer;
11975
+ if (outcome.verdict === TRANSFER_VERDICT.REFUSED && outcome.coreCode !== null) {
11976
+ return { outcome, failure: uploadRefusedError(outcome.coreCode, served?.message ?? null, status, outcome) };
11977
+ }
11978
+ if (outcome.verdict === TRANSFER_VERDICT.DEFERRED) {
11979
+ return {
11980
+ outcome,
11981
+ failure: new UploadApiError(RECEIVED_PUBLISHING_MESSAGE, 'upload_received_publishing', status, { status }, outcome),
11982
+ };
11983
+ }
11984
+ const detail = summarizeErrorBody(answer.body);
11985
+ return {
11986
+ outcome,
11987
+ failure: new UploadApiError(read.failureMessage, read.code, status, {
11988
+ status,
11989
+ ...(detail ? { serverDetail: detail } : {}),
11990
+ ...(outcome.coreCode !== null ? { coreCode: outcome.coreCode } : {}),
11991
+ }, outcome),
11992
+ };
11993
+ }
11147
11994
  const SESSION_CREATION = {
11148
11995
  name: 'Upload session creation',
11149
11996
  code: 'tus_create_failed',
11150
- serverFailureMessage: 'The upload could not be started: the server did not open an upload session.',
11997
+ failureMessage: 'The upload could not be started: the server did not open an upload session.',
11151
11998
  networkMessage: 'Unable to start the upload. Please check your connection and try again.',
11999
+ receipt: false,
11152
12000
  };
11153
12001
  const RESUME_CHECK = {
11154
12002
  name: 'Upload resume check',
11155
12003
  code: 'resume_check_failed',
11156
- serverFailureMessage: 'Upload could not be resumed: the server no longer recognizes this upload session.',
12004
+ failureMessage: 'Upload could not be resumed: the server no longer recognizes this upload session.',
11157
12005
  networkMessage: 'Unable to resume upload. Please check your connection and try again.',
12006
+ receipt: false,
12007
+ timeoutMs: HEAD_AND_RECEIPT_TIMEOUT_MS,
11158
12008
  };
11159
12009
  const FINALIZATION_CHECK = {
11160
12010
  name: 'Upload finalization check',
11161
12011
  code: 'finalization_check_failed',
11162
- serverFailureMessage: 'Upload could not be confirmed: the server did not finalize the file.',
12012
+ failureMessage: 'Upload could not be confirmed: the server did not finalize the file.',
11163
12013
  networkMessage: 'Unable to confirm upload. Please check your connection and try again.',
12014
+ receipt: true,
12015
+ timeoutMs: HEAD_AND_RECEIPT_TIMEOUT_MS,
11164
12016
  };
11165
12017
  class UploadApi extends SparkVaultApi {
11166
12018
  constructor(config) {
@@ -11176,8 +12028,23 @@ class UploadApi extends SparkVaultApi {
11176
12028
  this.vaultInfoMemo = new Map();
11177
12029
  this.config = config;
11178
12030
  }
11179
- makeError(message, code, statusCode, details) {
11180
- return new UploadApiError(message, code, statusCode, details);
12031
+ /**
12032
+ * The shared transport's errors. It raises a request that got no answer (a
12033
+ * dropped connection, a timeout) with status 0, which the transfer policy
12034
+ * retries, a cancel aside; a refused API call it raises with its status is
12035
+ * Core's verdict, never a transfer's, so of the policy's reading it carries
12036
+ * only the floor Core named (`retryAfterMs`), for whoever acts on the
12037
+ * refusal — and Core's final refusal of the upload a call stages is that
12038
+ * upload's `upload_refused` ({@link stagingRefusal}).
12039
+ */
12040
+ makeError(message, code, statusCode, details, retryAfterMs = null) {
12041
+ const refused = statusCode > 0 ? stagingRefusal(code, message, statusCode, retryAfterMs) : null;
12042
+ if (refused)
12043
+ return refused;
12044
+ const unanswered = statusCode === 0 && code !== 'cancelled';
12045
+ return new UploadApiError(message, code, statusCode, details, unanswered
12046
+ ? classifyTransferResponse({ status: 0 })
12047
+ : { verdict: TRANSFER_VERDICT.REFUSED, retryAfterMs, offset: null, coreCode: null });
11181
12048
  }
11182
12049
  /**
11183
12050
  * Issue a request to a Core route and unwrap the standard `{ data, meta }`
@@ -11294,13 +12161,22 @@ class UploadApi extends SparkVaultApi {
11294
12161
  * every server-reported offset, and honors the session abort signal plus
11295
12162
  * per-request timeouts.
11296
12163
  *
11297
- * A chunk that fails in transit is retried against the session's *true*
11298
- * offset rather than failing the whole transfer — see {@link CHUNK_MAX_ATTEMPTS}
11299
- * and {@link readResumeOffset}.
12164
+ * Every answer is read through the transfer policy
12165
+ * (`@sparkvault/app-sdk/transfer-retry`) and every retry spends one budget
12166
+ * ({@link TusTransfer}). A chunk that fails in transit is resent only from
12167
+ * an offset the server just named — a 409's own `Upload-Offset` at once,
12168
+ * otherwise a HEAD after the backoff ({@link offsetAfterFailure}); a session
12169
+ * the server no longer holds throws `session_gone`, which only a new upload
12170
+ * recovers from (any code of Core's the server named rides
12171
+ * `details.coreCode`); an upload Core refused for good (a full storage pool,
12172
+ * a later upload that replaced it) throws `upload_refused` in Core's words,
12173
+ * which no new upload recovers from. While the browser is offline, the loop
12174
+ * waits for the network instead of spending attempts.
11300
12175
  *
11301
12176
  * Resolves only once the server has confirmed finalization
11302
12177
  * ({@link confirmServerFinalized}), so a caller that gets a resolved promise
11303
- * is always looking at a published ingot.
12178
+ * is always looking at a published ingot; a publication the server still
12179
+ * defers at the idle limit throws `upload_received_publishing`.
11304
12180
  */
11305
12181
  async uploadFileToForge(file, forgeUrl, onProgress) {
11306
12182
  if (typeof XMLHttpRequest === 'undefined') {
@@ -11316,15 +12192,21 @@ class UploadApi extends SparkVaultApi {
11316
12192
  // The session this upload runs in: a close ends this upload even if a new
11317
12193
  // session starts before the loop next looks.
11318
12194
  const sessionSignal = this.getAbortSignal();
11319
- const session = await this.createTusSession(target.endpoint, target.istk, file.size);
12195
+ const budget = createTransferBudget();
12196
+ const session = await this.createTusSession(target.endpoint, target.istk, file.size, budget, sessionSignal);
11320
12197
  // Every chunk carries the file's bytes, so the session must live under the
11321
12198
  // endpoint it was created at.
11322
12199
  const uploadUrl = resolveForgeSessionUrl(session.location, target.endpoint);
11323
12200
  if (!uploadUrl) {
11324
12201
  throw new UploadApiError('Upload session is outside the upload endpoint', 'tus_create_failed', 0);
11325
12202
  }
11326
- let offset = 0;
11327
- let failedAttempts = 0;
12203
+ const transfer = {
12204
+ uploadUrl,
12205
+ totalSize: file.size,
12206
+ chunkSize: session.chunkSize,
12207
+ budget,
12208
+ sessionSignal,
12209
+ };
11328
12210
  // Retries make raw progress non-monotonic (a chunk that streamed to 90%
11329
12211
  // then failed re-reports from its start on resend); callers get only the
11330
12212
  // high-water mark so a progress bar never runs backwards.
@@ -11337,55 +12219,90 @@ class UploadApi extends SparkVaultApi {
11337
12219
  }
11338
12220
  }
11339
12221
  : undefined;
11340
- while (offset < file.size) {
12222
+ let offset = 0;
12223
+ for (;;) {
11341
12224
  if (sessionSignal.aborted) {
11342
- throw new UploadApiError('Upload cancelled', 'cancelled', 0);
12225
+ throw cancelledError();
12226
+ }
12227
+ // One exit, one receipt: however the loop learned that every byte is on
12228
+ // the server (a chunk's 204, a HEAD, a 409), publication is confirmed
12229
+ // before the upload resolves.
12230
+ if (offset === file.size) {
12231
+ const receipt = await this.confirmServerFinalized(transfer);
12232
+ if (receipt.published)
12233
+ return;
12234
+ offset = receipt.resumeAt;
12235
+ continue;
11343
12236
  }
11344
12237
  const chunkEnd = Math.min(offset + session.chunkSize, file.size);
11345
12238
  try {
11346
- offset = await this.patchChunk(uploadUrl, file.slice(offset, chunkEnd), offset, file.size, monotonicProgress);
11347
- failedAttempts = 0;
11348
- continue;
12239
+ offset = await this.patchChunk(transfer, file.slice(offset, chunkEnd), offset, monotonicProgress);
12240
+ transfer.budget.progressed();
11349
12241
  }
11350
12242
  catch (error) {
11351
- failedAttempts += 1;
11352
- if (failedAttempts >= CHUNK_MAX_ATTEMPTS || !isRetryableTransferFailure(error)) {
11353
- throw error;
11354
- }
12243
+ offset = await this.offsetAfterFailure(transfer, error, offset);
11355
12244
  }
11356
- // Resync against server truth before ANY further PATCH: the failed
11357
- // chunk may have landed (the acknowledgment was lost), and a PATCH at
11358
- // the client's stale offset is an offset mismatch the server rejects
11359
- // as a terminal 400. The blip that killed the PATCH is also the
11360
- // likeliest thing to kill this HEAD moments later, so the HEAD is
11361
- // retried out of the same per-position budget — the backoff races the
11362
- // session's abort signal so cancellation stays prompt.
11363
- let serverOffset;
11364
- for (;;) {
11365
- await abortableDelay(CHUNK_RETRY_BASE_MS * 2 ** (failedAttempts - 1), sessionSignal);
11366
- try {
11367
- serverOffset = await this.readResumeOffset(uploadUrl, file.size, session.chunkSize);
11368
- break;
11369
- }
11370
- catch (headError) {
11371
- if (!isRetryableTransferFailure(headError)) {
11372
- throw headError;
11373
- }
11374
- failedAttempts += 1;
11375
- if (failedAttempts >= CHUNK_MAX_ATTEMPTS) {
11376
- throw headError;
11377
- }
12245
+ }
12246
+ }
12247
+ /**
12248
+ * Where the upload stands after a failed chunk PATCH, in the server's words:
12249
+ * a 409's own `Upload-Offset` at once, otherwise the session's HEAD after
12250
+ * the backoff. The failed chunk may have landed with its answer lost, and a
12251
+ * PATCH at the client's stale offset is refused, so no chunk is ever sent
12252
+ * again at an offset the server did not just name. The blip that killed the
12253
+ * PATCH is also the likeliest thing to kill the HEAD moments later, so the
12254
+ * HEAD is retried the same way, out of the same budget.
12255
+ */
12256
+ async offsetAfterFailure(transfer, error, sentOffset) {
12257
+ let failure = transferFailure(error);
12258
+ for (;;) {
12259
+ if (failure.verdict === TRANSFER_VERDICT.RESYNC) {
12260
+ return this.resyncedOffset(transfer, failure, sentOffset);
12261
+ }
12262
+ await this.backOff(transfer, failure);
12263
+ try {
12264
+ const serverOffset = await this.readResumeOffset(transfer);
12265
+ if (serverOffset > sentOffset) {
12266
+ // Bytes reached the server despite the failure, so the transfer is
12267
+ // alive: the budget starts over rather than being spent down across
12268
+ // the many chunks of a large file.
12269
+ transfer.budget.progressed();
11378
12270
  }
12271
+ return serverOffset;
11379
12272
  }
11380
- if (serverOffset > offset) {
11381
- // Bytes reached the server despite the failure, so the transfer is
11382
- // alive: the budget is earned back rather than spent down across the
11383
- // many chunks of a large file.
11384
- failedAttempts = 0;
12273
+ catch (headError) {
12274
+ failure = transferFailure(headError);
11385
12275
  }
11386
- offset = serverOffset;
11387
12276
  }
11388
- await this.confirmServerFinalized(uploadUrl, file.size);
12277
+ }
12278
+ /**
12279
+ * Continue from the offset a 409 named, at once and without a HEAD: the
12280
+ * server just said where the session stands. Past what this client sent,
12281
+ * the server holds more than it knew, which is progress; anywhere else the
12282
+ * answer contradicts the request, so it spends the budget like any failure
12283
+ * and repeating it ends the upload.
12284
+ */
12285
+ resyncedOffset(transfer, failure, sentOffset) {
12286
+ const offset = this.checkResumeOffset(failure.serverOffset, transfer);
12287
+ if (offset > sentOffset) {
12288
+ transfer.budget.progressed();
12289
+ }
12290
+ else if (!transfer.budget.failed(TRANSFER_VERDICT.RESYNC)) {
12291
+ throw failure;
12292
+ }
12293
+ return offset;
12294
+ }
12295
+ /**
12296
+ * Wait out the backoff of a failed or deferred request to the upload's
12297
+ * session ({@link waitToRetry}, keyed by the session URL), or throw: a gone
12298
+ * session as `session_gone`, an answer no retry follows as it is, and the
12299
+ * last failure, or the deferral, once the budget is spent.
12300
+ */
12301
+ async backOff(transfer, failure) {
12302
+ if (failure.verdict === TRANSFER_VERDICT.GONE) {
12303
+ throw sessionGoneError(failure);
12304
+ }
12305
+ await waitToRetry(transfer.budget, failure, transfer.uploadUrl, transfer.sessionSignal);
11389
12306
  }
11390
12307
  /**
11391
12308
  * Confirm the server finalized a fully received upload — the one receipt
@@ -11399,42 +12316,62 @@ class UploadApi extends SparkVaultApi {
11399
12316
  * re-drive — it short-circuits to 204 on an already-finalized session, and
11400
12317
  * on a received-but-unfinalized one it answers only after publication.
11401
12318
  *
11402
- * A 409 means another writer is inside the finalizer right now; that is the
11403
- * outcome the budget exists for, so the retry waits it out rather than
11404
- * failing a transfer that is about to succeed. A 400 is the opposite — the
11405
- * server is behind the offset we claim — and fails immediately.
12319
+ * While another request finalizes the receipt answers 409 with
12320
+ * `Retry-After`, polled again after the policy's backoff as a failure; while
12321
+ * the publication is deferred it answers 503 with `Retry-After`, a deferral
12322
+ * the receipt is polled through without spending a failure, each ask after
12323
+ * a longer backoff, until the idle limit throws
12324
+ * `upload_received_publishing`: every byte is on the server, which finishes
12325
+ * the publication on its own. A 503 naming no `Retry-After` is no deferral
12326
+ * of Forge's, so it is polled as a failure. A 400 is the server's verdict
12327
+ * and fails immediately, as does the refusal Core decided
12328
+ * (`upload_refused`); a 409 naming an earlier offset means bytes are
12329
+ * missing, and the upload continues from there.
11406
12330
  */
11407
- async confirmServerFinalized(uploadUrl, totalSize) {
12331
+ async confirmServerFinalized(transfer) {
11408
12332
  let consecutiveTimeouts = 0;
11409
- for (let attempt = 1;; attempt++) {
12333
+ for (;;) {
11410
12334
  try {
11411
- await this.tusRequest(uploadUrl, {
12335
+ await this.tusRequest(transfer.uploadUrl, {
11412
12336
  method: 'PATCH',
11413
12337
  headers: {
11414
12338
  'Tus-Resumable': TUS_VERSION,
11415
- 'Upload-Offset': String(totalSize),
12339
+ 'Upload-Offset': String(transfer.totalSize),
11416
12340
  'Content-Type': 'application/offset+octet-stream',
11417
12341
  },
11418
12342
  }, FINALIZATION_CHECK);
11419
- return;
12343
+ return { published: true };
11420
12344
  }
11421
12345
  catch (error) {
11422
- const timedOut = error instanceof UploadApiError && error.code === 'timeout';
12346
+ const failure = transferFailure(error);
11423
12347
  // Any answer at all — a 409 above all — proves someone is on the other
11424
12348
  // end, so the timeout tally starts over.
11425
- consecutiveTimeouts = timedOut ? consecutiveTimeouts + 1 : 0;
11426
- if (attempt >= FINALIZE_MAX_ATTEMPTS ||
11427
- consecutiveTimeouts >= FINALIZE_MAX_CONSECUTIVE_TIMEOUTS ||
11428
- !isRetryableTransferFailure(error)) {
11429
- throw error;
12349
+ consecutiveTimeouts = failure.code === 'timeout' ? consecutiveTimeouts + 1 : 0;
12350
+ if (consecutiveTimeouts >= FINALIZE_MAX_CONSECUTIVE_TIMEOUTS) {
12351
+ throw failure;
12352
+ }
12353
+ if (failure.verdict === TRANSFER_VERDICT.RESYNC) {
12354
+ const resumeAt = this.resyncedOffset(transfer, failure, transfer.totalSize);
12355
+ if (resumeAt < transfer.totalSize)
12356
+ return { published: false, resumeAt };
12357
+ continue;
11430
12358
  }
11431
- await abortableDelay(FINALIZE_RETRY_MS, this.getAbortSignal());
12359
+ await this.backOff(transfer, failure);
11432
12360
  }
11433
12361
  }
11434
12362
  }
11435
12363
  /**
11436
- * Read the offset a failed chunk should resume from — the one place a
11437
- * server-reported resume point is judged.
12364
+ * Read the offset a failed chunk should resume from, from the session's
12365
+ * HEAD. At the full offset it proves receipt only, published or not, so the
12366
+ * loop then takes the receipt.
12367
+ */
12368
+ async readResumeOffset(transfer) {
12369
+ return this.checkResumeOffset(await this.headUploadOffset(transfer.uploadUrl, RESUME_CHECK), transfer);
12370
+ }
12371
+ /**
12372
+ * Judge an offset the server named for the upload to resume from — a HEAD's,
12373
+ * or a 409's `Upload-Offset` — the one place a server-reported resume point
12374
+ * is judged.
11438
12375
  *
11439
12376
  * Forge commits a chunk before it answers, so a PATCH that died in transit
11440
12377
  * may have landed in full or not at all (never in part — the chunk object
@@ -11442,21 +12379,19 @@ class UploadApi extends SparkVaultApi {
11442
12379
  * persisted offset knows which, and the client's arithmetic is worthless
11443
12380
  * here.
11444
12381
  *
11445
- * Two contracts disqualify an answer. TUS sanity: an offset past the
11446
- * declared total would end the loop early and report a partial upload as
11447
- * complete, the same trap {@link patchChunk} guards against on a PATCH's own
11448
- * offset. Forge chunk granularity: a session advances only in whole
11449
- * committed chunks, so an offset that is neither chunk-aligned nor the file
11450
- * end is a corrupt session, and resuming from it would send a short
11451
- * non-final chunk Forge rejects anyway.
12382
+ * Two contracts disqualify an answer (`resumeOffsetProblem`). TUS sanity: an
12383
+ * offset past the declared total would end the loop early and report a
12384
+ * partial upload as complete, the same trap {@link patchChunk} guards
12385
+ * against on a PATCH's own offset. Forge chunk granularity: a session
12386
+ * advances only in whole committed chunks, so an offset that is neither
12387
+ * chunk-aligned nor the file end is a corrupt session, and resuming from it
12388
+ * would send a short non-final chunk Forge rejects anyway.
11452
12389
  */
11453
- async readResumeOffset(uploadUrl, totalSize, chunkSize) {
11454
- const offset = await this.headUploadOffset(uploadUrl, RESUME_CHECK);
11455
- if (offset > totalSize) {
11456
- throw new UploadApiError(`Server returned invalid upload offset (${offset})`, 'invalid_offset', 0);
11457
- }
11458
- if (offset % chunkSize !== 0 && offset !== totalSize) {
11459
- throw new UploadApiError(`Server returned misaligned upload offset (${offset})`, 'invalid_offset', 0);
12390
+ checkResumeOffset(offset, transfer) {
12391
+ const problem = resumeOffsetProblem(offset, transfer);
12392
+ if (offset === null || problem !== null) {
12393
+ const shape = problem === RESUME_OFFSET_PROBLEM.MISALIGNED ? 'misaligned' : 'invalid';
12394
+ throw new UploadApiError(`Server returned ${shape} upload offset (${offset})`, 'invalid_offset', 0);
11460
12395
  }
11461
12396
  return offset;
11462
12397
  }
@@ -11464,16 +12399,39 @@ class UploadApi extends SparkVaultApi {
11464
12399
  * Create the TUS upload session. Forge reads only `Tus-Resumable`,
11465
12400
  * `Upload-Length`, and `X-ISTK` on create, and returns the session URL in
11466
12401
  * `Location` (possibly relative) plus its chunk size in `X-Chunk-Size`.
12402
+ *
12403
+ * A create the transfer policy calls RETRY (no answer, 408, 425, 429, a 5xx)
12404
+ * is sent again under the upload's budget: Forge refuses such a create
12405
+ * before it claims the token, or hands the claim back on a transient
12406
+ * key-service failure (503 + `Retry-After`), so the same ISTK opens the
12407
+ * session on a later attempt. Every other answer is final, a 401 included:
12408
+ * the token was already used, by an earlier attempt whose answer was lost,
12409
+ * and no `Location` survives to continue that session from. No session URL
12410
+ * exists yet to spread the retries by, and the ISTK never feeds one, so
12411
+ * they spread by a key of the endpoint (`transferJitterKey`).
11467
12412
  */
11468
- async createTusSession(endpoint, istk, totalSize) {
11469
- const response = await this.tusRequest(endpoint, {
11470
- method: 'POST',
11471
- headers: {
11472
- 'Tus-Resumable': TUS_VERSION,
11473
- 'Upload-Length': String(totalSize),
11474
- 'X-ISTK': istk,
11475
- },
11476
- }, SESSION_CREATION);
12413
+ async createTusSession(endpoint, istk, totalSize, budget, sessionSignal) {
12414
+ const jitterKey = transferJitterKey(endpoint);
12415
+ let response;
12416
+ for (;;) {
12417
+ try {
12418
+ ({ response } = await this.tusRequest(endpoint, {
12419
+ method: 'POST',
12420
+ headers: {
12421
+ 'Tus-Resumable': TUS_VERSION,
12422
+ 'Upload-Length': String(totalSize),
12423
+ 'X-ISTK': istk,
12424
+ },
12425
+ }, SESSION_CREATION));
12426
+ break;
12427
+ }
12428
+ catch (error) {
12429
+ const failure = transferFailure(error);
12430
+ if (failure.verdict !== TRANSFER_VERDICT.RETRY)
12431
+ throw failure;
12432
+ await waitToRetry(budget, failure, jitterKey, sessionSignal);
12433
+ }
12434
+ }
11477
12435
  const location = response.headers.get('Location');
11478
12436
  if (!location) {
11479
12437
  throw new UploadApiError('Server did not return upload location', 'tus_create_failed', response.status);
@@ -11486,23 +12444,31 @@ class UploadApi extends SparkVaultApi {
11486
12444
  if (chunkSize === null) {
11487
12445
  throw new UploadApiError('Server did not return a valid X-Chunk-Size', 'tus_create_failed', response.status, { header: 'X-Chunk-Size', received: chunkSizeHeader });
11488
12446
  }
12447
+ // The session exists: the server confirmed progress.
12448
+ budget.progressed();
11489
12449
  return { location, chunkSize };
11490
12450
  }
11491
12451
  /**
11492
12452
  * PATCH one chunk with XMLHttpRequest (fetch exposes no upload progress).
11493
- * Resolves with the server-confirmed offset for the next iteration.
12453
+ * Resolves with the server-confirmed offset for the next iteration; a
12454
+ * failure carries the transfer policy's verdict on its answer, read here.
11494
12455
  *
11495
12456
  * The server's `Upload-Offset` is validated, never trusted: it must be a
11496
- * finite number that strictly advances past this chunk's start (this client
12457
+ * whole number that strictly advances past this chunk's start (this client
11497
12458
  * never sends an empty chunk, so a non-advancing 2xx would loop forever)
11498
12459
  * and never exceeds the file size (an inflated offset would skip real
11499
12460
  * chunks and report a partial upload as success).
12461
+ *
12462
+ * Bytes leaving are a sign of life: they restart the transfer's idle clock
12463
+ * (never its failure count, which only the server's confirmation resets), so
12464
+ * a slow chunk is never counted as idle time.
11500
12465
  */
11501
- patchChunk(uploadUrl, chunk, chunkStart, totalSize, onProgress) {
12466
+ patchChunk(transfer, chunk, chunkStart, onProgress) {
12467
+ const { uploadUrl, totalSize, budget } = transfer;
11502
12468
  return new Promise((resolve, reject) => {
11503
- const closeSignal = this.getAbortSignal();
12469
+ const closeSignal = transfer.sessionSignal;
11504
12470
  if (closeSignal.aborted) {
11505
- reject(new UploadApiError('Upload cancelled', 'cancelled', 0));
12471
+ reject(cancelledError());
11506
12472
  return;
11507
12473
  }
11508
12474
  const xhr = new XMLHttpRequest();
@@ -11532,28 +12498,33 @@ class UploadApi extends SparkVaultApi {
11532
12498
  closeSignal.addEventListener('abort', onCloseAbort);
11533
12499
  xhr.upload.onprogress = (event) => {
11534
12500
  resetWatchdog();
12501
+ budget.alive();
11535
12502
  if (event.lengthComputable) {
11536
12503
  onProgress?.(chunkStart + event.loaded, totalSize);
11537
12504
  }
11538
12505
  };
11539
12506
  xhr.onload = () => {
11540
- if (xhr.status >= 200 && xhr.status < 300) {
11541
- const header = xhr.getResponseHeader('Upload-Offset');
11542
- const newOffset = header !== null ? parseInt(header, 10) : NaN;
11543
- if (!Number.isFinite(newOffset) || newOffset <= chunkStart || newOffset > totalSize) {
11544
- finish(() => reject(new UploadApiError(`Server returned invalid upload offset (${newOffset})`, 'invalid_offset', xhr.status)));
11545
- return;
11546
- }
11547
- finish(() => resolve(newOffset));
12507
+ const { status } = xhr;
12508
+ const { outcome, failure } = readTransferAnswer({
12509
+ status,
12510
+ header: (name) => xhr.getResponseHeader(name),
12511
+ body: status >= 200 && status < 300 ? '' : xhr.responseText,
12512
+ }, { receipt: false, code: 'chunk_upload_failed', failureMessage: `Chunk upload failed with status ${status}` });
12513
+ if (failure) {
12514
+ finish(() => reject(failure));
12515
+ return;
11548
12516
  }
11549
- else {
11550
- finish(() => reject(new UploadApiError(`Chunk upload failed with status ${xhr.status}`, 'chunk_upload_failed', xhr.status)));
12517
+ const newOffset = outcome.offset;
12518
+ if (newOffset === null || newOffset <= chunkStart || newOffset > totalSize) {
12519
+ finish(() => reject(new UploadApiError(`Server returned invalid upload offset (${xhr.getResponseHeader('Upload-Offset')})`, 'invalid_offset', xhr.status)));
12520
+ return;
11551
12521
  }
12522
+ finish(() => resolve(newOffset));
11552
12523
  };
11553
- xhr.onerror = () => finish(() => reject(new UploadApiError('Chunk upload failed', 'network_error', 0)));
12524
+ xhr.onerror = () => finish(() => reject(new UploadApiError('Chunk upload failed', 'network_error', 0, undefined, classifyTransferResponse({ status: 0 }))));
11554
12525
  xhr.onabort = () => finish(() => reject(timedOut
11555
- ? new UploadApiError(`Chunk upload timed out after ${CHUNK_INACTIVITY_TIMEOUT_MS}ms of inactivity`, 'timeout', 0)
11556
- : new UploadApiError('Upload cancelled', 'cancelled', 0)));
12526
+ ? new UploadApiError(`Chunk upload timed out after ${CHUNK_INACTIVITY_TIMEOUT_MS}ms of inactivity`, 'timeout', 0, undefined, classifyTransferResponse({ status: 0 }))
12527
+ : cancelledError()));
11557
12528
  xhr.open('PATCH', uploadUrl);
11558
12529
  xhr.setRequestHeader('Tus-Resumable', TUS_VERSION);
11559
12530
  xhr.setRequestHeader('Upload-Offset', String(chunkStart));
@@ -11569,13 +12540,11 @@ class UploadApi extends SparkVaultApi {
11569
12540
  * @param check - Which caller this read serves; shapes the failure copy.
11570
12541
  */
11571
12542
  async headUploadOffset(uploadUrl, check) {
11572
- const response = await this.tusRequest(uploadUrl, { method: 'HEAD', headers: { 'Tus-Resumable': TUS_VERSION } }, check);
11573
- const header = response.headers.get('Upload-Offset');
11574
- const offset = header !== null ? parseInt(header, 10) : NaN;
11575
- if (!Number.isFinite(offset) || offset < 0) {
12543
+ const { response, outcome } = await this.tusRequest(uploadUrl, { method: 'HEAD', headers: { 'Tus-Resumable': TUS_VERSION } }, check);
12544
+ if (outcome.offset === null) {
11576
12545
  throw new UploadApiError(`${check.name} returned an invalid offset`, check.code, response.status);
11577
12546
  }
11578
- return offset;
12547
+ return outcome.offset;
11579
12548
  }
11580
12549
  /**
11581
12550
  * Issue one bodyless TUS request: the single transport behind every
@@ -11585,26 +12554,33 @@ class UploadApi extends SparkVaultApi {
11585
12554
  * Uses the raw response rather than the JSON envelope helper: TUS responses
11586
12555
  * carry an empty body and surface state in headers. Runs through the one SDK
11587
12556
  * transport (session close signal, deadline, failure classification) and
11588
- * resolves only on a 2xx so no caller has to re-check `response.ok`.
12557
+ * resolves only on a 2xx, with the transfer policy's reading of it, so no
12558
+ * caller has to re-check `response.ok`; a non-2xx throws carrying the
12559
+ * policy's verdict on its answer.
11589
12560
  *
11590
12561
  * @param check - Which caller this request serves; shapes the failure copy.
11591
12562
  */
11592
12563
  tusRequest(uploadUrl, init, check) {
12564
+ const timeoutMs = check.timeoutMs ?? this.timeoutMs;
11593
12565
  return this.send(uploadUrl, { method: init.method, headers: init.headers }, {
11594
12566
  cancelled: 'Upload cancelled',
11595
- timeout: `${check.name} timed out after ${this.timeoutMs}ms`,
12567
+ timeout: `${check.name} timed out after ${timeoutMs}ms`,
11596
12568
  network: check.networkMessage,
11597
12569
  }, async (response) => {
11598
- if (!response.ok) {
11599
- // Read the body even though the message does not need it: an unread
11600
- // body pins its connection, and a retried receipt would strand one per
11601
- // attempt. What it says is the only server-side detail this client
11602
- // ever sees, so it rides along in `details` for support.
11603
- const detail = summarizeErrorBody(await response.text().catch(() => ''));
11604
- throw new UploadApiError(check.serverFailureMessage, check.code, response.status, { status: response.status, ...(detail ? { serverDetail: detail } : {}) });
11605
- }
11606
- return response;
11607
- });
12570
+ // A failed answer's body is read whole: an unread body pins its
12571
+ // connection, and a retried receipt would strand one per attempt.
12572
+ // Forge's error envelope in it is what names the refusal Core
12573
+ // decided, and otherwise the only server-side detail this client
12574
+ // ever sees, so it rides along in `details` for support.
12575
+ const { outcome, failure } = readTransferAnswer({
12576
+ status: response.status,
12577
+ header: (name) => response.headers.get(name),
12578
+ body: response.ok ? '' : await response.text().catch(() => ''),
12579
+ }, check);
12580
+ if (failure)
12581
+ throw failure;
12582
+ return { response, outcome };
12583
+ }, timeoutMs);
11608
12584
  }
11609
12585
  }
11610
12586
 
@@ -13849,7 +14825,34 @@ class UploadRenderer {
13849
14825
  statusCode: error.statusCode,
13850
14826
  });
13851
14827
  }
13852
- else if (error.statusCode === 404) {
14828
+ else if (error.code === 'upload_received_publishing') {
14829
+ // Every byte reached the server, which is still saving the file and
14830
+ // finishes it on its own: nothing failed, and nothing is left to do.
14831
+ // The host still hears it through onError, with this code, which
14832
+ // tells it never to upload the file again.
14833
+ this.setState({
14834
+ view: 'error',
14835
+ title: 'Upload Received',
14836
+ message: error.message,
14837
+ code: error.code,
14838
+ statusCode: error.statusCode,
14839
+ });
14840
+ }
14841
+ else if (error.code === 'upload_refused') {
14842
+ // Core refused the upload for good, in its own words (whom to contact
14843
+ // about a full storage pool, or the later upload that replaced this
14844
+ // one): a sentence that never asks for the file again.
14845
+ this.setState({
14846
+ view: 'error',
14847
+ title: 'Upload Not Saved',
14848
+ message: error.message,
14849
+ code: error.code,
14850
+ statusCode: error.statusCode,
14851
+ });
14852
+ }
14853
+ else if (error.statusCode === 404 && error.code !== 'session_gone') {
14854
+ // A vault or upload route that does not exist. A gone upload session
14855
+ // can answer 404 too, and its own sentence says what became of the file.
13853
14856
  this.setState({
13854
14857
  view: 'error',
13855
14858
  title: 'Upload Page Not Found',
@@ -14473,38 +15476,13 @@ function readIngotAccess(entry) {
14473
15476
  };
14474
15477
  }
14475
15478
 
14476
- /**
14477
- * Whether sending the SAME request again can succeed, read from its HTTP
14478
- * status: the one retry rule every client and every provider adapter applies.
14479
- *
14480
- * A retry rule restated beside every client drifts, and the copy that drifted
14481
- * decides whether a deliverable message is retried or abandoned, or whether a
14482
- * download is tried again. Each caller keeps its provider's own extras on top of
14483
- * this rule (a success body, a dead-token reason, a vendor error name).
14484
- *
14485
- * Browser-safe and import-free: sdk-js bundles it and sdk-mobile mirrors it.
14486
- */
14487
-
14488
- /**
14489
- * Is this HTTP status one a retry of the same request can turn into a success?
14490
- *
14491
- * RFC 9110: 408 means the server never received the whole request, 429 that it
14492
- * throttled it, and a 5xx that it failed; every other status is the server's
14493
- * verdict on this exact request. A caller that got no response at all (a network
14494
- * error, a timeout) has no status to pass and decides that case itself.
14495
- *
14496
- * @param {number} status
14497
- * @returns {boolean}
14498
- */
14499
- function isTransientHttpStatus(status) {
14500
- return status === 408 || status === 429 || status >= 500;
14501
- }
14502
-
14503
15479
  /**
14504
15480
  * The one browser transfer for a signed ingot download link: fetch it into a
14505
- * Blob under liveness bounds. `sv.ingots.download` uses it, and so can a caller
15481
+ * Blob under liveness bounds, resuming from the bytes it holds when the caller
15482
+ * can mint another link. `sv.ingots.download` uses it, and so can a caller
14506
15483
  * that mints its own link (`createDownloadLink`, or its own authenticated
14507
- * call) and needs cancellation, byte progress or the published revision.
15484
+ * call) and needs cancellation, byte progress, resumption or the published
15485
+ * revision.
14508
15486
  */
14509
15487
  /**
14510
15488
  * Time-to-first-byte bound: how long the download host may take to return
@@ -14569,15 +15547,104 @@ function assertDownloadUrl(url, isAllowedHost = isSparkVaultOwnedHostname) {
14569
15547
  }
14570
15548
  /**
14571
15549
  * Fetch a signed download URL as a Blob under liveness bounds: one deadline
14572
- * for the response headers, then an idle deadline rearmed on every body chunk.
14573
- * Nothing caps the transfer as a whole, so file size never decides whether a
14574
- * download can finish. The link is single-use: a caller that retries mints a
14575
- * fresh one first. A link that is not a Forge decrypt URL on an allowed host is
14576
- * refused before anything is sent (assertDownloadUrl).
14577
- */
14578
- async function fetchDownload(url, options = {}) {
14579
- const { signal, onProgress, expectedContentVersion, isAllowedHost } = options;
14580
- assertDownloadUrl(url, isAllowedHost);
15550
+ * for each response's headers, then an idle deadline rearmed on every body
15551
+ * chunk. Nothing caps the transfer as a whole, so file size never decides
15552
+ * whether a download can finish. The link is single-use, so a failed transfer
15553
+ * is retried only through `options.remint`, on a link minted for the retry. A
15554
+ * link that is not a Forge decrypt URL on an allowed host, the first or a
15555
+ * minted one, is refused before anything is sent to it (assertDownloadUrl).
15556
+ */
15557
+ function fetchDownload(url, options = {}) {
15558
+ return runDownload(() => Promise.resolve(url), options);
15559
+ }
15560
+ /**
15561
+ * {@link fetchDownload} for a caller whose every link is minted, the first
15562
+ * included: a mint that fails before any byte has moved is retried under the
15563
+ * same policy as any other failure. `sv.ingots.download` runs this.
15564
+ */
15565
+ function fetchMintedDownload(mint, options = {}) {
15566
+ return runDownload(mint, { ...options, remint: mint });
15567
+ }
15568
+ /** A failure no answer came with (a reset, a deadline, a lost connection): the policy retries it. */
15569
+ const UNANSWERED = classifyTransferResponse({ status: 0 });
15570
+ /** A failure that is this transfer's own verdict (content that is not the file held, a range that does not continue it): final. */
15571
+ const FINAL = { verdict: TRANSFER_VERDICT.REFUSED, retryAfterMs: null, offset: null, coreCode: null };
15572
+ /** `bytes <first>-<last>/<length>`: the one Content-Range form a 206 continuing a download carries. */
15573
+ const CONTENT_RANGE = /^bytes (\d+)-(\d+)\/(\d+)$/;
15574
+ /** A strong entity tag (RFC 9110 §8.8.3): an If-Range never carries a weak one. */
15575
+ const STRONG_ETAG = /^"[^"]*"$/;
15576
+ const CONTENT_CHANGED_MESSAGE = 'The file changed while it was downloading. Please try again.';
15577
+ /**
15578
+ * The transfer: an attempt on the link `firstLink` resolves to, then, while
15579
+ * the transfer policy retries a failure and the caller can mint, one attempt
15580
+ * per minted link, each after the policy's backoff. Retries are bounded by the
15581
+ * policy's budget, failures in a row and time without progress, both of which
15582
+ * start over whenever bytes arrive past what any attempt held.
15583
+ */
15584
+ async function runDownload(firstLink, options) {
15585
+ const { signal, remint } = options;
15586
+ const state = { received: new ReceivedBytes(), budget: createTransferBudget(), held: null, furthest: 0 };
15587
+ // The link carries the ISTK, a credential, which never feeds anything
15588
+ // observable such as a delay: the retries spread by a key of the download's
15589
+ // kind and start instead (transferJitterKey).
15590
+ const jitterKey = transferJitterKey('download');
15591
+ for (let nextLink = firstLink;;) {
15592
+ const result = await attemptWith(nextLink, state, options);
15593
+ if (result.ok)
15594
+ return result.download;
15595
+ if (signal?.aborted)
15596
+ throw signal.reason;
15597
+ const { error, outcome } = result;
15598
+ if (!remint || outcome.verdict !== TRANSFER_VERDICT.RETRY || !state.budget.failed(TRANSFER_VERDICT.RETRY, outcome.retryAfterMs)) {
15599
+ throw error;
15600
+ }
15601
+ await waitBeforeRetry(retryDelayMs({ attempt: state.budget.attempt, retryAfterMs: outcome.retryAfterMs, jitterKey }), signal);
15602
+ // A link is spent once its request has reached Forge, whatever came back:
15603
+ // every retry fetches one minted for it.
15604
+ nextLink = remint;
15605
+ }
15606
+ }
15607
+ /**
15608
+ * One attempt: take its link, minted when the source mints, hold it to the
15609
+ * transfer-URL rule, then fetch it. A mint that fails is read the way a
15610
+ * transfer answer is ({@link mintOutcome}).
15611
+ */
15612
+ async function attemptWith(source, state, options) {
15613
+ let link;
15614
+ try {
15615
+ link = await source();
15616
+ assertDownloadUrl(link, options.isAllowedHost);
15617
+ }
15618
+ catch (error) {
15619
+ return { ok: false, error, outcome: mintOutcome(error) };
15620
+ }
15621
+ return attemptDownload(link, state, options);
15622
+ }
15623
+ /**
15624
+ * The transfer policy's reading of a failed mint. The HTTP client read the
15625
+ * answer when it built the error: its status gives the verdict (a refused link
15626
+ * is a 400, so final) and the `Retry-After` it named rides on the error
15627
+ * (`retryAfterMs`), so a mint Core defers waits out Core's floor exactly as a
15628
+ * deferred Forge answer does. A failure with no status got no answer.
15629
+ */
15630
+ function mintOutcome(error) {
15631
+ if (!(error instanceof SparkVaultError) || typeof error.statusCode !== 'number')
15632
+ return UNANSWERED;
15633
+ return { ...classifyTransferResponse({ status: error.statusCode }), retryAfterMs: error.retryAfterMs };
15634
+ }
15635
+ /**
15636
+ * Fetch one link: the rest of the file held, conditioned on its validator,
15637
+ * when the bytes held can be resumed, the whole file otherwise. A 206 appends
15638
+ * to the bytes held; any whole-file answer replaces them, so a file replaced
15639
+ * since the bytes held began starts over as its new content, never spliced
15640
+ * onto the old.
15641
+ */
15642
+ async function attemptDownload(link, state, options) {
15643
+ const { signal, onProgress, expectedContentVersion } = options;
15644
+ const { received } = state;
15645
+ const resume = resumePoint(state);
15646
+ if (!resume)
15647
+ received.discard();
14581
15648
  const controller = new AbortController();
14582
15649
  const abortFromCaller = () => controller.abort(signal?.reason);
14583
15650
  if (signal?.aborted) {
@@ -14586,61 +15653,231 @@ async function fetchDownload(url, options = {}) {
14586
15653
  else {
14587
15654
  signal?.addEventListener('abort', abortFromCaller, { once: true });
14588
15655
  }
15656
+ // What a whole download is, once the answer has named its content.
15657
+ const whole = (content) => ({
15658
+ ok: true,
15659
+ download: { blob: received.toBlob(content.contentType), contentVersion: content.contentVersion },
15660
+ });
15661
+ let held = null;
15662
+ let delivered = false;
14589
15663
  try {
14590
- const response = await withDeadline(fetch(url, { signal: controller.signal }), DOWNLOAD_TTFB_TIMEOUT_MS, controller, 'Download timed out waiting for response headers');
15664
+ const response = await withDeadline(fetch(link, resume
15665
+ ? { signal: controller.signal, headers: { Range: `bytes=${resume.at}-`, 'If-Range': resume.validator } }
15666
+ : { signal: controller.signal }), DOWNLOAD_TTFB_TIMEOUT_MS, controller, 'Download timed out waiting for response headers');
14591
15667
  if (!response.ok) {
14592
- // The TTFB timer cleared when headers arrived, so nothing else would ever
14593
- // reap this connection: abort it or a retrying caller leaks one socket
14594
- // per failed attempt.
14595
- controller.abort();
14596
- throw new SparkVaultError(`Download failed with status ${response.status}`, 'download_failed', response.status);
15668
+ return {
15669
+ ok: false,
15670
+ error: new SparkVaultError(`Download failed with status ${response.status}`, 'download_failed', response.status),
15671
+ outcome: classifyTransferResponse({ status: response.status, headers: (name) => response.headers.get(name) }),
15672
+ };
14597
15673
  }
14598
- const contentVersion = response.headers.get('x-content-version') || null;
14599
- if (expectedContentVersion && contentVersion && contentVersion !== expectedContentVersion) {
14600
- controller.abort();
14601
- throw new SparkVaultError('The file changed while it was downloading. Please try again.', 'content_changed');
14602
- }
14603
- const contentType = response.headers.get('content-type') ?? '';
14604
- const total = Number(response.headers.get('content-length')) || 0;
14605
- // Safari 10.1-14.4 ships fetch without `Response.body`, and the SDK's
14606
- // support floor reaches back into that range. There the transfer keeps
14607
- // whole-transfer wall-clock semantics: blob() surfaces no chunk arrivals,
14608
- // so there is no liveness to observe.
14609
- if (!response.body) {
14610
- const blob = await withDeadline(response.blob(), DOWNLOAD_BODY_TIMEOUT_MS, controller, 'Download timed out');
14611
- onProgress?.(blob.size, total);
14612
- return { blob, contentVersion };
14613
- }
14614
- const reader = response.body.getReader();
14615
- const parts = [];
14616
- let pending = [];
14617
- let pendingBytes = 0;
14618
- let loaded = 0;
14619
- for (;;) {
14620
- const { done, value } = await withDeadline(reader.read(), DOWNLOAD_IDLE_TIMEOUT_MS, controller, 'Download stalled: no data received');
14621
- if (done)
14622
- break;
14623
- pending.push(value);
14624
- pendingBytes += value.byteLength;
14625
- loaded += value.byteLength;
14626
- onProgress?.(loaded, total);
14627
- if (pendingBytes >= DOWNLOAD_BLOB_FLUSH_BYTES) {
14628
- // Fetch body chunks are ArrayBuffer-backed; the lib types over-generalize
14629
- // to ArrayBufferLike, which the Blob constructor's part type rejects.
14630
- parts.push(new Blob(pending));
14631
- pending = [];
14632
- pendingBytes = 0;
15674
+ if (resume && response.status === 206) {
15675
+ const continued = continuation(response, resume);
15676
+ if (continued instanceof SparkVaultError)
15677
+ return { ok: false, error: continued, outcome: FINAL };
15678
+ held = continued;
15679
+ }
15680
+ else {
15681
+ received.discard();
15682
+ const contentVersion = response.headers.get('x-content-version') || null;
15683
+ if (expectedContentVersion && contentVersion && contentVersion !== expectedContentVersion) {
15684
+ return { ok: false, error: new SparkVaultError(CONTENT_CHANGED_MESSAGE, 'content_changed'), outcome: FINAL };
14633
15685
  }
15686
+ held = {
15687
+ contentType: response.headers.get('content-type') ?? '',
15688
+ contentVersion,
15689
+ total: Number(response.headers.get('content-length')) || 0,
15690
+ validator: resumeValidator(response.headers),
15691
+ };
14634
15692
  }
14635
- if (pending.length > 0) {
14636
- parts.push(new Blob(pending));
15693
+ // Named before the body is read: a body that fails part-way leaves the
15694
+ // next attempt what it needs to resume.
15695
+ state.held = held;
15696
+ await readBody(response, controller, state, held.total, onProgress);
15697
+ delivered = true;
15698
+ return whole(held);
15699
+ }
15700
+ catch (error) {
15701
+ if (error instanceof ProgressCallbackFailure)
15702
+ return { ok: false, error: error.failure, outcome: FINAL };
15703
+ // Every declared byte arrived before the body failed to end: the file is
15704
+ // whole, and a resume would ask for a range past its end (a 416).
15705
+ if (held !== null && held.total > 0 && received.loaded === held.total && !signal?.aborted) {
15706
+ return whole(held);
14637
15707
  }
14638
- return { blob: new Blob(parts, { type: contentType }), contentVersion };
15708
+ return { ok: false, error, outcome: UNANSWERED };
14639
15709
  }
14640
15710
  finally {
15711
+ // An attempt that ends short of its body leaves a connection that no
15712
+ // deadline will reap any more: abort it, or every retry leaks one socket.
15713
+ if (!delivered)
15714
+ controller.abort();
14641
15715
  signal?.removeEventListener('abort', abortFromCaller);
14642
15716
  }
14643
15717
  }
15718
+ /** The resume point the bytes held allow, or null when the attempt fetches the whole file. */
15719
+ function resumePoint(state) {
15720
+ const { held, received } = state;
15721
+ if (held === null || held.validator === null || received.loaded === 0)
15722
+ return null;
15723
+ return { held, validator: held.validator, at: received.loaded };
15724
+ }
15725
+ /**
15726
+ * What a resume conditions its range on: the response's ETag when it is
15727
+ * strong and the response accepts byte ranges, or null. An edge that rewrites
15728
+ * a body (compression) weakens its ETag, and then nothing binds the bytes held
15729
+ * to the bytes a range would be served from.
15730
+ */
15731
+ function resumeValidator(headers) {
15732
+ const etag = headers.get('etag');
15733
+ const acceptsBytes = (headers.get('accept-ranges') ?? '')
15734
+ .split(',')
15735
+ .some((unit) => unit.trim().toLowerCase() === 'bytes');
15736
+ return etag !== null && STRONG_ETAG.test(etag) && acceptsBytes ? etag : null;
15737
+ }
15738
+ /**
15739
+ * The content a 206 answering a resume continues, or why it cannot: it must
15740
+ * start at the first byte lacking, run to the end of the same file, and name
15741
+ * the publication the bytes held are when it names one (a server that honored
15742
+ * the range despite a changed publication would splice two of them).
15743
+ */
15744
+ function continuation(response, resume) {
15745
+ const etag = response.headers.get('etag');
15746
+ if (etag !== null && etag.replace(/^W\//, '') !== resume.validator) {
15747
+ return new SparkVaultError(CONTENT_CHANGED_MESSAGE, 'content_changed');
15748
+ }
15749
+ const range = CONTENT_RANGE.exec(response.headers.get('content-range') ?? '');
15750
+ const [first, last, length] = range ? range.slice(1).map(Number) : [NaN, NaN, NaN];
15751
+ const { total } = resume.held;
15752
+ if (first !== resume.at || last !== length - 1 || (total > 0 && length !== total)) {
15753
+ return new SparkVaultError('The resumed download did not continue where it stopped', 'download_failed', response.status, { reason: 'range_mismatch' });
15754
+ }
15755
+ return { ...resume.held, total: length };
15756
+ }
15757
+ /**
15758
+ * Read a response body onto the bytes held under liveness bounds, reporting
15759
+ * cumulative progress against the file's declared length.
15760
+ */
15761
+ async function readBody(response, controller, state, total, onProgress) {
15762
+ const { received } = state;
15763
+ // Safari 10.1-14.4 ships fetch without `Response.body`, and the SDK's
15764
+ // support floor reaches back into that range. There the transfer keeps
15765
+ // whole-transfer wall-clock semantics: blob() surfaces no chunk arrivals,
15766
+ // so there is no liveness to observe, and a failure holds no bytes to
15767
+ // resume from.
15768
+ if (!response.body) {
15769
+ received.appendBlob(await withDeadline(response.blob(), DOWNLOAD_BODY_TIMEOUT_MS, controller, 'Download timed out'));
15770
+ noteArrival(state);
15771
+ reportProgress(onProgress, received.loaded, total);
15772
+ return;
15773
+ }
15774
+ const reader = response.body.getReader();
15775
+ for (;;) {
15776
+ const { done, value } = await withDeadline(reader.read(), DOWNLOAD_IDLE_TIMEOUT_MS, controller, 'Download stalled: no data received');
15777
+ if (done)
15778
+ return;
15779
+ received.append(value);
15780
+ noteArrival(state);
15781
+ reportProgress(onProgress, received.loaded, total);
15782
+ }
15783
+ }
15784
+ /**
15785
+ * The caller's progress callback failed: its own error, which no retry can
15786
+ * cure. Unmarked, it would read as a transfer that lost its connection, and a
15787
+ * callback that throws on every report would cost a mint and a request per
15788
+ * chunk until the file completed.
15789
+ */
15790
+ class ProgressCallbackFailure extends Error {
15791
+ constructor(failure) {
15792
+ super('onProgress threw');
15793
+ this.failure = failure;
15794
+ }
15795
+ }
15796
+ function reportProgress(onProgress, loaded, total) {
15797
+ if (!onProgress)
15798
+ return;
15799
+ try {
15800
+ onProgress(loaded, total);
15801
+ }
15802
+ catch (failure) {
15803
+ throw new ProgressCallbackFailure(failure);
15804
+ }
15805
+ }
15806
+ /** Bytes arrived: past the most any attempt held, progress; short of it, a sign of life. */
15807
+ function noteArrival(state) {
15808
+ if (state.received.loaded > state.furthest) {
15809
+ state.furthest = state.received.loaded;
15810
+ state.budget.progressed();
15811
+ }
15812
+ else {
15813
+ state.budget.alive();
15814
+ }
15815
+ }
15816
+ /** Wait out a retry's backoff; the caller's cancel ends the wait with the signal's reason. */
15817
+ function waitBeforeRetry(ms, signal) {
15818
+ return new Promise((resolve, reject) => {
15819
+ if (signal?.aborted) {
15820
+ reject(signal.reason);
15821
+ return;
15822
+ }
15823
+ const onAbort = () => {
15824
+ clearTimeout(timer);
15825
+ reject(signal?.reason);
15826
+ };
15827
+ const timer = setTimeout(() => {
15828
+ signal?.removeEventListener('abort', onAbort);
15829
+ resolve();
15830
+ }, ms);
15831
+ signal?.addEventListener('abort', onAbort, { once: true });
15832
+ });
15833
+ }
15834
+ /**
15835
+ * The bytes a transfer holds, in the order they arrived: at most one window
15836
+ * on the JS heap, the rest folded into Blob parts the platform's blob store
15837
+ * owns, so heap growth is capped whatever the file's size.
15838
+ */
15839
+ class ReceivedBytes {
15840
+ constructor() {
15841
+ this.parts = [];
15842
+ this.pending = [];
15843
+ this.pendingBytes = 0;
15844
+ this.count = 0;
15845
+ }
15846
+ get loaded() {
15847
+ return this.count;
15848
+ }
15849
+ append(chunk) {
15850
+ this.pending.push(chunk);
15851
+ this.pendingBytes += chunk.byteLength;
15852
+ this.count += chunk.byteLength;
15853
+ if (this.pendingBytes >= DOWNLOAD_BLOB_FLUSH_BYTES)
15854
+ this.fold();
15855
+ }
15856
+ appendBlob(blob) {
15857
+ this.fold();
15858
+ this.parts.push(blob);
15859
+ this.count += blob.size;
15860
+ }
15861
+ discard() {
15862
+ this.parts = [];
15863
+ this.pending = [];
15864
+ this.pendingBytes = 0;
15865
+ this.count = 0;
15866
+ }
15867
+ toBlob(type) {
15868
+ this.fold();
15869
+ return new Blob(this.parts, { type });
15870
+ }
15871
+ fold() {
15872
+ if (this.pending.length === 0)
15873
+ return;
15874
+ // Fetch body chunks are ArrayBuffer-backed; the lib types over-generalize
15875
+ // to ArrayBufferLike, which the Blob constructor's part type rejects.
15876
+ this.parts.push(new Blob(this.pending));
15877
+ this.pending = [];
15878
+ this.pendingBytes = 0;
15879
+ }
15880
+ }
14644
15881
 
14645
15882
  /**
14646
15883
  * Folders Module
@@ -14815,8 +16052,6 @@ const NAME_CONFLICT_POLICIES = ['upsert', 'complete_pending', 'refuse', 'new_nam
14815
16052
  * (shared with the public upload widget), with server-side finalization and
14816
16053
  * download-host allowlisting enforced — no per-size branching.
14817
16054
  */
14818
- const DOWNLOAD_MAX_ATTEMPTS = 3;
14819
- const DOWNLOAD_RETRY_BASE_MS = 500;
14820
16055
  class IngotsModule {
14821
16056
  constructor(config, http) {
14822
16057
  /** The client's transfer-host allowlist (`allowedDownloadHostPatterns`), as a download link is read against it. */
@@ -14829,7 +16064,10 @@ class IngotsModule {
14829
16064
  *
14830
16065
  * Reserves the ingot record and returns the Forge upload URL (carrying the
14831
16066
  * ISTK upload session token). Use this when you want to drive the TUS
14832
- * transfer yourself; otherwise prefer {@link upload}.
16067
+ * transfer yourself; otherwise prefer {@link upload}. A create another
16068
+ * upload of the same file superseded before its token was issued rejects
16069
+ * with code `upload_refused` (`details.coreCode` UPLOAD_SUPERSEDED): the
16070
+ * later upload is the one kept, so a new upload is no remedy.
14833
16071
  *
14834
16072
  * @example
14835
16073
  * const session = await sv.ingots.createUpload({
@@ -14874,6 +16112,18 @@ class IngotsModule {
14874
16112
  * published, so a resolved promise never stands for a stored file whose
14875
16113
  * ingot never went live.
14876
16114
  *
16115
+ * Transient failures are retried inside the transfer; a session the server
16116
+ * no longer holds (it expired, was cancelled, or its ingot was removed)
16117
+ * rejects with code `session_gone`, and only a new upload session — a new
16118
+ * {@link createUpload}, or {@link upload} again — can store the file. An
16119
+ * upload the server refused for good (the account's storage pool cannot
16120
+ * take it, or a later upload replaced it) rejects with code
16121
+ * `upload_refused`, its message the server's own sentence and its code in
16122
+ * `details.coreCode`: a new upload is no remedy. A publication the server
16123
+ * still defers at the transfer's idle limit rejects with code
16124
+ * `upload_received_publishing`: every byte is received, and the server
16125
+ * finishes the publication on its own, so never upload the file again.
16126
+ *
14877
16127
  * @param options.signal - Cancels this transfer (it rejects with code
14878
16128
  * `cancelled`); other transfers carry on.
14879
16129
  * @param options.onProgress - Bytes sent so far and the file size; never runs backwards.
@@ -14905,7 +16155,10 @@ class IngotsModule {
14905
16155
  * Upload a file as a new ingot (high-level flow).
14906
16156
  *
14907
16157
  * Creates the upload session, streams the file to Forge over TUS, then
14908
- * confirms the server finalized the upload before resolving.
16158
+ * confirms the server finalized the upload before resolving. A file the
16159
+ * server refused for good — another upload of it superseded this one, at
16160
+ * its create or while it streamed, or the storage pool cannot take it —
16161
+ * rejects with code `upload_refused`, as {@link sendUpload} does.
14909
16162
  *
14910
16163
  * @example
14911
16164
  * const ingot = await sv.ingots.upload(unsealed, {
@@ -14931,7 +16184,9 @@ class IngotsModule {
14931
16184
  return this.transferAndFinalize(created, created.created, options.file, options.onProgress);
14932
16185
  }
14933
16186
  /**
14934
- * Replace an existing ingot's content (high-level flow).
16187
+ * Replace an existing ingot's content (high-level flow). Rejects as
16188
+ * {@link upload} does, a replacement another upload of the same ingot
16189
+ * superseded included (`upload_refused`).
14935
16190
  *
14936
16191
  * @example
14937
16192
  * await sv.ingots.replace(unsealed, 'ing_abc', { file: updatedFile });
@@ -14947,7 +16202,9 @@ class IngotsModule {
14947
16202
  content_type: contentType,
14948
16203
  size_bytes: options.file.size,
14949
16204
  ...(options.contentHmac && { content_hmac: options.contentHmac }),
14950
- }, { vat: vault.vatToken });
16205
+ }, { vat: vault.vatToken }).catch((error) => {
16206
+ throw stagingRefusalOf(error);
16207
+ });
14951
16208
  if (!response.data.forge_url) {
14952
16209
  throw new ValidationError('Replace endpoint did not return a Forge upload URL');
14953
16210
  }
@@ -15070,11 +16327,15 @@ class IngotsModule {
15070
16327
  * Create a signed download link for an ingot (discrete primitive).
15071
16328
  *
15072
16329
  * Validates the returned URL against the download-host allowlist. Use this
15073
- * when you want the URL itself; otherwise prefer {@link download}.
16330
+ * when you want the URL itself; otherwise prefer {@link download}. The link
16331
+ * is single-use: Forge claims it the moment a request arrives, so a retry or
16332
+ * a resume needs a link of its own (`fetchDownload`'s `remint`).
15074
16333
  *
15075
16334
  * @example
15076
16335
  * const link = await sv.ingots.createDownloadLink(unsealed, 'ing_abc');
15077
- * window.location.href = link.downloadUrl;
16336
+ * const { blob } = await fetchDownload(link.downloadUrl, {
16337
+ * remint: async () => (await sv.ingots.createDownloadLink(unsealed, 'ing_abc')).downloadUrl,
16338
+ * });
15078
16339
  */
15079
16340
  async createDownloadLink(vault, ingotId) {
15080
16341
  const vaultId = requireVaultId(vault);
@@ -15096,35 +16357,26 @@ class IngotsModule {
15096
16357
  /**
15097
16358
  * Download an ingot as a Blob (high-level flow).
15098
16359
  *
15099
- * Requests a fresh signed link on every attempt (server URLs are
15100
- * short-lived) and retries transient transport failures with exponential
15101
- * backoff. Validation failures (bad host, non-HTTPS) are never retried.
15102
- *
15103
- * Each attempt is bounded by liveness, never by total duration: a deadline
15104
- * on the response headers, then an idle deadline rearmed on every body
15105
- * chunk. A stalled transfer restarts from byte zero: this path requests no
15106
- * byte range, so a full retry is the only recovery.
16360
+ * Every attempt fetches a signed link minted for it ({@link createDownloadLink}:
16361
+ * a link is single-use), under liveness bounds, never a cap on total
16362
+ * duration: a deadline on the response headers, then an idle deadline
16363
+ * rearmed on every body chunk. A failure the platform's transfer policy
16364
+ * retries (`@sparkvault/app-sdk/transfer-retry`: no answer, 408, 425, 429 or
16365
+ * a 5xx, a mint's included) is retried after the policy's backoff, never
16366
+ * sooner than `Retry-After`, until its budget ends. Once bytes have arrived
16367
+ * the retry resumes from the first byte it lacks, conditioned on the
16368
+ * publication's ETag (`If-Range`), so a stall at 90% fetches only the rest;
16369
+ * a file replaced meanwhile starts over as its new content, and one served
16370
+ * with no strong ETag starts over from its first byte. Any other refusal,
16371
+ * and a link that is not a Forge decrypt URL on an allowed host, is final.
15107
16372
  *
15108
16373
  * @example
15109
16374
  * const blob = await sv.ingots.download(unsealed, 'ing_abc');
15110
16375
  * const url = URL.createObjectURL(blob);
15111
16376
  */
15112
16377
  async download(vault, ingotId) {
15113
- let lastError = null;
15114
- for (let attempt = 1; attempt <= DOWNLOAD_MAX_ATTEMPTS; attempt++) {
15115
- try {
15116
- const link = await this.createDownloadLink(vault, ingotId);
15117
- return (await fetchDownload(link.downloadUrl, { isAllowedHost: this.allowsTransferHost })).blob;
15118
- }
15119
- catch (err) {
15120
- lastError = err instanceof Error ? err : new Error(String(err));
15121
- if (!isRetryableDownloadError(lastError) || attempt === DOWNLOAD_MAX_ATTEMPTS) {
15122
- throw lastError;
15123
- }
15124
- await delayExponential(attempt);
15125
- }
15126
- }
15127
- throw lastError ?? new Error('Download failed');
16378
+ const mint = async () => (await this.createDownloadLink(vault, ingotId)).downloadUrl;
16379
+ return (await fetchMintedDownload(mint, { isAllowedHost: this.allowsTransferHost })).blob;
15128
16380
  }
15129
16381
  /**
15130
16382
  * Get an ingot's sharing configuration.
@@ -15246,7 +16498,9 @@ class IngotsModule {
15246
16498
  payload.on_name_conflict = body.onNameConflict;
15247
16499
  }
15248
16500
  const vaultId = requireVaultId(vault);
15249
- const response = await this.http.post(apiPath `/v1/vaults/${vaultId}/ingots`, payload, { vat: vault.vatToken });
16501
+ const response = await this.http.post(apiPath `/v1/vaults/${vaultId}/ingots`, payload, { vat: vault.vatToken }).catch((error) => {
16502
+ throw stagingRefusalOf(error);
16503
+ });
15250
16504
  if (!response.data.forge_url) {
15251
16505
  throw new ValidationError('Upload endpoint did not return a Forge upload URL');
15252
16506
  }
@@ -15327,22 +16581,6 @@ function mapInvite(wire) {
15327
16581
  identityType: wire.identity_type ?? 'email',
15328
16582
  };
15329
16583
  }
15330
- function delayExponential(attempt) {
15331
- return new Promise((resolve) => setTimeout(resolve, DOWNLOAD_RETRY_BASE_MS * 2 ** (attempt - 1)));
15332
- }
15333
- /**
15334
- * True when retrying a failed download can succeed. A validation failure always
15335
- * fails the same way again, and a refused download carries its status, retried
15336
- * only when the platform's retry rule (`@sparkvault/app-sdk/transient`) calls it
15337
- * transient; every other failure (connectivity, an answer that could not be
15338
- * read) is worth another attempt.
15339
- */
15340
- function isRetryableDownloadError(err) {
15341
- if (err instanceof ValidationError)
15342
- return false;
15343
- const status = err instanceof SparkVaultError ? err.statusCode : undefined;
15344
- return typeof status !== 'number' || status < 400 || isTransientHttpStatus(status);
15345
- }
15346
16584
 
15347
16585
  /**
15348
16586
  * Sparks Module
@@ -16052,7 +17290,7 @@ class SparkVault {
16052
17290
  }
16053
17291
  /** Get the SDK version */
16054
17292
  static get version() {
16055
- return '11.0.1';
17293
+ return '11.0.3';
16056
17294
  }
16057
17295
  }
16058
17296
  if (typeof window !== 'undefined') {