@molecule/app-file-upload-filepond 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,115 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work.
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship.
43
+
44
+ "Contribution" shall mean any work of authorship, including the
45
+ original version of the Work and any modifications or additions
46
+ to that Work, that is intentionally submitted to the Licensor for
47
+ inclusion in the Work by the copyright owner or by an individual or
48
+ Legal Entity authorized to submit on behalf of the copyright owner.
49
+
50
+ "Contributor" shall mean Licensor and any individual or Legal Entity
51
+ on behalf of whom a Contribution has been received by the Licensor and
52
+ subsequently incorporated within the Work.
53
+
54
+ 2. Grant of Copyright License. Subject to the terms and conditions of
55
+ this License, each Contributor hereby grants to You a perpetual,
56
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
57
+ copyright license to reproduce, prepare Derivative Works of,
58
+ publicly display, publicly perform, sublicense, and distribute the
59
+ Work and such Derivative Works in Source or Object form.
60
+
61
+ 3. Grant of Patent License. Subject to the terms and conditions of
62
+ this License, each Contributor hereby grants to You a perpetual,
63
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
64
+ patent license to make, have made, use, offer to sell, sell, import,
65
+ and otherwise transfer the Work.
66
+
67
+ 4. Redistribution. You may reproduce and distribute copies of the
68
+ Work or Derivative Works thereof in any medium, with or without
69
+ modifications, and in Source or Object form, provided that You
70
+ meet the following conditions:
71
+
72
+ (a) You must give any other recipients of the Work or
73
+ Derivative Works a copy of this License; and
74
+
75
+ (b) You must cause any modified files to carry prominent notices
76
+ stating that You changed the files; and
77
+
78
+ (c) You must retain, in the Source form of any Derivative Works
79
+ that You distribute, all copyright, patent, trademark, and
80
+ attribution notices from the Source form of the Work,
81
+ excluding those notices that do not pertain to any part of
82
+ the Derivative Works; and
83
+
84
+ (d) If the Work includes a "NOTICE" text file as part of its
85
+ distribution, then any Derivative Works that You distribute must
86
+ include a readable copy of the attribution notices contained
87
+ within such NOTICE file.
88
+
89
+ 5. Submission of Contributions.
90
+
91
+ 6. Trademarks. This License does not grant permission to use the trade
92
+ names, trademarks, service marks, or product names of the Licensor.
93
+
94
+ 7. Disclaimer of Warranty. Unless required by applicable law or
95
+ agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
96
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
97
+
98
+ 8. Limitation of Liability. In no event and under no legal theory shall
99
+ any Contributor be liable to You for damages.
100
+
101
+ 9. Accepting Warranty or Additional Liability.
102
+
103
+ Copyright 2026 Molecule Dev, Inc.
104
+
105
+ Licensed under the Apache License, Version 2.0 (the "License");
106
+ you may not use this file except in compliance with the License.
107
+ You may obtain a copy of the License at
108
+
109
+ http://www.apache.org/licenses/LICENSE-2.0
110
+
111
+ Unless required by applicable law or agreed to in writing, software
112
+ distributed under the License is distributed on an "AS IS" BASIS,
113
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
114
+ See the License for the specific language governing permissions and
115
+ limitations under the License.
@@ -0,0 +1,37 @@
1
+ /**
2
+ * FilePond file upload provider for the molecule file upload interface.
3
+ *
4
+ * Implements `FileUploadProvider` from `@molecule/app-file-upload` using a
5
+ * headless upload engine with validation, progress tracking, concurrency
6
+ * control, and image preview generation following FilePond's patterns.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { provider } from '@molecule/app-file-upload-filepond'
11
+ * import { setProvider } from '@molecule/app-file-upload'
12
+ *
13
+ * setProvider(provider)
14
+ * ```
15
+ *
16
+ * @remarks
17
+ * Transport is ONE multipart/form-data request per file to
18
+ * `destination.url` (default method POST, default field name `'file'`,
19
+ * `additionalData` appended as extra fields); the response is parsed as
20
+ * JSON when possible (else raw text) and can be reshaped with
21
+ * `destination.parseResponse`. This is NOT FilePond's process/revert server
22
+ * protocol — any endpoint accepting a multipart POST works. Files that fail
23
+ * validation are reported via `events.onValidationError` and NEVER enter
24
+ * the queue (they won't appear in `getFiles()`). `timeout` defaults to 0
25
+ * (no timeout). Every error/validation message routes through `t()` under the
26
+ * `fileUpload.error.*` namespace with an English `defaultValue`, so English
27
+ * works out of the box. There is no dedicated companion locale bond yet —
28
+ * to translate these, register `fileUpload.error.*` keys with your i18n
29
+ * provider (e.g. `addTranslations('fr', { 'fileUpload.error.timedOut': '…' })`).
30
+ * Interpolated messages expose `{{maxSize}}`, `{{minSize}}`, `{{type}}`,
31
+ * `{{extension}}`, `{{maxFiles}}`, and `{{status}}`.
32
+ *
33
+ * @module
34
+ */
35
+ export * from './provider.js';
36
+ export * from './types.js';
37
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AAEH,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * FilePond file upload provider for the molecule file upload interface.
3
+ *
4
+ * Implements `FileUploadProvider` from `@molecule/app-file-upload` using a
5
+ * headless upload engine with validation, progress tracking, concurrency
6
+ * control, and image preview generation following FilePond's patterns.
7
+ *
8
+ * @example
9
+ * ```typescript
10
+ * import { provider } from '@molecule/app-file-upload-filepond'
11
+ * import { setProvider } from '@molecule/app-file-upload'
12
+ *
13
+ * setProvider(provider)
14
+ * ```
15
+ *
16
+ * @remarks
17
+ * Transport is ONE multipart/form-data request per file to
18
+ * `destination.url` (default method POST, default field name `'file'`,
19
+ * `additionalData` appended as extra fields); the response is parsed as
20
+ * JSON when possible (else raw text) and can be reshaped with
21
+ * `destination.parseResponse`. This is NOT FilePond's process/revert server
22
+ * protocol — any endpoint accepting a multipart POST works. Files that fail
23
+ * validation are reported via `events.onValidationError` and NEVER enter
24
+ * the queue (they won't appear in `getFiles()`). `timeout` defaults to 0
25
+ * (no timeout). Every error/validation message routes through `t()` under the
26
+ * `fileUpload.error.*` namespace with an English `defaultValue`, so English
27
+ * works out of the box. There is no dedicated companion locale bond yet —
28
+ * to translate these, register `fileUpload.error.*` keys with your i18n
29
+ * provider (e.g. `addTranslations('fr', { 'fileUpload.error.timedOut': '…' })`).
30
+ * Interpolated messages expose `{{maxSize}}`, `{{minSize}}`, `{{type}}`,
31
+ * `{{extension}}`, `{{maxFiles}}`, and `{{status}}`.
32
+ *
33
+ * @module
34
+ */
35
+ export * from './provider.js';
36
+ export * from './types.js';
@@ -0,0 +1,29 @@
1
+ /**
2
+ * FilePond-style implementation of the molecule FileUploadProvider.
3
+ *
4
+ * Provides a headless file upload engine with validation, progress tracking,
5
+ * concurrency control, and image preview generation following FilePond's
6
+ * patterns and server protocol.
7
+ *
8
+ * @module
9
+ */
10
+ import type { FileUploadProvider } from '@molecule/app-file-upload';
11
+ import type { FilepondConfig } from './types.js';
12
+ /**
13
+ * Creates a FilePond-style file upload provider.
14
+ *
15
+ * @param config - Optional FilePond-specific configuration.
16
+ * @returns A `FileUploadProvider` backed by FilePond-style processing.
17
+ *
18
+ * @example
19
+ * ```typescript
20
+ * import { createFilepondProvider } from '@molecule/app-file-upload-filepond'
21
+ * import { setProvider } from '@molecule/app-file-upload'
22
+ *
23
+ * setProvider(createFilepondProvider())
24
+ * ```
25
+ */
26
+ export declare function createFilepondProvider(config?: FilepondConfig): FileUploadProvider;
27
+ /** Default FilePond file upload provider instance. */
28
+ export declare const provider: FileUploadProvider;
29
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAGV,kBAAkB,EAInB,MAAM,2BAA2B,CAAA;AAGlC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAA;AAkqBhD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,sBAAsB,CAAC,MAAM,GAAE,cAAmB,GAAG,kBAAkB,CAMtF;AAED,sDAAsD;AACtD,eAAO,MAAM,QAAQ,EAAE,kBAA6C,CAAA"}
@@ -0,0 +1,529 @@
1
+ /**
2
+ * FilePond-style implementation of the molecule FileUploadProvider.
3
+ *
4
+ * Provides a headless file upload engine with validation, progress tracking,
5
+ * concurrency control, and image preview generation following FilePond's
6
+ * patterns and server protocol.
7
+ *
8
+ * @module
9
+ */
10
+ import { t } from '@molecule/app-i18n';
11
+ // ---------------------------------------------------------------------------
12
+ // ID generation
13
+ // ---------------------------------------------------------------------------
14
+ let idCounter = 0;
15
+ /**
16
+ * Generates a unique file ID.
17
+ *
18
+ * @returns A unique string identifier.
19
+ */
20
+ function generateId() {
21
+ idCounter += 1;
22
+ return `fp-${Date.now()}-${idCounter}`;
23
+ }
24
+ // ---------------------------------------------------------------------------
25
+ // Validation
26
+ // ---------------------------------------------------------------------------
27
+ /**
28
+ * Validates a file against the provided validation rules.
29
+ *
30
+ * @param file - The upload file to validate.
31
+ * @param validation - The validation constraints.
32
+ * @param currentFileCount - Current number of files already in the queue.
33
+ * @returns An array of error messages (empty if valid).
34
+ */
35
+ function validateFile(file, validation, currentFileCount) {
36
+ if (!validation)
37
+ return [];
38
+ const errors = [];
39
+ if (validation.maxSize !== undefined && file.size > validation.maxSize) {
40
+ errors.push(t('fileUpload.error.maxSize', { maxSize: validation.maxSize }, { defaultValue: 'File exceeds maximum size of {{maxSize}} bytes' }));
41
+ }
42
+ if (validation.minSize !== undefined && file.size < validation.minSize) {
43
+ errors.push(t('fileUpload.error.minSize', { minSize: validation.minSize }, { defaultValue: 'File is below minimum size of {{minSize}} bytes' }));
44
+ }
45
+ if (validation.acceptedTypes?.length) {
46
+ const accepted = validation.acceptedTypes.some((type) => {
47
+ if (type.endsWith('/*')) {
48
+ return file.type.startsWith(type.slice(0, -1));
49
+ }
50
+ return file.type === type;
51
+ });
52
+ if (!accepted) {
53
+ errors.push(t('fileUpload.error.typeNotAccepted', { type: file.type }, { defaultValue: 'File type "{{type}}" is not accepted' }));
54
+ }
55
+ }
56
+ if (validation.acceptedExtensions?.length) {
57
+ const dotIdx = file.name.lastIndexOf('.');
58
+ const ext = dotIdx >= 0 ? file.name.slice(dotIdx).toLowerCase() : '';
59
+ if (!validation.acceptedExtensions.includes(ext)) {
60
+ errors.push(t('fileUpload.error.extensionNotAccepted', { extension: ext }, { defaultValue: 'File extension "{{extension}}" is not accepted' }));
61
+ }
62
+ }
63
+ if (validation.maxFiles !== undefined && currentFileCount >= validation.maxFiles) {
64
+ errors.push(t('fileUpload.error.maxFiles', { maxFiles: validation.maxFiles }, { defaultValue: 'Maximum number of files ({{maxFiles}}) reached' }));
65
+ }
66
+ if (validation.custom) {
67
+ const customError = validation.custom(file);
68
+ if (customError) {
69
+ errors.push(customError);
70
+ }
71
+ }
72
+ return errors;
73
+ }
74
+ /**
75
+ * Uploads a single file using XMLHttpRequest (browser) with progress events,
76
+ * falling back to fetch when XMLHttpRequest is unavailable (Node/SSR).
77
+ *
78
+ * @param source - The File object to upload.
79
+ * @param destination - Upload destination configuration.
80
+ * @param onProgress - Progress callback receiving loaded and total bytes.
81
+ * @param timeout - Request timeout in milliseconds.
82
+ * @returns An UploadHandle with promise and abort.
83
+ */
84
+ function uploadTransport(source, destination, onProgress, timeout) {
85
+ const method = destination.method ?? 'POST';
86
+ const fieldName = destination.fieldName ?? 'file';
87
+ const formData = new FormData();
88
+ formData.append(fieldName, source);
89
+ if (destination.additionalData) {
90
+ for (const [key, value] of Object.entries(destination.additionalData)) {
91
+ formData.append(key, value);
92
+ }
93
+ }
94
+ // Use XMLHttpRequest when available (browser) for progress events
95
+ if (typeof XMLHttpRequest !== 'undefined') {
96
+ return uploadWithXHR(destination.url, method, formData, destination.headers, onProgress, timeout);
97
+ }
98
+ // Fallback to fetch (Node/SSR) — no upload progress events
99
+ return uploadWithFetch(destination.url, method, formData, destination.headers, timeout);
100
+ }
101
+ /**
102
+ * Uploads using XMLHttpRequest with upload progress events.
103
+ *
104
+ * @param url - Target URL.
105
+ * @param method - HTTP method.
106
+ * @param body - Form data body.
107
+ * @param headers - Optional headers.
108
+ * @param onProgress - Progress callback.
109
+ * @param timeout - Request timeout.
110
+ * @returns An UploadHandle.
111
+ */
112
+ function uploadWithXHR(url, method, body, headers, onProgress, timeout) {
113
+ const xhr = new XMLHttpRequest();
114
+ const promise = new Promise((resolve, reject) => {
115
+ xhr.upload.addEventListener('progress', (e) => {
116
+ if (e.lengthComputable) {
117
+ onProgress(e.loaded, e.total);
118
+ }
119
+ });
120
+ xhr.addEventListener('load', () => {
121
+ if (xhr.status >= 200 && xhr.status < 300) {
122
+ try {
123
+ resolve(JSON.parse(xhr.responseText));
124
+ }
125
+ catch (_error) {
126
+ // Response is not valid JSON — treat it as a plain-text string, which is safe.
127
+ resolve(xhr.responseText);
128
+ }
129
+ }
130
+ else {
131
+ reject(new Error(t('fileUpload.error.uploadFailedStatus', { status: xhr.status }, { defaultValue: 'Upload failed with status {{status}}' })));
132
+ }
133
+ });
134
+ xhr.addEventListener('error', () => {
135
+ reject(new Error(t('fileUpload.error.networkError', undefined, {
136
+ defaultValue: 'Upload failed due to a network error',
137
+ })));
138
+ });
139
+ xhr.addEventListener('abort', () => {
140
+ reject(new Error(t('fileUpload.error.cancelled', undefined, { defaultValue: 'Upload cancelled' })));
141
+ });
142
+ xhr.addEventListener('timeout', () => {
143
+ reject(new Error(t('fileUpload.error.timedOut', undefined, { defaultValue: 'Upload timed out' })));
144
+ });
145
+ xhr.open(method, url);
146
+ xhr.timeout = timeout;
147
+ if (headers) {
148
+ for (const [key, value] of Object.entries(headers)) {
149
+ xhr.setRequestHeader(key, value);
150
+ }
151
+ }
152
+ xhr.send(body);
153
+ });
154
+ return { promise, abort: () => xhr.abort() };
155
+ }
156
+ /**
157
+ * Uploads using fetch (no upload progress events).
158
+ *
159
+ * @param url - Target URL.
160
+ * @param method - HTTP method.
161
+ * @param body - Form data body.
162
+ * @param headers - Optional headers.
163
+ * @param timeout - Request timeout.
164
+ * @returns An UploadHandle.
165
+ */
166
+ function uploadWithFetch(url, method, body, headers, timeout) {
167
+ const controller = new AbortController();
168
+ let timeoutId;
169
+ if (timeout > 0) {
170
+ // Abort with an explicit reason so a timeout rejects with 'Upload timed out'
171
+ // (parity with the XHR path) instead of a generic AbortError — otherwise a
172
+ // caller cannot tell a timeout apart from a cancellation or network abort.
173
+ timeoutId = setTimeout(() => controller.abort(new Error(t('fileUpload.error.timedOut', undefined, { defaultValue: 'Upload timed out' }))), timeout);
174
+ }
175
+ const promise = fetch(url, {
176
+ method,
177
+ body,
178
+ headers,
179
+ signal: controller.signal,
180
+ })
181
+ .then(async (res) => {
182
+ if (timeoutId)
183
+ clearTimeout(timeoutId);
184
+ if (!res.ok) {
185
+ throw new Error(t('fileUpload.error.uploadFailedStatus', { status: res.status }, { defaultValue: 'Upload failed with status {{status}}' }));
186
+ }
187
+ const text = await res.text();
188
+ try {
189
+ return JSON.parse(text);
190
+ }
191
+ catch (_error) {
192
+ // Response is not valid JSON — treat it as a plain-text string, which is safe.
193
+ return text;
194
+ }
195
+ })
196
+ .catch((err) => {
197
+ if (timeoutId)
198
+ clearTimeout(timeoutId);
199
+ throw err;
200
+ });
201
+ return {
202
+ promise,
203
+ abort: () => {
204
+ if (timeoutId)
205
+ clearTimeout(timeoutId);
206
+ controller.abort();
207
+ },
208
+ };
209
+ }
210
+ // ---------------------------------------------------------------------------
211
+ // Image preview
212
+ // ---------------------------------------------------------------------------
213
+ /**
214
+ * Generates a data URL preview for an image file.
215
+ *
216
+ * @param file - The File object.
217
+ * @param maxSize - Maximum width/height in pixels.
218
+ * @returns A promise resolving to the data URL string, or undefined.
219
+ */
220
+ async function generatePreview(file, maxSize) {
221
+ if (!file.type.startsWith('image/'))
222
+ return undefined;
223
+ if (typeof FileReader === 'undefined')
224
+ return undefined;
225
+ return new Promise((resolve) => {
226
+ const reader = new FileReader();
227
+ reader.onload = () => {
228
+ const dataUrl = reader.result;
229
+ // If no canvas available (Node), return the raw data URL
230
+ if (typeof document === 'undefined' || typeof HTMLCanvasElement === 'undefined') {
231
+ resolve(dataUrl);
232
+ return;
233
+ }
234
+ // Resize using canvas in browser environments
235
+ const img = new Image();
236
+ img.onload = () => {
237
+ let { width, height } = img;
238
+ if (width > maxSize || height > maxSize) {
239
+ const ratio = Math.min(maxSize / width, maxSize / height);
240
+ width = Math.round(width * ratio);
241
+ height = Math.round(height * ratio);
242
+ }
243
+ const canvas = document.createElement('canvas');
244
+ canvas.width = width;
245
+ canvas.height = height;
246
+ const ctx = canvas.getContext('2d');
247
+ if (ctx) {
248
+ ctx.drawImage(img, 0, 0, width, height);
249
+ resolve(canvas.toDataURL(file.type));
250
+ }
251
+ else {
252
+ resolve(dataUrl);
253
+ }
254
+ };
255
+ img.onerror = () => resolve(undefined);
256
+ img.src = dataUrl;
257
+ };
258
+ reader.onerror = () => resolve(undefined);
259
+ reader.readAsDataURL(file);
260
+ });
261
+ }
262
+ // ---------------------------------------------------------------------------
263
+ // Upload instance
264
+ // ---------------------------------------------------------------------------
265
+ /**
266
+ * Creates a FileUploadInstance backed by FilePond-style processing.
267
+ *
268
+ * @param options - Upload configuration including destination, validation, and events.
269
+ * @param config - Optional FilePond-specific settings.
270
+ * @returns A FileUploadInstance for managing queued files and uploads.
271
+ */
272
+ function createUploaderInstance(options, config = {}) {
273
+ const files = [];
274
+ const activeUploads = new Map();
275
+ const events = options.events ?? {};
276
+ const maxConcurrent = options.maxConcurrent ?? 3;
277
+ const allowMultiple = options.multiple ?? true;
278
+ const timeout = config.timeout ?? 0;
279
+ /**
280
+ * Processes the upload queue, starting uploads up to the concurrency limit.
281
+ */
282
+ function processQueue() {
283
+ const activeCount = activeUploads.size;
284
+ const idleFiles = files.filter((f) => f.status === 'idle');
285
+ const slotsAvailable = maxConcurrent - activeCount;
286
+ for (let i = 0; i < Math.min(slotsAvailable, idleFiles.length); i++) {
287
+ startUpload(idleFiles[i]);
288
+ }
289
+ }
290
+ /**
291
+ * Starts uploading a single file.
292
+ *
293
+ * @param file - The UploadFile record to upload.
294
+ */
295
+ function startUpload(file) {
296
+ if (!file.source) {
297
+ const noSourceMsg = t('fileUpload.error.noSource', undefined, {
298
+ defaultValue: 'No source file available',
299
+ });
300
+ Object.assign(file, { status: 'error', error: noSourceMsg });
301
+ events.onError?.(file, noSourceMsg);
302
+ checkAllComplete();
303
+ return;
304
+ }
305
+ Object.assign(file, { status: 'uploading', progress: 0 });
306
+ const handle = uploadTransport(file.source, options.destination, (loaded, total) => {
307
+ const progress = Math.round((loaded / total) * 100);
308
+ file.progress = progress;
309
+ events.onProgress?.(file, progress);
310
+ }, timeout);
311
+ activeUploads.set(file.id, handle);
312
+ handle.promise
313
+ .then((response) => {
314
+ activeUploads.delete(file.id);
315
+ const result = options.destination.parseResponse
316
+ ? options.destination.parseResponse(response)
317
+ : typeof response === 'string'
318
+ ? response
319
+ : JSON.stringify(response);
320
+ Object.assign(file, { status: 'complete', progress: 100, result });
321
+ events.onComplete?.(file);
322
+ processQueue();
323
+ checkAllComplete();
324
+ })
325
+ .catch((err) => {
326
+ activeUploads.delete(file.id);
327
+ if (file.status === 'cancelled') {
328
+ processQueue();
329
+ checkAllComplete();
330
+ return;
331
+ }
332
+ const errorMsg = err.message ||
333
+ t('fileUpload.error.uploadFailed', undefined, { defaultValue: 'Upload failed' });
334
+ Object.assign(file, { status: 'error', error: errorMsg });
335
+ events.onError?.(file, errorMsg);
336
+ processQueue();
337
+ checkAllComplete();
338
+ });
339
+ }
340
+ /**
341
+ * Checks if all files have been processed and fires onAllComplete if so.
342
+ */
343
+ function checkAllComplete() {
344
+ // Every non-terminal FileUploadStatus counts as pending, including 'processing'
345
+ // (this implementation never sets it — startUpload() only moves a file through
346
+ // 'idle' -> 'uploading' -> 'complete'/'error'/'cancelled' — but a future
347
+ // contributor using the core FileUploadStatus enum must not get an early
348
+ // onAllComplete for a file the core contract still calls in-flight).
349
+ const pending = files.some((f) => f.status === 'idle' ||
350
+ f.status === 'uploading' ||
351
+ f.status === 'preparing' ||
352
+ f.status === 'processing');
353
+ if (!pending && files.length > 0) {
354
+ events.onAllComplete?.([...files]);
355
+ }
356
+ }
357
+ // -------------------------------------------------------------------------
358
+ // Instance
359
+ // -------------------------------------------------------------------------
360
+ const instance = {
361
+ addFiles(incoming) {
362
+ const toProcess = allowMultiple ? incoming : incoming.slice(0, 1);
363
+ const added = [];
364
+ for (const source of toProcess) {
365
+ const uploadFile = {
366
+ id: generateId(),
367
+ name: source.name,
368
+ size: source.size,
369
+ type: source.type,
370
+ status: 'idle',
371
+ progress: 0,
372
+ source,
373
+ };
374
+ const errors = validateFile(uploadFile, options.validation, files.length);
375
+ if (errors.length > 0) {
376
+ events.onValidationError?.(uploadFile, errors);
377
+ continue;
378
+ }
379
+ files.push(uploadFile);
380
+ added.push(uploadFile);
381
+ // Generate preview asynchronously if enabled
382
+ if (options.imagePreview && source.type.startsWith('image/')) {
383
+ const maxSize = options.imagePreviewMaxSize ?? 200;
384
+ void generatePreview(source, maxSize).then((preview) => {
385
+ if (preview) {
386
+ uploadFile.preview = preview;
387
+ }
388
+ });
389
+ }
390
+ }
391
+ if (added.length > 0) {
392
+ events.onFilesAdded?.(added);
393
+ if (options.autoUpload) {
394
+ processQueue();
395
+ }
396
+ }
397
+ return added;
398
+ },
399
+ removeFile(fileId) {
400
+ const idx = files.findIndex((f) => f.id === fileId);
401
+ if (idx === -1)
402
+ return;
403
+ const file = files[idx];
404
+ // Cancel if actively uploading. Mark 'cancelled' BEFORE aborting so the
405
+ // transport rejection is recognized as intentional — otherwise removing an
406
+ // uploading file fires onError with a spurious "Upload cancelled"/abort
407
+ // message for a user-initiated removal.
408
+ const handle = activeUploads.get(fileId);
409
+ if (handle) {
410
+ file.status = 'cancelled';
411
+ handle.abort();
412
+ activeUploads.delete(fileId);
413
+ }
414
+ files.splice(idx, 1);
415
+ events.onFileRemoved?.(file);
416
+ },
417
+ clearFiles() {
418
+ for (const [id, handle] of activeUploads) {
419
+ // Mark 'cancelled' before aborting (see removeFile) so cleared files
420
+ // don't surface onError from their aborted transports.
421
+ const file = files.find((f) => f.id === id);
422
+ if (file)
423
+ file.status = 'cancelled';
424
+ handle.abort();
425
+ activeUploads.delete(id);
426
+ }
427
+ files.length = 0;
428
+ },
429
+ getFiles() {
430
+ return [...files];
431
+ },
432
+ getFile(fileId) {
433
+ return files.find((f) => f.id === fileId);
434
+ },
435
+ upload() {
436
+ processQueue();
437
+ },
438
+ cancelUpload(fileId) {
439
+ const file = files.find((f) => f.id === fileId);
440
+ if (!file || file.status !== 'uploading')
441
+ return;
442
+ const handle = activeUploads.get(fileId);
443
+ if (handle) {
444
+ handle.abort();
445
+ activeUploads.delete(fileId);
446
+ }
447
+ file.status = 'cancelled';
448
+ },
449
+ cancelAll() {
450
+ for (const file of files) {
451
+ if (file.status === 'uploading') {
452
+ const handle = activeUploads.get(file.id);
453
+ if (handle) {
454
+ handle.abort();
455
+ activeUploads.delete(file.id);
456
+ }
457
+ file.status = 'cancelled';
458
+ }
459
+ }
460
+ },
461
+ retry(fileId) {
462
+ const file = files.find((f) => f.id === fileId);
463
+ if (!file || (file.status !== 'error' && file.status !== 'cancelled'))
464
+ return;
465
+ Object.assign(file, { status: 'idle', progress: 0, error: undefined });
466
+ if (options.autoUpload) {
467
+ processQueue();
468
+ }
469
+ },
470
+ retryAll() {
471
+ for (const file of files) {
472
+ if (file.status === 'error' || file.status === 'cancelled') {
473
+ Object.assign(file, { status: 'idle', progress: 0, error: undefined });
474
+ }
475
+ }
476
+ if (options.autoUpload) {
477
+ processQueue();
478
+ }
479
+ },
480
+ isUploading() {
481
+ return files.some((f) => f.status === 'uploading');
482
+ },
483
+ getTotalProgress() {
484
+ if (files.length === 0)
485
+ return 0;
486
+ const total = files.reduce((sum, f) => sum + f.progress, 0);
487
+ return Math.round(total / files.length);
488
+ },
489
+ destroy() {
490
+ for (const [id, handle] of activeUploads) {
491
+ // Mark 'cancelled' before aborting (see removeFile) so no onError fires
492
+ // after the instance has been destroyed.
493
+ const file = files.find((f) => f.id === id);
494
+ if (file)
495
+ file.status = 'cancelled';
496
+ handle.abort();
497
+ }
498
+ activeUploads.clear();
499
+ files.length = 0;
500
+ },
501
+ };
502
+ return instance;
503
+ }
504
+ // ---------------------------------------------------------------------------
505
+ // Provider
506
+ // ---------------------------------------------------------------------------
507
+ /**
508
+ * Creates a FilePond-style file upload provider.
509
+ *
510
+ * @param config - Optional FilePond-specific configuration.
511
+ * @returns A `FileUploadProvider` backed by FilePond-style processing.
512
+ *
513
+ * @example
514
+ * ```typescript
515
+ * import { createFilepondProvider } from '@molecule/app-file-upload-filepond'
516
+ * import { setProvider } from '@molecule/app-file-upload'
517
+ *
518
+ * setProvider(createFilepondProvider())
519
+ * ```
520
+ */
521
+ export function createFilepondProvider(config = {}) {
522
+ return {
523
+ createUploader(options) {
524
+ return createUploaderInstance(options, config);
525
+ },
526
+ };
527
+ }
528
+ /** Default FilePond file upload provider instance. */
529
+ export const provider = createFilepondProvider();
@@ -0,0 +1,16 @@
1
+ /**
2
+ * FilePond file upload provider configuration types.
3
+ *
4
+ * @module
5
+ */
6
+ /**
7
+ * Configuration options for the FilePond file upload provider.
8
+ */
9
+ export interface FilepondConfig {
10
+ /**
11
+ * Timeout in milliseconds for individual upload requests.
12
+ * Set to `0` for no timeout. Defaults to `0`.
13
+ */
14
+ timeout?: number;
15
+ }
16
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,OAAO,CAAC,EAAE,MAAM,CAAA;CACjB"}
package/dist/types.js ADDED
@@ -0,0 +1,6 @@
1
+ /**
2
+ * FilePond file upload provider configuration types.
3
+ *
4
+ * @module
5
+ */
6
+ export {};
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@molecule/app-file-upload-filepond",
3
+ "version": "1.0.0",
4
+ "description": "FilePond-style file upload provider for @molecule/app-file-upload",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "tsc",
10
+ "test": "vitest run",
11
+ "test:watch": "vitest"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "keywords": [
23
+ "molecule",
24
+ "file",
25
+ "upload",
26
+ "filepond"
27
+ ],
28
+ "license": "Apache-2.0",
29
+ "peerDependencies": {
30
+ "@molecule/app-file-upload": ">=1.0.0",
31
+ "@molecule/app-i18n": ">=1.0.0"
32
+ },
33
+ "devDependencies": {
34
+ "@molecule/app-file-upload": "1.0.0",
35
+ "@molecule/app-i18n": "1.0.0",
36
+ "@types/node": "26.1.2",
37
+ "typescript": "6.0.3",
38
+ "vitest": "4.1.10"
39
+ }
40
+ }