@adminide-stack/yantra-mobile 12.0.44-alpha.6 → 12.0.44
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/lib/bridge/handlers/NavigationBridgeHandler.js +3 -1
- package/lib/bridge/handlers/NavigationBridgeHandler.js.map +1 -1
- package/lib/components/CustomDrawer.js +122 -82
- package/lib/components/CustomDrawer.js.map +1 -1
- package/lib/components/KeyboardComposerDock.js +10 -1
- package/lib/components/KeyboardComposerDock.js.map +1 -1
- package/lib/components/NavigationHeader/NavigationHeader.js +16 -30
- package/lib/components/NavigationHeader/NavigationHeader.js.map +1 -1
- package/lib/compute.js +54 -5
- package/lib/compute.js.map +1 -1
- package/lib/config/env-config.js +13 -0
- package/lib/config/env-config.js.map +1 -1
- package/lib/features/apps/AppsCatalog.js +200 -0
- package/lib/features/apps/AppsCatalog.js.map +1 -0
- package/lib/features/apps/mobileAppCatalog.js +1 -0
- package/lib/features/apps/mobileAppCatalog.js.map +1 -1
- package/lib/features/apps/resolveSurfaceUrl.js +22 -2
- package/lib/features/apps/resolveSurfaceUrl.js.map +1 -1
- package/lib/features/attachments/ComposerAttachmentBar.js +64 -0
- package/lib/features/attachments/ComposerAttachmentBar.js.map +1 -0
- package/lib/features/attachments/MessageAttachmentPreviews.js +77 -0
- package/lib/features/attachments/MessageAttachmentPreviews.js.map +1 -0
- package/lib/features/attachments/attachmentPreviewUri.js +9 -0
- package/lib/features/attachments/attachmentPreviewUri.js.map +1 -0
- package/lib/features/attachments/buildGatewayMedia.js +118 -0
- package/lib/features/attachments/buildGatewayMedia.js.map +1 -0
- package/lib/features/attachments/composerAttachmentHandoff.js +15 -0
- package/lib/features/attachments/composerAttachmentHandoff.js.map +1 -0
- package/lib/features/attachments/displayUserMessageText.js +19 -0
- package/lib/features/attachments/displayUserMessageText.js.map +1 -0
- package/lib/features/attachments/historyAttachmentLabel.js +51 -0
- package/lib/features/attachments/historyAttachmentLabel.js.map +1 -0
- package/lib/features/attachments/isImageAttachment.js +7 -0
- package/lib/features/attachments/isImageAttachment.js.map +1 -0
- package/lib/features/attachments/preserveAttachmentPreviews.js +41 -0
- package/lib/features/attachments/preserveAttachmentPreviews.js.map +1 -0
- package/lib/features/attachments/uploadChatAttachments.js +102 -0
- package/lib/features/attachments/uploadChatAttachments.js.map +1 -0
- package/lib/features/attachments/useImageAttachments.js +102 -7
- package/lib/features/attachments/useImageAttachments.js.map +1 -1
- package/lib/features/canvas/nativeViewerRegistry.js +8 -1
- package/lib/features/canvas/nativeViewerRegistry.js.map +1 -1
- package/lib/features/canvas/surfaceIndex.js +25 -0
- package/lib/features/canvas/surfaceIndex.js.map +1 -0
- package/lib/features/canvas/useCanvasSession.js +57 -0
- package/lib/features/canvas/useCanvasSession.js.map +1 -0
- package/lib/features/chat/ChatTranscript.js +202 -0
- package/lib/features/chat/ChatTranscript.js.map +1 -0
- package/lib/features/chat/MessageActionBar.js +56 -0
- package/lib/features/chat/MessageActionBar.js.map +1 -0
- package/lib/hooks/mintSurfaceSystemToken.js +86 -5
- package/lib/hooks/mintSurfaceSystemToken.js.map +1 -1
- package/lib/hooks/resolveSurfaceAuthGraphqlUrl.js +48 -0
- package/lib/hooks/resolveSurfaceAuthGraphqlUrl.js.map +1 -0
- package/lib/hooks/useCdecliChannel.js +5 -3
- package/lib/hooks/useCdecliChannel.js.map +1 -1
- package/lib/hooks/useChatApi.js +32 -15
- package/lib/hooks/useChatApi.js.map +1 -1
- package/lib/hooks/useChatStream.js +35 -8
- package/lib/hooks/useChatStream.js.map +1 -1
- package/lib/hooks/useKeyboardBottomOffset.js +22 -2
- package/lib/hooks/useKeyboardBottomOffset.js.map +1 -1
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/lib/routes.json +56 -4
- package/lib/screens/Apps/index.js +20 -0
- package/lib/screens/Apps/index.js.map +1 -0
- package/lib/screens/CanvasBoard/index.js +20 -15
- package/lib/screens/CanvasBoard/index.js.map +1 -1
- package/lib/screens/Chat/index.js +50 -59
- package/lib/screens/Chat/index.js.map +1 -1
- package/lib/screens/ChatHistory/index.js +2 -8
- package/lib/screens/ChatHistory/index.js.map +1 -1
- package/lib/screens/Home/HomeScreen.js +57 -21
- package/lib/screens/Home/HomeScreen.js.map +1 -1
- package/lib/screens/Home/components/ChatHistoryLanding.js +15 -9
- package/lib/screens/Home/components/ChatHistoryLanding.js.map +1 -1
- package/lib/screens/Home/components/WebBuilderPrewarm.js +2 -2
- package/lib/screens/Home/components/WebBuilderPrewarm.js.map +1 -1
- package/lib/screens/WebBuilder/index.js +25 -16
- package/lib/screens/WebBuilder/index.js.map +1 -1
- package/lib/screens/WebBuilder/webbuilderWarmCache.js +19 -10
- package/lib/screens/WebBuilder/webbuilderWarmCache.js.map +1 -1
- package/lib/utils/navigateToNewChatHome.js +40 -0
- package/lib/utils/navigateToNewChatHome.js.map +1 -0
- package/package.json +4 -4
- package/lib/components/AppsMenu/AppsMenu.js +0 -295
- package/lib/components/AppsMenu/AppsMenu.js.map +0 -1
- package/lib/components/NavigationHeader/ChatHistoryToggleMobile.js +0 -6
- package/lib/components/NavigationHeader/ChatHistoryToggleMobile.js.map +0 -1
- package/lib/features/canvas/canvasCore.js +0 -41
- package/lib/features/canvas/canvasCore.js.map +0 -1
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
function isImageAttachment(attachment) {
|
|
2
|
+
var _a, _b;
|
|
3
|
+
if (attachment.type === "screenshot") return true;
|
|
4
|
+
if ((_a = attachment.mimeType) == null ? void 0 : _a.startsWith("image/")) return true;
|
|
5
|
+
if ((_b = attachment.dataUrl) == null ? void 0 : _b.startsWith("data:image/")) return true;
|
|
6
|
+
return Boolean(attachment.url && /\.(png|jpe?g|gif|webp|svg)(\?|$)/i.test(attachment.url));
|
|
7
|
+
}export{isImageAttachment};//# sourceMappingURL=isImageAttachment.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"isImageAttachment.js","sources":["../../../src/features/attachments/isImageAttachment.ts"],"sourcesContent":["import type { MessageAttachment } from '../../hooks/useChatStream';\n\n/** True when the attachment can be shown as a photo rather than a file chip. */\nexport function isImageAttachment(attachment: MessageAttachment): boolean {\n if (attachment.type === 'screenshot') return true;\n if (attachment.mimeType?.startsWith('image/')) return true;\n if (attachment.dataUrl?.startsWith('data:image/')) return true;\n return Boolean(attachment.url && /\\.(png|jpe?g|gif|webp|svg)(\\?|$)/i.test(attachment.url));\n}\n"],"names":[],"mappings":"AAGO,SAAS,kBAAkB,UAAwC,EAAA;AAH1E,EAAA,IAAA,EAAA,EAAA,EAAA;AAIE,EAAI,IAAA,UAAA,CAAW,IAAS,KAAA,YAAA,EAAqB,OAAA,IAAA;AAC7C,EAAA,IAAA,CAAI,EAAW,GAAA,UAAA,CAAA,QAAA,KAAX,IAAqB,GAAA,MAAA,GAAA,EAAA,CAAA,UAAA,CAAW,WAAkB,OAAA,IAAA;AACtD,EAAA,IAAA,CAAI,EAAW,GAAA,UAAA,CAAA,OAAA,KAAX,IAAoB,GAAA,MAAA,GAAA,EAAA,CAAA,UAAA,CAAW,gBAAuB,OAAA,IAAA;AAC1D,EAAA,OAAO,QAAQ,UAAW,CAAA,GAAA,IAAO,oCAAoC,IAAK,CAAA,UAAA,CAAW,GAAG,CAAC,CAAA;AAC3F"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __defProps = Object.defineProperties;
|
|
3
|
+
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
4
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
7
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
8
|
+
var __spreadValues = (a, b) => {
|
|
9
|
+
for (var prop in b || (b = {}))
|
|
10
|
+
if (__hasOwnProp.call(b, prop))
|
|
11
|
+
__defNormalProp(a, prop, b[prop]);
|
|
12
|
+
if (__getOwnPropSymbols)
|
|
13
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
14
|
+
if (__propIsEnum.call(b, prop))
|
|
15
|
+
__defNormalProp(a, prop, b[prop]);
|
|
16
|
+
}
|
|
17
|
+
return a;
|
|
18
|
+
};
|
|
19
|
+
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
20
|
+
function attachmentHasPreview(attachment) {
|
|
21
|
+
return Boolean(attachment.dataUrl || attachment.url);
|
|
22
|
+
}
|
|
23
|
+
function preserveAttachmentPreviews(prev, incoming) {
|
|
24
|
+
const unused = [...prev];
|
|
25
|
+
return incoming.map((msg) => {
|
|
26
|
+
var _a;
|
|
27
|
+
if (msg.role !== "user") return msg;
|
|
28
|
+
if (((_a = msg.attachments) != null ? _a : []).some(attachmentHasPreview)) return msg;
|
|
29
|
+
const idx = unused.findIndex((local) => {
|
|
30
|
+
var _a2;
|
|
31
|
+
return local.role === "user" && local.content === msg.content && ((_a2 = local.attachments) != null ? _a2 : []).some(attachmentHasPreview);
|
|
32
|
+
});
|
|
33
|
+
if (idx >= 0) {
|
|
34
|
+
const [local] = unused.splice(idx, 1);
|
|
35
|
+
return __spreadProps(__spreadValues({}, msg), {
|
|
36
|
+
attachments: local.attachments
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
return msg;
|
|
40
|
+
});
|
|
41
|
+
}export{preserveAttachmentPreviews};//# sourceMappingURL=preserveAttachmentPreviews.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"preserveAttachmentPreviews.js","sources":["../../../src/features/attachments/preserveAttachmentPreviews.ts"],"sourcesContent":["import type { MessageAttachment } from '../../hooks/useChatStream';\n\ntype MessageWithAttachments = {\n role: string;\n content: string;\n attachments?: MessageAttachment[];\n};\n\nfunction attachmentHasPreview(attachment: MessageAttachment): boolean {\n return Boolean(attachment.dataUrl || attachment.url);\n}\n\n/**\n * Backend hydration often has the filename but not the in-memory data URL.\n * Keep the local preview so the bubble doesn't fall back to \"Attached: file.jpg\".\n */\nexport function preserveAttachmentPreviews<T extends MessageWithAttachments>(prev: T[], incoming: T[]): T[] {\n const unused = [...prev];\n return incoming.map((msg) => {\n if (msg.role !== 'user') return msg;\n if ((msg.attachments ?? []).some(attachmentHasPreview)) return msg;\n const idx = unused.findIndex(\n (local) =>\n local.role === 'user' &&\n local.content === msg.content &&\n (local.attachments ?? []).some(attachmentHasPreview),\n );\n if (idx >= 0) {\n const [local] = unused.splice(idx, 1);\n return { ...msg, attachments: local.attachments };\n }\n return msg;\n });\n}\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;;;;AAMA,SAAS,qBAAqB,UAAwC,EAAA;AACpE,EAAA,OAAO,OAAQ,CAAA,UAAA,CAAW,OAAW,IAAA,UAAA,CAAW,GAAG,CAAA;AACrD;AAMgB,SAAA,0BAAA,CAA6D,MAAW,QAAoB,EAAA;AAC1G,EAAM,MAAA,MAAA,GAAS,CAAC,GAAG,IAAI,CAAA;AACvB,EAAO,OAAA,QAAA,CAAS,IAAI,CAAO,GAAA,KAAA;AAhB7B,IAAA,IAAA,EAAA;AAiBI,IAAI,IAAA,GAAA,CAAI,IAAS,KAAA,MAAA,EAAe,OAAA,GAAA;AAChC,IAAK,IAAA,CAAA,CAAA,EAAA,GAAA,GAAA,CAAI,gBAAJ,IAAmB,GAAA,EAAA,GAAA,IAAI,IAAK,CAAA,oBAAoB,GAAU,OAAA,GAAA;AAC/D,IAAM,MAAA,GAAA,GAAM,MAAO,CAAA,SAAA,CAAU,CAAM,KAAA,KAAA;AAnBvC,MAAAA,IAAAA,GAAAA;AAmB0C,MAAA,OAAA,KAAA,CAAM,IAAS,KAAA,MAAA,IAAU,KAAM,CAAA,OAAA,KAAY,IAAI,OAAYA,IAAAA,CAAAA,CAAAA,GAAAA,GAAA,KAAM,CAAA,WAAA,KAAN,IAAAA,GAAAA,GAAAA,GAAqB,EAAC,EAAG,KAAK,oBAAoB,CAAA;AAAA,KAAC,CAAA;AACpJ,IAAA,IAAI,OAAO,CAAG,EAAA;AACZ,MAAA,MAAM,CAAC,KAAK,CAAA,GAAI,MAAO,CAAA,MAAA,CAAO,KAAK,CAAC,CAAA;AACpC,MAAA,OAAO,iCACF,GADE,CAAA,EAAA;AAAA,QAEL,aAAa,KAAM,CAAA;AAAA,OACrB,CAAA;AAAA;AAEF,IAAO,OAAA,GAAA;AAAA,GACR,CAAA;AACH"}
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __defProps = Object.defineProperties;
|
|
3
|
+
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
4
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
7
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
8
|
+
var __spreadValues = (a, b) => {
|
|
9
|
+
for (var prop in b || (b = {}))
|
|
10
|
+
if (__hasOwnProp.call(b, prop))
|
|
11
|
+
__defNormalProp(a, prop, b[prop]);
|
|
12
|
+
if (__getOwnPropSymbols)
|
|
13
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
14
|
+
if (__propIsEnum.call(b, prop))
|
|
15
|
+
__defNormalProp(a, prop, b[prop]);
|
|
16
|
+
}
|
|
17
|
+
return a;
|
|
18
|
+
};
|
|
19
|
+
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
20
|
+
function getBaseUrlFromSignedUrl(signedUrl) {
|
|
21
|
+
return signedUrl.split("?")[0];
|
|
22
|
+
}
|
|
23
|
+
function isRemoteObjectUrl(url) {
|
|
24
|
+
return Boolean(url && /^https:\/\//i.test(url) && !url.startsWith("data:"));
|
|
25
|
+
}
|
|
26
|
+
function loadFileSystem() {
|
|
27
|
+
return require("expo-file-system");
|
|
28
|
+
}
|
|
29
|
+
async function localFileForUpload(attachment) {
|
|
30
|
+
var _a, _b, _c, _d;
|
|
31
|
+
const url = (_a = attachment.url) == null ? void 0 : _a.trim();
|
|
32
|
+
if (url && /^(file:|content:)/i.test(url)) return url;
|
|
33
|
+
const dataUrl = (_b = attachment.dataUrl) != null ? _b : "";
|
|
34
|
+
const base64 = dataUrl.includes("base64,") ? dataUrl.split("base64,")[1] : "";
|
|
35
|
+
if (!base64) return null;
|
|
36
|
+
const fs = loadFileSystem();
|
|
37
|
+
const dir = fs.cacheDirectory;
|
|
38
|
+
if (!dir || typeof fs.writeAsStringAsync !== "function") return null;
|
|
39
|
+
const safeName = (attachment.name || "upload").replace(/[^\w.-]+/g, "_");
|
|
40
|
+
const dest = `${dir}yantra-upload-${Date.now()}-${safeName}`;
|
|
41
|
+
const encoding = (_d = (_c = fs.EncodingType) == null ? void 0 : _c.Base64) != null ? _d : "base64";
|
|
42
|
+
await fs.writeAsStringAsync(dest, base64, {
|
|
43
|
+
encoding
|
|
44
|
+
});
|
|
45
|
+
return dest;
|
|
46
|
+
}
|
|
47
|
+
async function putObject(signedUrl, attachment) {
|
|
48
|
+
var _a, _b;
|
|
49
|
+
const fileUri = await localFileForUpload(attachment);
|
|
50
|
+
if (!fileUri) {
|
|
51
|
+
throw new Error(`No bytes to upload for ${attachment.name}`);
|
|
52
|
+
}
|
|
53
|
+
const mimeType = attachment.mimeType || "application/octet-stream";
|
|
54
|
+
const fs = loadFileSystem();
|
|
55
|
+
if (typeof fs.uploadAsync === "function") {
|
|
56
|
+
const result = await fs.uploadAsync(signedUrl, fileUri, {
|
|
57
|
+
httpMethod: "PUT",
|
|
58
|
+
headers: {
|
|
59
|
+
"Content-Type": mimeType
|
|
60
|
+
},
|
|
61
|
+
uploadType: (_b = (_a = fs.FileSystemUploadType) == null ? void 0 : _a.BINARY_CONTENT) != null ? _b : 0
|
|
62
|
+
});
|
|
63
|
+
if (typeof result.status === "number" && result.status >= 400) {
|
|
64
|
+
throw new Error(`S3 upload failed for "${attachment.name}" with status ${result.status}`);
|
|
65
|
+
}
|
|
66
|
+
return;
|
|
67
|
+
}
|
|
68
|
+
const body = await fetch(fileUri).then((res2) => res2.blob());
|
|
69
|
+
const res = await fetch(signedUrl, {
|
|
70
|
+
method: "PUT",
|
|
71
|
+
headers: {
|
|
72
|
+
"Content-Type": mimeType
|
|
73
|
+
},
|
|
74
|
+
body
|
|
75
|
+
});
|
|
76
|
+
if (!res.ok) {
|
|
77
|
+
throw new Error(`S3 upload failed for "${attachment.name}" with status ${res.status}`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
async function uploadChatAttachments(attachments, createFileUploadLinks) {
|
|
81
|
+
const uploadEntries = attachments.map((attachment, index) => ({
|
|
82
|
+
attachment,
|
|
83
|
+
index
|
|
84
|
+
})).filter(({
|
|
85
|
+
attachment
|
|
86
|
+
}) => !isRemoteObjectUrl(attachment.url));
|
|
87
|
+
let signedUrls = [];
|
|
88
|
+
if (uploadEntries.length > 0) {
|
|
89
|
+
const filenames = uploadEntries.map(({
|
|
90
|
+
attachment
|
|
91
|
+
}) => attachment.name || `file-${Date.now()}`);
|
|
92
|
+
signedUrls = await createFileUploadLinks(filenames);
|
|
93
|
+
if (signedUrls.length !== uploadEntries.length) {
|
|
94
|
+
throw new Error(`Expected ${uploadEntries.length} signed URLs but received ${signedUrls.length}`);
|
|
95
|
+
}
|
|
96
|
+
await Promise.all(uploadEntries.map((entry, i) => putObject(signedUrls[i], entry.attachment)));
|
|
97
|
+
}
|
|
98
|
+
const urlByIndex = new Map(uploadEntries.map((entry, i) => [entry.index, getBaseUrlFromSignedUrl(signedUrls[i])]));
|
|
99
|
+
return attachments.map((attachment, index) => __spreadProps(__spreadValues({}, attachment), {
|
|
100
|
+
objectUrl: isRemoteObjectUrl(attachment.url) ? attachment.url : urlByIndex.get(index)
|
|
101
|
+
}));
|
|
102
|
+
}export{uploadChatAttachments};//# sourceMappingURL=uploadChatAttachments.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"uploadChatAttachments.js","sources":["../../../src/features/attachments/uploadChatAttachments.ts"],"sourcesContent":["import type { MessageAttachment } from '../../hooks/useChatStream';\n\nfunction getBaseUrlFromSignedUrl(signedUrl: string): string {\n return signedUrl.split('?')[0];\n}\n\nfunction isRemoteObjectUrl(url: string | undefined): boolean {\n return Boolean(url && /^https:\\/\\//i.test(url) && !url.startsWith('data:'));\n}\n\nfunction loadFileSystem(): {\n cacheDirectory?: string | null;\n writeAsStringAsync?: (uri: string, data: string, options?: { encoding?: string }) => Promise<void>;\n uploadAsync?: (\n url: string,\n fileUri: string,\n options?: { httpMethod?: string; headers?: Record<string, string>; uploadType?: number },\n ) => Promise<{ status?: number }>;\n EncodingType?: { Base64?: string };\n FileSystemUploadType?: { BINARY_CONTENT?: number };\n} {\n // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require\n return require('expo-file-system') as ReturnType<typeof loadFileSystem>;\n}\n\nasync function localFileForUpload(attachment: MessageAttachment): Promise<string | null> {\n const url = attachment.url?.trim();\n if (url && /^(file:|content:)/i.test(url)) return url;\n\n const dataUrl = attachment.dataUrl ?? '';\n const base64 = dataUrl.includes('base64,') ? dataUrl.split('base64,')[1] : '';\n if (!base64) return null;\n\n const fs = loadFileSystem();\n const dir = fs.cacheDirectory;\n if (!dir || typeof fs.writeAsStringAsync !== 'function') return null;\n const safeName = (attachment.name || 'upload').replace(/[^\\w.-]+/g, '_');\n const dest = `${dir}yantra-upload-${Date.now()}-${safeName}`;\n const encoding = fs.EncodingType?.Base64 ?? 'base64';\n await fs.writeAsStringAsync(dest, base64, { encoding });\n return dest;\n}\n\nasync function putObject(signedUrl: string, attachment: MessageAttachment): Promise<void> {\n const fileUri = await localFileForUpload(attachment);\n if (!fileUri) {\n throw new Error(`No bytes to upload for ${attachment.name}`);\n }\n const mimeType = attachment.mimeType || 'application/octet-stream';\n const fs = loadFileSystem();\n if (typeof fs.uploadAsync === 'function') {\n const result = await fs.uploadAsync(signedUrl, fileUri, {\n httpMethod: 'PUT',\n headers: { 'Content-Type': mimeType },\n uploadType: fs.FileSystemUploadType?.BINARY_CONTENT ?? 0,\n });\n if (typeof result.status === 'number' && result.status >= 400) {\n throw new Error(`S3 upload failed for \"${attachment.name}\" with status ${result.status}`);\n }\n return;\n }\n const body = await fetch(fileUri).then((res) => res.blob());\n const res = await fetch(signedUrl, {\n method: 'PUT',\n headers: { 'Content-Type': mimeType },\n body,\n });\n if (!res.ok) {\n throw new Error(`S3 upload failed for \"${attachment.name}\" with status ${res.status}`);\n }\n}\n\n/**\n * Browser `buildAttachmentsForMessage`: PUT each local file to a presigned\n * chat-attachment URL and return copies with the bare S3 object URL set.\n * Local `file:` / `data:` preview fields are left intact on the original objects.\n */\nexport async function uploadChatAttachments(\n attachments: MessageAttachment[],\n createFileUploadLinks: (filenames: string[]) => Promise<string[]>,\n): Promise<Array<MessageAttachment & { objectUrl?: string }>> {\n const uploadEntries = attachments\n .map((attachment, index) => ({ attachment, index }))\n .filter(({ attachment }) => !isRemoteObjectUrl(attachment.url));\n\n let signedUrls: string[] = [];\n if (uploadEntries.length > 0) {\n const filenames = uploadEntries.map(({ attachment }) => attachment.name || `file-${Date.now()}`);\n signedUrls = await createFileUploadLinks(filenames);\n if (signedUrls.length !== uploadEntries.length) {\n throw new Error(`Expected ${uploadEntries.length} signed URLs but received ${signedUrls.length}`);\n }\n await Promise.all(uploadEntries.map((entry, i) => putObject(signedUrls[i], entry.attachment)));\n }\n\n const urlByIndex = new Map(uploadEntries.map((entry, i) => [entry.index, getBaseUrlFromSignedUrl(signedUrls[i])]));\n\n return attachments.map((attachment, index) => ({\n ...attachment,\n objectUrl: isRemoteObjectUrl(attachment.url) ? attachment.url : urlByIndex.get(index),\n }));\n}\n"],"names":["res"],"mappings":";;;;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UAAA,CAAW,MAAW,KAAA,aAAA,CAAc,MAAQ,EAAA;AAC9C,MAAM,MAAA,IAAI,MAAM,CAAY,SAAA,EAAA,aAAA,CAAc,MAAM,CAA6B,0BAAA,EAAA,UAAA,CAAW,MAAM,CAAE,CAAA,CAAA;AAAA;AAElG,IAAA,MAAM,OAAQ,CAAA,GAAA,CAAI,aAAc,CAAA,GAAA,CAAI,CAAC,KAAO,EAAA,CAAA,KAAM,SAAU,CAAA,UAAA,CAAW,CAAC,CAAA,EAAG,KAAM,CAAA,UAAU,CAAC,CAAC,CAAA;AAAA;AAE/F,EAAA,MAAM,aAAa,IAAI,GAAA,CAAI,aAAc,CAAA,GAAA,CAAI,CAAC,KAAO,EAAA,CAAA,KAAM,CAAC,KAAA,CAAM,OAAO,uBAAwB,CAAA,UAAA,CAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;AACjH,EAAA,OAAO,YAAY,GAAI,CAAA,CAAC,UAAY,EAAA,KAAA,KAAW,iCAC1C,UAD0C,CAAA,EAAA;AAAA,IAE7C,SAAA,EAAW,kBAAkB,UAAW,CAAA,GAAG,IAAI,UAAW,CAAA,GAAA,GAAM,UAAW,CAAA,GAAA,CAAI,KAAK;AAAA,GACpF,CAAA,CAAA;AACJ"}
|
|
@@ -25,7 +25,7 @@ function base64Bytes(base64) {
|
|
|
25
25
|
return Math.floor(base64.length * 3 / 4) - padding;
|
|
26
26
|
}
|
|
27
27
|
function toAttachment(asset, index) {
|
|
28
|
-
var _a, _b, _c;
|
|
28
|
+
var _a, _b, _c, _d;
|
|
29
29
|
const base64 = (_a = asset.base64) == null ? void 0 : _a.trim();
|
|
30
30
|
if (!base64) return null;
|
|
31
31
|
const size = base64Bytes(base64);
|
|
@@ -39,20 +39,83 @@ function toAttachment(asset, index) {
|
|
|
39
39
|
type: "file",
|
|
40
40
|
mimeType,
|
|
41
41
|
dataUrl: `data:${mimeType};base64,${base64}`,
|
|
42
|
+
url: ((_d = asset.uri) == null ? void 0 : _d.trim()) || void 0,
|
|
42
43
|
size
|
|
43
44
|
};
|
|
44
45
|
}
|
|
45
46
|
function loadPicker() {
|
|
46
47
|
return require("expo-image-picker");
|
|
47
48
|
}
|
|
49
|
+
function loadDocumentPicker() {
|
|
50
|
+
var _a, _b, _c;
|
|
51
|
+
const core = require("expo-modules-core");
|
|
52
|
+
const native = (_c = (_a = core.requireOptionalNativeModule) == null ? void 0 : _a.call(core, "ExpoDocumentPicker")) != null ? _c : (_b = core.requireNativeModule) == null ? void 0 : _b.call(core, "ExpoDocumentPicker");
|
|
53
|
+
if (!(native == null ? void 0 : native.getDocumentAsync)) {
|
|
54
|
+
throw new Error("File picker is not available in this build.");
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
getDocumentAsync: (options) => {
|
|
58
|
+
var _a2, _b2, _c2;
|
|
59
|
+
return native.getDocumentAsync({
|
|
60
|
+
type: Array.isArray(options.type) ? options.type : [(_a2 = options.type) != null ? _a2 : "*/*"],
|
|
61
|
+
multiple: (_b2 = options.multiple) != null ? _b2 : false,
|
|
62
|
+
copyToCacheDirectory: (_c2 = options.copyToCacheDirectory) != null ? _c2 : true
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
function loadFileSystem() {
|
|
68
|
+
return require("expo-file-system");
|
|
69
|
+
}
|
|
70
|
+
const DOCUMENT_MIME_TYPES = ["application/pdf", "text/plain", "text/markdown", "text/csv", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "image/*"];
|
|
71
|
+
const MAX_FILES = 6;
|
|
72
|
+
const MAX_DOCUMENT_BYTES = 15 * 1024 * 1024;
|
|
73
|
+
function normalizeDocumentAssets(result) {
|
|
74
|
+
if (!result || result.canceled || result.type === "cancel") return [];
|
|
75
|
+
if (Array.isArray(result.assets) && result.assets.length > 0) return result.assets;
|
|
76
|
+
if (result.uri) {
|
|
77
|
+
return [{
|
|
78
|
+
uri: result.uri,
|
|
79
|
+
name: result.name,
|
|
80
|
+
mimeType: result.mimeType,
|
|
81
|
+
size: result.size
|
|
82
|
+
}];
|
|
83
|
+
}
|
|
84
|
+
return [];
|
|
85
|
+
}
|
|
86
|
+
async function documentToAttachment(asset, index) {
|
|
87
|
+
var _a, _b, _c, _d, _e;
|
|
88
|
+
const uri = (_a = asset.uri) == null ? void 0 : _a.trim();
|
|
89
|
+
if (!uri) return null;
|
|
90
|
+
if (typeof asset.size === "number" && asset.size > MAX_DOCUMENT_BYTES) return null;
|
|
91
|
+
const fs = loadFileSystem();
|
|
92
|
+
const encoding = (_c = (_b = fs.EncodingType) == null ? void 0 : _b.Base64) != null ? _c : "base64";
|
|
93
|
+
if (typeof fs.readAsStringAsync !== "function") return null;
|
|
94
|
+
const base64 = (await fs.readAsStringAsync(uri, {
|
|
95
|
+
encoding
|
|
96
|
+
})).trim();
|
|
97
|
+
if (!base64) return null;
|
|
98
|
+
const size = typeof asset.size === "number" && asset.size > 0 ? asset.size : base64Bytes(base64);
|
|
99
|
+
if (size < MIN_BYTES || size > MAX_DOCUMENT_BYTES) return null;
|
|
100
|
+
const mimeType = ((_d = asset.mimeType) == null ? void 0 : _d.trim()) || "application/octet-stream";
|
|
101
|
+
const name = ((_e = asset.name) == null ? void 0 : _e.trim()) || `file-${Date.now()}-${index}`;
|
|
102
|
+
return {
|
|
103
|
+
id: `file-${Date.now()}-${index}`,
|
|
104
|
+
name,
|
|
105
|
+
type: "file",
|
|
106
|
+
mimeType,
|
|
107
|
+
dataUrl: `data:${mimeType};base64,${base64}`,
|
|
108
|
+
url: uri,
|
|
109
|
+
size
|
|
110
|
+
};
|
|
111
|
+
}
|
|
48
112
|
function useImageAttachments() {
|
|
49
113
|
const [pending, setPending] = useState([]);
|
|
50
|
-
const [
|
|
114
|
+
const [busyKind, setBusyKind] = useState(null);
|
|
51
115
|
const [error, setError] = useState(null);
|
|
52
116
|
const run = useCallback(async (mode) => {
|
|
53
117
|
var _a;
|
|
54
118
|
setError(null);
|
|
55
|
-
setBusy(true);
|
|
56
119
|
try {
|
|
57
120
|
const picker = loadPicker();
|
|
58
121
|
const permission = mode === "camera" ? await picker.requestCameraPermissionsAsync() : await picker.requestMediaLibraryPermissionsAsync();
|
|
@@ -60,6 +123,7 @@ function useImageAttachments() {
|
|
|
60
123
|
setError(mode === "camera" ? "Camera access is off for Yantra. Turn it on in Settings to attach a photo." : "Photo access is off for Yantra. Turn it on in Settings to attach an image.");
|
|
61
124
|
return;
|
|
62
125
|
}
|
|
126
|
+
setBusyKind(mode);
|
|
63
127
|
const options = {
|
|
64
128
|
// `base64` is what the message carries; `quality` + the picker's
|
|
65
129
|
// own resize keep it small enough to travel inline.
|
|
@@ -81,26 +145,57 @@ function useImageAttachments() {
|
|
|
81
145
|
setError("That image was too large to attach. Try a smaller one.");
|
|
82
146
|
return;
|
|
83
147
|
}
|
|
84
|
-
setPending((prev) => [...prev, ...mapped]);
|
|
148
|
+
setPending((prev) => [...prev, ...mapped].slice(0, MAX_FILES));
|
|
85
149
|
} catch (e) {
|
|
86
150
|
setError(e instanceof Error ? e.message : "Could not attach that image.");
|
|
87
151
|
} finally {
|
|
88
|
-
|
|
152
|
+
setBusyKind(null);
|
|
89
153
|
}
|
|
90
154
|
}, []);
|
|
91
155
|
const pickFromLibrary = useCallback(() => run("library"), [run]);
|
|
92
156
|
const captureFromCamera = useCallback(() => run("camera"), [run]);
|
|
157
|
+
const pickDocuments = useCallback(async () => {
|
|
158
|
+
setError(null);
|
|
159
|
+
try {
|
|
160
|
+
const picker = loadDocumentPicker();
|
|
161
|
+
setBusyKind("documents");
|
|
162
|
+
const result = await picker.getDocumentAsync({
|
|
163
|
+
type: DOCUMENT_MIME_TYPES,
|
|
164
|
+
multiple: true,
|
|
165
|
+
copyToCacheDirectory: true
|
|
166
|
+
});
|
|
167
|
+
const assets = normalizeDocumentAssets(result);
|
|
168
|
+
if (assets.length === 0) return;
|
|
169
|
+
const mapped = [];
|
|
170
|
+
for (let i = 0; i < assets.length; i += 1) {
|
|
171
|
+
const next = await documentToAttachment(assets[i], i);
|
|
172
|
+
if (next) mapped.push(next);
|
|
173
|
+
}
|
|
174
|
+
if (mapped.length === 0) {
|
|
175
|
+
setError("That file was too large to attach. Try a smaller one.");
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
setPending((prev) => [...prev, ...mapped].slice(0, MAX_FILES));
|
|
179
|
+
} catch (e) {
|
|
180
|
+
setError(e instanceof Error ? e.message : "Could not attach that file.");
|
|
181
|
+
} finally {
|
|
182
|
+
setBusyKind(null);
|
|
183
|
+
}
|
|
184
|
+
}, []);
|
|
93
185
|
const remove = useCallback((id) => setPending((prev) => prev.filter((a) => a.id !== id)), []);
|
|
94
186
|
const clear = useCallback(() => setPending([]), []);
|
|
95
|
-
const forSend = useCallback(() => pending.length > 0 ? pending : void 0, [pending]);
|
|
187
|
+
const forSend = useCallback(() => pending.length > 0 ? pending.map((a) => __spreadValues({}, a)) : void 0, [pending]);
|
|
188
|
+
const busy = busyKind !== null;
|
|
96
189
|
return useMemo(() => ({
|
|
97
190
|
pending,
|
|
98
191
|
busy,
|
|
192
|
+
busyKind,
|
|
99
193
|
error,
|
|
100
194
|
pickFromLibrary,
|
|
101
195
|
captureFromCamera,
|
|
196
|
+
pickDocuments,
|
|
102
197
|
remove,
|
|
103
198
|
clear,
|
|
104
199
|
forSend
|
|
105
|
-
}), [pending, busy, error, pickFromLibrary, captureFromCamera, remove, clear, forSend]);
|
|
200
|
+
}), [pending, busy, busyKind, error, pickFromLibrary, captureFromCamera, pickDocuments, remove, clear, forSend]);
|
|
106
201
|
}export{useImageAttachments};//# sourceMappingURL=useImageAttachments.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useImageAttachments.js","sources":["../../../src/features/attachments/useImageAttachments.ts"],"sourcesContent":["/**\n * Image attachments for the native composer.\n *\n * The transport was already there — `useChatStream.sendMessage(content,\n * attachments)` carries `MessageAttachment[]` and the gateway media lane is\n * covered by `aiwork/e2e-tests/gateway-media-upload.spec.ts`. What was missing\n * was any way to produce one on a phone: the composer shipped with\n * `image`/`camera`/`attach` hard-disabled, and nothing in the mobile package\n * touched `expo-image-picker` even though it is a dependency and the photo and\n * camera permission strings are already declared in `app.json`.\n *\n * Payload size is the whole game here. A modern iPhone photo is ~3-5 MB and\n * ~4000px wide; base64 inflates that by a third, and it travels inline on the\n * chat message. So we ask the picker to downscale and re-encode before we ever\n * see the bytes, then hard-reject anything still oversized rather than let a\n * send hang on a slow uplink.\n */\nimport { useCallback, useMemo, useState } from 'react';\nimport type { MessageAttachment } from '../../hooks/useChatStream';\n\n/** Longest edge, in px, we send. Plenty for a model to read; ~10x smaller than source. */\nconst MAX_EDGE = 1280;\n/** JPEG quality handed to the picker (0-1). */\nconst PICKER_QUALITY = 0.7;\n/** Refuse anything above this after re-encoding — a send is better failed than hung. */\nconst MAX_BYTES = 4 * 1024 * 1024;\n/** Nothing sensible is this small; treat as a failed decode. */\nconst MIN_BYTES = 64;\n\nexport interface ImageAttachmentsApi {\n /** Attachments staged for the next send. */\n pending: MessageAttachment[];\n /** True while the picker/encode is in flight, for the toolbar spinner. */\n busy: boolean;\n /** Human-readable failure for the composer's error banner, or null. */\n error: string | null;\n pickFromLibrary: () => Promise<void>;\n captureFromCamera: () => Promise<void>;\n remove: (id: string) => void;\n clear: () => void;\n /** Pass to `sendMessage` — undefined when empty, which is what it expects. */\n forSend: () => MessageAttachment[] | undefined;\n}\n\ntype PickedAsset = {\n uri?: string | null;\n base64?: string | null;\n mimeType?: string | null;\n fileName?: string | null;\n fileSize?: number | null;\n width?: number | null;\n height?: number | null;\n};\n\n/** Base64 decodes to 3 bytes per 4 chars, minus `=` padding. */\nfunction base64Bytes(base64: string): number {\n const padding = base64.endsWith('==') ? 2 : base64.endsWith('=') ? 1 : 0;\n return Math.floor((base64.length * 3) / 4) - padding;\n}\n\nfunction toAttachment(asset: PickedAsset, index: number): MessageAttachment | null {\n const base64 = asset.base64?.trim();\n if (!base64) return null;\n const size = base64Bytes(base64);\n if (size < MIN_BYTES || size > MAX_BYTES) return null;\n const mimeType = asset.mimeType?.trim() || 'image/jpeg';\n const name = asset.fileName?.trim() || `image-${Date.now()}-${index}.jpg`;\n return {\n // Local id only — the gateway assigns its own.\n id: `img-${Date.now()}-${index}`,\n name,\n type: 'file',\n mimeType,\n dataUrl: `data:${mimeType};base64,${base64}`,\n size,\n };\n}\n\n/**\n * Lazily required so a unit test or a non-Expo bundle importing this hook does\n * not hard-fail on the native module.\n */\nfunction loadPicker() {\n // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require\n return require('expo-image-picker') as typeof import('expo-image-picker');\n}\n\nexport function useImageAttachments(): ImageAttachmentsApi {\n const [pending, setPending] = useState<MessageAttachment[]>([]);\n const [busy, setBusy] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n const run = useCallback(async (mode: 'library' | 'camera') => {\n setError(null);\n setBusy(true);\n try {\n const picker = loadPicker();\n\n const permission =\n mode === 'camera'\n ? await picker.requestCameraPermissionsAsync()\n : await picker.requestMediaLibraryPermissionsAsync();\n if (!permission.granted) {\n setError(\n mode === 'camera'\n ? 'Camera access is off for Yantra. Turn it on in Settings to attach a photo.'\n : 'Photo access is off for Yantra. Turn it on in Settings to attach an image.',\n );\n return;\n }\n\n const options: import('expo-image-picker').ImagePickerOptions = {\n // `base64` is what the message carries; `quality` + the picker's\n // own resize keep it small enough to travel inline.\n base64: true,\n quality: PICKER_QUALITY,\n allowsMultipleSelection: mode === 'library',\n mediaTypes: ['images'],\n // Selection limit mirrors MAX_BYTES: four 1280px JPEGs still fit\n // comfortably inside a single turn.\n selectionLimit: 4,\n exif: false,\n };\n\n const result =\n mode === 'camera'\n ? await picker.launchCameraAsync({ ...options, allowsMultipleSelection: false })\n : await picker.launchImageLibraryAsync(options);\n\n if (result.canceled) return;\n\n const mapped = (result.assets ?? [])\n .map((asset, i) => toAttachment(asset as PickedAsset, i))\n .filter((a): a is MessageAttachment => a !== null);\n\n if (mapped.length === 0) {\n setError('That image was too large to attach. Try a smaller one.');\n return;\n }\n setPending((prev) => [...prev, ...mapped]);\n } catch (e) {\n setError(e instanceof Error ? e.message : 'Could not attach that image.');\n } finally {\n setBusy(false);\n }\n }, []);\n\n const pickFromLibrary = useCallback(() => run('library'), [run]);\n const captureFromCamera = useCallback(() => run('camera'), [run]);\n const remove = useCallback((id: string) => setPending((prev) => prev.filter((a) => a.id !== id)), []);\n const clear = useCallback(() => setPending([]), []);\n const forSend = useCallback(() => (pending.length > 0 ? pending : undefined), [pending]);\n\n return useMemo(\n () => ({ pending, busy, error, pickFromLibrary, captureFromCamera, remove, clear, forSend }),\n [pending, busy, error, pickFromLibrary, captureFromCamera, remove, clear, forSend],\n );\n}\n\nexport const IMAGE_ATTACHMENT_LIMITS = { MAX_EDGE, MAX_BYTES, PICKER_QUALITY } as const;\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAuBA,MAAM,cAAiB,GAAA,GAAA;AAEvB,MAAM,SAAA,GAAY,IAAI,IAAO,GAAA,IAAA;AAE7B,MAAM,SAAY,GAAA,EAAA;AA0BlB,SAAS,YAAY,MAAwB,EAAA;AAC3C,EAAM,MAAA,OAAA,GAAU,MAAO,CAAA,QAAA,CAAS,IAAI,CAAA,GAAI,IAAI,MAAO,CAAA,QAAA,CAAS,GAAG,CAAA,GAAI,CAAI,GAAA,CAAA;AACvE,EAAA,OAAO,KAAK,KAAM,CAAA,MAAA,CAAO,MAAS,GAAA,CAAA,GAAI,CAAC,CAAI,GAAA,OAAA;AAC7C;AACA,SAAS,YAAA,CAAa,OAAoB,KAAyC,EAAA;AAzDnF,EAAA,IAAA,EAAA,EAAA,EAAA,EAAA,EAAA;AA0DE,EAAM,MAAA,MAAA,GAAA,CAAS,EAAM,GAAA,KAAA,CAAA,MAAA,KAAN,IAAc,GAAA,MAAA,GAAA,EAAA,CAAA,IAAA,EAAA;AAC7B,EAAI,IAAA,CAAC,QAAe,OAAA,IAAA;AACpB,EAAM,MAAA,IAAA,G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S,CAAa,YAAA,KAAA,GAAQ,CAAE,CAAA,OAAA,GAAU,8BAA8B,CAAA;AAAA,KACxE,SAAA;AACA,MAAA,OAAA,CAAQ,KAAK,CAAA;AAAA;AACf,GACF,EAAG,EAAE,CAAA;AACL,EAAM,MAAA,eAAA,GAAkB,YAAY,MAAM,GAAA,CAAI,SAAS,CAAG,EAAA,CAAC,GAAG,CAAC,CAAA;AAC/D,EAAM,MAAA,iBAAA,GAAoB,YAAY,MAAM,GAAA,CAAI,QAAQ,CAAG,EAAA,CAAC,GAAG,CAAC,CAAA;AAChE,EAAA,MAAM,MAAS,GAAA,WAAA,CAAY,CAAC,EAAA,KAAe,WAAW,CAAQ,IAAA,KAAA,IAAA,CAAK,MAAO,CAAA,CAAA,CAAA,KAAK,EAAE,EAAO,KAAA,EAAE,CAAC,CAAA,EAAG,EAAE,CAAA;AAChG,EAAM,MAAA,KAAA,GAAQ,YAAY,MAAM,UAAA,CAAW,EAAE,CAAA,EAAG,EAAE,CAAA;AAClD,EAAM,MAAA,OAAA,GAAU,WAAY,CAAA,MAAM,OAAQ,CAAA,MAAA,GAAS,IAAI,OAAU,GAAA,MAAA,EAAW,CAAC,OAAO,CAAC,CAAA;AACrF,EAAA,OAAO,QAAQ,OAAO;AAAA,IACpB,OAAA;AAAA,IACA,IAAA;AAAA,IACA,KAAA;AAAA,IACA,eAAA;AAAA,IACA,iBAAA;AAAA,IACA,MAAA;AAAA,IACA,KAAA;AAAA,IACA;AAAA,GACF,CAAA,EAAI,CAAC,OAAA,EAAS,IAAM,EAAA,KAAA,EAAO,iBAAiB,iBAAmB,EAAA,MAAA,EAAQ,KAAO,EAAA,OAAO,CAAC,CAAA;AACxF"}
|
|
1
|
+
{"version":3,"file":"useImageAttachments.js","sources":["../../../src/features/attachments/useImageAttachments.ts"],"sourcesContent":["/**\n * Image attachments for the native composer.\n *\n * The transport was already there — `useChatStream.sendMessage(content,\n * attachments)` carries `MessageAttachment[]` and the gateway media lane is\n * covered by `aiwork/e2e-tests/gateway-media-upload.spec.ts`. What was missing\n * was any way to produce one on a phone: the composer shipped with\n * `image`/`camera`/`attach` hard-disabled, and nothing in the mobile package\n * touched `expo-image-picker` even though it is a dependency and the photo and\n * camera permission strings are already declared in `app.json`.\n *\n * Payload size is the whole game here. A modern iPhone photo is ~3-5 MB and\n * ~4000px wide; base64 inflates that by a third, and it travels inline on the\n * chat message. So we ask the picker to downscale and re-encode before we ever\n * see the bytes, then hard-reject anything still oversized rather than let a\n * send hang on a slow uplink.\n */\nimport { useCallback, useMemo, useState } from 'react';\nimport type { MessageAttachment } from '../../hooks/useChatStream';\n\n/** Longest edge, in px, we send. Plenty for a model to read; ~10x smaller than source. */\nconst MAX_EDGE = 1280;\n/** JPEG quality handed to the picker (0-1). */\nconst PICKER_QUALITY = 0.7;\n/** Refuse anything above this after re-encoding — a send is better failed than hung. */\nconst MAX_BYTES = 4 * 1024 * 1024;\n/** Nothing sensible is this small; treat as a failed decode. */\nconst MIN_BYTES = 64;\n\nexport type AttachmentBusyKind = 'camera' | 'library' | 'documents' | null;\n\nexport interface ImageAttachmentsApi {\n /** Attachments staged for the next send. */\n pending: MessageAttachment[];\n /** True while any picker/encode is in flight. */\n busy: boolean;\n /** Which toolbar control is waiting — only that one should spin. */\n busyKind: AttachmentBusyKind;\n /** Human-readable failure for the composer's error banner, or null. */\n error: string | null;\n pickFromLibrary: () => Promise<void>;\n captureFromCamera: () => Promise<void>;\n pickDocuments: () => Promise<void>;\n remove: (id: string) => void;\n clear: () => void;\n /** Pass to `sendMessage` — undefined when empty, which is what it expects. */\n forSend: () => MessageAttachment[] | undefined;\n}\n\ntype PickedAsset = {\n uri?: string | null;\n base64?: string | null;\n mimeType?: string | null;\n fileName?: string | null;\n fileSize?: number | null;\n width?: number | null;\n height?: number | null;\n};\n\n/** Base64 decodes to 3 bytes per 4 chars, minus `=` padding. */\nfunction base64Bytes(base64: string): number {\n const padding = base64.endsWith('==') ? 2 : base64.endsWith('=') ? 1 : 0;\n return Math.floor((base64.length * 3) / 4) - padding;\n}\n\nfunction toAttachment(asset: PickedAsset, index: number): MessageAttachment | null {\n const base64 = asset.base64?.trim();\n if (!base64) return null;\n const size = base64Bytes(base64);\n if (size < MIN_BYTES || size > MAX_BYTES) return null;\n const mimeType = asset.mimeType?.trim() || 'image/jpeg';\n const name = asset.fileName?.trim() || `image-${Date.now()}-${index}.jpg`;\n return {\n // Local id only — the gateway assigns its own.\n id: `img-${Date.now()}-${index}`,\n name,\n type: 'file',\n mimeType,\n dataUrl: `data:${mimeType};base64,${base64}`,\n url: asset.uri?.trim() || undefined,\n size,\n };\n}\n\ntype PickedDocument = {\n uri?: string | null;\n name?: string | null;\n mimeType?: string | null;\n size?: number | null;\n};\n\n/**\n * Lazily required so a unit test or a non-Expo bundle importing this hook does\n * not hard-fail on the native module.\n */\nfunction loadPicker() {\n // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require\n return require('expo-image-picker') as typeof import('expo-image-picker');\n}\n\nfunction loadDocumentPicker(): {\n getDocumentAsync: (options: {\n type?: string | string[];\n multiple?: boolean;\n copyToCacheDirectory?: boolean;\n }) => Promise<{\n canceled?: boolean;\n type?: string;\n uri?: string;\n name?: string;\n mimeType?: string;\n size?: number;\n assets?: PickedDocument[];\n }>;\n} {\n // Use the native module Expo Go already ships. Do not `require('expo-document-picker')`\n // — that package's published `main` is `build/index.js`, which is often missing\n // from this workspace install, and Metro then fails the whole bundle.\n // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require\n const core = require('expo-modules-core') as {\n requireOptionalNativeModule?: (name: string) => { getDocumentAsync?: Function } | null;\n requireNativeModule?: (name: string) => { getDocumentAsync?: Function };\n };\n const native =\n core.requireOptionalNativeModule?.('ExpoDocumentPicker') ?? core.requireNativeModule?.('ExpoDocumentPicker');\n if (!native?.getDocumentAsync) {\n throw new Error('File picker is not available in this build.');\n }\n return {\n getDocumentAsync: (options) =>\n native.getDocumentAsync({\n type: Array.isArray(options.type) ? options.type : [options.type ?? '*/*'],\n multiple: options.multiple ?? false,\n copyToCacheDirectory: options.copyToCacheDirectory ?? true,\n }) as Promise<{\n canceled?: boolean;\n type?: string;\n uri?: string;\n name?: string;\n mimeType?: string;\n size?: number;\n assets?: PickedDocument[];\n }>,\n };\n}\n\nfunction loadFileSystem() {\n // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require\n return require('expo-file-system') as typeof import('expo-file-system');\n}\n\n/** Web `ACCEPTED_FILE_TYPES` — docs + images. */\nconst DOCUMENT_MIME_TYPES = [\n 'application/pdf',\n 'text/plain',\n 'text/markdown',\n 'text/csv',\n 'application/msword',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'image/*',\n];\nconst MAX_FILES = 6;\nconst MAX_DOCUMENT_BYTES = 15 * 1024 * 1024;\n\nfunction normalizeDocumentAssets(result: {\n canceled?: boolean;\n type?: string;\n uri?: string;\n name?: string;\n mimeType?: string;\n size?: number;\n assets?: PickedDocument[];\n}): PickedDocument[] {\n if (!result || result.canceled || result.type === 'cancel') return [];\n if (Array.isArray(result.assets) && result.assets.length > 0) return result.assets;\n if (result.uri) {\n return [{ uri: result.uri, name: result.name, mimeType: result.mimeType, size: result.size }];\n }\n return [];\n}\n\nasync function documentToAttachment(asset: PickedDocument, index: number): Promise<MessageAttachment | null> {\n const uri = asset.uri?.trim();\n if (!uri) return null;\n if (typeof asset.size === 'number' && asset.size > MAX_DOCUMENT_BYTES) return null;\n\n const fs = loadFileSystem() as {\n readAsStringAsync?: (uri: string, options?: { encoding?: string }) => Promise<string>;\n EncodingType?: { Base64?: string };\n };\n const encoding = fs.EncodingType?.Base64 ?? 'base64';\n if (typeof fs.readAsStringAsync !== 'function') return null;\n const base64 = (await fs.readAsStringAsync(uri, { encoding })).trim();\n if (!base64) return null;\n const size = typeof asset.size === 'number' && asset.size > 0 ? asset.size : base64Bytes(base64);\n if (size < MIN_BYTES || size > MAX_DOCUMENT_BYTES) return null;\n const mimeType = asset.mimeType?.trim() || 'application/octet-stream';\n const name = asset.name?.trim() || `file-${Date.now()}-${index}`;\n return {\n id: `file-${Date.now()}-${index}`,\n name,\n type: 'file',\n mimeType,\n dataUrl: `data:${mimeType};base64,${base64}`,\n url: uri,\n size,\n };\n}\n\nexport function useImageAttachments(): ImageAttachmentsApi {\n const [pending, setPending] = useState<MessageAttachment[]>([]);\n const [busyKind, setBusyKind] = useState<AttachmentBusyKind>(null);\n const [error, setError] = useState<string | null>(null);\n\n const run = useCallback(async (mode: 'library' | 'camera') => {\n setError(null);\n try {\n const picker = loadPicker();\n\n const permission =\n mode === 'camera'\n ? await picker.requestCameraPermissionsAsync()\n : await picker.requestMediaLibraryPermissionsAsync();\n if (!permission.granted) {\n setError(\n mode === 'camera'\n ? 'Camera access is off for Yantra. Turn it on in Settings to attach a photo.'\n : 'Photo access is off for Yantra. Turn it on in Settings to attach an image.',\n );\n return;\n }\n\n // Spin only the control that was tapped, and only after permission\n // so the iOS prompt does not turn camera+gallery+attach into loaders.\n setBusyKind(mode);\n const options: import('expo-image-picker').ImagePickerOptions = {\n // `base64` is what the message carries; `quality` + the picker's\n // own resize keep it small enough to travel inline.\n base64: true,\n quality: PICKER_QUALITY,\n allowsMultipleSelection: mode === 'library',\n mediaTypes: ['images'],\n // Selection limit mirrors MAX_BYTES: four 1280px JPEGs still fit\n // comfortably inside a single turn.\n selectionLimit: 4,\n exif: false,\n };\n\n const result =\n mode === 'camera'\n ? await picker.launchCameraAsync({ ...options, allowsMultipleSelection: false })\n : await picker.launchImageLibraryAsync(options);\n\n if (result.canceled) return;\n\n const mapped = (result.assets ?? [])\n .map((asset, i) => toAttachment(asset as PickedAsset, i))\n .filter((a): a is MessageAttachment => a !== null);\n\n if (mapped.length === 0) {\n setError('That image was too large to attach. Try a smaller one.');\n return;\n }\n setPending((prev) => [...prev, ...mapped].slice(0, MAX_FILES));\n } catch (e) {\n setError(e instanceof Error ? e.message : 'Could not attach that image.');\n } finally {\n setBusyKind(null);\n }\n }, []);\n\n const pickFromLibrary = useCallback(() => run('library'), [run]);\n const captureFromCamera = useCallback(() => run('camera'), [run]);\n const pickDocuments = useCallback(async () => {\n setError(null);\n try {\n const picker = loadDocumentPicker();\n setBusyKind('documents');\n const result = await picker.getDocumentAsync({\n type: DOCUMENT_MIME_TYPES,\n multiple: true,\n copyToCacheDirectory: true,\n });\n const assets = normalizeDocumentAssets(result as Parameters<typeof normalizeDocumentAssets>[0]);\n if (assets.length === 0) return;\n\n const mapped: MessageAttachment[] = [];\n for (let i = 0; i < assets.length; i += 1) {\n const next = await documentToAttachment(assets[i], i);\n if (next) mapped.push(next);\n }\n if (mapped.length === 0) {\n setError('That file was too large to attach. Try a smaller one.');\n return;\n }\n setPending((prev) => [...prev, ...mapped].slice(0, MAX_FILES));\n } catch (e) {\n setError(e instanceof Error ? e.message : 'Could not attach that file.');\n } finally {\n setBusyKind(null);\n }\n }, []);\n const remove = useCallback((id: string) => setPending((prev) => prev.filter((a) => a.id !== id)), []);\n const clear = useCallback(() => setPending([]), []);\n const forSend = useCallback(() => (pending.length > 0 ? pending.map((a) => ({ ...a })) : undefined), [pending]);\n const busy = busyKind !== null;\n\n return useMemo(\n () => ({\n pending,\n busy,\n busyKind,\n error,\n pickFromLibrary,\n captureFromCamera,\n pickDocuments,\n remove,\n clear,\n forSend,\n }),\n [pending, busy, busyKind, error, pickFromLibrary, captureFromCamera, pickDocuments, remove, clear, forSend],\n );\n}\n\nexport const IMAGE_ATTACHMENT_LIMITS = { MAX_EDGE, MAX_BYTES, PICKER_QUALITY } as const;\n"],"names":["_a","_b","_c"],"mappings":";;;;;;;;;;;;;;;;;;;AAuBA,MAAM,cAAiB,GAAA,GAAA;AAEvB,MAAM,SAAA,GAAY,IAAI,IAAO,GAAA,IAAA;AAE7B,MAAM,SAAY,GAAA,EAAA;AA8BlB,SAAS,YAAY,MAAwB,EAAA;AAC3C,EAAM,MAAA,OAAA,GAAU,MAAO,CAAA,QAAA,CAAS,IAAI,CAAA,GAAI,IAAI,MAAO,CAAA,QAAA,CAA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A;AAC1B,EAAA,MAAM,OAAO,QAAa,KAAA,IAAA;AAC1B,EAAA,OAAO,QAAQ,OAAO;AAAA,IACpB,OAAA;AAAA,IACA,IAAA;AAAA,IACA,QAAA;AAAA,IACA,KAAA;AAAA,IACA,eAAA;AAAA,IACA,iBAAA;AAAA,IACA,aAAA;AAAA,IACA,MAAA;AAAA,IACA,KAAA;AAAA,IACA;AAAA,GACE,CAAA,EAAA,CAAC,OAAS,EAAA,IAAA,EAAM,QAAU,EAAA,KAAA,EAAO,eAAiB,EAAA,iBAAA,EAAmB,aAAe,EAAA,MAAA,EAAQ,KAAO,EAAA,OAAO,CAAC,CAAA;AACjH"}
|
|
@@ -4,4 +4,11 @@ function registerNativeCanvasViewer(component) {
|
|
|
4
4
|
}
|
|
5
5
|
function getNativeCanvasViewer() {
|
|
6
6
|
return registered;
|
|
7
|
-
}
|
|
7
|
+
}
|
|
8
|
+
let experience = null;
|
|
9
|
+
function registerNativeCanvasExperience(component) {
|
|
10
|
+
experience = component;
|
|
11
|
+
}
|
|
12
|
+
function getNativeCanvasExperience() {
|
|
13
|
+
return experience;
|
|
14
|
+
}export{getNativeCanvasExperience,getNativeCanvasViewer,registerNativeCanvasExperience,registerNativeCanvasViewer};//# sourceMappingURL=nativeViewerRegistry.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nativeViewerRegistry.js","sources":["../../../src/features/canvas/nativeViewerRegistry.ts"],"sourcesContent":["/**\n * Seam between the app shell and this package for the FEDERATED canvas viewer.\n *\n * The federated loader (`import('canvas_native/Viewer')`) must live in the app\n * (portable-devices/mobile): this package also builds through rollup for lib/,\n * and rollup must never see a bare `canvas_native/...` specifier. The screen,\n * however, lives HERE, where routes register. So the app injects its loader at\n * startup and the screen reads it back - the same inversion the surfaces use\n * for host services, scaled down to one component.\n */\nimport type { ComponentType } from 'react';\nimport type { NativeCanvasViewerProps } from './NativeCanvasViewer';\n\nlet registered: ComponentType<NativeCanvasViewerProps> | null = null;\n\nexport function registerNativeCanvasViewer(component: ComponentType<NativeCanvasViewerProps>): void {\n registered = component;\n}\n\n/** Null when the host app has not injected a loader (e.g. a build without federation). */\nexport function getNativeCanvasViewer(): ComponentType<NativeCanvasViewerProps> | null {\n return registered;\n}\n"],"names":[],"mappings":"AAYA,IAAI,UAA4D,GAAA,IAAA;AACzD,SAAS,2BAA2B,SAAyD,EAAA;AAClG,EAAa,UAAA,GAAA,SAAA;AACf;AAGO,SAAS,qBAAuE,GAAA;AACrF,EAAO,OAAA,UAAA;AACT"}
|
|
1
|
+
{"version":3,"file":"nativeViewerRegistry.js","sources":["../../../src/features/canvas/nativeViewerRegistry.ts"],"sourcesContent":["/**\n * Seam between the app shell and this package for the FEDERATED canvas viewer.\n *\n * The federated loader (`import('canvas_native/Viewer')`) must live in the app\n * (portable-devices/mobile): this package also builds through rollup for lib/,\n * and rollup must never see a bare `canvas_native/...` specifier. The screen,\n * however, lives HERE, where routes register. So the app injects its loader at\n * startup and the screen reads it back - the same inversion the surfaces use\n * for host services, scaled down to one component.\n */\nimport type { ComponentType } from 'react';\nimport type { NativeCanvasViewerProps } from './NativeCanvasViewer';\n\nlet registered: ComponentType<NativeCanvasViewerProps> | null = null;\n\nexport function registerNativeCanvasViewer(component: ComponentType<NativeCanvasViewerProps>): void {\n registered = component;\n}\n\n/** Null when the host app has not injected a loader (e.g. a build without federation). */\nexport function getNativeCanvasViewer(): ComponentType<NativeCanvasViewerProps> | null {\n return registered;\n}\n\n/**\n * The federated canvas EXPERIENCE (boards + viewer), registered by the app the\n * same way the viewer is. Kept as a separate seam so a host that only wants the\n * raw renderer - a preview, a test - is unaffected.\n */\nexport type CanvasExperienceComponent = ComponentType<{\n token?: string | null;\n indexUrl: string;\n channelId?: string;\n sessionError?: string | null;\n}>;\n\nlet experience: CanvasExperienceComponent | null = null;\n\nexport function registerNativeCanvasExperience(component: CanvasExperienceComponent): void {\n experience = component;\n}\n\nexport function getNativeCanvasExperience(): CanvasExperienceComponent | null {\n return experience;\n}\n"],"names":[],"mappings":"AAYA,IAAI,UAA4D,GAAA,IAAA;AACzD,SAAS,2BAA2B,SAAyD,EAAA;AAClG,EAAa,UAAA,GAAA,SAAA;AACf;AAGO,SAAS,qBAAuE,GAAA;AACrF,EAAO,OAAA,UAAA;AACT;AAaA,IAAI,UAA+C,GAAA,IAAA;AAC5C,SAAS,+BAA+B,SAA4C,EAAA;AACzF,EAAa,UAAA,GAAA,SAAA;AACf;AACO,SAAS,yBAA8D,GAAA;AAC5E,EAAO,OAAA,UAAA;AACT"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
function surfaceIndexUrl(graphqlUrl, explicit) {
|
|
2
|
+
const override = (explicit || "").trim();
|
|
3
|
+
if (override) return override;
|
|
4
|
+
const base = (graphqlUrl || "").trim();
|
|
5
|
+
if (!base) return "";
|
|
6
|
+
try {
|
|
7
|
+
const {
|
|
8
|
+
protocol,
|
|
9
|
+
host
|
|
10
|
+
} = parseOrigin(base);
|
|
11
|
+
const labels = host.split(".");
|
|
12
|
+
if (labels.length < 3) return "";
|
|
13
|
+
return `${protocol}//surface-index-backend.${labels.slice(1).join(".")}/graphql`;
|
|
14
|
+
} catch (e) {
|
|
15
|
+
return "";
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
function parseOrigin(url) {
|
|
19
|
+
const match = url.match(/^(https?:)\/\/([^/]+)/i);
|
|
20
|
+
if (!match) throw new Error(`unparseable url: ${url}`);
|
|
21
|
+
return {
|
|
22
|
+
protocol: match[1].toLowerCase(),
|
|
23
|
+
host: match[2].toLowerCase()
|
|
24
|
+
};
|
|
25
|
+
}export{surfaceIndexUrl};//# sourceMappingURL=surfaceIndex.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"surfaceIndex.js","sources":["../../../src/features/canvas/surfaceIndex.ts"],"sourcesContent":["/**\n * Native reader for the canvas boards in the SurfaceChannel index.\n *\n * The index (`servers/surface-index-subgraph-server`) is the ONLY store for a\n * canvas: the whole `PersistedCanvasState` rides in the row's `metadata`, and\n * `mySurfaceChannels` enumerates the caller's boards. Rows are per-USER, so the\n * phone — signed in as the same user — sees exactly what the web surface sees.\n *\n * This is the native twin of `@yantra/canvas-surface`'s `state/boards.ts`\n * (`pullBoards`). It is copied rather than imported for the same reason\n * `canvasCore.ts` is: that package builds for the DOM (vite, `import.meta.env`,\n * `window.location`), and importing it would drag the web toolchain into Metro.\n * The contract that matters is the wire shape, which both sides pin.\n *\n * Reads are best-effort: an unreachable index yields an error string for the UI\n * rather than throwing, matching how the web surface degrades.\n */\nimport { parseBoardState, type PersistedCanvasState } from './canvasCore';\n\n/** Fields the index returns for a channel row (mirror of CHANNEL_FIELDS). */\nconst CHANNEL_FIELDS = 'id surface channelId title metadata updatedAt';\n\n/**\n * The web surface's `/c/new` scratch board. It is not a real board (no host\n * session backs it), and `pullBoards` skips it — so must this, or an empty\n * scratch row would shadow the user's actual canvases.\n */\nconst SCRATCH_BOARD_ID = 'global';\n\nexport interface CanvasBoardSummary {\n channelId: string;\n title?: string;\n savedAt: number;\n itemCount: number;\n board: PersistedCanvasState;\n}\n\n/**\n * Where the index lives for this environment.\n *\n * Mirrors the surface-kit fallback: the index is a sibling host of the backend,\n * so drop the backend's first label and prefix `surface-index-backend.`\n * (`ideback.yantra-app-v1.cdebase.dev` -> `surface-index-backend.yantra-app-v1.cdebase.dev`).\n * An explicit URL always wins, so a non-standard environment sets one env var\n * instead of needing a code change.\n */\nexport function surfaceIndexUrl(graphqlUrl: string, explicit?: string): string {\n const override = (explicit || '').trim();\n if (override) return override;\n\n const base = (graphqlUrl || '').trim();\n if (!base) return '';\n try {\n const { protocol, host } = parseOrigin(base);\n const labels = host.split('.');\n if (labels.length < 3) return '';\n return `${protocol}//surface-index-backend.${labels.slice(1).join('.')}/graphql`;\n } catch {\n return '';\n }\n}\n\nfunction parseOrigin(url: string): { protocol: string; host: string } {\n // RN has URL via react-native-url-polyfill (imported in the app entry), but\n // this module is also loaded by jest and the surface build, so parse by hand.\n const match = url.match(/^(https?:)\\/\\/([^/]+)/i);\n if (!match) throw new Error(`unparseable url: ${url}`);\n return { protocol: match[1].toLowerCase(), host: match[2].toLowerCase() };\n}\n\nexport interface FetchBoardsOptions {\n url: string;\n token?: string | null;\n signal?: AbortSignal;\n}\n\nexport interface FetchBoardsResult {\n boards: CanvasBoardSummary[];\n /** Plain sentence for the UI; null when the read succeeded. */\n error: string | null;\n}\n\n/**\n * The caller's canvases, newest first.\n *\n * Empty boards are dropped exactly as the web grid drops them: a row whose\n * `metadata` holds no items is a canvas that was opened and never drawn on, and\n * showing it as a board the user can open is a dead end.\n */\nexport async function fetchMyCanvasBoards(opts: FetchBoardsOptions): Promise<FetchBoardsResult> {\n if (!opts.url) {\n return { boards: [], error: 'No canvas index configured for this build.' };\n }\n\n let payload: SurfaceIndexResponse;\n try {\n const response = await fetch(opts.url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n ...(opts.token ? { authorization: `Bearer ${opts.token}` } : {}),\n },\n body: JSON.stringify({\n query: `query MySurfaceChannels($surface: SurfaceType) {\n mySurfaceChannels(surface: $surface) { ${CHANNEL_FIELDS} }\n }`,\n variables: { surface: 'canvas' },\n }),\n signal: opts.signal,\n });\n\n if (response.status === 401 || response.status === 403) {\n return { boards: [], error: 'Your session expired. Sign in again to see your canvases.' };\n }\n if (!response.ok) {\n return { boards: [], error: `The canvas index is unreachable (HTTP ${response.status}).` };\n }\n payload = (await response.json()) as SurfaceIndexResponse;\n } catch (err) {\n if (err instanceof Error && err.name === 'AbortError') {\n return { boards: [], error: null };\n }\n return { boards: [], error: 'Could not reach the canvas index. Check your connection.' };\n }\n\n if (payload?.errors?.length) {\n // GraphQL errors arrive with HTTP 200. The index reports an unauthenticated\n // caller as \"Missing tenantId in userContext\", which is a developer\n // sentence - say what the user can actually do about it.\n const raw = payload.errors[0]?.message || '';\n const isAuth = /tenantid|unauthenticated|unauthorized|not authorised|forbidden/i.test(raw);\n return {\n boards: [],\n error: isAuth\n ? 'Your session expired. Sign in again to see your canvases.'\n : raw || 'The canvas index rejected the request.',\n };\n }\n\n const rows = payload?.data?.mySurfaceChannels ?? [];\n const boards: CanvasBoardSummary[] = [];\n for (const row of rows) {\n const channelId = typeof row?.channelId === 'string' ? row.channelId : '';\n if (!channelId || channelId === SCRATCH_BOARD_ID) continue;\n const board = parseBoardState(coerceMetadata(row?.metadata));\n if (!board || board.items.length === 0) continue;\n boards.push({\n channelId,\n title: board.title || (typeof row?.title === 'string' ? row.title : undefined),\n savedAt: board.savedAt,\n itemCount: board.items.length,\n board,\n });\n }\n\n boards.sort((a, b) => b.savedAt - a.savedAt);\n return { boards, error: null };\n}\n\n/**\n * `metadata` is a JSON scalar, which arrives decoded — but a backend that types\n * it as a String hands back the encoded text instead, and a board that silently\n * fails to parse looks exactly like an empty canvas. Accept both.\n */\nfunction coerceMetadata(value: unknown): unknown {\n if (typeof value !== 'string') return value;\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n}\n\ninterface SurfaceIndexResponse {\n data?: { mySurfaceChannels?: Array<Record<string, unknown>> | null } | null;\n errors?: Array<{ message?: string }>;\n}\n"],"names":[],"mappings":"AA6CgB,SAAA,eAAA,CAAgB,YAAoB,QAA2B,EAAA;AAC7E,EAAM,MAAA,QAAA,GAAA,CAAY,QAAY,IAAA,EAAA,EAAI,IAAK,EAAA;AACvC,EAAA,IAAI,UAAiB,OAAA,QAAA;AACrB,EAAM,MAAA,IAAA,GAAA,CAAQ,UAAc,IAAA,EAAA,EAAI,IAAK,EAAA;AACrC,EAAI,IAAA,CAAC,MAAa,OAAA,EAAA;AAClB,EAAI,IAAA;AACF,IAAM,MAAA;AAAA,MACJ,QAAA;AAAA,MACA;AAAA,KACF,GAAI,YAAY,IAAI,CAAA;AACpB,IAAM,MAAA,MAAA,GAAS,IAAK,CAAA,KAAA,CAAM,GAAG,CAAA;AAC7B,IAAI,IAAA,MAAA,CAAO,MAAS,GAAA,CAAA,EAAU,OAAA,EAAA;AAC9B,IAAO,OAAA,CAAA,EAAG,QAAQ,CAA2B,wBAAA,EAAA,MAAA,CAAO,MAAM,CAAC,CAAA,CAAE,IAAK,CAAA,GAAG,CAAC,CAAA,QAAA,CAAA;AAAA,GAChE,CAAA,OAAA,CAAA,EAAA;AACN,IAAO,OAAA,EAAA;AAAA;AAEX;AACA,SAAS,YAAY,GAGnB,EAAA;AAGA,EAAM,MAAA,KAAA,GAAQ,GAAI,CAAA,KAAA,CAAM,wBAAwB,CAAA;AAChD,EAAA,IAAI,CAAC,KAAO,EAAA,MAAM,IAAI,KAAM,CAAA,CAAA,iBAAA,EAAoB,GAAG,CAAE,CAAA,CAAA;AACrD,EAAO,OAAA;AAAA,IACL,QAAU,EAAA,KAAA,CAAM,CAAC,CAAA,CAAE,WAAY,EAAA;AAAA,IAC/B,IAAM,EAAA,KAAA,CAAM,CAAC,CAAA,CAAE,WAAY;AAAA,GAC7B;AACF"}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import {useState,useMemo,useRef,useEffect}from'react';import {config}from'../../config/env-config.js';import {usePrerequisiteIds}from'../../hooks/usePrerequisiteIds.js';import {useObtainSystemToken}from'../../hooks/useObtainSystemToken.js';import {warmWebBuilderSession}from'../../screens/WebBuilder/webbuilderWarmCache.js';import {surfaceIndexUrl}from'./surfaceIndex.js';function useCanvasSession() {
|
|
2
|
+
const [token, setToken] = useState(null);
|
|
3
|
+
const [error, setError] = useState(null);
|
|
4
|
+
const [ready, setReady] = useState(false);
|
|
5
|
+
const {
|
|
6
|
+
orgName,
|
|
7
|
+
projectId,
|
|
8
|
+
tagId
|
|
9
|
+
} = usePrerequisiteIds();
|
|
10
|
+
const {
|
|
11
|
+
obtainSystemToken
|
|
12
|
+
} = useObtainSystemToken(true);
|
|
13
|
+
const indexUrl = useMemo(() => surfaceIndexUrl(config.GRAPHQL_URL, config.SURFACE_INDEX_URL), []);
|
|
14
|
+
const idsRef = useRef({
|
|
15
|
+
orgName,
|
|
16
|
+
projectId,
|
|
17
|
+
tagId
|
|
18
|
+
});
|
|
19
|
+
idsRef.current = {
|
|
20
|
+
orgName,
|
|
21
|
+
projectId,
|
|
22
|
+
tagId
|
|
23
|
+
};
|
|
24
|
+
useEffect(() => {
|
|
25
|
+
let cancelled = false;
|
|
26
|
+
(async () => {
|
|
27
|
+
try {
|
|
28
|
+
const session = await warmWebBuilderSession({
|
|
29
|
+
graphqlUrl: config.GRAPHQL_URL,
|
|
30
|
+
orgName: idsRef.current.orgName,
|
|
31
|
+
projectId: idsRef.current.projectId,
|
|
32
|
+
tagId: idsRef.current.tagId,
|
|
33
|
+
obtainSystemToken
|
|
34
|
+
});
|
|
35
|
+
if (cancelled) return;
|
|
36
|
+
setToken(session.token);
|
|
37
|
+
setError(null);
|
|
38
|
+
} catch (err) {
|
|
39
|
+
if (cancelled) return;
|
|
40
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
41
|
+
if (/waiting for org\/project/i.test(message) || !idsRef.current.orgName) return;
|
|
42
|
+
setError("Could not sign in to load your canvases.");
|
|
43
|
+
} finally {
|
|
44
|
+
if (!cancelled) setReady(true);
|
|
45
|
+
}
|
|
46
|
+
})();
|
|
47
|
+
return () => {
|
|
48
|
+
cancelled = true;
|
|
49
|
+
};
|
|
50
|
+
}, [obtainSystemToken, orgName, projectId]);
|
|
51
|
+
return {
|
|
52
|
+
token,
|
|
53
|
+
indexUrl,
|
|
54
|
+
error,
|
|
55
|
+
ready
|
|
56
|
+
};
|
|
57
|
+
}export{useCanvasSession};//# sourceMappingURL=useCanvasSession.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"useCanvasSession.js","sources":["../../../src/features/canvas/useCanvasSession.ts"],"sourcesContent":["/**\n * The host half of the canvas: session + endpoint, nothing else.\n *\n * Everything about READING a canvas lives in the federated remote\n * (`CanvasExperience`) so it can be fixed by a surface deploy. What the remote\n * cannot know is this environment's index URL and a token the index accepts —\n * that is what this resolves and hands over.\n *\n * Auth reuses the WebBuilder warm session rather than minting its own: it is the\n * same system JWT the surfaces already run on, it is cached app-wide, and going\n * through Apollo is what makes the token acceptable to the backend (a raw\n * SecureStore Auth0 bearer 401s — see the note in WebBuilder).\n */\nimport { useEffect, useMemo, useRef, useState } from 'react';\nimport { config } from '../../config/env-config';\nimport { usePrerequisiteIds } from '../../hooks/usePrerequisiteIds';\nimport { useObtainSystemToken } from '../../hooks/useObtainSystemToken';\nimport { warmWebBuilderSession } from '../../screens/WebBuilder/webbuilderWarmCache';\nimport { surfaceIndexUrl } from './surfaceIndex';\n\nexport interface CanvasSession {\n token: string | null;\n indexUrl: string;\n /** Plain sentence when the session could not be established, else null. */\n error: string | null;\n ready: boolean;\n}\n\nexport function useCanvasSession(): CanvasSession {\n const [token, setToken] = useState<string | null>(null);\n const [error, setError] = useState<string | null>(null);\n const [ready, setReady] = useState(false);\n\n const { orgName, projectId, tagId } = usePrerequisiteIds();\n const { obtainSystemToken } = useObtainSystemToken(true);\n\n const indexUrl = useMemo(\n () => surfaceIndexUrl(config.GRAPHQL_URL, (config as { SURFACE_INDEX_URL?: string }).SURFACE_INDEX_URL),\n [],\n );\n\n // org/project arrive a beat after mount; hold the latest in a ref so a\n // resolved id does not restart an in-flight mint.\n const idsRef = useRef({ orgName, projectId, tagId });\n idsRef.current = { orgName, projectId, tagId };\n\n useEffect(() => {\n let cancelled = false;\n\n (async () => {\n try {\n const session = await warmWebBuilderSession({\n graphqlUrl: config.GRAPHQL_URL,\n orgName: idsRef.current.orgName,\n projectId: idsRef.current.projectId,\n tagId: idsRef.current.tagId,\n obtainSystemToken,\n });\n if (cancelled) return;\n setToken(session.token);\n setError(null);\n } catch (err) {\n if (cancelled) return;\n const message = err instanceof Error ? err.message : String(err);\n // Missing org/project is a not-yet, not a failure: leave the\n // experience on its loading state rather than showing an error.\n if (/waiting for org\\/project/i.test(message) || !idsRef.current.orgName) return;\n setError('Could not sign in to load your canvases.');\n } finally {\n if (!cancelled) setReady(true);\n }\n })();\n\n return () => {\n cancel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