@widgetic/file-browser 0.5.48 → 0.5.49
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/actions/dragSelectedToFolder.js +115 -104
- package/dist/components/FolderTree.svelte.d.ts +7 -4
- package/dist/components/core/FileBrowser.svelte +1 -3
- package/dist/components/core/dropzoneClick.js +2 -3
- package/dist/components/previews/FilePreview.svelte.d.ts +2 -2
- package/dist/config.js +3 -4
- package/dist/i18n/context.js +2 -2
- package/dist/i18n/errors.js +1 -2
- package/dist/i18n/messages.js +2 -2
- package/dist/i18n/text.js +2 -2
- package/dist/mediaLibrary/capabilities.js +3 -4
- package/dist/mediaLibrary/context.js +3 -4
- package/dist/mediaLibrary/errors.js +35 -46
- package/dist/mediaLibrary/normalize.js +42 -45
- package/dist/mediaLibrary/paging.js +45 -100
- package/dist/mediaLibrary/resolve.js +95 -214
- package/dist/mediaLibrary/treeOps.js +20 -40
- package/dist/mediaLibrary/urls.js +10 -12
- package/dist/mediaLibrary/widgetic.js +54 -140
- package/dist/stores/dragStore.js +1 -1
- package/dist/stores/fileStore.d.ts +3 -3
- package/dist/stores/fileStore.js +37 -44
- package/dist/stores/folderCountStore.js +11 -12
- package/dist/stores/missingFilesStore.js +3 -3
- package/dist/stores/navigationStore.d.ts +1 -1
- package/dist/stores/navigationStore.js +178 -217
- package/dist/stores/persistentSelectStore.d.ts +1 -1
- package/dist/stores/persistentSelectStore.js +94 -117
- package/dist/stores/searchStore.js +1 -1
- package/dist/stores/uploadApiStore.js +7 -7
- package/dist/stores/viewportStore.js +4 -4
- package/dist/types/index.js +1 -0
- package/dist/utils/apiConfig.js +9 -9
- package/dist/utils/brandKitLibraryTree.js +42 -57
- package/dist/utils/dateUtils.js +9 -11
- package/dist/utils/dragToFolder/batchMoveResult.js +54 -114
- package/dist/utils/dragToFolder/folderDropTarget.js +17 -23
- package/dist/utils/dragToFolder/springStep.js +3 -4
- package/dist/utils/fileGoneProbe.js +16 -65
- package/dist/utils/fileKinds.js +13 -14
- package/dist/utils/fileNames.js +7 -7
- package/dist/utils/fileOperations.js +332 -440
- package/dist/utils/fileTypes.js +14 -19
- package/dist/utils/fileUtils.js +31 -85
- package/dist/utils/folderUtils.js +4 -5
- package/dist/utils/gridLayout.js +7 -7
- package/dist/utils/imagePreviewCache.js +15 -26
- package/dist/utils/imagePreviewFrame.js +13 -13
- package/dist/utils/imagePreviewVisualState.js +4 -5
- package/dist/utils/imageTransform.js +14 -27
- package/dist/utils/itemMenuCapabilities.js +7 -7
- package/dist/utils/libraryTree.js +39 -55
- package/dist/utils/pendingUploadDeletes.js +113 -289
- package/dist/utils/previewKeys.js +1 -1
- package/dist/utils/previewListNavigation.js +11 -13
- package/dist/utils/previewNavigation.js +7 -10
- package/dist/utils/recentFiles.js +6 -16
- package/dist/utils/recentFilesLimit.js +2 -2
- package/dist/utils/removeItems.js +29 -61
- package/dist/utils/resolveFileUrl.js +6 -6
- package/dist/utils/safeText.js +12 -14
- package/dist/utils/searchDropdownPhase.js +2 -2
- package/dist/utils/searchItems.js +14 -30
- package/dist/utils/searchNavigation.js +5 -5
- package/dist/utils/uploadAuth.js +36 -111
- package/dist/utils/uploadDisplayProgress.js +1 -1
- package/dist/utils/uploadLimits.js +66 -138
- package/dist/utils/uploadListReconcile.js +11 -24
- package/dist/utils/uploadPanelDismiss.js +1 -1
- package/dist/utils/uploadPanelProgress.js +4 -4
- package/dist/utils/uploadProgressMath.js +11 -13
- package/dist/utils/uploadRefusals.js +24 -40
- package/dist/utils/uploadResponseMapping.js +8 -9
- package/dist/utils/uploadUiHelpers.js +17 -17
- package/dist/utils/userUploadsStorage.js +133 -270
- package/dist/utils/videoFrame.js +2 -2
- package/dist/utils/widgeticDelete.js +30 -103
- package/dist/utils/widgeticTusUpload.js +105 -189
- package/dist/utils/widgeticUpload.js +62 -130
- package/dist/utils/xhrMultipartUpload.js +116 -164
- package/package.json +1 -1
|
@@ -1,127 +1,54 @@
|
|
|
1
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
2
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
3
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
4
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
5
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
6
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
7
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
8
|
-
});
|
|
9
|
-
};
|
|
10
|
-
var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
11
|
-
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
12
|
-
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
13
|
-
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
14
|
-
function step(op) {
|
|
15
|
-
if (f) throw new TypeError("Generator is already executing.");
|
|
16
|
-
while (g && (g = 0, op[0] && (_ = 0)), _) try {
|
|
17
|
-
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
18
|
-
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
19
|
-
switch (op[0]) {
|
|
20
|
-
case 0: case 1: t = op; break;
|
|
21
|
-
case 4: _.label++; return { value: op[1], done: false };
|
|
22
|
-
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
23
|
-
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
24
|
-
default:
|
|
25
|
-
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
26
|
-
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
27
|
-
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
28
|
-
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
29
|
-
if (t[2]) _.ops.pop();
|
|
30
|
-
_.trys.pop(); continue;
|
|
31
|
-
}
|
|
32
|
-
op = body.call(thisArg, _);
|
|
33
|
-
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
34
|
-
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
35
|
-
}
|
|
36
|
-
};
|
|
37
1
|
import { MediaLibraryError, codeForHttpStatus } from '../mediaLibrary/errors';
|
|
38
2
|
import { withTokenRetriedOnce } from './uploadAuth';
|
|
39
3
|
function authHeaders(token) {
|
|
40
|
-
return { Authorization:
|
|
4
|
+
return { Authorization: `Bearer ${token.replace(/^Bearer\s+/i, '')}` };
|
|
41
5
|
}
|
|
42
6
|
/**
|
|
43
7
|
* Soft-deletes one upload row via DELETE /v1/uploads/:id.
|
|
44
8
|
*/
|
|
45
|
-
export function deleteUploadFromWidgeticApi(
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
detail = "Delete upload failed (".concat(response.status, ")");
|
|
67
|
-
_c.label = 2;
|
|
68
|
-
case 2:
|
|
69
|
-
_c.trys.push([2, 4, , 5]);
|
|
70
|
-
return [4 /*yield*/, response.json()];
|
|
71
|
-
case 3:
|
|
72
|
-
errJson = _c.sent();
|
|
73
|
-
detail = (errJson === null || errJson === void 0 ? void 0 : errJson.message) || ((_b = errJson === null || errJson === void 0 ? void 0 : errJson.error) === null || _b === void 0 ? void 0 : _b.message) || detail;
|
|
74
|
-
return [3 /*break*/, 5];
|
|
75
|
-
case 4:
|
|
76
|
-
_a = _c.sent();
|
|
77
|
-
return [3 /*break*/, 5];
|
|
78
|
-
case 5: throw new MediaLibraryError(codeForHttpStatus(response.status), detail, { status: response.status });
|
|
79
|
-
case 6: return [2 /*return*/];
|
|
80
|
-
}
|
|
81
|
-
});
|
|
82
|
-
});
|
|
9
|
+
export async function deleteUploadFromWidgeticApi(config, uploadId, options = {}) {
|
|
10
|
+
const basePath = config.apiBasePath.replace(/\/+$/, '');
|
|
11
|
+
// With the token the page gives now, and once more with a fresh one when the API refuses it (see `uploadAuth.ts`).
|
|
12
|
+
const response = await withTokenRetriedOnce(config, (accessToken) => fetch(`${basePath}/uploads/${encodeURIComponent(uploadId)}`, {
|
|
13
|
+
method: 'DELETE',
|
|
14
|
+
headers: authHeaders(accessToken),
|
|
15
|
+
signal: options.signal,
|
|
16
|
+
}), { signal: options.signal });
|
|
17
|
+
if (response.status === 404)
|
|
18
|
+
return;
|
|
19
|
+
if (!response.ok) {
|
|
20
|
+
let detail = `Delete upload failed (${response.status})`;
|
|
21
|
+
try {
|
|
22
|
+
const errJson = await response.json();
|
|
23
|
+
detail = errJson?.message || errJson?.error?.message || detail;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
/* ignore */
|
|
27
|
+
}
|
|
28
|
+
throw new MediaLibraryError(codeForHttpStatus(response.status), detail, { status: response.status });
|
|
29
|
+
}
|
|
83
30
|
}
|
|
84
31
|
/** Every file id in a folder subtree (depth-first). */
|
|
85
32
|
export function collectFileIdsInSubtree(item) {
|
|
86
|
-
|
|
33
|
+
const ids = [];
|
|
87
34
|
function walk(node) {
|
|
88
35
|
if (node.type === 'file') {
|
|
89
36
|
ids.push(node.id);
|
|
90
37
|
return;
|
|
91
38
|
}
|
|
92
39
|
if (node.type === 'folder' && node.children) {
|
|
93
|
-
for (
|
|
94
|
-
var child = _a[_i];
|
|
40
|
+
for (const child of node.children)
|
|
95
41
|
walk(child);
|
|
96
|
-
}
|
|
97
42
|
}
|
|
98
43
|
}
|
|
99
44
|
walk(item);
|
|
100
45
|
return ids;
|
|
101
46
|
}
|
|
102
47
|
/** Deletes each upload in a folder tree via the Widgetic API, then returns all file ids removed. */
|
|
103
|
-
export function deleteSubtreeUploadsOnApi(
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
case 0:
|
|
110
|
-
fileIds = collectFileIdsInSubtree(item);
|
|
111
|
-
_i = 0, fileIds_1 = fileIds;
|
|
112
|
-
_a.label = 1;
|
|
113
|
-
case 1:
|
|
114
|
-
if (!(_i < fileIds_1.length)) return [3 /*break*/, 4];
|
|
115
|
-
id = fileIds_1[_i];
|
|
116
|
-
return [4 /*yield*/, deleteUploadFromWidgeticApi(config, id, options)];
|
|
117
|
-
case 2:
|
|
118
|
-
_a.sent();
|
|
119
|
-
_a.label = 3;
|
|
120
|
-
case 3:
|
|
121
|
-
_i++;
|
|
122
|
-
return [3 /*break*/, 1];
|
|
123
|
-
case 4: return [2 /*return*/, fileIds];
|
|
124
|
-
}
|
|
125
|
-
});
|
|
126
|
-
});
|
|
48
|
+
export async function deleteSubtreeUploadsOnApi(config, item, options = {}) {
|
|
49
|
+
const fileIds = collectFileIdsInSubtree(item);
|
|
50
|
+
for (const id of fileIds) {
|
|
51
|
+
await deleteUploadFromWidgeticApi(config, id, options);
|
|
52
|
+
}
|
|
53
|
+
return fileIds;
|
|
127
54
|
}
|
|
@@ -1,86 +1,39 @@
|
|
|
1
|
-
var __assign = (this && this.__assign) || function () {
|
|
2
|
-
__assign = Object.assign || function(t) {
|
|
3
|
-
for (var s, i = 1, n = arguments.length; i < n; i++) {
|
|
4
|
-
s = arguments[i];
|
|
5
|
-
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
|
|
6
|
-
t[p] = s[p];
|
|
7
|
-
}
|
|
8
|
-
return t;
|
|
9
|
-
};
|
|
10
|
-
return __assign.apply(this, arguments);
|
|
11
|
-
};
|
|
12
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
13
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
14
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
15
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
16
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
17
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
18
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
19
|
-
});
|
|
20
|
-
};
|
|
21
|
-
var __generator = (this && this.__generator) || function (thisArg, body) {
|
|
22
|
-
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
|
|
23
|
-
return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
|
|
24
|
-
function verb(n) { return function (v) { return step([n, v]); }; }
|
|
25
|
-
function step(op) {
|
|
26
|
-
if (f) throw new TypeError("Generator is already executing.");
|
|
27
|
-
while (g && (g = 0, op[0] && (_ = 0)), _) try {
|
|
28
|
-
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
|
|
29
|
-
if (y = 0, t) op = [op[0] & 2, t.value];
|
|
30
|
-
switch (op[0]) {
|
|
31
|
-
case 0: case 1: t = op; break;
|
|
32
|
-
case 4: _.label++; return { value: op[1], done: false };
|
|
33
|
-
case 5: _.label++; y = op[1]; op = [0]; continue;
|
|
34
|
-
case 7: op = _.ops.pop(); _.trys.pop(); continue;
|
|
35
|
-
default:
|
|
36
|
-
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
|
|
37
|
-
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
|
|
38
|
-
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
|
|
39
|
-
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
|
|
40
|
-
if (t[2]) _.ops.pop();
|
|
41
|
-
_.trys.pop(); continue;
|
|
42
|
-
}
|
|
43
|
-
op = body.call(thisArg, _);
|
|
44
|
-
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
|
|
45
|
-
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
|
|
46
|
-
}
|
|
47
|
-
};
|
|
48
1
|
import * as tus from 'tus-js-client';
|
|
49
2
|
import { mapWidgeticUploadSuccessJson } from './uploadResponseMapping';
|
|
50
3
|
/** Matches api-gateway MULTIPART_MAX_UPLOAD_BYTES — use TUS above this. */
|
|
51
|
-
export
|
|
52
|
-
|
|
4
|
+
export const WIDGETIC_MULTIPART_MAX_BYTES = 10 * 1024 * 1024;
|
|
5
|
+
const DEFAULT_TUS_CHUNK_SIZE = 5 * 1024 * 1024;
|
|
53
6
|
/** The `error.code` api-gateway answers `POST …/complete` with (HTTP 409) while another request still has the upload. */
|
|
54
|
-
|
|
7
|
+
const TUS_UPLOAD_BUSY_CODE = 'TUS_UPLOAD_BUSY';
|
|
55
8
|
/** Pauses before asking again after a "busy" answer: 0.5, 1, 2, 4 and 8 seconds, about 15 seconds in all. */
|
|
56
|
-
|
|
9
|
+
const COMPLETE_BUSY_RETRY_DELAYS_MS = [500, 1000, 2000, 4000, 8000];
|
|
57
10
|
function parseErrorMessage(response, fallback) {
|
|
58
11
|
return response
|
|
59
12
|
.json()
|
|
60
|
-
.then(
|
|
61
|
-
.catch(
|
|
13
|
+
.then((json) => json?.message || json?.error?.message || fallback)
|
|
14
|
+
.catch(() => fallback);
|
|
62
15
|
}
|
|
63
16
|
/** The `error.code` of a failed answer, or undefined when the body is not the API's error envelope. */
|
|
64
17
|
function readErrorCode(response) {
|
|
65
18
|
return response
|
|
66
19
|
.json()
|
|
67
|
-
.then(
|
|
68
|
-
.catch(
|
|
20
|
+
.then((json) => (typeof json?.error?.code === 'string' ? json.error.code : undefined))
|
|
21
|
+
.catch(() => undefined);
|
|
69
22
|
}
|
|
70
23
|
/** Resolves after `delayMs`, or at once when the upload is cancelled meanwhile. */
|
|
71
24
|
function waitBeforeRetry(delayMs, abortSignal) {
|
|
72
|
-
return new Promise(
|
|
73
|
-
if (abortSignal
|
|
25
|
+
return new Promise((resolve) => {
|
|
26
|
+
if (abortSignal?.aborted) {
|
|
74
27
|
resolve();
|
|
75
28
|
return;
|
|
76
29
|
}
|
|
77
|
-
|
|
30
|
+
const finish = () => {
|
|
78
31
|
clearTimeout(timer);
|
|
79
|
-
abortSignal
|
|
32
|
+
abortSignal?.removeEventListener('abort', finish);
|
|
80
33
|
resolve();
|
|
81
34
|
};
|
|
82
|
-
|
|
83
|
-
abortSignal
|
|
35
|
+
const timer = setTimeout(finish, delayMs);
|
|
36
|
+
abortSignal?.addEventListener('abort', finish, { once: true });
|
|
84
37
|
});
|
|
85
38
|
}
|
|
86
39
|
/**
|
|
@@ -89,46 +42,28 @@ function waitBeforeRetry(delayMs, abortSignal) {
|
|
|
89
42
|
* 409 `TUS_UPLOAD_INCOMPLETE` means chunks are missing, and asking again cannot bring them.
|
|
90
43
|
* Returns the last answer; the caller tells success from failure.
|
|
91
44
|
*/
|
|
92
|
-
export function requestTusComplete(
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
return [4 /*yield*/, readErrorCode(response.clone())];
|
|
109
|
-
case 3:
|
|
110
|
-
// Read a copy, so the caller can still read the message of an answer that turns out to be final.
|
|
111
|
-
if ((_c.sent()) !== TUS_UPLOAD_BUSY_CODE)
|
|
112
|
-
return [2 /*return*/, response];
|
|
113
|
-
console.warn("[widgeticTusUpload] Upload is busy; asking again in ".concat(retryDelaysMs[retriesDone], " ms (retry ").concat(retriesDone + 1, " of ").concat(retryDelaysMs.length, ")"));
|
|
114
|
-
return [4 /*yield*/, waitBeforeRetry(retryDelaysMs[retriesDone], options.abortSignal)];
|
|
115
|
-
case 4:
|
|
116
|
-
_c.sent();
|
|
117
|
-
if ((_b = options.abortSignal) === null || _b === void 0 ? void 0 : _b.aborted)
|
|
118
|
-
return [2 /*return*/, response];
|
|
119
|
-
retriesDone += 1;
|
|
120
|
-
_c.label = 5;
|
|
121
|
-
case 5: return [3 /*break*/, 1];
|
|
122
|
-
case 6: return [2 /*return*/];
|
|
123
|
-
}
|
|
124
|
-
});
|
|
125
|
-
});
|
|
45
|
+
export async function requestTusComplete(url, init, options = {}) {
|
|
46
|
+
const retryDelaysMs = options.retryDelaysMs ?? COMPLETE_BUSY_RETRY_DELAYS_MS;
|
|
47
|
+
let retriesDone = 0;
|
|
48
|
+
for (;;) {
|
|
49
|
+
const response = await fetch(url, init);
|
|
50
|
+
if (response.status !== 409 || retriesDone >= retryDelaysMs.length)
|
|
51
|
+
return response;
|
|
52
|
+
// Read a copy, so the caller can still read the message of an answer that turns out to be final.
|
|
53
|
+
if ((await readErrorCode(response.clone())) !== TUS_UPLOAD_BUSY_CODE)
|
|
54
|
+
return response;
|
|
55
|
+
console.warn(`[widgeticTusUpload] Upload is busy; asking again in ${retryDelaysMs[retriesDone]} ms (retry ${retriesDone + 1} of ${retryDelaysMs.length})`);
|
|
56
|
+
await waitBeforeRetry(retryDelaysMs[retriesDone], options.abortSignal);
|
|
57
|
+
if (options.abortSignal?.aborted)
|
|
58
|
+
return response;
|
|
59
|
+
retriesDone += 1;
|
|
60
|
+
}
|
|
126
61
|
}
|
|
127
62
|
function extractTusId(uploadUrl) {
|
|
128
63
|
if (!uploadUrl)
|
|
129
64
|
return null;
|
|
130
|
-
|
|
131
|
-
|
|
65
|
+
const trimmed = uploadUrl.replace(/\/+$/, '');
|
|
66
|
+
const lastSegment = trimmed.split('/').pop();
|
|
132
67
|
return lastSegment || null;
|
|
133
68
|
}
|
|
134
69
|
function mapCompleteResponse(data, file) {
|
|
@@ -137,42 +72,38 @@ function mapCompleteResponse(data, file) {
|
|
|
137
72
|
/**
|
|
138
73
|
* Resumable upload via TUS (POST/PATCH /v1/uploads/tus + POST .../complete).
|
|
139
74
|
*/
|
|
140
|
-
export function uploadToWidgeticApiTus(file, config, options) {
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
var tusUpload = null;
|
|
149
|
-
var settled = false;
|
|
150
|
-
var finish = function (result) {
|
|
151
|
-
var _a;
|
|
75
|
+
export function uploadToWidgeticApiTus(file, config, options = {}) {
|
|
76
|
+
const basePath = config.apiBasePath.replace(/\/+$/, '');
|
|
77
|
+
const token = config.accessToken.replace(/^Bearer\s+/i, '');
|
|
78
|
+
const endpoint = `${basePath}/uploads/tus`;
|
|
79
|
+
return new Promise((resolve) => {
|
|
80
|
+
let tusUpload = null;
|
|
81
|
+
let settled = false;
|
|
82
|
+
const finish = (result) => {
|
|
152
83
|
if (settled)
|
|
153
84
|
return;
|
|
154
85
|
settled = true;
|
|
155
|
-
|
|
86
|
+
options.abortSignal?.removeEventListener('abort', abortHandler);
|
|
156
87
|
if (typeof window !== 'undefined')
|
|
157
88
|
window.removeEventListener('offline', offlineHandler);
|
|
158
89
|
resolve(result);
|
|
159
90
|
};
|
|
160
|
-
|
|
161
|
-
tusUpload
|
|
91
|
+
const abortHandler = () => {
|
|
92
|
+
tusUpload?.abort(true);
|
|
162
93
|
finish({ success: false, error: 'Upload cancelled.' });
|
|
163
94
|
};
|
|
164
95
|
// Going offline leaves the current piece hanging until the browser gives up (often ~15s),
|
|
165
96
|
// and then the retries wait again. Stop that piece as soon as the browser says the connection is gone.
|
|
166
|
-
|
|
167
|
-
tusUpload
|
|
97
|
+
const offlineHandler = () => {
|
|
98
|
+
tusUpload?.abort(true);
|
|
168
99
|
finish({ success: false, error: 'Could not reach the media library.' });
|
|
169
100
|
};
|
|
170
|
-
if (
|
|
101
|
+
if (options.abortSignal?.aborted) {
|
|
171
102
|
resolve({ success: false, error: 'Upload cancelled.' });
|
|
172
103
|
return;
|
|
173
104
|
}
|
|
174
|
-
|
|
175
|
-
|
|
105
|
+
options.abortSignal?.addEventListener('abort', abortHandler, { once: true });
|
|
106
|
+
const metadata = {
|
|
176
107
|
filename: file.name,
|
|
177
108
|
filetype: file.type || 'application/octet-stream',
|
|
178
109
|
context_type: config.contextType || 'content-property',
|
|
@@ -183,96 +114,81 @@ export function uploadToWidgeticApiTus(file, config, options) {
|
|
|
183
114
|
if (config.conversationId)
|
|
184
115
|
metadata.conversation_id = config.conversationId;
|
|
185
116
|
tusUpload = new tus.Upload(file, {
|
|
186
|
-
endpoint
|
|
117
|
+
endpoint,
|
|
187
118
|
chunkSize: DEFAULT_TUS_CHUNK_SIZE,
|
|
188
119
|
retryDelays: [0, 400, 800],
|
|
189
|
-
onShouldRetry:
|
|
190
|
-
var _a, _b;
|
|
120
|
+
onShouldRetry: (error) => {
|
|
191
121
|
if (typeof navigator !== 'undefined' && navigator.onLine === false)
|
|
192
122
|
return false;
|
|
193
|
-
|
|
123
|
+
const status = error.originalResponse?.getStatus?.();
|
|
194
124
|
return status !== 0;
|
|
195
125
|
},
|
|
196
|
-
metadata
|
|
126
|
+
metadata,
|
|
197
127
|
headers: {
|
|
198
|
-
Authorization:
|
|
128
|
+
Authorization: `Bearer ${token}`,
|
|
199
129
|
},
|
|
200
|
-
onError:
|
|
201
|
-
var _a, _b;
|
|
130
|
+
onError: (error) => {
|
|
202
131
|
console.error('[widgeticTusUpload] TUS error:', error);
|
|
203
132
|
// A refusal from the server (for example 401 for an expired token) carries its status; a lost connection does not.
|
|
204
|
-
|
|
205
|
-
finish(
|
|
133
|
+
const refusedWithStatus = error.originalResponse?.getStatus?.();
|
|
134
|
+
finish({
|
|
135
|
+
success: false,
|
|
136
|
+
error: error.message || 'TUS upload failed.',
|
|
137
|
+
...(typeof refusedWithStatus === 'number' && { status: refusedWithStatus }),
|
|
138
|
+
});
|
|
206
139
|
},
|
|
207
|
-
onProgress:
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
(_a = options.onProgress) === null || _a === void 0 ? void 0 : _a.call(options, { bytesUploaded: bytesUploaded, bytesTotal: bytesTotal, percentage: percentage });
|
|
140
|
+
onProgress: (bytesUploaded, bytesTotal) => {
|
|
141
|
+
const percentage = bytesTotal > 0 ? Math.round((bytesUploaded / bytesTotal) * 100) : 0;
|
|
142
|
+
options.onProgress?.({ bytesUploaded, bytesTotal, percentage });
|
|
211
143
|
},
|
|
212
|
-
onSuccess:
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
if (!!completeResponse.ok) return [3 /*break*/, 4];
|
|
240
|
-
// Cancelled while waiting to ask again: say so, instead of repeating the server's "busy" answer.
|
|
241
|
-
if ((_b = options.abortSignal) === null || _b === void 0 ? void 0 : _b.aborted) {
|
|
242
|
-
finish({ success: false, error: 'Upload cancelled.' });
|
|
243
|
-
return [2 /*return*/];
|
|
244
|
-
}
|
|
245
|
-
return [4 /*yield*/, parseErrorMessage(completeResponse, "Complete failed (".concat(completeResponse.status, ")"))];
|
|
246
|
-
case 3:
|
|
247
|
-
detail = _d.sent();
|
|
248
|
-
finish({ success: false, error: detail, status: completeResponse.status });
|
|
249
|
-
return [2 /*return*/];
|
|
250
|
-
case 4: return [4 /*yield*/, completeResponse.json()];
|
|
251
|
-
case 5:
|
|
252
|
-
json = _d.sent();
|
|
253
|
-
data = ((_c = json === null || json === void 0 ? void 0 : json.data) !== null && _c !== void 0 ? _c : json);
|
|
254
|
-
finish(mapCompleteResponse(data, file));
|
|
255
|
-
return [3 /*break*/, 7];
|
|
256
|
-
case 6:
|
|
257
|
-
error_1 = _d.sent();
|
|
258
|
-
console.error('[widgeticTusUpload] Complete request failed:', error_1);
|
|
259
|
-
finish({
|
|
260
|
-
success: false,
|
|
261
|
-
error: error_1 instanceof Error ? error_1.message : 'Failed to finalize upload.',
|
|
262
|
-
});
|
|
263
|
-
return [3 /*break*/, 7];
|
|
264
|
-
case 7: return [2 /*return*/];
|
|
144
|
+
onSuccess: async () => {
|
|
145
|
+
if (settled)
|
|
146
|
+
return;
|
|
147
|
+
// Chunks are on the server; finalize/processing may take a while.
|
|
148
|
+
options.onAwaitingResponse?.();
|
|
149
|
+
const tusId = extractTusId(tusUpload?.url);
|
|
150
|
+
if (!tusId) {
|
|
151
|
+
finish({ success: false, error: 'TUS upload finished without upload id.' });
|
|
152
|
+
return;
|
|
153
|
+
}
|
|
154
|
+
try {
|
|
155
|
+
const completeResponse = await requestTusComplete(`${endpoint}/${tusId}/complete`, {
|
|
156
|
+
method: 'POST',
|
|
157
|
+
headers: {
|
|
158
|
+
Authorization: `Bearer ${token}`,
|
|
159
|
+
'Content-Type': 'application/json',
|
|
160
|
+
},
|
|
161
|
+
}, { abortSignal: options.abortSignal });
|
|
162
|
+
if (!completeResponse.ok) {
|
|
163
|
+
// Cancelled while waiting to ask again: say so, instead of repeating the server's "busy" answer.
|
|
164
|
+
if (options.abortSignal?.aborted) {
|
|
165
|
+
finish({ success: false, error: 'Upload cancelled.' });
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
const detail = await parseErrorMessage(completeResponse, `Complete failed (${completeResponse.status})`);
|
|
169
|
+
finish({ success: false, error: detail, status: completeResponse.status });
|
|
170
|
+
return;
|
|
265
171
|
}
|
|
266
|
-
|
|
267
|
-
|
|
172
|
+
const json = await completeResponse.json();
|
|
173
|
+
const data = (json?.data ?? json);
|
|
174
|
+
finish(mapCompleteResponse(data, file));
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
console.error('[widgeticTusUpload] Complete request failed:', error);
|
|
178
|
+
finish({
|
|
179
|
+
success: false,
|
|
180
|
+
error: error instanceof Error ? error.message : 'Failed to finalize upload.',
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
},
|
|
268
184
|
});
|
|
269
185
|
if (typeof window !== 'undefined')
|
|
270
186
|
window.addEventListener('offline', offlineHandler);
|
|
271
|
-
tusUpload.findPreviousUploads().then(
|
|
187
|
+
tusUpload.findPreviousUploads().then((previousUploads) => {
|
|
272
188
|
if (previousUploads.length > 0) {
|
|
273
|
-
tusUpload
|
|
189
|
+
tusUpload?.resumeFromPreviousUpload(previousUploads[0]);
|
|
274
190
|
}
|
|
275
|
-
tusUpload
|
|
191
|
+
tusUpload?.start();
|
|
276
192
|
});
|
|
277
193
|
});
|
|
278
194
|
}
|