@zapwebp/core 1.1.1 → 1.1.2
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/README.md +79 -51
- package/agent.json +180 -0
- package/package.json +8 -2
- package/src/cache.js +145 -0
- package/src/engine/decode.js +60 -0
- package/src/engine/encode.js +106 -0
- package/src/engine/pipeline.js +116 -0
- package/src/engine/transform.js +37 -0
- package/src/errors/index.js +34 -0
- package/src/formats/avif.js +1 -1
- package/src/formats/gif.js +8 -2
- package/src/formats/index.js +5 -0
- package/src/formats/jpeg.js +14 -3
- package/src/formats/png.js +1 -1
- package/src/formats/svg.js +76 -14
- package/src/formats/tiff.js +8 -2
- package/src/formats/webp.js +1 -1
- package/src/index.d.ts +286 -9
- package/src/index.js +951 -80
- package/src/journal/index.js +73 -0
- package/src/metadata/c2pa.js +3 -10
- package/src/metadata/chunk-stripper.js +235 -0
- package/src/metadata/exif.js +3 -11
- package/src/metadata/icc.js +3 -10
- package/src/metadata/png-text.js +3 -10
- package/src/metadata/registry.js +25 -2
- package/src/metadata/xmp.js +3 -16
- package/src/parallel.js +134 -0
- package/src/policy.js +95 -6
- package/src/registry/compression.js +84 -0
- package/src/registry/formats.js +30 -0
- package/src/registry/metadata.js +28 -0
- package/src/registry/transforms.js +76 -0
- package/src/report.js +404 -0
- package/src/safety/path.js +52 -0
- package/src/safety/runtime.js +66 -0
- package/src/safety/ssrf.js +9 -0
- package/src/safety/svg.js +66 -0
- package/src/signals.js +683 -0
- package/src/smart.js +351 -0
- package/src/team-policy.js +319 -0
- package/src/testing.d.ts +18 -0
- package/src/testing.js +114 -0
- package/src/tools.js +240 -0
- package/src/types.ts +68 -0
package/src/signals.js
ADDED
|
@@ -0,0 +1,683 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Zapwebp Smart Layer: Content Signals, Suggestions, and Custom Metadata
|
|
5
|
+
*
|
|
6
|
+
* Provides deterministic, dependency-free content signals and heuristics
|
|
7
|
+
* to power developer-provided AI and vision model pipelines.
|
|
8
|
+
*
|
|
9
|
+
* THE RULE: Zapwebp never imports an AI library. It never calls an AI API.
|
|
10
|
+
* It provides structured signals and hooks; the developer brings the model.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
// IEEE 802.3 CRC32 Table for standard PNG chunk generation
|
|
14
|
+
const CRC_TABLE = new Uint32Array(256);
|
|
15
|
+
for (let i = 0; i < 256; i++) {
|
|
16
|
+
let c = i;
|
|
17
|
+
for (let k = 0; k < 8; k++) {
|
|
18
|
+
c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
|
|
19
|
+
}
|
|
20
|
+
CRC_TABLE[i] = c >>> 0;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Calculates 32-bit cyclic redundancy check.
|
|
25
|
+
* @param {Buffer} buf
|
|
26
|
+
* @returns {number}
|
|
27
|
+
*/
|
|
28
|
+
function crc32(buf) {
|
|
29
|
+
let crc = 0xffffffff;
|
|
30
|
+
for (let i = 0; i < buf.length; i++) {
|
|
31
|
+
crc = CRC_TABLE[(crc ^ buf[i]) & 0xff] ^ (crc >>> 8);
|
|
32
|
+
}
|
|
33
|
+
return (crc ^ 0xffffffff) >>> 0;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Analyzes raw RGBA pixel thumbnail to compute mathematical content signals.
|
|
38
|
+
*
|
|
39
|
+
* @param {Buffer|Uint8Array} rawData - Raw 8-bit RGBA pixel buffer
|
|
40
|
+
* @param {number} width - Thumbnail width
|
|
41
|
+
* @param {number} height - Thumbnail height
|
|
42
|
+
* @param {object} [context] - Contextual format and metadata hints
|
|
43
|
+
* @returns {{ content: object, palette: object }}
|
|
44
|
+
*/
|
|
45
|
+
function extractSignalsFromRgba(rawData, width, height, context = {}) {
|
|
46
|
+
const totalPixels = width * height;
|
|
47
|
+
if (!totalPixels || !rawData || rawData.length < totalPixels * 4) {
|
|
48
|
+
return {
|
|
49
|
+
content: {
|
|
50
|
+
edgeDensity: 0,
|
|
51
|
+
colorCount: 1,
|
|
52
|
+
sharpness: 0,
|
|
53
|
+
luminanceMean: 0.5,
|
|
54
|
+
luminanceVariance: 0,
|
|
55
|
+
transparencyCoverage: 0,
|
|
56
|
+
estimatedType: 'photo',
|
|
57
|
+
estimatedTypeConfidence: 0.5,
|
|
58
|
+
},
|
|
59
|
+
palette: {
|
|
60
|
+
dominant: '#000000',
|
|
61
|
+
colors: [{ hex: '#000000', percentage: 1 }],
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const lum = new Float32Array(totalPixels);
|
|
67
|
+
let alphaTransparentCount = 0;
|
|
68
|
+
let sumL = 0;
|
|
69
|
+
const colorMap = new Map();
|
|
70
|
+
|
|
71
|
+
for (let i = 0; i < totalPixels; i++) {
|
|
72
|
+
const offset = i * 4;
|
|
73
|
+
const r = rawData[offset];
|
|
74
|
+
const g = rawData[offset + 1];
|
|
75
|
+
const b = rawData[offset + 2];
|
|
76
|
+
const a = rawData[offset + 3];
|
|
77
|
+
|
|
78
|
+
if (a < 255) {
|
|
79
|
+
alphaTransparentCount++;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Standard Rec. 709 Luminance
|
|
83
|
+
const l = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
|
|
84
|
+
lum[i] = l;
|
|
85
|
+
sumL += l;
|
|
86
|
+
|
|
87
|
+
// Quantize RGB to 15-bit (5 bits per channel: 32x32x32 buckets)
|
|
88
|
+
// Ignore fully transparent background pixels (alpha < 16)
|
|
89
|
+
if (a >= 16) {
|
|
90
|
+
const key = ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3);
|
|
91
|
+
colorMap.set(key, (colorMap.get(key) || 0) + 1);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// 1. Transparency coverage
|
|
96
|
+
const transparencyCoverage = Number((alphaTransparentCount / totalPixels).toFixed(4));
|
|
97
|
+
|
|
98
|
+
// 2. Luminance Mean & Variance (Contrast)
|
|
99
|
+
const meanL = sumL / totalPixels;
|
|
100
|
+
let sumSqDiff = 0;
|
|
101
|
+
for (let i = 0; i < totalPixels; i++) {
|
|
102
|
+
const diff = lum[i] - meanL;
|
|
103
|
+
sumSqDiff += diff * diff;
|
|
104
|
+
}
|
|
105
|
+
const varL = sumSqDiff / totalPixels;
|
|
106
|
+
const luminanceMean = Number(meanL.toFixed(4));
|
|
107
|
+
const luminanceVariance = Number(varL.toFixed(4));
|
|
108
|
+
|
|
109
|
+
// 3. Laplacian Sharpness & Edge Density
|
|
110
|
+
let edgeCount = 0;
|
|
111
|
+
let lapSum = 0;
|
|
112
|
+
let lapSumSq = 0;
|
|
113
|
+
let innerPixels = 0;
|
|
114
|
+
|
|
115
|
+
for (let y = 1; y < height - 1; y++) {
|
|
116
|
+
const row = y * width;
|
|
117
|
+
for (let x = 1; x < width - 1; x++) {
|
|
118
|
+
const center = row + x;
|
|
119
|
+
const lap = lum[center - width] + lum[center + width] + lum[center - 1] + lum[center + 1] - 4 * lum[center];
|
|
120
|
+
lapSum += lap;
|
|
121
|
+
lapSumSq += lap * lap;
|
|
122
|
+
innerPixels++;
|
|
123
|
+
|
|
124
|
+
if (Math.abs(lap) > 0.08) {
|
|
125
|
+
edgeCount++;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const lapMean = innerPixels > 0 ? lapSum / innerPixels : 0;
|
|
131
|
+
const lapVar = innerPixels > 0 ? (lapSumSq / innerPixels) - (lapMean * lapMean) : 0;
|
|
132
|
+
const sharpness = Number(Math.min(1, Math.max(0, Math.sqrt(Math.max(0, lapVar)) * 4)).toFixed(4));
|
|
133
|
+
const edgeDensity = Number((innerPixels > 0 ? edgeCount / innerPixels : 0).toFixed(4));
|
|
134
|
+
|
|
135
|
+
// 4. Color count & Palette
|
|
136
|
+
const colorCount = colorMap.size;
|
|
137
|
+
const sortedColors = Array.from(colorMap.entries()).sort((a, b) => b[1] - a[1]);
|
|
138
|
+
const totalColoredPixels = Array.from(colorMap.values()).reduce((a, b) => a + b, 0);
|
|
139
|
+
|
|
140
|
+
function binToHex(key) {
|
|
141
|
+
const r5 = (key >> 10) & 0x1f;
|
|
142
|
+
const g5 = (key >> 5) & 0x1f;
|
|
143
|
+
const b5 = key & 0x1f;
|
|
144
|
+
const r8 = Math.round((r5 * 255) / 31);
|
|
145
|
+
const g8 = Math.round((g5 * 255) / 31);
|
|
146
|
+
const b8 = Math.round((b5 * 255) / 31);
|
|
147
|
+
return `#${r8.toString(16).padStart(2, '0')}${g8.toString(16).padStart(2, '0')}${b8.toString(16).padStart(2, '0')}`;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
const dominant = sortedColors.length > 0 ? binToHex(sortedColors[0][0]) : '#000000';
|
|
151
|
+
const colors = sortedColors.slice(0, 6).map(([key, count]) => ({
|
|
152
|
+
hex: binToHex(key),
|
|
153
|
+
percentage: Number((count / (totalColoredPixels || 1)).toFixed(4)),
|
|
154
|
+
}));
|
|
155
|
+
|
|
156
|
+
// 5. Estimated Type Heuristics
|
|
157
|
+
let estimatedType = 'photo';
|
|
158
|
+
let estimatedTypeConfidence = 0.8;
|
|
159
|
+
const format = String(context.format || '').toLowerCase();
|
|
160
|
+
const rawString = context.rawString || '';
|
|
161
|
+
const origWidth = context.width || width;
|
|
162
|
+
const origHeight = context.height || height;
|
|
163
|
+
|
|
164
|
+
if (format === 'svg') {
|
|
165
|
+
if (rawString && /<(?:text|tspan)/i.test(rawString)) {
|
|
166
|
+
estimatedType = 'text';
|
|
167
|
+
estimatedTypeConfidence = 0.92;
|
|
168
|
+
} else if (transparencyCoverage > 0.05) {
|
|
169
|
+
estimatedType = (origWidth <= 256 && origHeight <= 256) ? 'icon' : 'logo';
|
|
170
|
+
estimatedTypeConfidence = 0.9;
|
|
171
|
+
} else {
|
|
172
|
+
estimatedType = 'diagram';
|
|
173
|
+
estimatedTypeConfidence = 0.85;
|
|
174
|
+
}
|
|
175
|
+
} else if (transparencyCoverage > 0.15 && colorCount <= 256) {
|
|
176
|
+
estimatedType = (origWidth <= 256 && origHeight <= 256) ? 'icon' : 'logo';
|
|
177
|
+
estimatedTypeConfidence = 0.88;
|
|
178
|
+
} else if (colorCount < 80 && edgeDensity > 0.04 && luminanceVariance > 0.03) {
|
|
179
|
+
estimatedType = 'text';
|
|
180
|
+
estimatedTypeConfidence = 0.85;
|
|
181
|
+
} else if (colorCount > 500 && luminanceVariance > 0.012 && transparencyCoverage < 0.05) {
|
|
182
|
+
estimatedType = 'photo';
|
|
183
|
+
estimatedTypeConfidence = 0.92;
|
|
184
|
+
} else if (edgeDensity > 0.12 && colorCount <= 750) {
|
|
185
|
+
estimatedType = 'screenshot';
|
|
186
|
+
estimatedTypeConfidence = 0.8;
|
|
187
|
+
} else if (colorCount <= 200) {
|
|
188
|
+
estimatedType = 'diagram';
|
|
189
|
+
estimatedTypeConfidence = 0.76;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
return {
|
|
193
|
+
content: {
|
|
194
|
+
edgeDensity,
|
|
195
|
+
colorCount,
|
|
196
|
+
sharpness,
|
|
197
|
+
luminanceMean,
|
|
198
|
+
luminanceVariance,
|
|
199
|
+
transparencyCoverage,
|
|
200
|
+
estimatedType,
|
|
201
|
+
estimatedTypeConfidence,
|
|
202
|
+
},
|
|
203
|
+
palette: {
|
|
204
|
+
dominant,
|
|
205
|
+
colors: colors.length ? colors : [{ hex: dominant, percentage: 1 }],
|
|
206
|
+
},
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Computes content signals and dominant color palette for any image input.
|
|
212
|
+
*
|
|
213
|
+
* @param {Buffer} data
|
|
214
|
+
* @param {object} meta - Basic inspected format and dimensions
|
|
215
|
+
* @param {Function} getSharp
|
|
216
|
+
* @returns {Promise<{ content: object, palette: object }>}
|
|
217
|
+
*/
|
|
218
|
+
async function computeContentSignals(data, meta, getSharp) {
|
|
219
|
+
const format = (meta.format || '').toLowerCase();
|
|
220
|
+
let rawString = '';
|
|
221
|
+
if (format === 'svg') {
|
|
222
|
+
rawString = data.toString('utf8');
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
try {
|
|
226
|
+
const sharp = getSharp();
|
|
227
|
+
const thumbnail = await sharp(data, { failOn: 'none', limitInputPixels: 16777216 })
|
|
228
|
+
.resize(128, 128, { fit: 'inside' })
|
|
229
|
+
.ensureAlpha()
|
|
230
|
+
.raw()
|
|
231
|
+
.toBuffer({ resolveWithObject: true });
|
|
232
|
+
|
|
233
|
+
return extractSignalsFromRgba(thumbnail.data, thumbnail.info.width, thumbnail.info.height, {
|
|
234
|
+
format,
|
|
235
|
+
rawString,
|
|
236
|
+
width: meta.width,
|
|
237
|
+
height: meta.height,
|
|
238
|
+
});
|
|
239
|
+
} catch {
|
|
240
|
+
// Graceful fallback for non-renderable or unusual vector inputs
|
|
241
|
+
return extractSignalsFromRgba(null, 0, 0, { format, rawString, width: meta.width, height: meta.height });
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Recommends target formats and quality profiles based on content signals and intended placement context.
|
|
247
|
+
*
|
|
248
|
+
* @param {object} info - InspectResult with content signals
|
|
249
|
+
* @param {'icon'|'photo'|'hero'|'thumbnail'|'logo'|'banner'|'general'} [useCase='general']
|
|
250
|
+
* @returns {Array<{ to: string, quality: number, lossless: boolean, reason: string, expectedBytes: number, expectedSavings: number }>}
|
|
251
|
+
*/
|
|
252
|
+
function suggest(info, useCase = 'general') {
|
|
253
|
+
const srcBytes = info.bytes || 100000;
|
|
254
|
+
const content = info.content || {};
|
|
255
|
+
const estType = content.estimatedType || (info.hasAlpha ? 'icon' : 'photo');
|
|
256
|
+
const targetCase = useCase || 'general';
|
|
257
|
+
|
|
258
|
+
const explicitPhoto = targetCase === 'photo' || targetCase === 'hero' || targetCase === 'banner';
|
|
259
|
+
const explicitIcon = targetCase === 'icon' || targetCase === 'logo';
|
|
260
|
+
|
|
261
|
+
const isVectorOrIcon = explicitIcon || (!explicitPhoto && (info.format === 'svg' || estType === 'icon' || estType === 'logo' || estType === 'diagram'));
|
|
262
|
+
const isPhoto = explicitPhoto || (targetCase === 'general' && (estType === 'photo' || estType === 'screenshot'));
|
|
263
|
+
|
|
264
|
+
if (isVectorOrIcon) {
|
|
265
|
+
return [
|
|
266
|
+
{
|
|
267
|
+
to: 'webp',
|
|
268
|
+
quality: 90,
|
|
269
|
+
lossless: content.colorCount !== undefined ? content.colorCount < 128 : true,
|
|
270
|
+
reason: 'Icon and logo assets benefit from crisp alpha edges and high transparency fidelity in WebP.',
|
|
271
|
+
expectedBytes: Math.max(128, Math.round(srcBytes * 0.45)),
|
|
272
|
+
expectedSavings: 0.55,
|
|
273
|
+
},
|
|
274
|
+
{
|
|
275
|
+
to: 'avif',
|
|
276
|
+
quality: 80,
|
|
277
|
+
lossless: false,
|
|
278
|
+
reason: 'Modern AVIF format provides extreme transparency compression for modern web browsers.',
|
|
279
|
+
expectedBytes: Math.max(128, Math.round(srcBytes * 0.38)),
|
|
280
|
+
expectedSavings: 0.62,
|
|
281
|
+
},
|
|
282
|
+
{
|
|
283
|
+
to: 'png',
|
|
284
|
+
quality: 100,
|
|
285
|
+
lossless: true,
|
|
286
|
+
reason: 'Lossless fallback for legacy rendering engines requiring pixel-perfect transparency.',
|
|
287
|
+
expectedBytes: Math.max(256, Math.round(srcBytes * 0.85)),
|
|
288
|
+
expectedSavings: 0.15,
|
|
289
|
+
},
|
|
290
|
+
];
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
if (isPhoto) {
|
|
294
|
+
const qAvif = targetCase === 'thumbnail' ? 65 : (targetCase === 'hero' ? 82 : 75);
|
|
295
|
+
const qWebp = targetCase === 'thumbnail' ? 75 : (targetCase === 'hero' ? 85 : 80);
|
|
296
|
+
|
|
297
|
+
const suggestions = [
|
|
298
|
+
{
|
|
299
|
+
to: 'avif',
|
|
300
|
+
quality: qAvif,
|
|
301
|
+
lossless: false,
|
|
302
|
+
reason: 'Photographic content achieves maximum compression with modern AVIF chroma subsampling.',
|
|
303
|
+
expectedBytes: Math.max(512, Math.round(srcBytes * 0.35)),
|
|
304
|
+
expectedSavings: 0.65,
|
|
305
|
+
},
|
|
306
|
+
{
|
|
307
|
+
to: 'webp',
|
|
308
|
+
quality: qWebp,
|
|
309
|
+
lossless: false,
|
|
310
|
+
reason: 'Universally supported web format delivering high visual fidelity with ~30% smaller size than JPEG.',
|
|
311
|
+
expectedBytes: Math.max(512, Math.round(srcBytes * 0.5)),
|
|
312
|
+
expectedSavings: 0.5,
|
|
313
|
+
},
|
|
314
|
+
];
|
|
315
|
+
|
|
316
|
+
if (!info.hasAlpha) {
|
|
317
|
+
suggestions.push({
|
|
318
|
+
to: 'jpeg',
|
|
319
|
+
quality: targetCase === 'hero' ? 85 : 80,
|
|
320
|
+
lossless: false,
|
|
321
|
+
reason: 'Universal legacy fallback for systems without WebP or AVIF support.',
|
|
322
|
+
expectedBytes: Math.max(512, Math.round(srcBytes * 0.72)),
|
|
323
|
+
expectedSavings: 0.28,
|
|
324
|
+
});
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
return suggestions;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// General fallback
|
|
331
|
+
if (info.hasAlpha) {
|
|
332
|
+
return [
|
|
333
|
+
{
|
|
334
|
+
to: 'webp',
|
|
335
|
+
quality: 85,
|
|
336
|
+
lossless: false,
|
|
337
|
+
reason: 'Image has transparency; WebP guarantees lossless or near-lossless alpha preservation.',
|
|
338
|
+
expectedBytes: Math.max(256, Math.round(srcBytes * 0.48)),
|
|
339
|
+
expectedSavings: 0.52,
|
|
340
|
+
},
|
|
341
|
+
{
|
|
342
|
+
to: 'avif',
|
|
343
|
+
quality: 75,
|
|
344
|
+
lossless: false,
|
|
345
|
+
reason: 'AVIF delivers high-efficiency lossy compression with alpha channel preservation.',
|
|
346
|
+
expectedBytes: Math.max(256, Math.round(srcBytes * 0.4)),
|
|
347
|
+
expectedSavings: 0.6,
|
|
348
|
+
},
|
|
349
|
+
];
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
return [
|
|
353
|
+
{
|
|
354
|
+
to: 'avif',
|
|
355
|
+
quality: 70,
|
|
356
|
+
lossless: false,
|
|
357
|
+
reason: 'Opaque image; AVIF produces the smallest payload for modern web delivery.',
|
|
358
|
+
expectedBytes: Math.max(512, Math.round(srcBytes * 0.38)),
|
|
359
|
+
expectedSavings: 0.62,
|
|
360
|
+
},
|
|
361
|
+
{
|
|
362
|
+
to: 'webp',
|
|
363
|
+
quality: 80,
|
|
364
|
+
lossless: false,
|
|
365
|
+
reason: 'Fast, high-fidelity universal delivery across all browsers and devices.',
|
|
366
|
+
expectedBytes: Math.max(512, Math.round(srcBytes * 0.52)),
|
|
367
|
+
expectedSavings: 0.48,
|
|
368
|
+
},
|
|
369
|
+
];
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Attaches developer-defined custom metadata to an output image buffer.
|
|
374
|
+
*
|
|
375
|
+
* @param {Buffer} buffer
|
|
376
|
+
* @param {string} format
|
|
377
|
+
* @param {Record<string, string|number|boolean>} customMetadata
|
|
378
|
+
* @returns {Buffer}
|
|
379
|
+
*/
|
|
380
|
+
function attachCustomMetadata(buffer, format, customMetadata) {
|
|
381
|
+
if (!customMetadata || typeof customMetadata !== 'object' || !buffer || !buffer.length) {
|
|
382
|
+
return buffer;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
const fmt = (format || '').toLowerCase();
|
|
386
|
+
const jsonString = JSON.stringify(customMetadata);
|
|
387
|
+
|
|
388
|
+
// 1. SVG: Inject into <metadata id="zapwebp-custom">
|
|
389
|
+
if (fmt === 'svg') {
|
|
390
|
+
const str = buffer.toString('utf8');
|
|
391
|
+
const tag = `<metadata id="zapwebp-custom"><script type="application/json">${jsonString}</script></metadata>`;
|
|
392
|
+
const closingTagIndex = str.lastIndexOf('</svg>');
|
|
393
|
+
if (closingTagIndex !== -1) {
|
|
394
|
+
const updated = str.slice(0, closingTagIndex) + tag + str.slice(closingTagIndex);
|
|
395
|
+
return Buffer.from(updated, 'utf8');
|
|
396
|
+
}
|
|
397
|
+
return Buffer.concat([buffer, Buffer.from(tag, 'utf8')]);
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
// 2. PNG: Inject standardized tEXt chunk before IEND
|
|
401
|
+
if (fmt === 'png' && buffer.length >= 24 && buffer[0] === 0x89 && buffer[1] === 0x50) {
|
|
402
|
+
const keyword = 'zapwebp:custom';
|
|
403
|
+
const textData = Buffer.concat([
|
|
404
|
+
Buffer.from(keyword + '\0', 'latin1'),
|
|
405
|
+
Buffer.from(jsonString, 'utf8'),
|
|
406
|
+
]);
|
|
407
|
+
|
|
408
|
+
const chunkLen = Buffer.alloc(4);
|
|
409
|
+
chunkLen.writeUInt32BE(textData.length, 0);
|
|
410
|
+
|
|
411
|
+
const chunkType = Buffer.from('tEXt', 'ascii');
|
|
412
|
+
const crcData = Buffer.concat([chunkType, textData]);
|
|
413
|
+
const chunkCrc = Buffer.alloc(4);
|
|
414
|
+
chunkCrc.writeUInt32BE(crc32(crcData), 0);
|
|
415
|
+
|
|
416
|
+
const tExtChunk = Buffer.concat([chunkLen, chunkType, textData, chunkCrc]);
|
|
417
|
+
|
|
418
|
+
// Locate IEND (last 12 bytes: 00 00 00 00 49 45 4E 44 AE 42 60 82)
|
|
419
|
+
const iendOffset = buffer.lastIndexOf(Buffer.from('IEND', 'ascii'));
|
|
420
|
+
if (iendOffset >= 4) {
|
|
421
|
+
const beforeIend = buffer.subarray(0, iendOffset - 4);
|
|
422
|
+
const iendAndAfter = buffer.subarray(iendOffset - 4);
|
|
423
|
+
return Buffer.concat([beforeIend, tExtChunk, iendAndAfter]);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// 3. JPEG: Inject COM marker right after SOI (0xFFD8)
|
|
428
|
+
if (fmt === 'jpeg' || fmt === 'jpg') {
|
|
429
|
+
if (buffer.length >= 2 && buffer[0] === 0xff && buffer[1] === 0xd8) {
|
|
430
|
+
const payload = Buffer.from(`zapwebp:custom:${jsonString}`, 'utf8');
|
|
431
|
+
if (payload.length <= 65530) {
|
|
432
|
+
const markerLen = payload.length + 2;
|
|
433
|
+
const comMarker = Buffer.alloc(4 + payload.length);
|
|
434
|
+
comMarker[0] = 0xff;
|
|
435
|
+
comMarker[1] = 0xfe; // COM
|
|
436
|
+
comMarker.writeUInt16BE(markerLen, 2);
|
|
437
|
+
payload.copy(comMarker, 4);
|
|
438
|
+
|
|
439
|
+
return Buffer.concat([buffer.subarray(0, 2), comMarker, buffer.subarray(2)]);
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// 4. WebP: Append standard ZAPM RIFF chunk
|
|
445
|
+
if (fmt === 'webp' && buffer.length >= 12 && buffer.subarray(0, 4).toString('ascii') === 'RIFF') {
|
|
446
|
+
const payload = Buffer.from(jsonString, 'utf8');
|
|
447
|
+
const chunkLen = payload.length;
|
|
448
|
+
const pad = chunkLen % 2;
|
|
449
|
+
const chunk = Buffer.alloc(8 + chunkLen + pad);
|
|
450
|
+
chunk.write('ZAPM', 0, 4, 'ascii');
|
|
451
|
+
chunk.writeUInt32LE(chunkLen, 4);
|
|
452
|
+
payload.copy(chunk, 8);
|
|
453
|
+
|
|
454
|
+
const out = Buffer.concat([buffer, chunk]);
|
|
455
|
+
out.writeUInt32LE(out.length - 8, 4); // Update RIFF payload size
|
|
456
|
+
return out;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
return buffer;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* Extracts developer custom metadata if present in the container.
|
|
464
|
+
*
|
|
465
|
+
* @param {Buffer} buffer
|
|
466
|
+
* @param {string} format
|
|
467
|
+
* @returns {Record<string, any>|null}
|
|
468
|
+
*/
|
|
469
|
+
function extractCustomMetadata(buffer, format) {
|
|
470
|
+
if (!buffer || !buffer.length) return null;
|
|
471
|
+
const fmt = (format || '').toLowerCase();
|
|
472
|
+
|
|
473
|
+
try {
|
|
474
|
+
// 1. SVG
|
|
475
|
+
if (fmt === 'svg') {
|
|
476
|
+
const str = buffer.toString('utf8');
|
|
477
|
+
const match = str.match(/<metadata id="zapwebp-custom">\s*<script type="application\/json">([\s\S]*?)<\/script>\s*<\/metadata>/i);
|
|
478
|
+
if (match && match[1]) {
|
|
479
|
+
return JSON.parse(match[1]);
|
|
480
|
+
}
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
// 2. PNG
|
|
484
|
+
if (fmt === 'png' && buffer.length >= 8 && buffer.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) {
|
|
485
|
+
let offset = 8;
|
|
486
|
+
while (offset + 8 <= buffer.length) {
|
|
487
|
+
const length = buffer.readUInt32BE(offset);
|
|
488
|
+
const type = buffer.subarray(offset + 4, offset + 8).toString('ascii');
|
|
489
|
+
if (type === 'tEXt' || type === 'iTXt') {
|
|
490
|
+
const chunkData = buffer.subarray(offset + 8, Math.min(offset + 8 + length, buffer.length));
|
|
491
|
+
const nullIdx = chunkData.indexOf(0x00);
|
|
492
|
+
if (nullIdx !== -1) {
|
|
493
|
+
const keyword = chunkData.subarray(0, nullIdx).toString('latin1');
|
|
494
|
+
if (keyword === 'zapwebp:custom') {
|
|
495
|
+
const text = chunkData.subarray(nullIdx + 1).toString('utf8');
|
|
496
|
+
return JSON.parse(text);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
offset += 12 + length;
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// 3. JPEG
|
|
505
|
+
if ((fmt === 'jpeg' || fmt === 'jpg') && buffer.length >= 2 && buffer[0] === 0xff && buffer[1] === 0xd8) {
|
|
506
|
+
let offset = 2;
|
|
507
|
+
while (offset + 4 <= buffer.length) {
|
|
508
|
+
if (buffer[offset] !== 0xff) { offset++; continue; }
|
|
509
|
+
const marker = buffer[offset + 1];
|
|
510
|
+
if (marker === 0xda || marker === 0xd9) break;
|
|
511
|
+
if (marker === 0x00 || (marker >= 0xd0 && marker <= 0xd7)) { offset += 2; continue; }
|
|
512
|
+
const length = buffer.readUInt16BE(offset + 2);
|
|
513
|
+
if (marker === 0xfe) { // COM
|
|
514
|
+
const comment = buffer.subarray(offset + 4, Math.min(offset + 2 + length, buffer.length)).toString('utf8');
|
|
515
|
+
if (comment.startsWith('zapwebp:custom:')) {
|
|
516
|
+
return JSON.parse(comment.slice('zapwebp:custom:'.length));
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
offset += 2 + length;
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// 4. WebP
|
|
524
|
+
if (fmt === 'webp' && buffer.length >= 12 && buffer.subarray(0, 4).toString('ascii') === 'RIFF') {
|
|
525
|
+
let offset = 12;
|
|
526
|
+
while (offset + 8 <= buffer.length) {
|
|
527
|
+
const fourcc = buffer.subarray(offset, offset + 4).toString('ascii');
|
|
528
|
+
const size = buffer.readUInt32LE(offset + 4);
|
|
529
|
+
if (fourcc === 'ZAPM') {
|
|
530
|
+
const jsonText = buffer.subarray(offset + 8, offset + 8 + size).toString('utf8');
|
|
531
|
+
return JSON.parse(jsonText);
|
|
532
|
+
}
|
|
533
|
+
offset += 8 + size + (size % 2);
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
} catch {
|
|
537
|
+
return null;
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
return null;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
/**
|
|
544
|
+
* Evaluates the quality integrity of the source asset.
|
|
545
|
+
*
|
|
546
|
+
* @param {string} format
|
|
547
|
+
* @param {Buffer} data
|
|
548
|
+
* @param {object} [content]
|
|
549
|
+
* @returns {{ estimated: 'high'|'medium'|'low', reason: string }}
|
|
550
|
+
*/
|
|
551
|
+
function evaluateSourceQuality(format, data, content) {
|
|
552
|
+
const fmt = String(format || '').toLowerCase();
|
|
553
|
+
if (fmt === 'svg') {
|
|
554
|
+
return {
|
|
555
|
+
estimated: 'high',
|
|
556
|
+
reason: 'Vector (SVG) input is mathematically pristine with zero prior rasterization loss.',
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
if (fmt === 'jpeg' || fmt === 'jpg') {
|
|
560
|
+
return {
|
|
561
|
+
estimated: 'low',
|
|
562
|
+
reason: 'Input is JPEG (already lossy). Lossless preserves existing compression artifacts.',
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
if (fmt === 'png' || fmt === 'tiff') {
|
|
566
|
+
if (content && content.sharpness < 0.15 && content.edgeDensity > 0.12) {
|
|
567
|
+
return {
|
|
568
|
+
estimated: 'medium',
|
|
569
|
+
reason: 'PNG input shows potential compression noise or blurring.',
|
|
570
|
+
};
|
|
571
|
+
}
|
|
572
|
+
return {
|
|
573
|
+
estimated: 'high',
|
|
574
|
+
reason: 'PNG input with no prior lossy compression detected.',
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
if (fmt === 'webp' || fmt === 'avif') {
|
|
578
|
+
return {
|
|
579
|
+
estimated: 'medium',
|
|
580
|
+
reason: `${fmt.toUpperCase()} input may have undergone previous lossy compression.`,
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
return {
|
|
584
|
+
estimated: 'medium',
|
|
585
|
+
reason: 'Source format quality is indeterminate.',
|
|
586
|
+
};
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* Calculates byte size impact comparing lossless actual vs estimated lossy equivalent.
|
|
591
|
+
*
|
|
592
|
+
* @param {number} outputBytes
|
|
593
|
+
* @param {number} sourceBytes
|
|
594
|
+
* @param {string} inputFormat
|
|
595
|
+
* @param {string} targetFormat
|
|
596
|
+
* @param {boolean} isLossless
|
|
597
|
+
* @returns {{ lossyEstimate: number, losslessActual: number, ratio: number, note: string }}
|
|
598
|
+
*/
|
|
599
|
+
function evaluateSizeImpact(outputBytes, sourceBytes, inputFormat, targetFormat, isLossless) {
|
|
600
|
+
const fmt = String(inputFormat || '').toLowerCase();
|
|
601
|
+
const isJpeg = fmt === 'jpeg' || fmt === 'jpg';
|
|
602
|
+
|
|
603
|
+
if (!isLossless) {
|
|
604
|
+
return {
|
|
605
|
+
lossyEstimate: outputBytes,
|
|
606
|
+
losslessActual: Math.round(outputBytes * 2.5),
|
|
607
|
+
ratio: 1.0,
|
|
608
|
+
note: 'Lossy compression applied. Output is optimized for minimal byte size.',
|
|
609
|
+
};
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
let lossyEstimate;
|
|
613
|
+
if (isJpeg) {
|
|
614
|
+
lossyEstimate = Math.max(512, Math.round(sourceBytes * 0.7));
|
|
615
|
+
} else if (fmt === 'svg') {
|
|
616
|
+
lossyEstimate = Math.max(256, Math.round(outputBytes * 0.4));
|
|
617
|
+
} else {
|
|
618
|
+
lossyEstimate = Math.max(512, Math.round(outputBytes * 0.35));
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
const ratio = Number((outputBytes / Math.max(1, lossyEstimate)).toFixed(1));
|
|
622
|
+
let note;
|
|
623
|
+
if (isJpeg) {
|
|
624
|
+
note = `Lossless is not recommended for JPEG sources. Output is ${ratio}× larger than a lossy equivalent. Switch to lossy.`;
|
|
625
|
+
} else if (ratio > 2.0) {
|
|
626
|
+
note = `Lossless output is ${ratio}× larger than a lossy equivalent. Use lossy if quality permits.`;
|
|
627
|
+
} else {
|
|
628
|
+
note = 'Lossless output preserves full pixel fidelity with reasonable compression ratio.';
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
return {
|
|
632
|
+
lossyEstimate,
|
|
633
|
+
losslessActual: outputBytes,
|
|
634
|
+
ratio,
|
|
635
|
+
note,
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
/**
|
|
640
|
+
* Verifies that decoded output pixels match input pixels identically in lossless mode.
|
|
641
|
+
*
|
|
642
|
+
* @param {Buffer} inputData - Source image bytes or raw transformed RGBA buffer
|
|
643
|
+
* @param {Buffer} outputData - Encoded output buffer
|
|
644
|
+
* @param {string} inputFormat - Source format
|
|
645
|
+
* @param {string} outputFormat - Target format
|
|
646
|
+
* @param {Function} getSharp - Sharp loader
|
|
647
|
+
* @returns {Promise<boolean>}
|
|
648
|
+
*/
|
|
649
|
+
async function verifyLosslessPixels(inputData, outputData, inputFormat, outputFormat, getSharp) {
|
|
650
|
+
try {
|
|
651
|
+
const sharp = getSharp();
|
|
652
|
+
const r1 = await sharp(inputData, { failOn: 'error' }).ensureAlpha().raw().toBuffer();
|
|
653
|
+
const r2 = await sharp(outputData, { failOn: 'error' }).ensureAlpha().raw().toBuffer();
|
|
654
|
+
|
|
655
|
+
if (r1.length !== r2.length) return false;
|
|
656
|
+
if (r1.equals(r2)) return true;
|
|
657
|
+
|
|
658
|
+
// Tolerance for zeroed RGB on fully transparent pixels (alpha = 0)
|
|
659
|
+
for (let i = 0; i < r1.length; i += 4) {
|
|
660
|
+
const a1 = r1[i + 3];
|
|
661
|
+
const a2 = r2[i + 3];
|
|
662
|
+
if (a1 === 0 && a2 === 0) continue;
|
|
663
|
+
if (r1[i] !== r2[i] || r1[i + 1] !== r2[i + 1] || r1[i + 2] !== r2[i + 2] || a1 !== a2) {
|
|
664
|
+
return false;
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
return true;
|
|
668
|
+
} catch {
|
|
669
|
+
return false;
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
module.exports = {
|
|
674
|
+
crc32,
|
|
675
|
+
extractSignalsFromRgba,
|
|
676
|
+
computeContentSignals,
|
|
677
|
+
suggest,
|
|
678
|
+
attachCustomMetadata,
|
|
679
|
+
extractCustomMetadata,
|
|
680
|
+
evaluateSourceQuality,
|
|
681
|
+
evaluateSizeImpact,
|
|
682
|
+
verifyLosslessPixels,
|
|
683
|
+
};
|