@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.
Files changed (81) hide show
  1. package/dist/actions/dragSelectedToFolder.js +115 -104
  2. package/dist/components/FolderTree.svelte.d.ts +7 -4
  3. package/dist/components/core/FileBrowser.svelte +1 -3
  4. package/dist/components/core/dropzoneClick.js +2 -3
  5. package/dist/components/previews/FilePreview.svelte.d.ts +2 -2
  6. package/dist/config.js +3 -4
  7. package/dist/i18n/context.js +2 -2
  8. package/dist/i18n/errors.js +1 -2
  9. package/dist/i18n/messages.js +2 -2
  10. package/dist/i18n/text.js +2 -2
  11. package/dist/mediaLibrary/capabilities.js +3 -4
  12. package/dist/mediaLibrary/context.js +3 -4
  13. package/dist/mediaLibrary/errors.js +35 -46
  14. package/dist/mediaLibrary/normalize.js +42 -45
  15. package/dist/mediaLibrary/paging.js +45 -100
  16. package/dist/mediaLibrary/resolve.js +95 -214
  17. package/dist/mediaLibrary/treeOps.js +20 -40
  18. package/dist/mediaLibrary/urls.js +10 -12
  19. package/dist/mediaLibrary/widgetic.js +54 -140
  20. package/dist/stores/dragStore.js +1 -1
  21. package/dist/stores/fileStore.d.ts +3 -3
  22. package/dist/stores/fileStore.js +37 -44
  23. package/dist/stores/folderCountStore.js +11 -12
  24. package/dist/stores/missingFilesStore.js +3 -3
  25. package/dist/stores/navigationStore.d.ts +1 -1
  26. package/dist/stores/navigationStore.js +178 -217
  27. package/dist/stores/persistentSelectStore.d.ts +1 -1
  28. package/dist/stores/persistentSelectStore.js +94 -117
  29. package/dist/stores/searchStore.js +1 -1
  30. package/dist/stores/uploadApiStore.js +7 -7
  31. package/dist/stores/viewportStore.js +4 -4
  32. package/dist/types/index.js +1 -0
  33. package/dist/utils/apiConfig.js +9 -9
  34. package/dist/utils/brandKitLibraryTree.js +42 -57
  35. package/dist/utils/dateUtils.js +9 -11
  36. package/dist/utils/dragToFolder/batchMoveResult.js +54 -114
  37. package/dist/utils/dragToFolder/folderDropTarget.js +17 -23
  38. package/dist/utils/dragToFolder/springStep.js +3 -4
  39. package/dist/utils/fileGoneProbe.js +16 -65
  40. package/dist/utils/fileKinds.js +13 -14
  41. package/dist/utils/fileNames.js +7 -7
  42. package/dist/utils/fileOperations.js +332 -440
  43. package/dist/utils/fileTypes.js +14 -19
  44. package/dist/utils/fileUtils.js +31 -85
  45. package/dist/utils/folderUtils.js +4 -5
  46. package/dist/utils/gridLayout.js +7 -7
  47. package/dist/utils/imagePreviewCache.js +15 -26
  48. package/dist/utils/imagePreviewFrame.js +13 -13
  49. package/dist/utils/imagePreviewVisualState.js +4 -5
  50. package/dist/utils/imageTransform.js +14 -27
  51. package/dist/utils/itemMenuCapabilities.js +7 -7
  52. package/dist/utils/libraryTree.js +39 -55
  53. package/dist/utils/pendingUploadDeletes.js +113 -289
  54. package/dist/utils/previewKeys.js +1 -1
  55. package/dist/utils/previewListNavigation.js +11 -13
  56. package/dist/utils/previewNavigation.js +7 -10
  57. package/dist/utils/recentFiles.js +6 -16
  58. package/dist/utils/recentFilesLimit.js +2 -2
  59. package/dist/utils/removeItems.js +29 -61
  60. package/dist/utils/resolveFileUrl.js +6 -6
  61. package/dist/utils/safeText.js +12 -14
  62. package/dist/utils/searchDropdownPhase.js +2 -2
  63. package/dist/utils/searchItems.js +14 -30
  64. package/dist/utils/searchNavigation.js +5 -5
  65. package/dist/utils/uploadAuth.js +36 -111
  66. package/dist/utils/uploadDisplayProgress.js +1 -1
  67. package/dist/utils/uploadLimits.js +66 -138
  68. package/dist/utils/uploadListReconcile.js +11 -24
  69. package/dist/utils/uploadPanelDismiss.js +1 -1
  70. package/dist/utils/uploadPanelProgress.js +4 -4
  71. package/dist/utils/uploadProgressMath.js +11 -13
  72. package/dist/utils/uploadRefusals.js +24 -40
  73. package/dist/utils/uploadResponseMapping.js +8 -9
  74. package/dist/utils/uploadUiHelpers.js +17 -17
  75. package/dist/utils/userUploadsStorage.js +133 -270
  76. package/dist/utils/videoFrame.js +2 -2
  77. package/dist/utils/widgeticDelete.js +30 -103
  78. package/dist/utils/widgeticTusUpload.js +105 -189
  79. package/dist/utils/widgeticUpload.js +62 -130
  80. package/dist/utils/xhrMultipartUpload.js +116 -164
  81. package/package.json +1 -1
@@ -1,41 +1,32 @@
1
- var __extends = (this && this.__extends) || (function () {
2
- var extendStatics = function (d, b) {
3
- extendStatics = Object.setPrototypeOf ||
4
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
6
- return extendStatics(d, b);
7
- };
8
- return function (d, b) {
9
- if (typeof b !== "function" && b !== null)
10
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
11
- extendStatics(d, b);
12
- function __() { this.constructor = d; }
13
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
14
- };
15
- })();
16
1
  /** The longest message taken from a library's own error. Longer ones are cut so a toast stays readable. */
17
- var MAX_MESSAGE_LENGTH = 300;
2
+ const MAX_MESSAGE_LENGTH = 300;
18
3
  /** What Chrome, Firefox, Safari and React Native write in the TypeError of a `fetch` that could not reach the server. */
19
- var BROWSER_NETWORK_FAILURE_TEXT = /failed to fetch|networkerror|network request failed|load failed/i;
4
+ const BROWSER_NETWORK_FAILURE_TEXT = /failed to fetch|networkerror|network request failed|load failed/i;
20
5
  /** A failed call to a media library, with a reason the File Browser can act on. */
21
- var MediaLibraryError = /** @class */ (function (_super) {
22
- __extends(MediaLibraryError, _super);
23
- function MediaLibraryError(code, message, options) {
24
- if (options === void 0) { options = {}; }
25
- var _this = _super.call(this, message) || this;
26
- _this.name = 'MediaLibraryError';
27
- _this.code = code;
28
- _this.status = options.status;
29
- _this.messageKey = options.messageKey;
30
- _this.messageValues = options.messageValues;
6
+ export class MediaLibraryError extends Error {
7
+ code;
8
+ /** The HTTP status behind the failure, when there was one. */
9
+ status;
10
+ /**
11
+ * The catalog message that says the same thing in the visitor's language. Set when `message` is the File Browser's
12
+ * own English text (not one the library wrote): the visitor then reads the translation, while the `error` event and
13
+ * the console keep the English `message`. Absent when the library supplied the text, which is shown as it is.
14
+ */
15
+ messageKey;
16
+ /** The values the message at `messageKey` asks for (a size limit, a count), when it asks for any. */
17
+ messageValues;
18
+ constructor(code, message, options = {}) {
19
+ super(message);
20
+ this.name = 'MediaLibraryError';
21
+ this.code = code;
22
+ this.status = options.status;
23
+ this.messageKey = options.messageKey;
24
+ this.messageValues = options.messageValues;
31
25
  if (options.cause !== undefined) {
32
- _this.cause = options.cause;
26
+ this.cause = options.cause;
33
27
  }
34
- return _this;
35
28
  }
36
- return MediaLibraryError;
37
- }(Error));
38
- export { MediaLibraryError };
29
+ }
39
30
  /** The error code that fits an HTTP status. */
40
31
  export function codeForHttpStatus(status) {
41
32
  if (status === 401)
@@ -61,12 +52,10 @@ export function isCancellation(error) {
61
52
  }
62
53
  /** The HTTP status a thrown value carries, if it carries one in any of the usual places. */
63
54
  function statusOf(error) {
64
- var _a;
65
55
  if (error === null || typeof error !== 'object')
66
56
  return undefined;
67
- var candidate = error;
68
- for (var _i = 0, _b = [candidate.status, candidate.statusCode, (_a = candidate.response) === null || _a === void 0 ? void 0 : _a.status]; _i < _b.length; _i++) {
69
- var value = _b[_i];
57
+ const candidate = error;
58
+ for (const value of [candidate.status, candidate.statusCode, candidate.response?.status]) {
70
59
  if (typeof value === 'number' && Number.isInteger(value) && value >= 100 && value <= 599)
71
60
  return value;
72
61
  }
@@ -76,10 +65,10 @@ function statusOf(error) {
76
65
  function ownTextOf(text) {
77
66
  if (typeof text !== 'string')
78
67
  return null;
79
- var trimmed = text.trim();
68
+ const trimmed = text.trim();
80
69
  if (trimmed === '')
81
70
  return null;
82
- return trimmed.length > MAX_MESSAGE_LENGTH ? "".concat(trimmed.slice(0, MAX_MESSAGE_LENGTH), "\u2026") : trimmed;
71
+ return trimmed.length > MAX_MESSAGE_LENGTH ? `${trimmed.slice(0, MAX_MESSAGE_LENGTH)}…` : trimmed;
83
72
  }
84
73
  /**
85
74
  * Turns whatever a library's function threw (or rejected with) into a {@link MediaLibraryError}.
@@ -94,30 +83,30 @@ export function toMediaLibraryError(error, fallbackMessage, fallbackKey) {
94
83
  if (isAbortError(error)) {
95
84
  return new MediaLibraryError('ABORTED', 'The request was cancelled', { cause: error });
96
85
  }
97
- var status = statusOf(error);
98
- var ownText = ownTextOf(typeof error === 'string'
86
+ const status = statusOf(error);
87
+ const ownText = ownTextOf(typeof error === 'string'
99
88
  ? error
100
89
  : error !== null && typeof error === 'object'
101
90
  ? error.message
102
91
  : undefined);
103
- var message = ownText !== null && ownText !== void 0 ? ownText : fallbackMessage;
92
+ const message = ownText ?? fallbackMessage;
104
93
  // Only the File Browser's own words are translated; what the library wrote is shown as it is.
105
- var messageKey = ownText === null ? fallbackKey : undefined;
94
+ const messageKey = ownText === null ? fallbackKey : undefined;
106
95
  if (status !== undefined) {
107
- return new MediaLibraryError(codeForHttpStatus(status), message, { status: status, cause: error, messageKey: messageKey });
96
+ return new MediaLibraryError(codeForHttpStatus(status), message, { status, cause: error, messageKey });
108
97
  }
109
98
  // `fetch` rejects with a TypeError when the server cannot be reached at all. The browser's own text for it
110
99
  // ("Failed to fetch") is English whatever the visitor's language, so the visitor reads our sentence instead; the
111
100
  // host's `error` event still carries what the browser said. A TypeError the library threw with words of its own
112
101
  // is not a network failure, and its words are shown.
113
102
  if (error instanceof TypeError) {
114
- var isBrowserNetworkText = ownText !== null && BROWSER_NETWORK_FAILURE_TEXT.test(ownText);
115
- return new MediaLibraryError('NETWORK', ownText !== null && ownText !== void 0 ? ownText : 'Could not reach the media library', {
103
+ const isBrowserNetworkText = ownText !== null && BROWSER_NETWORK_FAILURE_TEXT.test(ownText);
104
+ return new MediaLibraryError('NETWORK', ownText ?? 'Could not reach the media library', {
116
105
  cause: error,
117
106
  messageKey: ownText === null || isBrowserNetworkText ? 'libraryError.unreachable' : undefined
118
107
  });
119
108
  }
120
- return new MediaLibraryError('FAILED', message, { cause: error, messageKey: messageKey });
109
+ return new MediaLibraryError('FAILED', message, { cause: error, messageKey });
121
110
  }
122
111
  /** True when the failure means the credentials were refused, so refreshing them and trying again may help. */
123
112
  export function isUnauthorized(error) {
@@ -1,18 +1,7 @@
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
1
  import { MediaLibraryError } from './errors';
13
2
  import { toSafeMediaUrl } from './urls';
14
3
  /** Limits that keep a library's data from breaking the screen. A value over its limit is cut or refused. */
15
- export var LIMITS = {
4
+ export const LIMITS = {
16
5
  idLength: 512,
17
6
  nameLength: 255,
18
7
  hashLength: 256,
@@ -20,10 +9,10 @@ export var LIMITS = {
20
9
  /** More files than this in one page are ignored. */
21
10
  itemsPerPage: 1000
22
11
  };
23
- var MEDIA_TYPE_PATTERN = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;
12
+ const MEDIA_TYPE_PATTERN = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/i;
24
13
  /** Control characters (line breaks, tabs, NUL ...) have no place in a name shown on one line. */
25
14
  // eslint-disable-next-line no-control-regex
26
- var CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]+/g;
15
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]+/g;
27
16
  function isPlainObject(value) {
28
17
  return value !== null && typeof value === 'object' && !Array.isArray(value);
29
18
  }
@@ -32,19 +21,19 @@ function toIdOrNull(value) {
32
21
  return String(value);
33
22
  if (typeof value !== 'string')
34
23
  return null;
35
- var trimmed = value.trim();
24
+ const trimmed = value.trim();
36
25
  return trimmed !== '' && trimmed.length <= LIMITS.idLength ? trimmed : null;
37
26
  }
38
27
  function toNameOrNull(value) {
39
28
  if (typeof value !== 'string')
40
29
  return null;
41
- var cleaned = value.replace(CONTROL_CHARACTERS, ' ').trim();
30
+ const cleaned = value.replace(CONTROL_CHARACTERS, ' ').trim();
42
31
  if (cleaned === '')
43
32
  return null;
44
33
  return cleaned.length > LIMITS.nameLength ? cleaned.slice(0, LIMITS.nameLength) : cleaned;
45
34
  }
46
35
  function toIsoDateOrUndefined(value) {
47
- var date = null;
36
+ let date = null;
48
37
  if (value instanceof Date)
49
38
  date = value;
50
39
  else if (typeof value === 'number' && Number.isFinite(value))
@@ -60,36 +49,45 @@ function toIsoDateOrUndefined(value) {
60
49
  * no id, no name, or no address the browser may fetch. Optional fields that are wrong (a size of -1, a media type
61
50
  * of `banana`) are dropped instead: the file is still usable without them.
62
51
  */
63
- export function normalizeMediaLibraryFile(raw, options) {
64
- var _a;
65
- if (options === void 0) { options = {}; }
52
+ export function normalizeMediaLibraryFile(raw, options = {}) {
66
53
  if (!isPlainObject(raw)) {
67
54
  throw new MediaLibraryError('INVALID_RESPONSE', 'A file in the media library is not an object');
68
55
  }
69
- var id = toIdOrNull(raw.id);
56
+ const id = toIdOrNull(raw.id);
70
57
  if (id === null) {
71
58
  throw new MediaLibraryError('INVALID_RESPONSE', 'A file in the media library has no id (a non-empty string)');
72
59
  }
73
- var name = toNameOrNull(raw.name);
60
+ const name = toNameOrNull(raw.name);
74
61
  if (name === null) {
75
- throw new MediaLibraryError('INVALID_RESPONSE', "The file \"".concat(id, "\" in the media library has no name"));
62
+ throw new MediaLibraryError('INVALID_RESPONSE', `The file "${id}" in the media library has no name`);
76
63
  }
77
- var url = toSafeMediaUrl(raw.url, { baseHref: options.baseHref });
64
+ const url = toSafeMediaUrl(raw.url, { baseHref: options.baseHref });
78
65
  if (url === null) {
79
- throw new MediaLibraryError('INVALID_RESPONSE', "The file \"".concat(id, "\" in the media library has no usable url (it must be an http or https address, or a path on this site)"));
66
+ throw new MediaLibraryError('INVALID_RESPONSE', `The file "${id}" in the media library has no usable url (it must be an http or https address, or a path on this site)`);
80
67
  }
81
- var mimeType = typeof raw.mimeType === 'string' && MEDIA_TYPE_PATTERN.test(raw.mimeType.trim())
68
+ const mimeType = typeof raw.mimeType === 'string' && MEDIA_TYPE_PATTERN.test(raw.mimeType.trim())
82
69
  ? raw.mimeType.trim().toLowerCase()
83
70
  : undefined;
84
- var size = typeof raw.size === 'number' && Number.isFinite(raw.size) && raw.size >= 0
71
+ const size = typeof raw.size === 'number' && Number.isFinite(raw.size) && raw.size >= 0
85
72
  ? raw.size
86
73
  : undefined;
87
- var thumbnail = (_a = toSafeMediaUrl(raw.thumbnail, { baseHref: options.baseHref, allowDataPicture: true })) !== null && _a !== void 0 ? _a : undefined;
88
- var hash = typeof raw.hash === 'string' && raw.hash !== '' && raw.hash.length <= LIMITS.hashLength
74
+ const thumbnail = toSafeMediaUrl(raw.thumbnail, { baseHref: options.baseHref, allowDataPicture: true }) ??
75
+ undefined;
76
+ const hash = typeof raw.hash === 'string' && raw.hash !== '' && raw.hash.length <= LIMITS.hashLength
89
77
  ? raw.hash
90
78
  : undefined;
91
- var modified = toIsoDateOrUndefined(raw.modified);
92
- return __assign(__assign(__assign(__assign(__assign({ id: id, name: name, type: 'file', url: url }, (mimeType !== undefined && { mimeType: mimeType })), (size !== undefined && { size: size })), (modified !== undefined && { modified: modified })), (thumbnail !== undefined && { thumbnail: thumbnail })), (hash !== undefined && { hash: hash }));
79
+ const modified = toIsoDateOrUndefined(raw.modified);
80
+ return {
81
+ id,
82
+ name,
83
+ type: 'file',
84
+ url,
85
+ ...(mimeType !== undefined && { mimeType }),
86
+ ...(size !== undefined && { size }),
87
+ ...(modified !== undefined && { modified }),
88
+ ...(thumbnail !== undefined && { thumbnail }),
89
+ ...(hash !== undefined && { hash })
90
+ };
93
91
  }
94
92
  function toCursorOrNull(value) {
95
93
  if (typeof value === 'number' && Number.isFinite(value))
@@ -104,27 +102,26 @@ function toCursorOrNull(value) {
104
102
  *
105
103
  * Throws only when the page itself is not a page: it is not `{ items: [...] }` (a bare array is accepted too).
106
104
  */
107
- export function normalizeMediaLibraryPage(raw, options) {
108
- if (options === void 0) { options = {}; }
109
- var rawItems = Array.isArray(raw) ? raw : isPlainObject(raw) ? raw.items : undefined;
105
+ export function normalizeMediaLibraryPage(raw, options = {}) {
106
+ const rawItems = Array.isArray(raw) ? raw : isPlainObject(raw) ? raw.items : undefined;
110
107
  if (!Array.isArray(rawItems)) {
111
108
  throw new MediaLibraryError('INVALID_RESPONSE', "The media library's list must resolve to { items: [...], nextCursor? }");
112
109
  }
113
- var nextCursor = isPlainObject(raw) ? toCursorOrNull(raw.nextCursor) : null;
114
- var items = [];
115
- var seenIds = new Set();
116
- var skippedReasons = [];
117
- var skipped = 0;
118
- var note = function (reason) {
110
+ const nextCursor = isPlainObject(raw) ? toCursorOrNull(raw.nextCursor) : null;
111
+ const items = [];
112
+ const seenIds = new Set();
113
+ const skippedReasons = [];
114
+ let skipped = 0;
115
+ const note = (reason) => {
119
116
  skipped += 1;
120
117
  if (skippedReasons.length < 3)
121
118
  skippedReasons.push(reason);
122
119
  };
123
- rawItems.slice(0, LIMITS.itemsPerPage).forEach(function (rawItem) {
120
+ rawItems.slice(0, LIMITS.itemsPerPage).forEach((rawItem) => {
124
121
  try {
125
- var item = normalizeMediaLibraryFile(rawItem, options);
122
+ const item = normalizeMediaLibraryFile(rawItem, options);
126
123
  if (seenIds.has(item.id)) {
127
- note("The file id \"".concat(item.id, "\" appears twice"));
124
+ note(`The file id "${item.id}" appears twice`);
128
125
  return;
129
126
  }
130
127
  seenIds.add(item.id);
@@ -136,7 +133,7 @@ export function normalizeMediaLibraryPage(raw, options) {
136
133
  });
137
134
  if (rawItems.length > LIMITS.itemsPerPage) {
138
135
  skipped += rawItems.length - LIMITS.itemsPerPage;
139
- skippedReasons.push("Only the first ".concat(LIMITS.itemsPerPage, " files of a page are used"));
136
+ skippedReasons.push(`Only the first ${LIMITS.itemsPerPage} files of a page are used`);
140
137
  }
141
- return { items: items, nextCursor: nextCursor, skipped: skipped, skippedReasons: skippedReasons };
138
+ return { items, nextCursor, skipped, skippedReasons };
142
139
  }
@@ -1,49 +1,13 @@
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, toMediaLibraryError } from './errors';
38
2
  /** How many files the File Browser asks for per page. */
39
- export var DEFAULT_PAGE_SIZE = 100;
3
+ export const DEFAULT_PAGE_SIZE = 100;
40
4
  /**
41
5
  * The most files the File Browser loads. Files beyond it are not shown (search and filters only look at the files
42
6
  * that were loaded), so a library with more files should list the ones a visitor is most likely to want first.
43
7
  */
44
- export var DEFAULT_MAX_ITEMS = 1000;
8
+ export const DEFAULT_MAX_ITEMS = 1000;
45
9
  /** A safety stop: no library is read for more pages than this, whatever it says about having more. */
46
- export var DEFAULT_MAX_PAGES = 50;
10
+ export const DEFAULT_MAX_PAGES = 50;
47
11
  /**
48
12
  * Reads a library page by page, newest first, until it runs out or a limit is reached.
49
13
  *
@@ -53,65 +17,46 @@ export var DEFAULT_MAX_PAGES = 50;
53
17
  * The first page failing throws (there is nothing to show). A later page failing returns what was loaded with the
54
18
  * failure attached, because most of the library is better than none of it.
55
19
  */
56
- export function loadLibraryPages(library, options) {
57
- return __awaiter(this, void 0, Promise, function () {
58
- var pageSize, maxItems, maxPages, items, seenIds, usedCursors, cursor, pageNumber, page, error_1, failure, newItems, failure;
59
- var _a, _b, _c, _d;
60
- return __generator(this, function (_e) {
61
- switch (_e.label) {
62
- case 0:
63
- pageSize = (_a = options.pageSize) !== null && _a !== void 0 ? _a : DEFAULT_PAGE_SIZE;
64
- maxItems = (_b = options.maxItems) !== null && _b !== void 0 ? _b : DEFAULT_MAX_ITEMS;
65
- maxPages = (_c = options.maxPages) !== null && _c !== void 0 ? _c : DEFAULT_MAX_PAGES;
66
- items = [];
67
- seenIds = new Set();
68
- usedCursors = new Set();
69
- pageNumber = 1;
70
- _e.label = 1;
71
- case 1:
72
- if (!(pageNumber <= maxPages)) return [3 /*break*/, 7];
73
- page = void 0;
74
- _e.label = 2;
75
- case 2:
76
- _e.trys.push([2, 4, , 5]);
77
- return [4 /*yield*/, library.listPage({ cursor: cursor, limit: pageSize, signal: options.signal })];
78
- case 3:
79
- page = _e.sent();
80
- return [3 /*break*/, 5];
81
- case 4:
82
- error_1 = _e.sent();
83
- failure = toMediaLibraryError(error_1, 'Could not load the files', 'libraryError.loadFailed');
84
- if (pageNumber === 1 || failure.code === 'ABORTED')
85
- throw failure;
86
- console.warn("[FileBrowser] Page ".concat(pageNumber, " of the media library \"").concat(library.id, "\" failed; showing the ").concat(items.length, " files already loaded:"), failure.message);
87
- return [2 /*return*/, { items: items, truncated: true, failure: failure }];
88
- case 5:
89
- if (page.skipped > 0) {
90
- console.warn("[FileBrowser] The media library \"".concat(library.id, "\" gave ").concat(page.skipped, " file(s) on page ").concat(pageNumber, " that cannot be shown:"), page.skippedReasons);
91
- }
92
- newItems = page.items.filter(function (item) { return !seenIds.has(item.id); });
93
- newItems.forEach(function (item) { return seenIds.add(item.id); });
94
- items.push.apply(items, newItems);
95
- if (newItems.length > 0)
96
- (_d = options.onPage) === null || _d === void 0 ? void 0 : _d.call(options, newItems, pageNumber);
97
- if (page.nextCursor === null)
98
- return [2 /*return*/, { items: items, truncated: false }];
99
- // The library says there is more. Make sure it is not going in circles before asking again.
100
- if (newItems.length === 0 || usedCursors.has(page.nextCursor) || page.nextCursor === cursor) {
101
- failure = new MediaLibraryError('INVALID_RESPONSE', 'The media library keeps returning the same files, so the rest was not loaded', { messageKey: 'libraryError.repeatedPage' });
102
- console.warn("[FileBrowser] The media library \"".concat(library.id, "\" returned a page with nothing new or a repeated cursor; stopping at ").concat(items.length, " files"));
103
- return [2 /*return*/, { items: items, truncated: true, failure: failure }];
104
- }
105
- if (items.length >= maxItems)
106
- return [2 /*return*/, { items: items, truncated: true }];
107
- usedCursors.add(page.nextCursor);
108
- cursor = page.nextCursor;
109
- _e.label = 6;
110
- case 6:
111
- pageNumber += 1;
112
- return [3 /*break*/, 1];
113
- case 7: return [2 /*return*/, { items: items, truncated: true }];
114
- }
115
- });
116
- });
20
+ export async function loadLibraryPages(library, options) {
21
+ const pageSize = options.pageSize ?? DEFAULT_PAGE_SIZE;
22
+ const maxItems = options.maxItems ?? DEFAULT_MAX_ITEMS;
23
+ const maxPages = options.maxPages ?? DEFAULT_MAX_PAGES;
24
+ const items = [];
25
+ const seenIds = new Set();
26
+ const usedCursors = new Set();
27
+ let cursor;
28
+ for (let pageNumber = 1; pageNumber <= maxPages; pageNumber += 1) {
29
+ let page;
30
+ try {
31
+ page = await library.listPage({ cursor, limit: pageSize, signal: options.signal });
32
+ }
33
+ catch (error) {
34
+ const failure = toMediaLibraryError(error, 'Could not load the files', 'libraryError.loadFailed');
35
+ if (pageNumber === 1 || failure.code === 'ABORTED')
36
+ throw failure;
37
+ console.warn(`[FileBrowser] Page ${pageNumber} of the media library "${library.id}" failed; showing the ${items.length} files already loaded:`, failure.message);
38
+ return { items, truncated: true, failure };
39
+ }
40
+ if (page.skipped > 0) {
41
+ console.warn(`[FileBrowser] The media library "${library.id}" gave ${page.skipped} file(s) on page ${pageNumber} that cannot be shown:`, page.skippedReasons);
42
+ }
43
+ const newItems = page.items.filter((item) => !seenIds.has(item.id));
44
+ newItems.forEach((item) => seenIds.add(item.id));
45
+ items.push(...newItems);
46
+ if (newItems.length > 0)
47
+ options.onPage?.(newItems, pageNumber);
48
+ if (page.nextCursor === null)
49
+ return { items, truncated: false };
50
+ // The library says there is more. Make sure it is not going in circles before asking again.
51
+ if (newItems.length === 0 || usedCursors.has(page.nextCursor) || page.nextCursor === cursor) {
52
+ const failure = new MediaLibraryError('INVALID_RESPONSE', 'The media library keeps returning the same files, so the rest was not loaded', { messageKey: 'libraryError.repeatedPage' });
53
+ console.warn(`[FileBrowser] The media library "${library.id}" returned a page with nothing new or a repeated cursor; stopping at ${items.length} files`);
54
+ return { items, truncated: true, failure };
55
+ }
56
+ if (items.length >= maxItems)
57
+ return { items, truncated: true };
58
+ usedCursors.add(page.nextCursor);
59
+ cursor = page.nextCursor;
60
+ }
61
+ return { items, truncated: true };
117
62
  }