@tensorpass/aiconnect 0.1.5 → 0.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/dist/attachments/attachmentPolicy.d.ts +31 -0
  2. package/dist/attachments/attachmentPolicy.js +72 -0
  3. package/dist/attachments/attachmentPolicy.js.map +1 -0
  4. package/dist/attachments/imagePrep.d.ts +13 -0
  5. package/dist/attachments/imagePrep.js +70 -0
  6. package/dist/attachments/imagePrep.js.map +1 -0
  7. package/dist/attachments/index.d.ts +5 -0
  8. package/dist/attachments/index.js +6 -0
  9. package/dist/attachments/index.js.map +1 -0
  10. package/dist/attachments/pdfModule.d.ts +1 -0
  11. package/dist/attachments/pdfModule.js +9 -0
  12. package/dist/attachments/pdfModule.js.map +1 -0
  13. package/dist/attachments/pdfPrep.d.ts +6 -0
  14. package/dist/attachments/pdfPrep.js +63 -0
  15. package/dist/attachments/pdfPrep.js.map +1 -0
  16. package/dist/attachments/preparedAttachment.d.ts +18 -0
  17. package/dist/attachments/preparedAttachment.js +52 -0
  18. package/dist/attachments/preparedAttachment.js.map +1 -0
  19. package/dist/chatContent.d.ts +7 -1
  20. package/dist/chatContent.js +29 -2
  21. package/dist/chatContent.js.map +1 -1
  22. package/dist/client.js +10 -0
  23. package/dist/client.js.map +1 -1
  24. package/dist/connectionState.d.ts +4 -1
  25. package/dist/connectionState.js.map +1 -1
  26. package/dist/dictation.d.ts +21 -0
  27. package/dist/dictation.js +7 -0
  28. package/dist/dictation.js.map +1 -0
  29. package/dist/guards/answerGuard.js +1 -1
  30. package/dist/guards/answerGuard.js.map +1 -1
  31. package/dist/guards/chatGuard.d.ts +2 -2
  32. package/dist/guards/chatGuard.js +38 -12
  33. package/dist/guards/chatGuard.js.map +1 -1
  34. package/dist/guards/envelopes.d.ts +1 -0
  35. package/dist/guards/envelopes.js +8 -0
  36. package/dist/guards/envelopes.js.map +1 -1
  37. package/dist/guards/index.d.ts +3 -3
  38. package/dist/guards/index.js +3 -3
  39. package/dist/guards/index.js.map +1 -1
  40. package/dist/guards/policy.d.ts +2 -0
  41. package/dist/guards/policy.js +1 -0
  42. package/dist/guards/policy.js.map +1 -1
  43. package/dist/guards/questionGuard.d.ts +2 -0
  44. package/dist/guards/questionGuard.js +38 -5
  45. package/dist/guards/questionGuard.js.map +1 -1
  46. package/dist/index.d.ts +4 -1
  47. package/dist/index.js +2 -1
  48. package/dist/index.js.map +1 -1
  49. package/dist/toolLoop.js +1 -2
  50. package/dist/toolLoop.js.map +1 -1
  51. package/dist/types.d.ts +13 -1
  52. package/dist/types.js.map +1 -1
  53. package/dist/walletProvider.d.ts +2 -0
  54. package/dist/walletProvider.js.map +1 -1
  55. package/dist/webAccounts/openAiWire.js +12 -6
  56. package/dist/webAccounts/openAiWire.js.map +1 -1
  57. package/dist/wireProtocols/anthropicMessages.js +18 -3
  58. package/dist/wireProtocols/anthropicMessages.js.map +1 -1
  59. package/dist/wireProtocols/geminiContents.js +11 -7
  60. package/dist/wireProtocols/geminiContents.js.map +1 -1
  61. package/dist/wireProtocols/openAiChat.js +4 -1
  62. package/dist/wireProtocols/openAiChat.js.map +1 -1
  63. package/dist/wireProtocols/openAiResponses.js +4 -1
  64. package/dist/wireProtocols/openAiResponses.js.map +1 -1
  65. package/dist/wireProtocols/wireProtocol.d.ts +2 -1
  66. package/dist/wireProtocols/wireProtocol.js +13 -1
  67. package/dist/wireProtocols/wireProtocol.js.map +1 -1
  68. package/package.json +7 -2
@@ -0,0 +1,31 @@
1
+ export interface AttachmentPolicy {
2
+ images?: boolean;
3
+ files?: boolean;
4
+ voice?: boolean;
5
+ accept?: string[];
6
+ maxBytes?: number;
7
+ maxFiles?: number;
8
+ }
9
+ export declare const DEFAULT_MAX_ATTACHMENT_BYTES: number;
10
+ export declare const DEFAULT_MAX_ATTACHMENTS = 10;
11
+ export declare const MAX_READ_BYTES: number;
12
+ export type AttachmentKind = 'image' | 'pdf' | 'text';
13
+ export type AttachmentRefusal = 'type' | 'size' | 'count';
14
+ export type AttachmentCheck = {
15
+ ok: true;
16
+ kind: AttachmentKind;
17
+ mediaType: string;
18
+ } | {
19
+ ok: false;
20
+ refusal: AttachmentRefusal;
21
+ };
22
+ export interface FileFacts {
23
+ name: string;
24
+ type: string;
25
+ size: number;
26
+ }
27
+ export declare function mediaTypeOf({ name, type }: Pick<FileFacts, 'name' | 'type'>): string;
28
+ export declare function attachmentsOn(policy: AttachmentPolicy | undefined): boolean;
29
+ export declare function acceptsType(mediaType: string, policy: AttachmentPolicy): boolean;
30
+ export declare function checkAttachment(file: FileFacts, policy: AttachmentPolicy, heldCount: number): AttachmentCheck;
31
+ export declare function fitsQuestion(bytes: number, heldBytes: number, policy: AttachmentPolicy): boolean;
@@ -0,0 +1,72 @@
1
+ // What a site lets its visitors attach to a question, and the checks a file meets: before the page reads it,
2
+ // its kind (an image, a PDF or a text file), the types the site accepts, the count of the question's files
3
+ // and the size the page agrees to read; once read, the size the question's files take on the way to the
4
+ // model, where an image counts as the page drew it again, often a tenth of the photo it came from.
5
+ import { isTextFile, PDF_TYPE } from "../chatContent.js";
6
+ // Five megabytes leave room for the conversation under the 8 million characters the wallet takes in one
7
+ // request, base64 writing 4 characters for 3 bytes.
8
+ export const DEFAULT_MAX_ATTACHMENT_BYTES = 5 * 1024 * 1024;
9
+ export const DEFAULT_MAX_ATTACHMENTS = 10;
10
+ // The largest file the page reads, such as a photo before it is drawn again.
11
+ export const MAX_READ_BYTES = 50 * 1024 * 1024;
12
+ // The text types browsers leave untyped or type in their own way, read from the file's extension.
13
+ const TEXT_EXTENSIONS = {
14
+ txt: 'text/plain',
15
+ md: 'text/markdown',
16
+ markdown: 'text/markdown',
17
+ csv: 'text/csv',
18
+ json: 'application/json',
19
+ };
20
+ // The media type the chat format carries for a file: its own, or the text type its extension names.
21
+ export function mediaTypeOf({ name, type }) {
22
+ const extension = name.split('.').pop()?.toLowerCase() ?? '';
23
+ return TEXT_EXTENSIONS[extension] ?? type;
24
+ }
25
+ function kindOf(mediaType) {
26
+ if (mediaType.startsWith('image/')) {
27
+ return 'image';
28
+ }
29
+ if (mediaType === PDF_TYPE) {
30
+ return 'pdf';
31
+ }
32
+ return isTextFile(mediaType) ? 'text' : null;
33
+ }
34
+ function allowedKind(kind, policy) {
35
+ return kind === 'image' ? policy.images !== false : policy.files !== false;
36
+ }
37
+ function acceptedType(mediaType, accept) {
38
+ if (!accept?.length) {
39
+ return true;
40
+ }
41
+ return accept.some((type) => (type.endsWith('/*') ? mediaType.startsWith(type.slice(0, -1)) : type === mediaType));
42
+ }
43
+ // Whether the policy takes any attachment at all, for the interface to show its attach button.
44
+ export function attachmentsOn(policy) {
45
+ return Boolean(policy) && (policy?.images !== false || policy?.files !== false);
46
+ }
47
+ // Whether a file of this media type may be attached, read before the drop from the dragged item's type.
48
+ export function acceptsType(mediaType, policy) {
49
+ const kind = kindOf(mediaType);
50
+ return kind !== null && allowedKind(kind, policy) && acceptedType(mediaType, policy.accept);
51
+ }
52
+ // The check of a file, before the page reads it, against the policy and the count of files the question
53
+ // already holds.
54
+ export function checkAttachment(file, policy, heldCount) {
55
+ const mediaType = mediaTypeOf(file);
56
+ const kind = kindOf(mediaType);
57
+ if (kind === null || !allowedKind(kind, policy) || !acceptedType(mediaType, policy.accept)) {
58
+ return { ok: false, refusal: 'type' };
59
+ }
60
+ if (heldCount >= (policy.maxFiles ?? DEFAULT_MAX_ATTACHMENTS)) {
61
+ return { ok: false, refusal: 'count' };
62
+ }
63
+ if (file.size > MAX_READ_BYTES) {
64
+ return { ok: false, refusal: 'size' };
65
+ }
66
+ return { ok: true, kind, mediaType };
67
+ }
68
+ // Whether a file the page read fits beside the files the question holds.
69
+ export function fitsQuestion(bytes, heldBytes, policy) {
70
+ return heldBytes + bytes <= (policy.maxBytes ?? DEFAULT_MAX_ATTACHMENT_BYTES);
71
+ }
72
+ //# sourceMappingURL=attachmentPolicy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attachmentPolic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AC,WAAW,CAAC,IAAI,EAAE,MAAM,CAAC,IAAI,CAAC,YAAY,CAAC,SAAS,EAAE,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC;QAC3F,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;IACxC,CAAC;IACD,IAAI,SAAS,IAAI,CAAC,MAAM,CAAC,QAAQ,IAAI,uBAAuB,CAAC,EAAE,CAAC;QAC9D,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,CAAC;IACzC,CAAC;IACD,IAAI,IAAI,CAAC,IAAI,GAAG,cAAc,EAAE,CAAC;QAC/B,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,CAAC;IACxC,CAAC;IACD,OAAO,EAAE,EAAE,EAAE,IAAI,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;AACvC,CAAC;AAED,yEAAyE;AACzE,MAAM,UAAU,YAAY,CAAC,KAAa,EAAE,SAAiB,EAAE,MAAwB;IACrF,OAAO,SAAS,GAAG,KAAK,IAAI,CAAC,MAAM,CAAC,QAAQ,IAAI,4BAA4B,CAAC,CAAC;AAChF,CAAC","sourcesContent":["// What a site lets its visitors attach to a question, and the checks a file meets: before the page reads it,\n// its kind (an image, a PDF or a text file), the types the site accepts, the count of the question's files\n// and the size the page agrees to read; once read, the size the question's files take on the way to the\n// model, where an image counts as the page drew it again, often a tenth of the photo it came from.\n\nimport { isTextFile, PDF_TYPE } from '../chatContent.ts';\n\nexport interface AttachmentPolicy {\n // Images, on by default.\n images?: boolean;\n // PDFs and text files (plain text, Markdown, CSV, JSON), on by default.\n files?: boolean;\n // Dictation into the question field, on by default.\n voice?: boolean;\n // The media types the site accepts, narrower than the kinds above, such as `['image/png', 'image/jpeg']`.\n // A type ending in `/*` accepts its whole family.\n accept?: string[];\n // The size the files of one question take together on the way to the model, in bytes.\n maxBytes?: number;\n maxFiles?: number;\n}\n\n// Five megabytes leave room for the conversation under the 8 million characters the wallet takes in one\n// request, base64 writing 4 characters for 3 bytes.\nexport const DEFAULT_MAX_ATTACHMENT_BYTES = 5 * 1024 * 1024;\nexport const DEFAULT_MAX_ATTACHMENTS = 10;\n\n// The largest file the page reads, such as a photo before it is drawn again.\nexport const MAX_READ_BYTES = 50 * 1024 * 1024;\n\nexport type AttachmentKind = 'image' | 'pdf' | 'text';\n\n// Why a file was not attached: a type the site or the chat does not take, a question over the size cap or\n// over the count.\nexport type AttachmentRefusal = 'type' | 'size' | 'count';\n\nexport type AttachmentCheck =\n | { ok: true; kind: AttachmentKind; mediaType: string }\n | { ok: false; refusal: AttachmentRefusal };\n\n// What the page knows of a file before reading it, as a `File` gives it.\nexport interface FileFacts {\n name: string;\n type: string;\n size: number;\n}\n\n// The text types browsers leave untyped or type in their own way, read from the file's extension.\nconst TEXT_EXTENSIONS: Record<string, string> = {\n txt: 'text/plain',\n md: 'text/markdown',\n markdown: 'text/markdown',\n csv: 'text/csv',\n json: 'application/json',\n};\n\n// The media type the chat format carries for a file: its own, or the text type its extension names.\nexport function mediaTypeOf({ name, type }: Pick<FileFacts, 'name' | 'type'>): string {\n const extension = name.split('.').pop()?.toLowerCase() ?? '';\n return TEXT_EXTENSIONS[extension] ?? type;\n}\n\nfunction kindOf(mediaType: string): AttachmentKind | null {\n if (mediaType.startsWith('image/')) {\n return 'image';\n }\n if (mediaType === PDF_TYPE) {\n return 'pdf';\n }\n return isTextFile(mediaType) ? 'text' : null;\n}\n\nfunction allowedKind(kind: AttachmentKind, policy: AttachmentPolicy): boolean {\n return kind === 'image' ? policy.images !== false : policy.files !== false;\n}\n\nfunction acceptedType(mediaType: string, accept: string[] | undefined): boolean {\n if (!accept?.length) {\n return true;\n }\n return accept.some((type) => (type.endsWith('/*') ? mediaType.startsWith(type.slice(0, -1)) : type === mediaType));\n}\n\n// Whether the policy takes any attachment at all, for the interface to show its attach button.\nexport function attachmentsOn(policy: AttachmentPolicy | undefined): boolean {\n return Boolean(policy) && (policy?.images !== false || policy?.files !== false);\n}\n\n// Whether a file of this media type may be attached, read before the drop from the dragged item's type.\nexport function acceptsType(mediaType: string, policy: AttachmentPolicy): boolean {\n const kind = kindOf(mediaType);\n return kind !== null && allowedKind(kind, policy) && acceptedType(mediaType, policy.accept);\n}\n\n// The check of a file, before the page reads it, against the policy and the count of files the question\n// already holds.\nexport function checkAttachment(file: FileFacts, policy: AttachmentPolicy, heldCount: number): AttachmentCheck {\n const mediaType = mediaTypeOf(file);\n const kind = kindOf(mediaType);\n if (kind === null || !allowedKind(kind, policy) || !acceptedType(mediaType, policy.accept)) {\n return { ok: false, refusal: 'type' };\n }\n if (heldCount >= (policy.maxFiles ?? DEFAULT_MAX_ATTACHMENTS)) {\n return { ok: false, refusal: 'count' };\n }\n if (file.size > MAX_READ_BYTES) {\n return { ok: false, refusal: 'size' };\n }\n return { ok: true, kind, mediaType };\n}\n\n// Whether a file the page read fits beside the files the question holds.\nexport function fitsQuestion(bytes: number, heldBytes: number, policy: AttachmentPolicy): boolean {\n return heldBytes + bytes <= (policy.maxBytes ?? DEFAULT_MAX_ATTACHMENT_BYTES);\n}\n"]}
@@ -0,0 +1,13 @@
1
+ import type { ImagePart } from '../types.ts';
2
+ export declare const IMAGE_LONG_SIDE = 1568;
3
+ export declare class UnreadableFileError extends Error {
4
+ constructor(name: string);
5
+ }
6
+ export declare function blobDataUrl(blob: Blob): Promise<string>;
7
+ export declare function drawnCanvas(source: CanvasImageSource, width: number, height: number, opaque?: boolean): HTMLCanvasElement;
8
+ export declare function encodedImage(source: CanvasImageSource, width: number, height: number): Promise<Blob>;
9
+ export declare function fittedSize(width: number, height: number, longSide?: number): {
10
+ width: number;
11
+ height: number;
12
+ };
13
+ export declare function preparedImage(file: File): Promise<ImagePart>;
@@ -0,0 +1,70 @@
1
+ // An image as the model receives it: drawn again in the page at 1568 pixels on its long side at most, the
2
+ // size Anthropic's docs recommend (https://platform.claude.com/docs/en/build-with-claude/vision), and
3
+ // encoded as WebP, or as JPEG in a browser whose canvas does not write WebP. Drawing it again drops its
4
+ // metadata, the GPS position of a photo included.
5
+ export const IMAGE_LONG_SIDE = 1568;
6
+ const QUALITY = 0.86;
7
+ // A file the browser could not read as an image, such as a HEIC photo in a browser without HEIC.
8
+ export class UnreadableFileError extends Error {
9
+ constructor(name) {
10
+ super(`The browser could not read ${name}`);
11
+ this.name = 'UnreadableFileError';
12
+ }
13
+ }
14
+ export function blobDataUrl(blob) {
15
+ return new Promise((resolve, reject) => {
16
+ const reader = new FileReader();
17
+ reader.onload = () => resolve(reader.result);
18
+ reader.onerror = () => reject(reader.error);
19
+ reader.readAsDataURL(blob);
20
+ });
21
+ }
22
+ function canvasBlob(canvas, type) {
23
+ return new Promise((resolve) => canvas.toBlob(resolve, type, QUALITY));
24
+ }
25
+ // A canvas of the given size with the image drawn on it, on white when the encoding has no transparency.
26
+ export function drawnCanvas(source, width, height, opaque = false) {
27
+ const canvas = document.createElement('canvas');
28
+ canvas.width = width;
29
+ canvas.height = height;
30
+ const context = canvas.getContext('2d');
31
+ if (!context) {
32
+ throw new Error('The browser gave no 2D canvas');
33
+ }
34
+ if (opaque) {
35
+ context.fillStyle = '#fff';
36
+ context.fillRect(0, 0, width, height);
37
+ }
38
+ context.drawImage(source, 0, 0, width, height);
39
+ return canvas;
40
+ }
41
+ // The image source as a WebP image, or a JPEG one where the browser writes no WebP.
42
+ export async function encodedImage(source, width, height) {
43
+ const webp = await canvasBlob(drawnCanvas(source, width, height), 'image/webp');
44
+ if (webp?.type === 'image/webp') {
45
+ return webp;
46
+ }
47
+ const jpeg = await canvasBlob(drawnCanvas(source, width, height, true), 'image/jpeg');
48
+ if (!jpeg) {
49
+ throw new Error('The browser could not encode the image');
50
+ }
51
+ return jpeg;
52
+ }
53
+ // The size of an image scaled down to the long side, never up.
54
+ export function fittedSize(width, height, longSide = IMAGE_LONG_SIDE) {
55
+ const scale = Math.min(1, longSide / Math.max(width, height));
56
+ return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };
57
+ }
58
+ export async function preparedImage(file) {
59
+ const bitmap = await createImageBitmap(file).catch(() => {
60
+ throw new UnreadableFileError(file.name);
61
+ });
62
+ try {
63
+ const { width, height } = fittedSize(bitmap.width, bitmap.height);
64
+ return { type: 'image', url: await blobDataUrl(await encodedImage(bitmap, width, height)) };
65
+ }
66
+ finally {
67
+ bitmap.close();
68
+ }
69
+ }
70
+ //# sourceMappingURL=imagePrep.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"imagePrep.js","sourceRoot":"","sources":["../../src/attachments/imagePrep.ts"],"names":[],"mappings":"AAAA,0GAA0G;AAC1G,sGAAsG;AACtG,wGAAwG;AACxG,kDAAkD;AAIlD,MAAM,CAAC,MAAM,eAAe,GAAG,IAAI,CAAC;AAEpC,MAAM,OAAO,GAAG,IAAI,CAAC;AAErB,iGAAiG;AACjG,MAAM,OAAO,mBAAoB,SAAQ,KAAK;IAC5C,YAAY,IAAY;QACtB,KAAK,CAAC,8BAA8B,IAAI,EAAE,CAAC,CAAC;QAC5C,IAAI,CAAC,IAAI,GAAG,qBAAqB,CAAC;IACpC,CAAC;CACF;AAED,MAAM,UAAU,WAAW,CAAC,IAAU;IACpC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACrC,MAAM,MAAM,GAAG,IAAI,UAAU,EAAE,CAAC;QAChC,MAAM,CAAC,MAAM,GAAG,GAAG,EAAE,CAAC,OAAO,CAAC,MAAM,CAAC,MAAgB,CAAC,CAAC;QACvD,MAAM,CAAC,OAAO,GAAG,GAAG,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QAC5C,MAAM,CAAC,aAAa,CAAC,IAAI,CAAC,CAAC;IAC7B,CAAC,CAAC,CAAC;AACL,CAAC;AAED,SAAS,UAAU,CAAC,MAAyB,EAAE,IAAY;IACzD,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,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long side at most, the\n// size Anthropic's docs recommend (https://platform.claude.com/docs/en/build-with-claude/vision), and\n// encoded as WebP, or as JPEG in a browser whose canvas does not write WebP. Drawing it again drops its\n// metadata, the GPS position of a photo included.\n\nimport type { ImagePart } from '../types.ts';\n\nexport const IMAGE_LONG_SIDE = 1568;\n\nconst QUALITY = 0.86;\n\n// A file the browser could not read as an image, such as a HEIC photo in a browser without HEIC.\nexport class UnreadableFileError extends Error {\n constructor(name: string) {\n super(`The browser could not read ${name}`);\n this.name = 'UnreadableFileError';\n }\n}\n\nexport function blobDataUrl(blob: Blob): Promise<string> {\n return new Promise((resolve, reject) => {\n const reader = new FileReader();\n reader.onload = () => resolve(reader.result as string);\n reader.onerror = () => reject(reader.error);\n reader.readAsDataURL(blob);\n });\n}\n\nfunction canvasBlob(canvas: HTMLCanvasElement, type: string): Promise<Blob | null> {\n return new Promise((resolve) => canvas.toBlob(resolve, type, QUALITY));\n}\n\n// A canvas of the given size with the image drawn on it, on white when the encoding has no transparency.\nexport function drawnCanvas(source: CanvasImageSource, width: number, height: number, opaque = false) {\n const canvas = document.createElement('canvas');\n canvas.width = width;\n canvas.height = height;\n const context = canvas.getContext('2d');\n if (!context) {\n throw new Error('The browser gave no 2D canvas');\n }\n if (opaque) {\n context.fillStyle = '#fff';\n context.fillRect(0, 0, width, height);\n }\n context.drawImage(source, 0, 0, width, height);\n return canvas;\n}\n\n// The image source as a WebP image, or a JPEG one where the browser writes no WebP.\nexport async function encodedImage(source: CanvasImageSource, width: number, height: number): Promise<Blob> {\n const webp = await canvasBlob(drawnCanvas(source, width, height), 'image/webp');\n if (webp?.type === 'image/webp') {\n return webp;\n }\n const jpeg = await canvasBlob(drawnCanvas(source, width, height, true), 'image/jpeg');\n if (!jpeg) {\n throw new Error('The browser could not encode the image');\n }\n return jpeg;\n}\n\n// The size of an image scaled down to the long side, never up.\nexport function fittedSize(width: number, height: number, longSide = IMAGE_LONG_SIDE) {\n const scale = Math.min(1, longSide / Math.max(width, height));\n return { width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)) };\n}\n\nexport async function preparedImage(file: File): Promise<ImagePart> {\n const bitmap = await createImageBitmap(file).catch(() => {\n throw new UnreadableFileError(file.name);\n });\n try {\n const { width, height } = fittedSize(bitmap.width, bitmap.height);\n return { type: 'image', url: await blobDataUrl(await encodedImage(bitmap, width, height)) };\n } finally {\n bitmap.close();\n }\n}\n"]}
@@ -0,0 +1,5 @@
1
+ export { acceptsType, attachmentsOn, checkAttachment, DEFAULT_MAX_ATTACHMENT_BYTES, DEFAULT_MAX_ATTACHMENTS, fitsQuestion, MAX_READ_BYTES, mediaTypeOf, } from './attachmentPolicy.ts';
2
+ export type { AttachmentCheck, AttachmentKind, AttachmentPolicy, AttachmentRefusal, FileFacts, } from './attachmentPolicy.ts';
3
+ export { IMAGE_LONG_SIDE, UnreadableFileError } from './imagePrep.ts';
4
+ export { partsForModel, prepareAttachment, readsAttachment, UNKNOWN_READS } from './preparedAttachment.ts';
5
+ export type { ModelParts, PreparedAttachment } from './preparedAttachment.ts';
@@ -0,0 +1,6 @@
1
+ // What a site's page does with the files a visitor attaches: the policy it sets, the check of each file,
2
+ // and the reading that turns a file into the parts the answering model reads.
3
+ export { acceptsType, attachmentsOn, checkAttachment, DEFAULT_MAX_ATTACHMENT_BYTES, DEFAULT_MAX_ATTACHMENTS, fitsQuestion, MAX_READ_BYTES, mediaTypeOf, } from "./attachmentPolicy.js";
4
+ export { IMAGE_LONG_SIDE, UnreadableFileError } from "./imagePrep.js";
5
+ export { partsForModel, prepareAttachment, readsAttachment, UNKNOWN_READS } from "./preparedAttachment.js";
6
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/attachments/index.ts"],"names":[],"mappings":"AAAA,yGAAyG;AACzG,8EAA8E;AAE9E,OAAO,EACL,WAAW,EAAE,aAAa,EAAE,eAAe,EAAE,4BAA4B,EAAE,uBAAuB,EAAE,YAAY,EAChH,cAAc,EAAE,WAAW,GAC5B,MAAM,uBAAuB,CAAC;AAI/B,OAAO,EAAE,eAAe,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AACtE,OAAO,EAAE,aAAa,EAAE,iBAAiB,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,yBAAyB,CAAC","sourcesContent":["// What a site's page does with the files a visitor attaches: the policy it sets, the check of each file,\n// and the reading that turns a file into the parts the answering model reads.\n\nexport {\n acceptsType, attachmentsOn, checkAttachment, DEFAULT_MAX_ATTACHMENT_BYTES, DEFAULT_MAX_ATTACHMENTS, fitsQuestion,\n MAX_READ_BYTES, mediaTypeOf,\n} from './attachmentPolicy.ts';\nexport type {\n AttachmentCheck, AttachmentKind, AttachmentPolicy, AttachmentRefusal, FileFacts,\n} from './attachmentPolicy.ts';\nexport { IMAGE_LONG_SIDE, UnreadableFileError } from './imagePrep.ts';\nexport { partsForModel, prepareAttachment, readsAttachment, UNKNOWN_READS } from './preparedAttachment.ts';\nexport type { ModelParts, PreparedAttachment } from './preparedAttachment.ts';\n"]}
@@ -0,0 +1 @@
1
+ export declare function loadPdfJs(): Promise<typeof import('pdfjs-dist')>;
@@ -0,0 +1,9 @@
1
+ // pdf.js for the page, loaded the first time a PDF is read for a model that does not read PDFs. Its worker
2
+ // module comes with it and registers itself, so pdf.js reads the PDF in the page and fetches no worker
3
+ // script from an address. The Web Components build puts its own copy of pdf.js, a script beside its own, in
4
+ // this module's place.
5
+ export async function loadPdfJs() {
6
+ const [pdfjs] = await Promise.all([import('pdfjs-dist'), import('pdfjs-dist/build/pdf.worker.min.mjs')]);
7
+ return pdfjs;
8
+ }
9
+ //# sourceMappingURL=pdfModule.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pdfModule.js","sourceRoot":"","sources":["../../src/attachments/pdfModule.ts"],"names":[],"mappings":"AAAA,2GAA2G;AAC3G,uGAAuG;AACvG,4GAA4G;AAC5G,uBAAuB;AAEvB,MAAM,CAAC,KAAK,UAAU,SAAS;IAC7B,MAAM,CAAC,KAAK,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,YAAY,CAAC,EAAE,MAAM,CAAC,qCAAqC,CAAC,CAAC,CAAC,CAAC;IACzG,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["// pdf.js for the page, loaded the first time a PDF is read for a model that does not read PDFs. Its worker\n// module comes with it and registers itself, so pdf.js reads the PDF in the page and fetches no worker\n// script from an address. The Web Components build puts its own copy of pdf.js, a script beside its own, in\n// this module's place.\n\nexport async function loadPdfJs(): Promise<typeof import('pdfjs-dist')> {\n const [pdfjs] = await Promise.all([import('pdfjs-dist'), import('pdfjs-dist/build/pdf.worker.min.mjs')]);\n return pdfjs;\n}\n"]}
@@ -0,0 +1,6 @@
1
+ import type { ContentPart } from '../types.ts';
2
+ export interface ReadPdf {
3
+ parts: ContentPart[];
4
+ unread: number;
5
+ }
6
+ export declare function readPdf(file: Blob, name: string, readsImages: boolean): Promise<ReadPdf>;
@@ -0,0 +1,63 @@
1
+ // A PDF for a model that does not read PDFs: pdf.js reads it in the page, its text goes as a text file
2
+ // under the PDF's name, and each page without text, such as a scan, goes as an image when the model reads
3
+ // images. pdf.js loads only when such a PDF is sent (pdfModule.ts).
4
+ import { encodeBase64Text } from "../chatContent.js";
5
+ import { blobDataUrl, encodedImage, fittedSize } from "./imagePrep.js";
6
+ import { loadPdfJs } from "./pdfModule.js";
7
+ // The pages read from one PDF, and the scanned pages sent as images.
8
+ const MAX_PAGES = 200;
9
+ const MAX_SCANNED_PAGES = 20;
10
+ // A page holding fewer characters than this is read as a scan.
11
+ const SCAN_TEXT_LENGTH = 16;
12
+ async function loadPdf(bytes) {
13
+ const pdfjs = await loadPdfJs();
14
+ return pdfjs.getDocument({ data: new Uint8Array(bytes) });
15
+ }
16
+ async function pageText(page) {
17
+ const content = await page.getTextContent();
18
+ return content.items
19
+ .map((item) => ('str' in item ? `${item.str}${item.hasEOL ? '\n' : ''}` : ''))
20
+ .join('')
21
+ .trim();
22
+ }
23
+ async function pageImage(page) {
24
+ const base = page.getViewport({ scale: 1 });
25
+ const { width } = fittedSize(base.width, base.height);
26
+ const viewport = page.getViewport({ scale: width / base.width });
27
+ const canvas = document.createElement('canvas');
28
+ canvas.width = Math.round(viewport.width);
29
+ canvas.height = Math.round(viewport.height);
30
+ await page.render({ canvas, viewport, background: '#fff' }).promise;
31
+ return { type: 'image', url: await blobDataUrl(await encodedImage(canvas, canvas.width, canvas.height)) };
32
+ }
33
+ export async function readPdf(file, name, readsImages) {
34
+ const loading = await loadPdf(await file.arrayBuffer());
35
+ const pdf = await loading.promise;
36
+ const texts = [];
37
+ const images = [];
38
+ let unread = Math.max(0, pdf.numPages - MAX_PAGES);
39
+ try {
40
+ for (let number = 1; number <= Math.min(pdf.numPages, MAX_PAGES); number += 1) {
41
+ const page = await pdf.getPage(number);
42
+ const text = await pageText(page);
43
+ if (text.length >= SCAN_TEXT_LENGTH) {
44
+ texts.push(`[Page ${number}]\n${text}`);
45
+ }
46
+ else if (readsImages && images.length < MAX_SCANNED_PAGES) {
47
+ images.push(await pageImage(page));
48
+ }
49
+ else {
50
+ unread += 1;
51
+ }
52
+ page.cleanup();
53
+ }
54
+ }
55
+ finally {
56
+ await loading.destroy();
57
+ }
58
+ const text = texts.length
59
+ ? [{ type: 'file', name, url: `data:text/plain;base64,${encodeBase64Text(texts.join('\n\n'))}` }]
60
+ : [];
61
+ return { parts: [...text, ...images], unread };
62
+ }
63
+ //# sourceMappingURL=pdfPrep.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pdfPrep.js","sourceRoot":"","sources":["../../src/attachments/pdfPrep.ts"],"names":[],"mappings":"AAAA,uGAAuG;AACvG,0GAA0G;AAC1G,oEAAoE;AAEpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAErD,OAAO,EAAE,WAAW,EAAE,YAAY,EAAE,UAAU,EAAE,MAAM,gBAAgB,CA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,KAAK,CAAC,IAAI,CAAC,SAAS,MAAM,MAAM,IAAI,EAAE,CAAC,CAAC;YAC1C,CAAC;iBAAM,IAAI,WAAW,IAAI,MAAM,CAAC,MAAM,GAAG,iBAAiB,EAAE,CAAC;gBAC5D,MAAM,CAAC,IAAI,CAAC,MAAM,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;YACrC,CAAC;iBAAM,CAAC;gBACN,MAAM,IAAI,CAAC,CAAC;YACd,CAAC;YACD,IAAI,CAAC,OAAO,EAAE,CAAC;QACjB,CAAC;IACH,CAAC;YAAS,CAAC;QACT,MAAM,OAAO,CAAC,OAAO,EAAE,CAAC;IAC1B,CAAC;IACD,MAAM,IAAI,GAAkB,KAAK,CAAC,MAAM;QACtC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,0BAA0B,gBAAgB,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,EAAE,EAAE,CAAC;QACjG,CAAC,CAAC,EAAE,CAAC;IACP,OAAO,EAAE,KAAK,EAAE,CAAC,GAAG,IAAI,EAAE,GAAG,MAAM,CAAC,EAAE,MAAM,EAAE,CAAC;AACjD,CAAC","sourcesContent":["// A PDF for a model that does not read PDFs: pdf.js reads it in the page, its text goes as a text file\n// under the PDF's name, and each page without text, such as a scan, goes as an image when the model reads\n// images. pdf.js loads only when such a PDF is sent (pdfModule.ts).\n\nimport { encodeBase64Text } from '../chatContent.ts';\nimport type { ContentPart } from '../types.ts';\nimport { blobDataUrl, encodedImage, fittedSize } from './imagePrep.ts';\nimport { loadPdfJs } from './pdfModule.ts';\n\n// The pages read from one PDF, and the scanned pages sent as images.\nconst MAX_PAGES = 200;\nconst MAX_SCANNED_PAGES = 20;\n\n// A page holding fewer characters than this is read as a scan.\nconst SCAN_TEXT_LENGTH = 16;\n\ntype PdfLoading = ReturnType<typeof import('pdfjs-dist').getDocument>;\ntype PdfPage = Awaited<ReturnType<Awaited<PdfLoading['promise']>['getPage']>>;\n\nasync function loadPdf(bytes: ArrayBuffer): Promise<PdfLoading> {\n const pdfjs = await loadPdfJs();\n return pdfjs.getDocument({ data: new Uint8Array(bytes) });\n}\n\nasync function pageText(page: PdfPage): Promise<string> {\n const content = await page.getTextContent();\n return content.items\n .map((item) => ('str' in item ? `${item.str}${item.hasEOL ? '\\n' : ''}` : ''))\n .join('')\n .trim();\n}\n\nasync function pageImage(page: PdfPage): Promise<ContentPart> {\n const base = page.getViewport({ scale: 1 });\n const { width } = fittedSize(base.width, base.height);\n const viewport = page.getViewport({ scale: width / base.width });\n const canvas = document.createElement('canvas');\n canvas.width = Math.round(viewport.width);\n canvas.height = Math.round(viewport.height);\n await page.render({ canvas, viewport, background: '#fff' }).promise;\n return { type: 'image', url: await blobDataUrl(await encodedImage(canvas, canvas.width, canvas.height)) };\n}\n\nexport interface ReadPdf {\n parts: ContentPart[];\n // Pages the model will not see: scans for a model without images, and pages past the limits.\n unread: number;\n}\n\nexport async function readPdf(file: Blob, name: string, readsImages: boolean): Promise<ReadPdf> {\n const loading = await loadPdf(await file.arrayBuffer());\n const pdf = await loading.promise;\n const texts: string[] = [];\n const images: ContentPart[] = [];\n let unread = Math.max(0, pdf.numPages - MAX_PAGES);\n try {\n for (let number = 1; number <= Math.min(pdf.numPages, MAX_PAGES); number += 1) {\n const page = await pdf.getPage(number);\n const text = await pageText(page);\n if (text.length >= SCAN_TEXT_LENGTH) {\n texts.push(`[Page ${number}]\\n${text}`);\n } else if (readsImages && images.length < MAX_SCANNED_PAGES) {\n images.push(await pageImage(page));\n } else {\n unread += 1;\n }\n page.cleanup();\n }\n } finally {\n await loading.destroy();\n }\n const text: ContentPart[] = texts.length\n ? [{ type: 'file', name, url: `data:text/plain;base64,${encodeBase64Text(texts.join('\\n\\n'))}` }]\n : [];\n return { parts: [...text, ...images], unread };\n}\n"]}
@@ -0,0 +1,18 @@
1
+ import type { ContentPart, FilePart, ImagePart, ReadableParts } from '../types.ts';
2
+ import type { AttachmentKind } from './attachmentPolicy.ts';
3
+ export interface PreparedAttachment {
4
+ name: string;
5
+ size: number;
6
+ kind: AttachmentKind;
7
+ part: ImagePart | FilePart;
8
+ bytes: number;
9
+ source?: Blob;
10
+ }
11
+ export declare const UNKNOWN_READS: ReadableParts;
12
+ export declare function prepareAttachment(file: File, kind: AttachmentKind, mediaType: string): Promise<PreparedAttachment>;
13
+ export declare function readsAttachment(kind: AttachmentKind, reads: ReadableParts): boolean;
14
+ export interface ModelParts {
15
+ parts: ContentPart[];
16
+ unread: number;
17
+ }
18
+ export declare function partsForModel(attachments: PreparedAttachment[], reads: ReadableParts): Promise<ModelParts>;
@@ -0,0 +1,52 @@
1
+ // A file the visitor attached, read in the page once it is added: an image drawn again at the size models
2
+ // read, a PDF kept whole, a text file as its text. When the question is sent, its attachments become the
3
+ // parts the answering model reads: a PDF whole for a model that reads PDFs and as its text and scanned pages
4
+ // for the others, and an image only for a model that reads images.
5
+ import { encodeBase64Text } from "../chatContent.js";
6
+ import { blobDataUrl, preparedImage } from "./imagePrep.js";
7
+ import { readPdf } from "./pdfPrep.js";
8
+ // What a model reads when its account does not say: images, which every account of the wallet passes on,
9
+ // and PDFs as their text.
10
+ export const UNKNOWN_READS = { image: true, pdf: false };
11
+ export async function prepareAttachment(file, kind, mediaType) {
12
+ const facts = { name: file.name, size: file.size, kind };
13
+ if (kind === 'image') {
14
+ const part = await preparedImage(file);
15
+ return { ...facts, part, bytes: partBytes(part) };
16
+ }
17
+ if (kind === 'pdf') {
18
+ const part = { type: 'file', name: file.name, url: await blobDataUrl(file) };
19
+ return { ...facts, part, bytes: file.size, source: file };
20
+ }
21
+ const text = encodeBase64Text(await file.text());
22
+ const part = { type: 'file', name: file.name, url: `data:${mediaType};base64,${text}` };
23
+ return { ...facts, part, bytes: partBytes(part) };
24
+ }
25
+ // The bytes a base64 `data:` URL holds.
26
+ function partBytes(part) {
27
+ const comma = part.url.indexOf(',');
28
+ return Math.floor(((part.url.length - comma - 1) * 3) / 4);
29
+ }
30
+ // Whether the model reads the attachment as the page prepared it, for the interface to say so on its chip.
31
+ export function readsAttachment(kind, reads) {
32
+ return kind !== 'image' || reads.image;
33
+ }
34
+ export async function partsForModel(attachments, reads) {
35
+ const parts = [];
36
+ let unread = 0;
37
+ for (const attachment of attachments) {
38
+ if (attachment.kind === 'image' && !reads.image) {
39
+ unread += 1;
40
+ }
41
+ else if (attachment.kind === 'pdf' && !reads.pdf && attachment.source) {
42
+ const pdf = await readPdf(attachment.source, attachment.name, reads.image);
43
+ parts.push(...pdf.parts);
44
+ unread += pdf.unread;
45
+ }
46
+ else {
47
+ parts.push(attachment.part);
48
+ }
49
+ }
50
+ return { parts, unread };
51
+ }
52
+ //# sourceMappingURL=preparedAttachment.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preparedAttachment.js","sourceRoot":"","sources":["../../src/attachments/preparedAttachment.ts"],"names":[],"mappings":"AAAA,0GAA0G;AAC1G,yGAAyG;AACzG,6GAA6G;AAC7G,mEAAmE;AAEnE,OAAO,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAGrD,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAC;AAC5D,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAcvC,yGAAyG;AACzG,0BAA0B;AAC1B,MAAM,CAAC,MAAM,aAAa,GAAkB,EAAE,KAAK,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,CAAC;AAExE,MAAM,CAAC,KAAK,UAAU,iBAAiB,CACrC,IAAU,EAAE,IAAoB,EAAE,SAAiB;IAEnD,MAAM,KAAK,GAAG,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,CAAC;IACzD,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;QACrB,MAAM,IAAI,GAAG,MAAM,aAAa,CAAC,IAAI,CAAC,CAAC;QACvC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AoB;IACzF,MAAM,KAAK,GAAkB,EAAE,CAAC;IAChC,IAAI,MAAM,GAAG,CAAC,CAAC;IACf,KAAK,MAAM,UAAU,IAAI,WAAW,EAAE,CAAC;QACrC,IAAI,UAAU,CAAC,IAAI,KAAK,OAAO,IAAI,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC;YAChD,MAAM,IAAI,CAAC,CAAC;QACd,CAAC;aAAM,IAAI,UAAU,CAAC,IAAI,KAAK,KAAK,IAAI,CAAC,KAAK,CAAC,GAAG,IAAI,UAAU,CAAC,MAAM,EAAE,CAAC;YACxE,MAAM,GAAG,GAAG,MAAM,OAAO,CAAC,UAAU,CAAC,MAAM,EAAE,UAAU,CAAC,IAAI,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;YAC3E,KAAK,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC;YACzB,MAAM,IAAI,GAAG,CAAC,MAAM,CAAC;QACvB,CAAC;aAAM,CAAC;YACN,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;QAC9B,CAAC;IACH,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,CAAC;AAC3B,CAAC","sourcesContent":["// A file the visitor attached, read in the page once it is added: an image drawn again at the size models\n// read, a PDF kept whole, a text file as its text. When the question is sent, its attachments become the\n// parts the answering model reads: a PDF whole for a model that reads PDFs and as its text and scanned pages\n// for the others, and an image only for a model that reads images.\n\nimport { encodeBase64Text } from '../chatContent.ts';\nimport type { ContentPart, FilePart, ImagePart, ReadableParts } from '../types.ts';\nimport type { AttachmentKind } from './attachmentPolicy.ts';\nimport { blobDataUrl, preparedImage } from './imagePrep.ts';\nimport { readPdf } from './pdfPrep.ts';\n\nexport interface PreparedAttachment {\n name: string;\n // The size of the file as the visitor gave it, in bytes.\n size: number;\n kind: AttachmentKind;\n part: ImagePart | FilePart;\n // The size the part takes on the way to the model, in bytes.\n bytes: number;\n // The PDF itself, read again by pdf.js for a model that does not read PDFs.\n source?: Blob;\n}\n\n// What a model reads when its account does not say: images, which every account of the wallet passes on,\n// and PDFs as their text.\nexport const UNKNOWN_READS: ReadableParts = { image: true, pdf: false };\n\nexport async function prepareAttachment(\n file: File, kind: AttachmentKind, mediaType: string,\n): Promise<PreparedAttachment> {\n const facts = { name: file.name, size: file.size, kind };\n if (kind === 'image') {\n const part = await preparedImage(file);\n return { ...facts, part, bytes: partBytes(part) };\n }\n if (kind === 'pdf') {\n const part: FilePart = { type: 'file', name: file.name, url: await blobDataUrl(file) };\n return { ...facts, part, bytes: file.size, source: file };\n }\n const text = encodeBase64Text(await file.text());\n const part: FilePart = { type: 'file', name: file.name, url: `data:${mediaType};base64,${text}` };\n return { ...facts, part, bytes: partBytes(part) };\n}\n\n// The bytes a base64 `data:` URL holds.\nfunction partBytes(part: ImagePart | FilePart): number {\n const comma = part.url.indexOf(',');\n return Math.floor(((part.url.length - comma - 1) * 3) / 4);\n}\n\n// Whether the model reads the attachment as the page prepared it, for the interface to say so on its chip.\nexport function readsAttachment(kind: AttachmentKind, reads: ReadableParts): boolean {\n return kind !== 'image' || reads.image;\n}\n\nexport interface ModelParts {\n parts: ContentPart[];\n // Images and pages the model will not see.\n unread: number;\n}\n\nexport async function partsForModel(attachments: PreparedAttachment[], reads: ReadableParts): Promise<ModelParts> {\n const parts: ContentPart[] = [];\n let unread = 0;\n for (const attachment of attachments) {\n if (attachment.kind === 'image' && !reads.image) {\n unread += 1;\n } else if (attachment.kind === 'pdf' && !reads.pdf && attachment.source) {\n const pdf = await readPdf(attachment.source, attachment.name, reads.image);\n parts.push(...pdf.parts);\n unread += pdf.unread;\n } else {\n parts.push(attachment.part);\n }\n }\n return { parts, unread };\n}\n"]}
@@ -1,9 +1,15 @@
1
- import type { ContentPart } from './types.ts';
1
+ import type { ContentPart, FilePart } from './types.ts';
2
2
  export interface InlineData {
3
3
  mediaType: string;
4
4
  data: string;
5
5
  }
6
+ export declare const PDF_TYPE = "application/pdf";
6
7
  export declare function contentParts(content: string | ContentPart[]): ContentPart[];
7
8
  export declare function textOf(content: string | ContentPart[]): string;
8
9
  export declare function inlineData(url: string): InlineData | null;
9
10
  export declare function dataUrl({ mediaType, data }: InlineData): string;
11
+ export declare function isTextFile(mediaType: string): boolean;
12
+ export declare function decodeBase64Text(data: string): string;
13
+ export declare function encodeBase64Text(text: string): string;
14
+ export declare function fileText(part: FilePart): string | null;
15
+ export declare function attachedText(content: string | ContentPart[]): string[];
@@ -1,12 +1,16 @@
1
- // Reads a message's content the same way in every translation: as parts, as plain text, and an
2
- // image's `data:` URL as its media type and base64 data.
1
+ // Reads a message's content the same way in every translation: as parts, as plain text, a `data:`
2
+ // URL as its media type and base64 data, and an attached text file as its text.
3
3
  const DATA_URL = /^data:([^;,]+);base64,(.*)$/s;
4
+ // The files a model reads as text. A PDF is the one other file type the chat format carries.
5
+ const TEXT_FILE_TYPES = new Set(['text/plain', 'text/markdown', 'text/csv', 'application/json']);
6
+ export const PDF_TYPE = 'application/pdf';
4
7
  export function contentParts(content) {
5
8
  if (typeof content !== 'string') {
6
9
  return content;
7
10
  }
8
11
  return content ? [{ type: 'text', text: content }] : [];
9
12
  }
13
+ // The text the visitor typed, without the attached files.
10
14
  export function textOf(content) {
11
15
  return contentParts(content)
12
16
  .map((part) => (part.type === 'text' ? part.text : ''))
@@ -20,4 +24,27 @@ export function inlineData(url) {
20
24
  export function dataUrl({ mediaType, data }) {
21
25
  return `data:${mediaType};base64,${data}`;
22
26
  }
27
+ export function isTextFile(mediaType) {
28
+ return TEXT_FILE_TYPES.has(mediaType);
29
+ }
30
+ export function decodeBase64Text(data) {
31
+ const bytes = Uint8Array.from(atob(data), (character) => character.charCodeAt(0));
32
+ return new TextDecoder().decode(bytes);
33
+ }
34
+ export function encodeBase64Text(text) {
35
+ const bytes = new TextEncoder().encode(text);
36
+ return btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(''));
37
+ }
38
+ // The text of an attached text file, or null for a PDF.
39
+ export function fileText(part) {
40
+ const inline = inlineData(part.url);
41
+ return inline && isTextFile(inline.mediaType) ? decodeBase64Text(inline.data) : null;
42
+ }
43
+ // The text of each text file attached to the content.
44
+ export function attachedText(content) {
45
+ return contentParts(content).flatMap((part) => {
46
+ const text = part.type === 'file' ? fileText(part) : null;
47
+ return text === null ? [] : [text];
48
+ });
49
+ }
23
50
  //# sourceMappingURL=chatContent.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"chatContent.js","sourceRoot":"","sources":["../src/chatContent.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAC/F,yDAAyD;AASzD,MAAM,QAAQ,GAAG,8BAA8B,CAAC;AAEhD,MAAM,UAAU,YAAY,CAAC,OAA+B;IAC1D,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QAChC,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,OAAO,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;AAC1D,CAAC;AAED,MAAM,UAAU,MAAM,CAAC,OAA+B;IACpD,OAAO,YAAY,CAAC,OAAO,CAAC;SACzB,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;SACtD,IAAI,CAAC,EAAE,CAAC,CAAC;AACd,CAAC;AAED,8EAA8E;AAC9E,MAAM,UAAU,UAAU,CAAC,GAAW;IACpC,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACjC,OAAO,KAAK,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;AAChE,CAAC;AAED,MAAM,UAAU,OAAO,CAAC,EAAE,SAAS,EAAE,IAAI,EAAc;IACrD,OAAO,QAAQ,SAAS,WAAW,IAAI,EAAE,CAAC;AAC5C,CAAC","sourcesContent":["// Reads a message's content the same way in every translation: as parts, as plain text, and an\n// image's `data:` URL as its media type and base64 data.\n\nimport type { ContentPart } from './types.ts';\n\nexport interface InlineData {\n mediaType: string;\n data: string;\n}\n\nconst DATA_URL = /^data:([^;,]+);base64,(.*)$/s;\n\nexport function contentParts(content: string | ContentPart[]): ContentPart[] {\n if (typeof content !== 'string') {\n return content;\n }\n return content ? [{ type: 'text', text: content }] : [];\n}\n\nexport function textOf(content: string | ContentPart[]): string {\n return contentParts(content)\n .map((part) => (part.type === 'text' ? part.text : ''))\n .join('');\n}\n\n// The media type and data of a base64 `data:` URL, or null for any other URL.\nexport function inlineData(url: string): InlineData | null {\n const match = DATA_URL.exec(url);\n return match ? { mediaType: match[1], data: match[2] } : null;\n}\n\nexport function dataUrl({ mediaType, data }: InlineData): string {\n return `data:${mediaType};base64,${data}`;\n}\n"]}
1
+ {"version":3,"file":"chatContent.js","sourceRoot":"","sources":["../src/chatContent.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,gFAAgF;AAShF,MAAM,QAAQ,GAAG,8BAA8B,CAAC;AAEhD,6FAA6F;AAC7F,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,CAAC,YAAY,EAAE,eAAe,EAAE,UAAU,EAAE,kBAAkB,CAAC,CAAC,CAAC;AAEjG,MAAM,CAAC,MAAM,QAAQ,GAAG,iBAAiB,CAAC;AAE1C,MAAM,UAAU,YAAY,CAAC,OAA+B;IAC1D,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE,CAAC;QAChC,OAAO,OAAO,CAAC;IACjB,CAAC;IACD,OAAO,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC,CAAC,EA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I,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,MAAM,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC;AAC/E,CAAC;AAED,wDAAwD;AACxD,MAAM,UAAU,QAAQ,CAAC,IAAc;IACrC,MAAM,MAAM,GAAG,UAAU,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IACpC,OAAO,MAAM,IAAI,UAAU,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,gBAAgB,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AACvF,CAAC;AAED,sDAAsD;AACtD,MAAM,UAAU,YAAY,CAAC,OAA+B;IAC1D,OAAO,YAAY,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,IAAI,EAAE,EAAE;QAC5C,MAAM,IAAI,GAAG,IAAI,CAAC,IAAI,KAAK,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;QAC1D,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IACrC,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["// Reads a message's content the same way in every translation: as parts, as plain text, a `data:`\n// URL as its media type and base64 data, and an attached text file as its text.\n\nimport type { ContentPart, FilePart } from './types.ts';\n\nexport interface InlineData {\n mediaType: string;\n data: string;\n}\n\nconst DATA_URL = /^data:([^;,]+);base64,(.*)$/s;\n\n// The files a model reads as text. A PDF is the one other file type the chat format carries.\nconst TEXT_FILE_TYPES = new Set(['text/plain', 'text/markdown', 'text/csv', 'application/json']);\n\nexport const PDF_TYPE = 'application/pdf';\n\nexport function contentParts(content: string | ContentPart[]): ContentPart[] {\n if (typeof content !== 'string') {\n return content;\n }\n return content ? [{ type: 'text', text: content }] : [];\n}\n\n// The text the visitor typed, without the attached files.\nexport function textOf(content: string | ContentPart[]): string {\n return contentParts(content)\n .map((part) => (part.type === 'text' ? part.text : ''))\n .join('');\n}\n\n// The media type and data of a base64 `data:` URL, or null for any other URL.\nexport function inlineData(url: string): InlineData | null {\n const match = DATA_URL.exec(url);\n return match ? { mediaType: match[1], data: match[2] } : null;\n}\n\nexport function dataUrl({ mediaType, data }: InlineData): string {\n return `data:${mediaType};base64,${data}`;\n}\n\nexport function isTextFile(mediaType: string): boolean {\n return TEXT_FILE_TYPES.has(mediaType);\n}\n\nexport function decodeBase64Text(data: string): string {\n const bytes = Uint8Array.from(atob(data), (character) => character.charCodeAt(0));\n return new TextDecoder().decode(bytes);\n}\n\nexport function encodeBase64Text(text: string): string {\n const bytes = new TextEncoder().encode(text);\n return btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join(''));\n}\n\n// The text of an attached text file, or null for a PDF.\nexport function fileText(part: FilePart): string | null {\n const inline = inlineData(part.url);\n return inline && isTextFile(inline.mediaType) ? decodeBase64Text(inline.data) : null;\n}\n\n// The text of each text file attached to the content.\nexport function attachedText(content: string | ContentPart[]): string[] {\n return contentParts(content).flatMap((part) => {\n const text = part.type === 'file' ? fileText(part) : null;\n return text === null ? [] : [text];\n });\n}\n"]}
package/dist/client.js CHANGED
@@ -53,6 +53,13 @@ function walletSession(wallet, link) {
53
53
  },
54
54
  };
55
55
  }
56
+ // The wallet's dictation for the account that answers, when the account has a transcription service.
57
+ function walletDictation(wallet, link) {
58
+ if (!wallet.dictate || !link.dictation || link.dictation === 'none') {
59
+ return null;
60
+ }
61
+ return { mode: link.dictation, start: wallet.dictate.bind(wallet) };
62
+ }
56
63
  export class AiConnect {
57
64
  // The visitor's browser, which names the install button.
58
65
  get browser() {
@@ -195,11 +202,14 @@ export class AiConnect {
195
202
  this.setState({ status: 'disconnected' });
196
203
  return;
197
204
  }
205
+ const dictation = walletDictation(wallet, link);
198
206
  this.setState({
199
207
  status: 'connected',
200
208
  providerName: link.providerName,
201
209
  model: link.model,
202
210
  session: walletSession(wallet, link),
211
+ ...(link.reads ? { reads: link.reads } : {}),
212
+ ...(dictation ? { dictation } : {}),
203
213
  });
204
214
  }
205
215
  setState(state) {