Open History to see the last commit
1import {
2 clampFileAttachmentUploadBytes,
3 fileAttachmentTooLargeMessage,
4} from "@t3tools/client-runtime/state/attachments";
5import { errorDisplayMessage } from "@t3tools/client-runtime/errors";
6import {
7 isProviderSendTurnSupportedImageMimeType,
8 PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
9 PROVIDER_SEND_TURN_MAX_FILE_BYTES,
10 PROVIDER_SEND_TURN_MAX_IMAGE_BYTES,
11 type EnvironmentId,
12 type PastedTextAttachmentSource,
13 type UploadChatImageAttachment,
14} from "@t3tools/contracts";
15import type { AttachmentUploadStatus } from "@t3tools/client-runtime/state/attachment-uploads";
16import type { DocumentPickerResult } from "expo-document-picker";
17import { msg } from "gt-react-native";
18import { m } from "../i18n/messages";
19import { estimateBase64ByteSize } from "./base64";
20import {
21 COMPOSER_ATTACHMENT_DIRECTORY,
22 isComposerAttachmentFileRetained,
23 resolveOwnedComposerAttachmentFileUri,
24} from "./composerAttachmentFiles";
25import { imageMimeType } from "@t3tools/shared/image";
26import { videoMimeType } from "@t3tools/shared/video";
27import { fitComposerImage, renderPhoto } from "./composerImageFit";
28import { beginForegroundHandoff } from "./foreground-handoff";
29import { uuidv4 } from "./uuid";
30import { writeFileAtomically } from "./atomic-file";
31
32export interface DraftComposerImageAttachment extends Omit<UploadChatImageAttachment, "dataUrl"> {
33 readonly id: string;
34 readonly previewUri: string;
35 readonly fileUri?: string;
36 readonly dataUrl?: string;
37 readonly uploadedAttachmentId?: string;
38 readonly uploadEnvironmentId?: EnvironmentId;
39}
40
41export interface DraftComposerFileAttachment {
42 readonly id: string;
43 readonly type: "file";
44 readonly name: string;
45 readonly mimeType: string;
46 readonly sizeBytes: number;
47 readonly fileUri: string;
48 readonly source?: PastedTextAttachmentSource;
49 readonly uploadedAttachmentId?: string;
50 readonly uploadEnvironmentId?: EnvironmentId;
51}
52
53export async function createPastedTextComposerAttachment(input: {
54 readonly text: string;
55 readonly name: string;
56 readonly maxBytes: number;
57}): Promise<DraftComposerFileAttachment> {
58 const bytes = new TextEncoder().encode(input.text).byteLength;
59 if (bytes <= 0) {
60 throw new Error(m(msg("Clipboard is empty.")));
61 }
62 if (bytes > input.maxBytes) {
63 throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes, m));
64 }
65
66 const { Directory, File, Paths } = await import("expo-file-system");
67 const directory = new Directory(Paths.document, COMPOSER_ATTACHMENT_DIRECTORY);
68 directory.create({ idempotent: true, intermediates: true });
69 const file = new File(directory, `${uuidv4()}-${input.name}`);
70 await writeFileAtomically(file, input.text);
71 return {
72 id: uuidv4(),
73 type: "file",
74 name: input.name,
75 mimeType: "text/plain;charset=utf-8",
76 sizeBytes: bytes,
77 fileUri: file.uri,
78 source: { _tag: "pasted-text" },
79 };
80}
81
82export type DraftComposerAttachment = DraftComposerImageAttachment | DraftComposerFileAttachment;
83
84/**
85 * Non-media attachments require chip references; missing references mean lost draft files.
86 * A chip cannot retry an upload or show its progress, so a document whose upload failed joins
87 * the strip until its retry finishes.
88 */
89export function composerStripAttachments(
90 attachments: ReadonlyArray<DraftComposerAttachment>,
91 uploadStatus: (attachment: DraftComposerAttachment) => AttachmentUploadStatus | undefined,
92): ReadonlyArray<DraftComposerAttachment> {
93 return attachments.filter((attachment) => {
94 if (
95 attachment.type === "image" ||
96 imageMimeType(attachment) !== null ||
97 videoMimeType(attachment) !== null
98 ) {
99 return true;
100 }
101 const upload = uploadStatus(attachment);
102 return (
103 upload?.status === "failed" || (upload?.status === "uploading" && upload.retrying === true)
104 );
105 });
106}
107
108/** Promote legacy document-picked images only when their originals fit the image contract. */
109export function isComposerImageAttachment(
110 attachment: DraftComposerAttachment,
111): attachment is DraftComposerImageAttachment {
112 return (
113 attachment.type === "image" ||
114 (attachment.sizeBytes <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES &&
115 imageMimeType(attachment) !== null)
116 );
117}
118
119export type FileBackedComposerAttachment = DraftComposerAttachment & { readonly fileUri: string };
120
121export function isFileBackedComposerAttachment(
122 attachment: DraftComposerAttachment,
123): attachment is FileBackedComposerAttachment {
124 return attachment.fileUri !== undefined;
125}
126
127/** Inline library/clipboard images own no file; local ids cannot resolve server assets. */
128export function composerAttachmentInlineUri(
129 attachment: DraftComposerAttachment | undefined,
130): string | undefined {
131 if (attachment === undefined || isFileBackedComposerAttachment(attachment)) return undefined;
132 return attachment.type === "image" ? (attachment.dataUrl ?? attachment.previewUri) : undefined;
133}
134
135const OWNED_PASTED_IMAGE_DIRECTORY = "t3-composer-paste";
136const ATTACHMENT_COPY_CHUNK_BYTES = 64 * 1024;
137
138export async function persistComposerAttachmentFile(
139 uri: string,
140 name: string,
141 maxBytes?: number,
142): Promise<string> {
143 const { Directory, File, FileMode, Paths } = await import("expo-file-system");
144 const directory = new Directory(Paths.document, COMPOSER_ATTACHMENT_DIRECTORY);
145 directory.create({ idempotent: true, intermediates: true });
146 // Android's java.net.URI rejects characters expo-file-system leaves unencoded, such as `[` and `]`.
147 const safeName = name.replace(/[^\w. -]/g, "-") || "file";
148 const destination = new File(directory, `${uuidv4()}-${safeName}`);
149 const source = new File(uri);
150 const sourceSize = source.size;
151 if (
152 maxBytes !== undefined &&
153 (sourceSize === null || (sourceSize === 0 && uri.startsWith("content:")))
154 ) {
155 destination.create();
156 try {
157 const reader = source.open(FileMode.ReadOnly);
158 try {
159 const writer = destination.open(FileMode.WriteOnly);
160 try {
161 let copiedBytes = 0;
162 while (true) {
163 const chunk = await reader.readBytes(
164 Math.min(ATTACHMENT_COPY_CHUNK_BYTES, maxBytes - copiedBytes + 1),
165 );
166 if (chunk.byteLength === 0) {
167 break;
168 }
169 copiedBytes += chunk.byteLength;
170 if (copiedBytes > maxBytes) {
171 throw new Error(fileAttachmentTooLargeMessage(name, maxBytes, m));
172 }
173 await writer.writeBytes(chunk);
174 }
175 } finally {
176 writer.close();
177 }
178 } finally {
179 reader.close();
180 }
181 } catch (error) {
182 if (destination.exists) {
183 destination.delete();
184 }
185 throw error;
186 }
187 return destination.uri;
188 }
189
190 if (maxBytes !== undefined && sourceSize !== null && sourceSize > maxBytes) {
191 throw new Error(fileAttachmentTooLargeMessage(name, maxBytes, m));
192 }
193 try {
194 await source.copy(destination);
195 } catch (error) {
196 // Failed copies may leave untracked partial files; delete before surfacing failure.
197 try {
198 if (destination.exists) {
199 destination.delete();
200 }
201 } catch (cleanupError) {
202 console.warn("[composer-attachments] could not remove a partial copy", cleanupError);
203 }
204 throw error;
205 }
206 // Android content streams may exceed reported size; validate the persisted copy.
207 const copiedSize = destination.size;
208 if (maxBytes !== undefined && copiedSize !== null && copiedSize > maxBytes) {
209 try {
210 if (destination.exists) {
211 destination.delete();
212 }
213 } catch (cleanupError) {
214 console.warn("[composer-attachments] could not remove an oversized copy", cleanupError);
215 }
216 throw new Error(fileAttachmentTooLargeMessage(name, maxBytes, m));
217 }
218 return destination.uri;
219}
220
221export async function removePersistedComposerAttachmentFile(uri: string): Promise<void> {
222 try {
223 const { File, Paths } = await import("expo-file-system");
224 const ownedUri = resolveOwnedComposerAttachmentFileUri(uri, Paths.document.uri);
225 if (ownedUri === null || isComposerAttachmentFileRetained(ownedUri)) {
226 return;
227 }
228 const file = new File(ownedUri);
229 if (file.exists) {
230 file.delete();
231 }
232 } catch (error) {
233 console.warn("[composer-attachments] could not remove local file", error);
234 }
235}
236
237export async function createComposerFileAttachment(input: {
238 readonly uri: string;
239 readonly name: string;
240 readonly mimeType: string;
241 readonly sizeBytes: number | null;
242 readonly maxBytes: number;
243}): Promise<DraftComposerFileAttachment> {
244 if (input.sizeBytes !== null && input.sizeBytes > input.maxBytes) {
245 throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes, m));
246 }
247 const { File } = await import("expo-file-system");
248 const fileUri = await persistComposerAttachmentFile(input.uri, input.name, input.maxBytes);
249 try {
250 const sizeBytes = new File(fileUri).size ?? input.sizeBytes ?? 0;
251 if (sizeBytes <= 0) {
252 throw new Error(m(msg("''{name}'' is empty or could not be read.", { name: input.name })));
253 }
254 if (sizeBytes > input.maxBytes) {
255 throw new Error(fileAttachmentTooLargeMessage(input.name, input.maxBytes, m));
256 }
257 return {
258 id: uuidv4(),
259 type: "file",
260 name: input.name,
261 mimeType: input.mimeType,
262 sizeBytes,
263 fileUri,
264 };
265 } catch (error) {
266 await removePersistedComposerAttachmentFile(fileUri);
267 throw error;
268 }
269}
270
271export async function pickComposerFiles(input: {
272 readonly existingCount: number;
273 readonly maxBytes?: number;
274}): Promise<{
275 readonly files: ReadonlyArray<DraftComposerAttachment>;
276 readonly error: string | null;
277}> {
278 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
279 if (remainingSlots <= 0) {
280 return {
281 files: [],
282 error: m(
283 msg("You can attach up to {max} files per message.", {
284 max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
285 }),
286 ),
287 };
288 }
289
290 const { getDocumentAsync } = await import("expo-document-picker");
291 const endHandoff = beginForegroundHandoff();
292 let result: DocumentPickerResult;
293 try {
294 // Import a readable cache copy because FileSystem may not read provider URIs directly.
295 result = await getDocumentAsync({ multiple: true, copyToCacheDirectory: true });
296 } catch (cause) {
297 return {
298 files: [],
299 error: errorDisplayMessage(cause, m) ?? m(msg("Could not open the file picker.")),
300 };
301 } finally {
302 endHandoff();
303 }
304 if (result.canceled) {
305 return { files: [], error: null };
306 }
307
308 const maxBytes = clampFileAttachmentUploadBytes(
309 input.maxBytes ?? PROVIDER_SEND_TURN_MAX_FILE_BYTES,
310 );
311 const attachments: DraftComposerAttachment[] = [];
312 let error: string | null = null;
313 let exceededAttachmentLimit = false;
314 for (const file of result.assets) {
315 if (attachments.length >= remainingSlots) {
316 exceededAttachmentLimit = true;
317 break;
318 }
319 // SAF can return blank display names, but the wire contract rejects them; fill before persisting.
320 const name = file.name.trim().length > 0 ? file.name : "file";
321 try {
322 const mimeType = imageMimeType({ name, mimeType: file.mimeType ?? "" });
323 const attachment = await createComposerFileAttachment({
324 uri: file.uri,
325 name,
326 mimeType: file.mimeType || "application/octet-stream",
327 sizeBytes: file.size ?? null,
328 maxBytes:
329 mimeType === null ? maxBytes : Math.max(maxBytes, PROVIDER_SEND_TURN_MAX_IMAGE_BYTES),
330 });
331 if (mimeType === null || attachment.sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
332 attachments.push(attachment);
333 continue;
334 }
335 try {
336 const { File } = await import("expo-file-system");
337 const original = await new File(attachment.fileUri).base64();
338 const candidate = await fitComposerImage({
339 uri: attachment.fileUri,
340 mimeType,
341 base64: original,
342 });
343 const fitted =
344 candidate !== null &&
345 estimateBase64ByteSize(candidate.base64) <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
346 ? candidate
347 : null;
348 const base64 = fitted?.base64 ?? original;
349 const sizeBytes = estimateBase64ByteSize(base64);
350 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
351 throw new Error(m(msg("''{name}'' exceeds the 10 MB attachment limit.", { name })));
352 }
353 const dataUrl = `data:${mimeType};base64,${base64}`;
354 attachments.push({
355 id: attachment.id,
356 type: "image",
357 name,
358 mimeType,
359 sizeBytes,
360 dataUrl,
361 previewUri: fitted?.uri ?? dataUrl,
362 });
363 } finally {
364 await removePersistedComposerAttachmentFile(attachment.fileUri);
365 }
366 } catch (cause) {
367 error = errorDisplayMessage(cause, m) ?? m(msg("Could not read ''{name}''.", { name }));
368 }
369 }
370 if (exceededAttachmentLimit) {
371 error = m(
372 msg("You can attach up to {max} files per message.", {
373 max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
374 }),
375 );
376 }
377 return { files: attachments, error };
378}
379
380async function loadImagePicker() {
381 try {
382 return await import("expo-image-picker");
383 } catch (error) {
384 throw new Error(m(msg("The photo library is unavailable right now.")), { cause: error });
385 }
386}
387
388export async function pickComposerImages(input: { readonly existingCount: number }): Promise<{
389 readonly images: ReadonlyArray<DraftComposerImageAttachment>;
390 readonly error: string | null;
391}> {
392 const result = await pickComposerMedia(input);
393 return {
394 images: result.attachments.filter((attachment) => attachment.type === "image"),
395 error: result.error,
396 };
397}
398
399export async function pickComposerMedia(input: {
400 readonly existingCount: number;
401 readonly maxVideoBytes?: number;
402}): Promise<{
403 readonly attachments: ReadonlyArray<DraftComposerAttachment>;
404 readonly error: string | null;
405}> {
406 const remainingSlots = PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
407 if (remainingSlots <= 0) {
408 return {
409 attachments: [],
410 error: m(
411 msg("You can attach up to {max} attachments per message.", {
412 max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
413 }),
414 ),
415 };
416 }
417
418 let imagePicker: Awaited<ReturnType<typeof loadImagePicker>>;
419 try {
420 imagePicker = await loadImagePicker();
421 } catch (error) {
422 return {
423 attachments: [],
424 error: errorDisplayMessage(error, m) ?? m(msg("The photo library is unavailable right now.")),
425 };
426 }
427
428 // Android pickers report background state; guard against deferred restarts mid-pick.
429 const endHandoff = beginForegroundHandoff();
430 let result: Awaited<ReturnType<typeof imagePicker.launchImageLibraryAsync>>;
431 try {
432 result = await imagePicker.launchImageLibraryAsync({
433 mediaTypes: input.maxVideoBytes === undefined ? ["images"] : ["images", "videos"],
434 allowsMultipleSelection: true,
435 selectionLimit: remainingSlots,
436 // Base64 makes iOS decode all full-size photos and stalls JS with large strings; read bytes only as needed.
437 base64: false,
438 quality: 1,
439 shouldDownloadFromNetwork: true,
440 });
441 } catch (error) {
442 return {
443 attachments: [],
444 error: errorDisplayMessage(error, m) ?? m(msg("Could not open the photo library.")),
445 };
446 } finally {
447 endHandoff();
448 }
449
450 if (result.canceled) {
451 return {
452 attachments: [],
453 error: null,
454 };
455 }
456
457 const attachments: DraftComposerAttachment[] = [];
458 let error: string | null = null;
459
460 for (const asset of result.assets) {
461 if (attachments.length >= remainingSlots) {
462 error = m(
463 msg("You can attach up to {max} attachments per message.", {
464 max: PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
465 }),
466 );
467 break;
468 }
469 const mimeType = asset.mimeType?.toLowerCase();
470 if (asset.type === "video" || mimeType?.startsWith("video/")) {
471 if (input.maxVideoBytes === undefined) {
472 error = m(msg("Video attachments are unavailable here."));
473 continue;
474 }
475 try {
476 const { File } = await import("expo-file-system");
477 const file = new File(asset.uri);
478 attachments.push(
479 await createComposerFileAttachment({
480 uri: asset.uri,
481 name: asset.fileName?.trim() || file.name || "video",
482 mimeType: mimeType || file.type || "application/octet-stream",
483 sizeBytes: asset.fileSize ?? null,
484 maxBytes: clampFileAttachmentUploadBytes(input.maxVideoBytes),
485 }),
486 );
487 } catch (cause) {
488 error =
489 errorDisplayMessage(cause, m) ??
490 m(msg("Could not read ''{name}''.", { name: asset.fileName ?? "video" }));
491 }
492 continue;
493 }
494 if (asset.type !== "image" && !mimeType?.startsWith("image/")) {
495 error = m(msg("Unsupported file type for ''{name}''.", { name: asset.fileName ?? "image" }));
496 continue;
497 }
498
499 const name = asset.fileName?.trim() || "image";
500 // Android content streams can exceed their reported size; measure the file before loading bytes into JS.
501 let sourceBytes: number | null = null;
502 try {
503 const { File } = await import("expo-file-system");
504 sourceBytes = new File(asset.uri).size;
505 } catch {
506 sourceBytes = null;
507 }
508 // Pass through supported, under-cap originals unchanged to preserve transparency and animation.
509 const originalMimeType =
510 mimeType !== undefined &&
511 isProviderSendTurnSupportedImageMimeType(mimeType) &&
512 sourceBytes !== null &&
513 sourceBytes > 0 &&
514 sourceBytes <= PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
515 ? mimeType
516 : null;
517
518 let image: { base64: string; mimeType: string; name: string; previewUri: string };
519 try {
520 if (originalMimeType !== null) {
521 const { File } = await import("expo-file-system");
522 const base64 = await new File(asset.uri).base64();
523 const fitted = await fitComposerImage({
524 uri: asset.uri,
525 mimeType: originalMimeType,
526 base64,
527 });
528 image = {
529 base64: fitted?.base64 ?? base64,
530 mimeType: originalMimeType,
531 name,
532 previewUri: fitted?.uri ?? asset.uri,
533 };
534 } else {
535 const rendered = await renderPhoto(asset.uri);
536 image = {
537 base64: rendered.base64,
538 mimeType: "image/jpeg",
539 name: /\.jpe?g$/i.test(name) ? name : `${name.replace(/\.[^.]+$/, "")}.jpg`,
540 previewUri: rendered.uri,
541 };
542 }
543 } catch {
544 error = m(msg("Failed to read ''{name}''.", { name }));
545 continue;
546 }
547
548 const sizeBytes = estimateBase64ByteSize(image.base64);
549 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
550 error = m(msg("''{name}'' exceeds the 10 MB attachment limit.", { name }));
551 continue;
552 }
553
554 attachments.push({
555 id: uuidv4(),
556 type: "image",
557 name: image.name,
558 mimeType: image.mimeType,
559 sizeBytes,
560 dataUrl: `data:${image.mimeType};base64,${image.base64}`,
561 previewUri: image.previewUri,
562 });
563 }
564
565 return {
566 attachments,
567 error,
568 };
569}
570
571function mimeTypeFromUri(uri: string): string {
572 const ext = uri.split(".").pop()?.toLowerCase();
573 switch (ext) {
574 case "png":
575 return "image/png";
576 case "jpg":
577 case "jpeg":
578 return "image/jpeg";
579 case "gif":
580 return "image/gif";
581 case "webp":
582 return "image/webp";
583 case "heic":
584 return "image/heic";
585 default:
586 return "image/png";
587 }
588}
589
590function isOwnedPastedImageUri(uri: string): boolean {
591 try {
592 const url = new URL(uri);
593 if (url.protocol !== "file:") {
594 return false;
595 }
596 const segments = url.pathname.split("/").filter(Boolean);
597 return segments.at(-2) === OWNED_PASTED_IMAGE_DIRECTORY;
598 } catch {
599 return false;
600 }
601}
602
603/** Leave out existingCount when the draft store caps after its duplicate check. */
604export async function convertPastedImagesToAttachments(input: {
605 readonly uris: ReadonlyArray<string>;
606 readonly existingCount?: number;
607}): Promise<{
608 readonly attachments: ReadonlyArray<DraftComposerImageAttachment>;
609 readonly error: string | null;
610}> {
611 const { File } = await import("expo-file-system");
612 const remainingSlots =
613 input.existingCount === undefined
614 ? Number.POSITIVE_INFINITY
615 : PROVIDER_SEND_TURN_MAX_ATTACHMENTS - input.existingCount;
616 const attachments: DraftComposerImageAttachment[] = [];
617 let error: string | null = null;
618
619 for (const [index, uri] of input.uris.entries()) {
620 const temporaryUris = isOwnedPastedImageUri(uri) ? [uri] : [];
621 try {
622 if (index >= Math.max(0, remainingSlots)) {
623 continue;
624 }
625 const file = new File(uri);
626 const reportedMimeType = file.type;
627 const sourceMimeType = reportedMimeType?.startsWith("image/")
628 ? reportedMimeType
629 : mimeTypeFromUri(uri);
630 let mimeType = isProviderSendTurnSupportedImageMimeType(sourceMimeType)
631 ? sourceMimeType
632 : "image/jpeg";
633 const rendered = mimeType === sourceMimeType ? null : await renderPhoto(uri);
634 const pastedBase64 = rendered?.base64 ?? (await file.base64());
635 const fitted = rendered ?? (await fitComposerImage({ uri, mimeType, base64: pastedBase64 }));
636 if (fitted !== null) {
637 temporaryUris.push(fitted.uri);
638 }
639 let base64 = fitted?.base64 ?? pastedBase64;
640 if (
641 rendered === null &&
642 estimateBase64ByteSize(base64) > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES
643 ) {
644 const jpeg = await renderPhoto(uri);
645 temporaryUris.push(jpeg.uri);
646 mimeType = "image/jpeg";
647 base64 = jpeg.base64;
648 }
649 const sizeBytes = estimateBase64ByteSize(base64);
650 if (sizeBytes <= 0 || sizeBytes > PROVIDER_SEND_TURN_MAX_IMAGE_BYTES) {
651 error =
652 sizeBytes > 0
653 ? m(msg("A pasted image exceeds the 10 MB attachment limit."))
654 : m(msg("Could not read a pasted image."));
655 continue;
656 }
657 const dataUrl = `data:${mimeType};base64,${base64}`;
658 attachments.push({
659 id: uuidv4(),
660 type: "image",
661 name: `pasted-image.${mimeType.split("/")[1] ?? "png"}`,
662 mimeType,
663 sizeBytes,
664 dataUrl,
665 previewUri: dataUrl,
666 });
667 } catch (cause) {
668 console.warn("Failed to read pasted image", uri, cause);
669 error = m(msg("Could not read a pasted image."));
670 } finally {
671 for (const temporaryUri of temporaryUris) {
672 try {
673 const file = new File(temporaryUri);
674 if (file.exists) {
675 file.delete();
676 }
677 } catch (error) {
678 console.warn("Failed to remove temporary pasted image", temporaryUri, error);
679 }
680 }
681 }
682 }
683
684 return { attachments, error };
685}