@widgetic/file-browser 0.5.47 → 0.5.48

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