@lexion-rte/image-tools 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/LICENSE +21 -0
- package/README.md +51 -2
- package/dist/bytes.d.ts +24 -0
- package/dist/bytes.d.ts.map +1 -0
- package/dist/bytes.js +113 -0
- package/dist/bytes.js.map +1 -0
- package/dist/data-url.d.ts +41 -0
- package/dist/data-url.d.ts.map +1 -0
- package/dist/data-url.js +76 -0
- package/dist/data-url.js.map +1 -0
- package/dist/downscale.d.ts +26 -0
- package/dist/downscale.d.ts.map +1 -0
- package/dist/downscale.js +67 -0
- package/dist/downscale.js.map +1 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +33 -0
- package/dist/index.js.map +1 -0
- package/dist/rtf.d.ts +20 -0
- package/dist/rtf.d.ts.map +1 -0
- package/dist/rtf.js +146 -0
- package/dist/rtf.js.map +1 -0
- package/package.json +41 -3
- package/src/bytes.ts +146 -0
- package/src/data-url.ts +125 -0
- package/src/downscale.ts +125 -0
- package/src/index.ts +61 -0
- package/src/rtf.ts +182 -0
- package/tsconfig.json +9 -0
package/dist/rtf.js
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
import { sniffImageType } from "./bytes.js";
|
|
2
|
+
import { DEFAULT_MAX_IMAGE_BYTES } from "./data-url.js";
|
|
3
|
+
const twipsToPx = (twips, scale) => twips && twips > 0 ? Math.round(((twips * scale) / 100 / 15) * 100) / 100 : null;
|
|
4
|
+
const hexToBytes = (hex) => {
|
|
5
|
+
const bytes = new Uint8Array(hex.length >> 1);
|
|
6
|
+
for (let index = 0; index < bytes.length; index += 1) {
|
|
7
|
+
bytes[index] = parseInt(hex.slice(index * 2, index * 2 + 2), 16);
|
|
8
|
+
}
|
|
9
|
+
return bytes;
|
|
10
|
+
};
|
|
11
|
+
const isHexDigit = (code) => (code >= 48 && code <= 57) || (code >= 65 && code <= 70) || (code >= 97 && code <= 102);
|
|
12
|
+
/**
|
|
13
|
+
* PNG and JPEG pictures (`\pict` with `\pngblip` / `\jpegblip`) in RTF, such as Word puts on
|
|
14
|
+
* the clipboard, in document order. `\nonshppict` copies (duplicates for old readers) are
|
|
15
|
+
* skipped, and so are WMF/EMF/other formats, pictures whose bytes do not match their declared
|
|
16
|
+
* format, and pictures over `maxBytes`. Never throws on malformed RTF.
|
|
17
|
+
*/
|
|
18
|
+
export const extractRtfImages = (rtf, options = {}) => {
|
|
19
|
+
const maxBytes = options.maxBytes ?? DEFAULT_MAX_IMAGE_BYTES;
|
|
20
|
+
const images = [];
|
|
21
|
+
const stack = [{ skip: false, picture: null, ignoreNext: false }];
|
|
22
|
+
const current = () => stack[stack.length - 1];
|
|
23
|
+
const finish = (picture) => {
|
|
24
|
+
const hex = picture.hex.join("");
|
|
25
|
+
const bytes = picture.binary.length > 0
|
|
26
|
+
? new Uint8Array(picture.binary)
|
|
27
|
+
: hexToBytes(hex.length % 2 === 0 ? hex : hex.slice(0, -1));
|
|
28
|
+
if (!picture.type || bytes.length === 0 || bytes.length > maxBytes) {
|
|
29
|
+
return;
|
|
30
|
+
}
|
|
31
|
+
if (sniffImageType(bytes) !== picture.type) {
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
images.push({
|
|
35
|
+
bytes,
|
|
36
|
+
type: picture.type,
|
|
37
|
+
width: twipsToPx(picture.goalWidth, picture.scaleX),
|
|
38
|
+
height: twipsToPx(picture.goalHeight, picture.scaleY)
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
let index = 0;
|
|
42
|
+
while (index < rtf.length) {
|
|
43
|
+
const character = rtf[index];
|
|
44
|
+
if (character === "{") {
|
|
45
|
+
stack.push({ skip: current().skip, picture: null, ignoreNext: false });
|
|
46
|
+
index += 1;
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (character === "}") {
|
|
50
|
+
const group = stack.length > 1 ? stack.pop() : undefined;
|
|
51
|
+
if (group?.picture && !group.skip) {
|
|
52
|
+
finish(group.picture);
|
|
53
|
+
}
|
|
54
|
+
index += 1;
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
if (character === "\\") {
|
|
58
|
+
const word = /^\\([a-zA-Z]{1,32})(-?\d{1,10})? ?/.exec(rtf.slice(index, index + 45));
|
|
59
|
+
if (!word) {
|
|
60
|
+
// Control symbol: `\'hh` (a hex-escaped character), `\*`, `\\`, `\{`…
|
|
61
|
+
const next = rtf[index + 1];
|
|
62
|
+
if (next === "*") {
|
|
63
|
+
current().ignoreNext = true;
|
|
64
|
+
}
|
|
65
|
+
index += next === "'" ? 4 : 2;
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
index += word[0].length;
|
|
69
|
+
const name = word[1];
|
|
70
|
+
const parameter = word[2] === undefined ? null : Number(word[2]);
|
|
71
|
+
const group = current();
|
|
72
|
+
const ignored = group.ignoreNext;
|
|
73
|
+
group.ignoreNext = false;
|
|
74
|
+
if (name === "nonshppict") {
|
|
75
|
+
stack[stack.length - 1] = { ...group, skip: true };
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (name === "pict" && !group.skip) {
|
|
79
|
+
group.picture = {
|
|
80
|
+
type: null,
|
|
81
|
+
hex: [],
|
|
82
|
+
binary: [],
|
|
83
|
+
goalWidth: null,
|
|
84
|
+
goalHeight: null,
|
|
85
|
+
scaleX: 100,
|
|
86
|
+
scaleY: 100
|
|
87
|
+
};
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (ignored && !group.picture && name !== "shppict") {
|
|
91
|
+
// An unknown `{\*\destination …}`: its text is not content.
|
|
92
|
+
stack[stack.length - 1] = { ...group, skip: true };
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const picture = group.picture;
|
|
96
|
+
if (!picture) {
|
|
97
|
+
continue;
|
|
98
|
+
}
|
|
99
|
+
if (name === "pngblip") {
|
|
100
|
+
picture.type = "image/png";
|
|
101
|
+
}
|
|
102
|
+
else if (name === "jpegblip") {
|
|
103
|
+
picture.type = "image/jpeg";
|
|
104
|
+
}
|
|
105
|
+
else if (name === "picwgoal") {
|
|
106
|
+
picture.goalWidth = parameter;
|
|
107
|
+
}
|
|
108
|
+
else if (name === "pichgoal") {
|
|
109
|
+
picture.goalHeight = parameter;
|
|
110
|
+
}
|
|
111
|
+
else if (name === "picscalex" && parameter !== null && parameter > 0) {
|
|
112
|
+
picture.scaleX = parameter;
|
|
113
|
+
}
|
|
114
|
+
else if (name === "picscaley" && parameter !== null && parameter > 0) {
|
|
115
|
+
picture.scaleY = parameter;
|
|
116
|
+
}
|
|
117
|
+
else if (name === "bin" && parameter !== null && parameter > 0) {
|
|
118
|
+
for (let offset = 0; offset < parameter && index + offset < rtf.length; offset += 1) {
|
|
119
|
+
picture.binary.push(rtf.charCodeAt(index + offset) & 0xff);
|
|
120
|
+
}
|
|
121
|
+
index += parameter;
|
|
122
|
+
}
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
const picture = current().picture;
|
|
126
|
+
if (picture && !current().skip) {
|
|
127
|
+
// Hex data runs until the next control word or group.
|
|
128
|
+
let end = index;
|
|
129
|
+
while (end < rtf.length && rtf[end] !== "\\" && rtf[end] !== "{" && rtf[end] !== "}") {
|
|
130
|
+
end += 1;
|
|
131
|
+
}
|
|
132
|
+
let run = "";
|
|
133
|
+
for (let position = index; position < end; position += 1) {
|
|
134
|
+
if (isHexDigit(rtf.charCodeAt(position))) {
|
|
135
|
+
run += rtf[position];
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
picture.hex.push(run);
|
|
139
|
+
index = end;
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
index += 1;
|
|
143
|
+
}
|
|
144
|
+
return images;
|
|
145
|
+
};
|
|
146
|
+
//# sourceMappingURL=rtf.js.map
|
package/dist/rtf.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
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AAC,OAAO,EAAE,CAAC,IAAI,EAAE,CAAC;YAC/B,sDAAsD;YACtD,IAAI,GAAG,GAAG,KAAK,CAAC;YAChB,OAAO,GAAG,GAAG,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,GAAG,CAAC,KAAK,IAAI,IAAI,GAAG,CAAC,GAAG,CAAC,KAAK,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,KAAK,GAAG,EAAE,CAAC;gBACrF,GAAG,IAAI,CAAC,CAAC;YACX,CAAC;YACD,IAAI,GAAG,GAAG,EAAE,CAAC;YACb,KAAK,IAAI,QAAQ,GAAG,KAAK,EAAE,QAAQ,GAAG,GAAG,EAAE,QAAQ,IAAI,CAAC,EAAE,CAAC;gBACzD,IAAI,UAAU,CAAC,GAAG,CAAC,UAAU,CAAC,QAAQ,CAAC,CAAC,EAAE,CAAC;oBACzC,GAAG,IAAI,GAAG,CAAC,QAAQ,CAAC,CAAC;gBACvB,CAAC;YACH,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;YACtB,KAAK,GAAG,GAAG,CAAC;YACZ,SAAS;QACX,CAAC;QACD,KAAK,IAAI,CAAC,CAAC;IACb,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@lexion-rte/image-tools",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Safe base64 images for the Lexion editor: type sniffing, data URLs, size limits, downscaling, a base64 uploader and RTF image extraction.",
|
|
5
|
+
"private": false,
|
|
6
|
+
"type": "module",
|
|
7
|
+
"main": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"sideEffects": false,
|
|
16
|
+
"license": "MIT",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "https://github.com/dariusve/lexion.git",
|
|
20
|
+
"directory": "packages/image-tools"
|
|
21
|
+
},
|
|
22
|
+
"homepage": "https://github.com/dariusve/lexion/tree/main/packages/image-tools",
|
|
23
|
+
"bugs": {
|
|
24
|
+
"url": "https://github.com/dariusve/lexion/issues"
|
|
25
|
+
},
|
|
26
|
+
"keywords": [
|
|
27
|
+
"lexion",
|
|
28
|
+
"editor",
|
|
29
|
+
"rich-text",
|
|
30
|
+
"image",
|
|
31
|
+
"base64",
|
|
32
|
+
"rtf"
|
|
33
|
+
],
|
|
34
|
+
"engines": {
|
|
35
|
+
"node": ">=18"
|
|
36
|
+
},
|
|
37
|
+
"publishConfig": {
|
|
38
|
+
"access": "public"
|
|
39
|
+
},
|
|
40
|
+
"scripts": {
|
|
41
|
+
"build": "tsc -p tsconfig.json",
|
|
42
|
+
"lint": "eslint src"
|
|
43
|
+
}
|
|
6
44
|
}
|
package/src/bytes.ts
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
/** Image types this package recognizes. SVG is never one of them (it can carry script). */
|
|
2
|
+
export type ImageType =
|
|
3
|
+
"image/png" | "image/jpeg" | "image/gif" | "image/webp" | "image/avif" | "image/bmp";
|
|
4
|
+
|
|
5
|
+
export const imageTypes: readonly ImageType[] = [
|
|
6
|
+
"image/png",
|
|
7
|
+
"image/jpeg",
|
|
8
|
+
"image/gif",
|
|
9
|
+
"image/webp",
|
|
10
|
+
"image/avif",
|
|
11
|
+
"image/bmp"
|
|
12
|
+
];
|
|
13
|
+
|
|
14
|
+
const startsWith = (bytes: Uint8Array, signature: readonly number[], offset = 0): boolean =>
|
|
15
|
+
bytes.length >= offset + signature.length &&
|
|
16
|
+
signature.every((byte, index) => bytes[offset + index] === byte);
|
|
17
|
+
|
|
18
|
+
const ascii = (text: string): number[] => Array.from(text, (character) => character.charCodeAt(0));
|
|
19
|
+
|
|
20
|
+
const readUint32BE = (bytes: Uint8Array, offset: number): number =>
|
|
21
|
+
(bytes[offset] ?? 0) * 0x1000000 +
|
|
22
|
+
(((bytes[offset + 1] ?? 0) << 16) | ((bytes[offset + 2] ?? 0) << 8) | (bytes[offset + 3] ?? 0));
|
|
23
|
+
|
|
24
|
+
const readUint32LE = (bytes: Uint8Array, offset: number): number =>
|
|
25
|
+
(bytes[offset + 3] ?? 0) * 0x1000000 +
|
|
26
|
+
(((bytes[offset + 2] ?? 0) << 16) | ((bytes[offset + 1] ?? 0) << 8) | (bytes[offset] ?? 0));
|
|
27
|
+
|
|
28
|
+
/** An ISO BMFF `ftyp` box whose major or compatible brands include `avif` or `avis`. */
|
|
29
|
+
const isAvif = (bytes: Uint8Array): boolean => {
|
|
30
|
+
if (!startsWith(bytes, ascii("ftyp"), 4)) {
|
|
31
|
+
return false;
|
|
32
|
+
}
|
|
33
|
+
const boxSize = Math.min(readUint32BE(bytes, 0), bytes.length);
|
|
34
|
+
for (let offset = 8; offset + 4 <= boxSize; offset += 4) {
|
|
35
|
+
// Offset 12 is the minor version, not a brand.
|
|
36
|
+
if (
|
|
37
|
+
offset !== 12 &&
|
|
38
|
+
(startsWith(bytes, ascii("avif"), offset) || startsWith(bytes, ascii("avis"), offset))
|
|
39
|
+
) {
|
|
40
|
+
return true;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return false;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** "BM" followed by a known DIB header size, so text starting with "BM" is not a bitmap. */
|
|
47
|
+
const isBmp = (bytes: Uint8Array): boolean =>
|
|
48
|
+
startsWith(bytes, ascii("BM")) &&
|
|
49
|
+
[12, 40, 52, 56, 64, 108, 124].includes(readUint32LE(bytes, 14));
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The image type from the file's first bytes (magic numbers), or `null`. Never trusts a file
|
|
53
|
+
* name or a declared MIME type, and never returns SVG.
|
|
54
|
+
*/
|
|
55
|
+
export const sniffImageType = (bytes: Uint8Array): ImageType | null => {
|
|
56
|
+
if (startsWith(bytes, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) {
|
|
57
|
+
return "image/png";
|
|
58
|
+
}
|
|
59
|
+
if (startsWith(bytes, [0xff, 0xd8, 0xff])) {
|
|
60
|
+
return "image/jpeg";
|
|
61
|
+
}
|
|
62
|
+
if (startsWith(bytes, ascii("GIF87a")) || startsWith(bytes, ascii("GIF89a"))) {
|
|
63
|
+
return "image/gif";
|
|
64
|
+
}
|
|
65
|
+
if (startsWith(bytes, ascii("RIFF")) && startsWith(bytes, ascii("WEBP"), 8)) {
|
|
66
|
+
return "image/webp";
|
|
67
|
+
}
|
|
68
|
+
if (isAvif(bytes)) {
|
|
69
|
+
return "image/avif";
|
|
70
|
+
}
|
|
71
|
+
return isBmp(bytes) ? "image/bmp" : null;
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
interface NodeBuffer {
|
|
75
|
+
from(bytes: Uint8Array): { toString(encoding: "base64"): string };
|
|
76
|
+
from(text: string, encoding: "base64"): Uint8Array;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const nodeBuffer = (): NodeBuffer | null =>
|
|
80
|
+
((globalThis as { Buffer?: NodeBuffer }).Buffer ?? null) as NodeBuffer | null;
|
|
81
|
+
|
|
82
|
+
/** Bytes per `String.fromCharCode` call: well below engines' argument limits. */
|
|
83
|
+
const chunkSize = 0x8000;
|
|
84
|
+
|
|
85
|
+
/** Base64 of `bytes`, without a call-stack overflow on large images (uses `Buffer` in Node). */
|
|
86
|
+
export const bytesToBase64 = (bytes: Uint8Array): string => {
|
|
87
|
+
const buffer = nodeBuffer();
|
|
88
|
+
if (buffer) {
|
|
89
|
+
return buffer.from(bytes).toString("base64");
|
|
90
|
+
}
|
|
91
|
+
let binary = "";
|
|
92
|
+
for (let offset = 0; offset < bytes.length; offset += chunkSize) {
|
|
93
|
+
binary += String.fromCharCode(...bytes.subarray(offset, offset + chunkSize));
|
|
94
|
+
}
|
|
95
|
+
return btoa(binary);
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const base64Pattern = /^[A-Za-z0-9+/]*={0,2}$/;
|
|
99
|
+
|
|
100
|
+
/** Bytes of a base64 string (whitespace ignored). Throws on anything that is not base64. */
|
|
101
|
+
export const base64ToBytes = (base64: string): Uint8Array => {
|
|
102
|
+
const compact = base64.replace(/\s+/g, "");
|
|
103
|
+
if (!base64Pattern.test(compact) || compact.length % 4 === 1) {
|
|
104
|
+
throw new ImageToolsError("invalid-data", "Not valid base64");
|
|
105
|
+
}
|
|
106
|
+
const buffer = nodeBuffer();
|
|
107
|
+
if (buffer) {
|
|
108
|
+
return new Uint8Array(buffer.from(compact, "base64"));
|
|
109
|
+
}
|
|
110
|
+
const binary = atob(compact);
|
|
111
|
+
const bytes = new Uint8Array(binary.length);
|
|
112
|
+
for (let index = 0; index < binary.length; index += 1) {
|
|
113
|
+
bytes[index] = binary.charCodeAt(index);
|
|
114
|
+
}
|
|
115
|
+
return bytes;
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The bytes of a `Blob`. Uses `blob.arrayBuffer()`, or `FileReader` where that is missing
|
|
120
|
+
* (older WebKit, jsdom).
|
|
121
|
+
*/
|
|
122
|
+
export const blobToBytes = async (blob: Blob): Promise<Uint8Array> => {
|
|
123
|
+
if (typeof blob.arrayBuffer === "function") {
|
|
124
|
+
return new Uint8Array(await blob.arrayBuffer());
|
|
125
|
+
}
|
|
126
|
+
return new Promise((resolve, reject) => {
|
|
127
|
+
const reader = new FileReader();
|
|
128
|
+
reader.onload = () => resolve(new Uint8Array(reader.result as ArrayBuffer));
|
|
129
|
+
reader.onerror = () => reject(new ImageToolsError("invalid-data", "Could not read the file"));
|
|
130
|
+
reader.readAsArrayBuffer(blob);
|
|
131
|
+
});
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
export type ImageToolsErrorCode =
|
|
135
|
+
"empty" | "too-large" | "unsupported-type" | "type-mismatch" | "invalid-data" | "unavailable";
|
|
136
|
+
|
|
137
|
+
/** Why an image was rejected; `code` is stable, `message` is for people. */
|
|
138
|
+
export class ImageToolsError extends Error {
|
|
139
|
+
public readonly code: ImageToolsErrorCode;
|
|
140
|
+
|
|
141
|
+
public constructor(code: ImageToolsErrorCode, message: string) {
|
|
142
|
+
super(message);
|
|
143
|
+
this.name = "ImageToolsError";
|
|
144
|
+
this.code = code;
|
|
145
|
+
}
|
|
146
|
+
}
|
package/src/data-url.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import {
|
|
2
|
+
base64ToBytes,
|
|
3
|
+
blobToBytes,
|
|
4
|
+
bytesToBase64,
|
|
5
|
+
ImageToolsError,
|
|
6
|
+
imageTypes,
|
|
7
|
+
sniffImageType,
|
|
8
|
+
type ImageType
|
|
9
|
+
} from "./bytes.js";
|
|
10
|
+
|
|
11
|
+
/** Default `maxBytes`: 5 MB per image. */
|
|
12
|
+
export const DEFAULT_MAX_IMAGE_BYTES = 5 * 1024 * 1024;
|
|
13
|
+
|
|
14
|
+
export type ImageInput = Blob | ArrayBuffer | Uint8Array;
|
|
15
|
+
|
|
16
|
+
export interface ToDataURLOptions {
|
|
17
|
+
/** Largest image accepted, in bytes. Default `DEFAULT_MAX_IMAGE_BYTES` (5 MB). */
|
|
18
|
+
readonly maxBytes?: number;
|
|
19
|
+
/** Types accepted. Default every `ImageType`. */
|
|
20
|
+
readonly allowedTypes?: readonly ImageType[];
|
|
21
|
+
/**
|
|
22
|
+
* The MIME type the bytes claim to be (a `Blob`'s `type` is used when this is left out).
|
|
23
|
+
* When set to an image type, it must match the sniffed type.
|
|
24
|
+
*/
|
|
25
|
+
readonly declaredType?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const readBytes = async (input: ImageInput): Promise<Uint8Array> => {
|
|
29
|
+
if (input instanceof Uint8Array) {
|
|
30
|
+
return input;
|
|
31
|
+
}
|
|
32
|
+
if (input instanceof ArrayBuffer) {
|
|
33
|
+
return new Uint8Array(input);
|
|
34
|
+
}
|
|
35
|
+
return blobToBytes(input);
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const normalizeType = (type: string): string => {
|
|
39
|
+
const lower = type.split(";")[0]?.trim().toLowerCase() ?? "";
|
|
40
|
+
return lower === "image/jpg" || lower === "image/pjpeg" ? "image/jpeg" : lower;
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Checks bytes and returns their sniffed type. Rejects empty or oversized input, unknown
|
|
45
|
+
* types (SVG and HTML included, whatever they are called), types not in `allowedTypes`, and
|
|
46
|
+
* a declared image type that differs from the sniffed one.
|
|
47
|
+
*/
|
|
48
|
+
export const checkImageBytes = (
|
|
49
|
+
bytes: Uint8Array,
|
|
50
|
+
options: Omit<ToDataURLOptions, "declaredType"> & {
|
|
51
|
+
readonly declaredType?: string | undefined;
|
|
52
|
+
} = {}
|
|
53
|
+
): ImageType => {
|
|
54
|
+
const maxBytes = options.maxBytes ?? DEFAULT_MAX_IMAGE_BYTES;
|
|
55
|
+
if (bytes.length === 0) {
|
|
56
|
+
throw new ImageToolsError("empty", "The image is empty");
|
|
57
|
+
}
|
|
58
|
+
if (bytes.length > maxBytes) {
|
|
59
|
+
throw new ImageToolsError(
|
|
60
|
+
"too-large",
|
|
61
|
+
`The image is ${bytes.length} bytes; the limit is ${maxBytes}`
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
const type = sniffImageType(bytes);
|
|
65
|
+
if (!type || !(options.allowedTypes ?? imageTypes).includes(type)) {
|
|
66
|
+
throw new ImageToolsError(
|
|
67
|
+
"unsupported-type",
|
|
68
|
+
type ? `Images of type ${type} are not allowed` : "Not a supported image"
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
const declared = normalizeType(options.declaredType ?? "");
|
|
72
|
+
if (declared.startsWith("image/") && declared !== type) {
|
|
73
|
+
throw new ImageToolsError("type-mismatch", `The image claims to be ${declared} but is ${type}`);
|
|
74
|
+
}
|
|
75
|
+
return type;
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* A `data:image/…;base64,…` URL for an image (`Blob`, `File`, `ArrayBuffer` or `Uint8Array`),
|
|
80
|
+
* after the checks of `checkImageBytes`. The type in the URL is always the sniffed one.
|
|
81
|
+
* Throws an `ImageToolsError`.
|
|
82
|
+
*/
|
|
83
|
+
export const toDataURL = async (
|
|
84
|
+
input: ImageInput,
|
|
85
|
+
options: ToDataURLOptions = {}
|
|
86
|
+
): Promise<string> => {
|
|
87
|
+
const bytes = await readBytes(input);
|
|
88
|
+
const type = checkImageBytes(bytes, {
|
|
89
|
+
...options,
|
|
90
|
+
declaredType: options.declaredType ?? (input instanceof Blob ? input.type : undefined)
|
|
91
|
+
});
|
|
92
|
+
return `data:${type};base64,${bytesToBase64(bytes)}`;
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const dataURLPattern = /^data:([^;,]+)((?:;[^;,]+)*?);base64,(.*)$/is;
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The bytes and sniffed type of a base64 image `data:` URL. The URL's type must be an image
|
|
99
|
+
* type matching the bytes (same rules as `toDataURL`, including `maxBytes`). Throws an
|
|
100
|
+
* `ImageToolsError`.
|
|
101
|
+
*/
|
|
102
|
+
export const dataURLToBytes = (
|
|
103
|
+
url: string,
|
|
104
|
+
options: Omit<ToDataURLOptions, "declaredType"> = {}
|
|
105
|
+
): { readonly bytes: Uint8Array; readonly type: ImageType } => {
|
|
106
|
+
const match = dataURLPattern.exec(url.trim());
|
|
107
|
+
if (!match?.[1] || match[3] === undefined) {
|
|
108
|
+
throw new ImageToolsError("invalid-data", "Not a base64 data: URL");
|
|
109
|
+
}
|
|
110
|
+
const declared = normalizeType(match[1]);
|
|
111
|
+
if (!declared.startsWith("image/")) {
|
|
112
|
+
throw new ImageToolsError("unsupported-type", `Not an image: ${declared}`);
|
|
113
|
+
}
|
|
114
|
+
const bytes = base64ToBytes(match[3]);
|
|
115
|
+
return { bytes, type: checkImageBytes(bytes, { ...options, declaredType: declared }) };
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
/** A `Blob` from a base64 image `data:` URL (for example to send it to `upload`). */
|
|
119
|
+
export const dataURLToBlob = (
|
|
120
|
+
url: string,
|
|
121
|
+
options: Omit<ToDataURLOptions, "declaredType"> = {}
|
|
122
|
+
): Blob => {
|
|
123
|
+
const { bytes, type } = dataURLToBytes(url, options);
|
|
124
|
+
return new Blob([bytes as BlobPart], { type });
|
|
125
|
+
};
|
package/src/downscale.ts
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { blobToBytes, ImageToolsError, sniffImageType, type ImageType } from "./bytes.js";
|
|
2
|
+
|
|
3
|
+
export interface DownscaleOptions {
|
|
4
|
+
/** Longest width in px. Default no limit. */
|
|
5
|
+
readonly maxWidth?: number;
|
|
6
|
+
/** Longest height in px. Default no limit. */
|
|
7
|
+
readonly maxHeight?: number;
|
|
8
|
+
/**
|
|
9
|
+
* Output type. Default: JPEG stays JPEG, WebP stays WebP, everything else becomes PNG (so
|
|
10
|
+
* screenshots stay sharp).
|
|
11
|
+
*/
|
|
12
|
+
readonly type?: "image/png" | "image/jpeg" | "image/webp";
|
|
13
|
+
/** Quality for JPEG and WebP, 0–1. Default `0.85`. */
|
|
14
|
+
readonly quality?: number;
|
|
15
|
+
/**
|
|
16
|
+
* Re-encode even when the image already fits, to strip metadata such as EXIF GPS
|
|
17
|
+
* positions. Default `false` (an image that fits is returned unchanged).
|
|
18
|
+
*/
|
|
19
|
+
readonly reencode?: boolean;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface Canvas2D {
|
|
23
|
+
drawImage(image: unknown, x: number, y: number, width: number, height: number): void;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface AnyCanvas {
|
|
27
|
+
width: number;
|
|
28
|
+
height: number;
|
|
29
|
+
getContext(type: "2d"): Canvas2D | null;
|
|
30
|
+
convertToBlob?: (options: { type: string; quality: number }) => Promise<Blob>;
|
|
31
|
+
toBlob?: (callback: (blob: Blob | null) => void, type: string, quality: number) => void;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface Bitmap {
|
|
35
|
+
readonly width: number;
|
|
36
|
+
readonly height: number;
|
|
37
|
+
close?: () => void;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const createCanvas = (width: number, height: number): AnyCanvas => {
|
|
41
|
+
const globals = globalThis as {
|
|
42
|
+
OffscreenCanvas?: new (width: number, height: number) => AnyCanvas;
|
|
43
|
+
document?: { createElement(tag: "canvas"): AnyCanvas };
|
|
44
|
+
};
|
|
45
|
+
if (globals.OffscreenCanvas) {
|
|
46
|
+
return new globals.OffscreenCanvas(width, height);
|
|
47
|
+
}
|
|
48
|
+
if (globals.document) {
|
|
49
|
+
const canvas = globals.document.createElement("canvas");
|
|
50
|
+
canvas.width = width;
|
|
51
|
+
canvas.height = height;
|
|
52
|
+
return canvas;
|
|
53
|
+
}
|
|
54
|
+
throw new ImageToolsError("unavailable", "No canvas is available to resize images");
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const canvasToBlob = (canvas: AnyCanvas, type: string, quality: number): Promise<Blob> => {
|
|
58
|
+
if (canvas.convertToBlob) {
|
|
59
|
+
return canvas.convertToBlob({ type, quality });
|
|
60
|
+
}
|
|
61
|
+
return new Promise((resolve, reject) => {
|
|
62
|
+
if (!canvas.toBlob) {
|
|
63
|
+
reject(new ImageToolsError("unavailable", "The canvas cannot encode images"));
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
canvas.toBlob(
|
|
67
|
+
(blob) =>
|
|
68
|
+
blob
|
|
69
|
+
? resolve(blob)
|
|
70
|
+
: reject(new ImageToolsError("invalid-data", "Could not encode the image")),
|
|
71
|
+
type,
|
|
72
|
+
quality
|
|
73
|
+
);
|
|
74
|
+
});
|
|
75
|
+
};
|
|
76
|
+
|
|
77
|
+
const outputType = (input: ImageType | null, wanted: DownscaleOptions["type"]): string =>
|
|
78
|
+
wanted ?? (input === "image/jpeg" || input === "image/webp" ? input : "image/png");
|
|
79
|
+
|
|
80
|
+
const limit = (value: number | undefined): number =>
|
|
81
|
+
typeof value === "number" && value > 0 ? value : Number.POSITIVE_INFINITY;
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Resizes an image to fit `maxWidth` × `maxHeight` (keeping its aspect ratio) and re-encodes
|
|
85
|
+
* it with `createImageBitmap` and a canvas. Browsers and Electron only. An image that already
|
|
86
|
+
* fits is returned as is, unless `reencode` is set. Throws an `ImageToolsError` with code
|
|
87
|
+
* `unavailable` where there is no `createImageBitmap` or canvas.
|
|
88
|
+
*/
|
|
89
|
+
export const downscaleImage = async (blob: Blob, options: DownscaleOptions = {}): Promise<Blob> => {
|
|
90
|
+
const decode = (globalThis as { createImageBitmap?: (blob: Blob) => Promise<Bitmap> })
|
|
91
|
+
.createImageBitmap;
|
|
92
|
+
if (!decode) {
|
|
93
|
+
throw new ImageToolsError("unavailable", "createImageBitmap is not available");
|
|
94
|
+
}
|
|
95
|
+
const inputType = sniffImageType(await blobToBytes(blob.slice(0, 64)));
|
|
96
|
+
if (!inputType) {
|
|
97
|
+
throw new ImageToolsError("unsupported-type", "Not a supported image");
|
|
98
|
+
}
|
|
99
|
+
const bitmap = await decode(blob);
|
|
100
|
+
try {
|
|
101
|
+
const scale = Math.min(
|
|
102
|
+
1,
|
|
103
|
+
limit(options.maxWidth) / bitmap.width,
|
|
104
|
+
limit(options.maxHeight) / bitmap.height
|
|
105
|
+
);
|
|
106
|
+
if (scale === 1 && !options.reencode) {
|
|
107
|
+
return blob;
|
|
108
|
+
}
|
|
109
|
+
const width = Math.max(1, Math.round(bitmap.width * scale));
|
|
110
|
+
const height = Math.max(1, Math.round(bitmap.height * scale));
|
|
111
|
+
const canvas = createCanvas(width, height);
|
|
112
|
+
const context = canvas.getContext("2d");
|
|
113
|
+
if (!context) {
|
|
114
|
+
throw new ImageToolsError("unavailable", "No 2D canvas context");
|
|
115
|
+
}
|
|
116
|
+
context.drawImage(bitmap, 0, 0, width, height);
|
|
117
|
+
return await canvasToBlob(
|
|
118
|
+
canvas,
|
|
119
|
+
outputType(inputType, options.type),
|
|
120
|
+
Math.min(1, Math.max(0, options.quality ?? 0.85))
|
|
121
|
+
);
|
|
122
|
+
} finally {
|
|
123
|
+
bitmap.close?.();
|
|
124
|
+
}
|
|
125
|
+
};
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { blobToBytes } from "./bytes.js";
|
|
2
|
+
import { checkImageBytes, toDataURL, type ToDataURLOptions } from "./data-url.js";
|
|
3
|
+
import { downscaleImage, type DownscaleOptions } from "./downscale.js";
|
|
4
|
+
|
|
5
|
+
export {
|
|
6
|
+
base64ToBytes,
|
|
7
|
+
blobToBytes,
|
|
8
|
+
bytesToBase64,
|
|
9
|
+
ImageToolsError,
|
|
10
|
+
imageTypes,
|
|
11
|
+
sniffImageType,
|
|
12
|
+
type ImageToolsErrorCode,
|
|
13
|
+
type ImageType
|
|
14
|
+
} from "./bytes.js";
|
|
15
|
+
export {
|
|
16
|
+
checkImageBytes,
|
|
17
|
+
DEFAULT_MAX_IMAGE_BYTES,
|
|
18
|
+
dataURLToBlob,
|
|
19
|
+
dataURLToBytes,
|
|
20
|
+
toDataURL,
|
|
21
|
+
type ImageInput,
|
|
22
|
+
type ToDataURLOptions
|
|
23
|
+
} from "./data-url.js";
|
|
24
|
+
export { downscaleImage, type DownscaleOptions } from "./downscale.js";
|
|
25
|
+
export { extractRtfImages, type ExtractRtfImagesOptions, type RtfImage } from "./rtf.js";
|
|
26
|
+
|
|
27
|
+
export interface Base64UploaderOptions extends Omit<ToDataURLOptions, "declaredType"> {
|
|
28
|
+
/**
|
|
29
|
+
* Resize (and re-encode) before encoding; `false` (default) keeps the file as it is.
|
|
30
|
+
* Browsers and Electron only. The size limit applies to the resized image.
|
|
31
|
+
*/
|
|
32
|
+
readonly downscale?: DownscaleOptions | false;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* An `upload` function for the starter kit's `Image` that turns pasted, dropped or picked
|
|
37
|
+
* images into base64 `data:` URLs, for apps that store images inside the document:
|
|
38
|
+
*
|
|
39
|
+
* ```ts
|
|
40
|
+
* Image.configure({ allowBase64: true, upload: createBase64Uploader({ maxBytes: 5_000_000 }) })
|
|
41
|
+
* ```
|
|
42
|
+
*
|
|
43
|
+
* Rejects (so the editor drops the placeholder) with an `ImageToolsError` for files that are
|
|
44
|
+
* not supported images, claim a different type, or are too large.
|
|
45
|
+
*/
|
|
46
|
+
export const createBase64Uploader =
|
|
47
|
+
(options: Base64UploaderOptions = {}) =>
|
|
48
|
+
async (file: Blob): Promise<string> => {
|
|
49
|
+
const { downscale = false, ...limits } = options;
|
|
50
|
+
if (!downscale) {
|
|
51
|
+
return toDataURL(file, limits);
|
|
52
|
+
}
|
|
53
|
+
// Check the original first (type only: the limit applies to the result), so a renamed
|
|
54
|
+
// SVG or HTML file never reaches the image decoder.
|
|
55
|
+
checkImageBytes(await blobToBytes(file), {
|
|
56
|
+
...limits,
|
|
57
|
+
maxBytes: Number.POSITIVE_INFINITY,
|
|
58
|
+
declaredType: file.type
|
|
59
|
+
});
|
|
60
|
+
return toDataURL(await downscaleImage(file, downscale), { ...limits, declaredType: "" });
|
|
61
|
+
};
|