@zapwebp/core 1.1.0 → 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 +9 -3
- 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 +3 -3
- package/src/formats/gif.js +8 -3
- package/src/formats/index.js +5 -0
- package/src/formats/jpeg.js +15 -4
- package/src/formats/png.js +3 -3
- package/src/formats/svg.js +75 -14
- package/src/formats/tiff.js +8 -3
- package/src/formats/webp.js +3 -3
- package/src/index.d.ts +286 -9
- package/src/index.js +998 -91
- package/src/journal/index.js +73 -0
- package/src/metadata/c2pa.js +3 -11
- package/src/metadata/chunk-stripper.js +235 -0
- package/src/metadata/exif.js +3 -12
- package/src/metadata/icc.js +3 -11
- package/src/metadata/png-text.js +3 -11
- package/src/metadata/registry.js +26 -3
- package/src/metadata/xmp.js +3 -17
- 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/README.md
CHANGED
|
@@ -6,27 +6,41 @@
|
|
|
6
6
|
|
|
7
7
|
The shared image conversion, format detection, SVG validation, and metadata cleaning engine behind the entire Zap ecosystem. Provides format-aware, memory-safe conversion across SVG, PNG, JPEG, WebP, AVIF, GIF, and TIFF with strict alpha preservation and zero telemetry.
|
|
8
8
|
|
|
9
|
+
Covers: Image conversion across SVG, PNG, JPEG, WebP, AVIF, GIF, and TIFF, alpha preservation, format autodetection, SVG sanitization, clean mode metadata stripping, and retina multiplier calculations.
|
|
10
|
+
|
|
11
|
+
Does not cover: CLI terminal arguments, MCP network transport, UI widgets, or cloud storage providers.
|
|
12
|
+
|
|
13
|
+
Applies to: `@zapwebp/core` v1.0.0 and later, Node.js >=22.0.0.
|
|
14
|
+
|
|
9
15
|
Documentation: [https://zapwebp.vercel.app/formats](https://zapwebp.vercel.app/formats)
|
|
10
16
|
|
|
11
|
-
|
|
17
|
+
## Quick start
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pnpm add @zapwebp/core
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
```javascript
|
|
24
|
+
const { convertImage } = require('@zapwebp/core');
|
|
25
|
+
|
|
26
|
+
// Convert SVG or raster image to WebP with target width
|
|
27
|
+
const webpBuffer = await convertImage(inputBuffer, {
|
|
28
|
+
to: 'webp',
|
|
29
|
+
width: 512,
|
|
30
|
+
quality: 85,
|
|
31
|
+
});
|
|
32
|
+
```
|
|
12
33
|
|
|
13
|
-
##
|
|
34
|
+
## What it does
|
|
14
35
|
|
|
36
|
+
`@zapwebp/core` is the foundational conversion and validation engine for Zapwebp:
|
|
15
37
|
- **Format Autodetection:** Sniffs image headers from raw magic bytes and XML patterns, never relying on file extensions alone.
|
|
16
38
|
- **Rust-Powered SVG Engine:** Rasterizes SVG vectors via `@resvg/resvg-js` over transparent canvases with subpixel accuracy.
|
|
17
39
|
- **Libvips Raster Pipeline:** High-throughput streaming image transform pipeline powered by `sharp`.
|
|
18
|
-
- **Alpha Guarantees:** Transparency is preserved across WebP, PNG, and AVIF. Converting transparent inputs to JPEG without an explicit background color throws a structured `
|
|
40
|
+
- **Alpha Guarantees:** Transparency is preserved across WebP, PNG, and AVIF. Converting transparent inputs to JPEG without an explicit background color throws a structured `E_ALPHA_NOT_REPRESENTABLE` error.
|
|
19
41
|
- **Clean Mode & AI Provenance:** Detects AI-generated metadata (C2PA Content Credentials, Midjourney, Adobe Firefly, Stable Diffusion) and generates cryptographically signed Clean Certificates.
|
|
20
42
|
- **Multiplier Tooling:** Utility functions for parsing scale arrays (`@1x`, `@2x`, `@3x`), generating filename suffixes, and building ready-to-paste `<img srcset>` HTML snippets.
|
|
21
|
-
- **Security Sandboxing:** Rejects SVGs containing active scripts (`<script>`, inline handlers), external entity expansions (XXE), or remote network references.
|
|
22
|
-
|
|
23
|
-
---
|
|
24
|
-
|
|
25
|
-
## Installation
|
|
26
|
-
|
|
27
|
-
```bash
|
|
28
|
-
pnpm add @zapwebp/core
|
|
29
|
-
```
|
|
43
|
+
- **Security Sandboxing:** Rejects SVGs containing active scripts (`<script>`, inline handlers), external entity expansions (XXE), or remote network references (`E_UNSAFE_SVG`).
|
|
30
44
|
|
|
31
45
|
---
|
|
32
46
|
|
|
@@ -55,45 +69,30 @@ function convertImage(
|
|
|
55
69
|
| `background` | string | `null` | Hex color (e.g. `'#ffffff'`). Required when alpha input is converted to JPEG. |
|
|
56
70
|
| `stripMetadata` | boolean | `true` | Strip EXIF, XMP, and ICC profiles |
|
|
57
71
|
|
|
58
|
-
#### Example
|
|
59
|
-
```javascript
|
|
60
|
-
const { convertImage } = require('@zapwebp/core');
|
|
61
|
-
|
|
62
|
-
// Convert SVG to WebP with target width
|
|
63
|
-
const webpBuffer = await convertImage(svgString, {
|
|
64
|
-
to: 'webp',
|
|
65
|
-
width: 512,
|
|
66
|
-
quality: 90,
|
|
67
|
-
});
|
|
68
|
-
```
|
|
69
|
-
|
|
70
72
|
---
|
|
71
73
|
|
|
72
74
|
### 2. `inspectImage(input)`
|
|
73
|
-
Analyzes image dimensions, format,
|
|
75
|
+
Analyzes image dimensions, format, alpha transparency, and embedded metadata.
|
|
74
76
|
|
|
75
77
|
```typescript
|
|
76
78
|
function inspectImage(input: Buffer | Uint8Array | string): Promise<{
|
|
77
79
|
format: string;
|
|
78
|
-
width
|
|
79
|
-
height
|
|
80
|
+
width?: number;
|
|
81
|
+
height?: number;
|
|
80
82
|
hasAlpha: boolean;
|
|
81
|
-
channels: number;
|
|
82
|
-
space: string;
|
|
83
83
|
bytes: number;
|
|
84
|
-
|
|
84
|
+
metadata: {
|
|
85
|
+
hasMetadata: boolean;
|
|
86
|
+
exif: boolean;
|
|
87
|
+
xmp: boolean;
|
|
88
|
+
c2pa: boolean;
|
|
89
|
+
comments: boolean;
|
|
90
|
+
chunks: string[];
|
|
91
|
+
summary: string[];
|
|
92
|
+
};
|
|
85
93
|
}>
|
|
86
94
|
```
|
|
87
95
|
|
|
88
|
-
#### Example
|
|
89
|
-
```javascript
|
|
90
|
-
const { inspectImage } = require('@zapwebp/core');
|
|
91
|
-
|
|
92
|
-
const info = await inspectImage(imageBuffer);
|
|
93
|
-
console.log(info.format, info.width, info.hasAlpha, info.aiProvenanceHints);
|
|
94
|
-
// => 'png', 1024, true, ['C2PA Manifest detected']
|
|
95
|
-
```
|
|
96
|
-
|
|
97
96
|
---
|
|
98
97
|
|
|
99
98
|
### 3. `detectFormat(input)`
|
|
@@ -114,12 +113,10 @@ Provides direct access to raw RGBA pixel buffers for custom transforms.
|
|
|
114
113
|
const { decodeToRgba, encodeFromRgba } = require('@zapwebp/core');
|
|
115
114
|
|
|
116
115
|
// Decode image to raw 8-bit RGBA buffer
|
|
117
|
-
const
|
|
118
|
-
|
|
119
|
-
// Process raw pixel buffer...
|
|
116
|
+
const raw = await decodeToRgba(inputBuffer);
|
|
120
117
|
|
|
121
118
|
// Encode raw RGBA back to modern format
|
|
122
|
-
const outputBuffer = await encodeFromRgba(
|
|
119
|
+
const outputBuffer = await encodeFromRgba(raw, {
|
|
123
120
|
to: 'webp',
|
|
124
121
|
quality: 85,
|
|
125
122
|
});
|
|
@@ -134,7 +131,6 @@ Parses and validates multiplier scale numbers:
|
|
|
134
131
|
```javascript
|
|
135
132
|
const { parseScales } = require('@zapwebp/core');
|
|
136
133
|
parseScales([1, 2, 3]); // => [1, 2, 3]
|
|
137
|
-
parseScales('1, 2x, 3'); // => [1, 2, 3]
|
|
138
134
|
```
|
|
139
135
|
|
|
140
136
|
#### `outputName(inputPath, format, scale)`
|
|
@@ -149,7 +145,6 @@ Generates responsive `<img srcset>` HTML markup:
|
|
|
149
145
|
```javascript
|
|
150
146
|
const { generateSrcset } = require('@zapwebp/core');
|
|
151
147
|
const html = generateSrcset('hero.png', [1, 2, 3], 'webp', 'Hero Banner');
|
|
152
|
-
// => <img src="hero.webp" srcset="hero.webp 1x, hero@2x.webp 2x, hero@3x.webp 3x" alt="Hero Banner">
|
|
153
148
|
```
|
|
154
149
|
|
|
155
150
|
---
|
|
@@ -184,12 +179,8 @@ Lints shell commands (e.g. `magick convert input.svg output.jpg`) for alpha loss
|
|
|
184
179
|
```javascript
|
|
185
180
|
const { auditConversionCommand } = require('@zapwebp/core');
|
|
186
181
|
const audit = auditConversionCommand('magick convert logo.svg logo.jpg');
|
|
187
|
-
// => { safe: false, issues: ['JPEG drops transparency'], recommendedCommand: 'zap logo.svg --to webp' }
|
|
188
182
|
```
|
|
189
183
|
|
|
190
|
-
#### `explainBlackBackground(context)`
|
|
191
|
-
Returns technical root cause and fix for WebP black background defects.
|
|
192
|
-
|
|
193
184
|
---
|
|
194
185
|
|
|
195
186
|
## Constants Reference
|
|
@@ -203,9 +194,46 @@ Returns technical root cause and fix for WebP black background defects.
|
|
|
203
194
|
|
|
204
195
|
---
|
|
205
196
|
|
|
206
|
-
##
|
|
197
|
+
## Errors
|
|
198
|
+
|
|
199
|
+
| Code | Cause | Fix |
|
|
200
|
+
|---|---|---|
|
|
201
|
+
| `E_UNSUPPORTED_FORMAT` | Source image format is not recognized or unsupported | Use a supported format (SVG, PNG, JPEG, WebP, AVIF, GIF, TIFF) |
|
|
202
|
+
| `E_CORRUPT_HEADER` | Image magic bytes or container header is truncated | Verify input file integrity |
|
|
203
|
+
| `E_ALPHA_NOT_REPRESENTABLE` | Converting transparent image to JPEG without background | Provide background color (`background: '#ffffff'`) |
|
|
204
|
+
| `E_INPUT_TOO_LARGE` | Input pixel dimensions exceed 4096×4096 limit | Downsample source image or resize prior to conversion |
|
|
205
|
+
| `E_UNSAFE_SVG` | SVG contains scripts, event handlers, or XXE entities | Sanitize vector XML before processing |
|
|
206
|
+
|
|
207
|
+
---
|
|
208
|
+
|
|
209
|
+
## For agents
|
|
210
|
+
|
|
211
|
+
```json
|
|
212
|
+
{
|
|
213
|
+
"tool": "@zapwebp/core",
|
|
214
|
+
"methods": [
|
|
215
|
+
"convertImage",
|
|
216
|
+
"inspectImage",
|
|
217
|
+
"detectFormat",
|
|
218
|
+
"decodeToRgba",
|
|
219
|
+
"encodeFromRgba",
|
|
220
|
+
"generateCleanCertificate",
|
|
221
|
+
"verifyAlpha"
|
|
222
|
+
],
|
|
223
|
+
"inputFormats": ["svg", "png", "jpeg", "webp", "avif", "gif", "tiff"],
|
|
224
|
+
"outputFormats": ["webp", "png", "jpeg", "avif"],
|
|
225
|
+
"maxDimension": 4096
|
|
226
|
+
}
|
|
227
|
+
```
|
|
228
|
+
|
|
229
|
+
---
|
|
230
|
+
|
|
231
|
+
## Related
|
|
207
232
|
|
|
208
|
-
|
|
233
|
+
- [Formats Documentation](https://zapwebp-docs.vercel.app/formats): Complete format matrix and alpha handling rules.
|
|
234
|
+
- [Clean Mode](https://zapwebp-docs.vercel.app/clean): Metadata stripping and C2PA certificate verification.
|
|
235
|
+
- [CLI Reference](https://zapwebp-docs.vercel.app/cli): Terminal usage powered by `@zapwebp/core`.
|
|
236
|
+
- [Adding a New Image Format Guide](ADDING_A_FORMAT.md): Instructions for community format contributors.
|
|
209
237
|
|
|
210
238
|
---
|
|
211
239
|
|
package/agent.json
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
{
|
|
2
|
+
"$schema": "https://zapwebp-docs.vercel.app/schemas/agent-manifest.json",
|
|
3
|
+
"name": "@zapwebp/core",
|
|
4
|
+
"version": "1.1.1",
|
|
5
|
+
"type": "core",
|
|
6
|
+
"description": "The Zapwebp core conversion engine. Converts images with deterministic transparency preservation and zero-trust metadata stripping.",
|
|
7
|
+
"capabilities": [
|
|
8
|
+
"convert",
|
|
9
|
+
"inspect",
|
|
10
|
+
"clean",
|
|
11
|
+
"verify_alpha",
|
|
12
|
+
"audit",
|
|
13
|
+
"safety",
|
|
14
|
+
"policy",
|
|
15
|
+
"testing"
|
|
16
|
+
],
|
|
17
|
+
"functions": [
|
|
18
|
+
{
|
|
19
|
+
"name": "convert",
|
|
20
|
+
"signature": "convert(input: Buffer | Uint8Array, options?: ConvertOptions): Promise<Buffer>",
|
|
21
|
+
"description": "Convert an image to a target format. Preserves transparency and strips privacy metadata by default.",
|
|
22
|
+
"example": "import { convert } from '@zapwebp/core';\nconst webp = await convert(svgBytes, { to: 'webp', quality: 85 });",
|
|
23
|
+
"options": {
|
|
24
|
+
"to": {
|
|
25
|
+
"type": "string",
|
|
26
|
+
"enum": [
|
|
27
|
+
"webp",
|
|
28
|
+
"avif",
|
|
29
|
+
"png",
|
|
30
|
+
"jpeg"
|
|
31
|
+
],
|
|
32
|
+
"default": "webp"
|
|
33
|
+
},
|
|
34
|
+
"quality": {
|
|
35
|
+
"type": "number",
|
|
36
|
+
"minimum": 1,
|
|
37
|
+
"maximum": 100,
|
|
38
|
+
"default": 85
|
|
39
|
+
},
|
|
40
|
+
"clean": {
|
|
41
|
+
"type": "boolean",
|
|
42
|
+
"default": true
|
|
43
|
+
},
|
|
44
|
+
"width": {
|
|
45
|
+
"type": "number"
|
|
46
|
+
},
|
|
47
|
+
"height": {
|
|
48
|
+
"type": "number"
|
|
49
|
+
},
|
|
50
|
+
"lossless": {
|
|
51
|
+
"type": "boolean",
|
|
52
|
+
"default": false
|
|
53
|
+
},
|
|
54
|
+
"background": {
|
|
55
|
+
"type": "string"
|
|
56
|
+
},
|
|
57
|
+
"maxOutputBytes": {
|
|
58
|
+
"type": "number"
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
"throws": [
|
|
62
|
+
"E_UNSAFE_SVG",
|
|
63
|
+
"E_ALPHA_NOT_REPRESENTABLE",
|
|
64
|
+
"E_TOO_LARGE",
|
|
65
|
+
"E_UNSUPPORTED_FORMAT"
|
|
66
|
+
]
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
"name": "convertImage",
|
|
70
|
+
"signature": "convertImage(input: Buffer | Uint8Array, options?: ConvertOptions): Promise<ConvertResult>",
|
|
71
|
+
"description": "Convert an image and return comprehensive metadata including dimensions, byte count, alpha preservation state, and format.",
|
|
72
|
+
"example": "import { convertImage } from '@zapwebp/core';\nconst result = await convertImage(inputBytes, { to: 'avif' });\nconsole.log(result.data, result.width, result.alphaPreserved);",
|
|
73
|
+
"options": {
|
|
74
|
+
"to": {
|
|
75
|
+
"type": "string",
|
|
76
|
+
"enum": [
|
|
77
|
+
"webp",
|
|
78
|
+
"avif",
|
|
79
|
+
"png",
|
|
80
|
+
"jpeg"
|
|
81
|
+
],
|
|
82
|
+
"default": "webp"
|
|
83
|
+
},
|
|
84
|
+
"quality": {
|
|
85
|
+
"type": "number",
|
|
86
|
+
"default": 85
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
"throws": [
|
|
90
|
+
"E_ALPHA_NOT_REPRESENTABLE",
|
|
91
|
+
"E_UNSUPPORTED_FORMAT"
|
|
92
|
+
]
|
|
93
|
+
},
|
|
94
|
+
{
|
|
95
|
+
"name": "convertSvgToWebp",
|
|
96
|
+
"signature": "convertSvgToWebp(svgStringOrBuffer: string | Buffer, options?: object): Promise<Buffer>",
|
|
97
|
+
"description": "Specialized high-performance vector-to-raster conversion via Rust resvg and libvips with crisp anti-aliasing.",
|
|
98
|
+
"example": "import { convertSvgToWebp } from '@zapwebp/core';\nconst webp = await convertSvgToWebp('<svg ...></svg>', { width: 512 });",
|
|
99
|
+
"throws": [
|
|
100
|
+
"E_UNSAFE_SVG"
|
|
101
|
+
]
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
"name": "inspectImage",
|
|
105
|
+
"signature": "inspectImage(input: Buffer | Uint8Array): Promise<InspectResult>",
|
|
106
|
+
"description": "Inspect image container chunks, format signature, dimensions, and alpha channel presence without re-encoding.",
|
|
107
|
+
"example": "import { inspectImage } from '@zapwebp/core';\nconst info = await inspectImage(bytes);\nconsole.log(info.format, info.width, info.hasAlpha);",
|
|
108
|
+
"throws": [
|
|
109
|
+
"E_CORRUPT_HEADER",
|
|
110
|
+
"E_UNSUPPORTED_FORMAT"
|
|
111
|
+
]
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
"name": "detectFormat",
|
|
115
|
+
"signature": "detectFormat(input: Buffer | Uint8Array): 'svg' | 'png' | 'jpeg' | 'webp' | 'avif' | 'gif' | 'tiff'",
|
|
116
|
+
"description": "Sniff magic bytes and header markers to identify image container format deterministically.",
|
|
117
|
+
"example": "import { detectFormat } from '@zapwebp/core';\nconst fmt = detectFormat(bytes);",
|
|
118
|
+
"throws": [
|
|
119
|
+
"E_UNSUPPORTED_FORMAT"
|
|
120
|
+
]
|
|
121
|
+
},
|
|
122
|
+
{
|
|
123
|
+
"name": "verifyAlpha",
|
|
124
|
+
"signature": "verifyAlpha(input: Buffer | Uint8Array): Promise<AlphaVerification>",
|
|
125
|
+
"description": "Examine decoded pixel buffer to verify if any pixel has an alpha value below 255.",
|
|
126
|
+
"example": "import { verifyAlpha } from '@zapwebp/core';\nconst check = await verifyAlpha(bytes);\nconsole.log(check.hasAlpha, check.transparentPixels);",
|
|
127
|
+
"throws": [
|
|
128
|
+
"E_CORRUPT_HEADER"
|
|
129
|
+
]
|
|
130
|
+
},
|
|
131
|
+
{
|
|
132
|
+
"name": "cleanMetadata",
|
|
133
|
+
"signature": "cleanMetadata(input: Buffer | Uint8Array): Promise<Buffer>",
|
|
134
|
+
"description": "Strip EXIF, XMP, IPTC, and C2PA metadata from an image while preserving container integrity.",
|
|
135
|
+
"example": "import { cleanMetadata } from '@zapwebp/core';\nconst scrubbed = await cleanMetadata(rawBytes);"
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
"name": "listTools",
|
|
139
|
+
"signature": "listTools(): Array<ToolDefinition>",
|
|
140
|
+
"description": "Return typed MCP-compliant tool schemas for runtime agent discovery without reading external docs.",
|
|
141
|
+
"example": "import { listTools } from '@zapwebp/core';\nconst tools = listTools();"
|
|
142
|
+
}
|
|
143
|
+
],
|
|
144
|
+
"errors": {
|
|
145
|
+
"E_ALPHA_NOT_REPRESENTABLE": {
|
|
146
|
+
"message": "JPEG cannot store transparency. Pass a background color to flatten, or choose WebP, PNG, or AVIF.",
|
|
147
|
+
"fix": "Pass background: '#ffffff' or choose to: 'webp'.",
|
|
148
|
+
"suggestedFix": {
|
|
149
|
+
"background": "#ffffff"
|
|
150
|
+
}
|
|
151
|
+
},
|
|
152
|
+
"E_UNSAFE_SVG": {
|
|
153
|
+
"message": "SVG contains active content (<script>, inline event handlers, or external entity).",
|
|
154
|
+
"fix": "Sanitize the SVG or pass allowUnsafe: true if in an isolated sandbox."
|
|
155
|
+
},
|
|
156
|
+
"E_TOO_LARGE": {
|
|
157
|
+
"message": "Input image exceeds maximum allowed dimension or byte limit.",
|
|
158
|
+
"fix": "Downscale the image or adjust maxInputBytes in conversion policy."
|
|
159
|
+
},
|
|
160
|
+
"E_UNSUPPORTED_FORMAT": {
|
|
161
|
+
"message": "Cannot decode or encode the requested container format.",
|
|
162
|
+
"fix": "Use one of the supported formats: svg, png, jpeg, webp, avif, gif, tiff."
|
|
163
|
+
}
|
|
164
|
+
},
|
|
165
|
+
"examples": [
|
|
166
|
+
{
|
|
167
|
+
"name": "Convert SVG to WebP preserving transparency",
|
|
168
|
+
"code": "import { convert } from '@zapwebp/core';\nimport { readFile, writeFile } from 'node:fs/promises';\n\nconst input = await readFile('logo.svg');\nconst output = await convert(input, { to: 'webp', quality: 90 });\nawait writeFile('logo.webp', output);"
|
|
169
|
+
},
|
|
170
|
+
{
|
|
171
|
+
"name": "Inspect before converting",
|
|
172
|
+
"code": "import { inspectImage, convert } from '@zapwebp/core';\n\nconst info = await inspectImage(inputBytes);\nif (info.hasAlpha) {\n const webp = await convert(inputBytes, { to: 'webp', clean: true });\n} else {\n const avif = await convert(inputBytes, { to: 'avif', quality: 65 });\n}"
|
|
173
|
+
},
|
|
174
|
+
{
|
|
175
|
+
"name": "Generate mock SVG in test",
|
|
176
|
+
"code": "import { createMockSvg } from '@zapwebp/core/testing';\nimport { convert } from '@zapwebp/core';\n\nconst mock = createMockSvg({ width: 200, height: 200, transparent: true });\nconst webp = await convert(mock, { to: 'webp' });"
|
|
177
|
+
}
|
|
178
|
+
],
|
|
179
|
+
"docs": "https://zapwebp-docs.vercel.app/sdk/core"
|
|
180
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zapwebp/core",
|
|
3
|
-
"version": "1.1.
|
|
3
|
+
"version": "1.1.2",
|
|
4
4
|
"description": "Format-aware image conversion engine with transparency-safe outputs.",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"types": "src/index.d.ts",
|
|
@@ -8,10 +8,16 @@
|
|
|
8
8
|
".": {
|
|
9
9
|
"types": "./src/index.d.ts",
|
|
10
10
|
"default": "./src/index.js"
|
|
11
|
-
}
|
|
11
|
+
},
|
|
12
|
+
"./testing": {
|
|
13
|
+
"types": "./src/testing.d.ts",
|
|
14
|
+
"default": "./src/testing.js"
|
|
15
|
+
},
|
|
16
|
+
"./agent.json": "./agent.json"
|
|
12
17
|
},
|
|
13
18
|
"files": [
|
|
14
19
|
"src",
|
|
20
|
+
"agent.json",
|
|
15
21
|
"README.md",
|
|
16
22
|
"LICENSE"
|
|
17
23
|
],
|
|
@@ -21,7 +27,7 @@
|
|
|
21
27
|
},
|
|
22
28
|
"dependencies": {
|
|
23
29
|
"@resvg/resvg-js": "^2.6.2",
|
|
24
|
-
"sharp": "^0.
|
|
30
|
+
"sharp": "^0.35.5",
|
|
25
31
|
"@zapwebp/shared": "1.1.2"
|
|
26
32
|
},
|
|
27
33
|
"publishConfig": {
|
package/src/cache.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const crypto = require('node:crypto');
|
|
4
|
+
|
|
5
|
+
const DEFAULT_MAX_CACHE_ENTRIES = 500;
|
|
6
|
+
const DEFAULT_MAX_CACHE_BYTES = 50 * 1024 * 1024; // 50 MB
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Computes a deterministic SHA-256 cache key from input bytes, options, and engine version.
|
|
10
|
+
*
|
|
11
|
+
* @param {Buffer|Uint8Array} input - Input image bytes
|
|
12
|
+
* @param {object} options - Conversion options
|
|
13
|
+
* @param {string} [engineVersion='1.1.1'] - Core engine version
|
|
14
|
+
* @returns {string}
|
|
15
|
+
*/
|
|
16
|
+
function computeCacheKey(input, options = {}, engineVersion = '1.1.1') {
|
|
17
|
+
const hash = crypto.createHash('sha256');
|
|
18
|
+
hash.update(input);
|
|
19
|
+
hash.update(`:v${engineVersion}:`);
|
|
20
|
+
|
|
21
|
+
// Canonical sorted options string
|
|
22
|
+
const sortedKeys = Object.keys(options).sort();
|
|
23
|
+
for (const key of sortedKeys) {
|
|
24
|
+
if (key === 'cache') continue;
|
|
25
|
+
const val = options[key];
|
|
26
|
+
if (val !== undefined && typeof val !== 'function') {
|
|
27
|
+
hash.update(`${key}=${JSON.stringify(val)};`);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
return hash.digest('hex');
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* High-performance, memory-bounded LRU Cache for deterministic conversion results.
|
|
36
|
+
*/
|
|
37
|
+
class ConversionCache {
|
|
38
|
+
/**
|
|
39
|
+
* @param {object} [options]
|
|
40
|
+
* @param {number} [options.maxEntries=500]
|
|
41
|
+
* @param {number} [options.maxBytes=52428800]
|
|
42
|
+
*/
|
|
43
|
+
constructor(options = {}) {
|
|
44
|
+
this.maxEntries = options.maxEntries || DEFAULT_MAX_CACHE_ENTRIES;
|
|
45
|
+
this.maxBytes = options.maxBytes || DEFAULT_MAX_CACHE_BYTES;
|
|
46
|
+
this.entries = new Map();
|
|
47
|
+
this.totalBytes = 0;
|
|
48
|
+
this.hits = 0;
|
|
49
|
+
this.misses = 0;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Retrieves a cached result by key and refreshes its LRU priority.
|
|
54
|
+
* @param {string} key
|
|
55
|
+
* @returns {object|null}
|
|
56
|
+
*/
|
|
57
|
+
get(key) {
|
|
58
|
+
if (!this.entries.has(key)) {
|
|
59
|
+
this.misses++;
|
|
60
|
+
return null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const item = this.entries.get(key);
|
|
64
|
+
// Refresh LRU order: delete and re-insert
|
|
65
|
+
this.entries.delete(key);
|
|
66
|
+
this.entries.set(key, item);
|
|
67
|
+
this.hits++;
|
|
68
|
+
|
|
69
|
+
// Return a shallow clone with a fresh Buffer copy to ensure caller mutation safety
|
|
70
|
+
return {
|
|
71
|
+
...item,
|
|
72
|
+
data: Buffer.from(item.data),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Stores a conversion result in the cache, evicting oldest entries if limits are exceeded.
|
|
78
|
+
* @param {string} key
|
|
79
|
+
* @param {object} result
|
|
80
|
+
*/
|
|
81
|
+
set(key, result) {
|
|
82
|
+
if (!result || !result.data) return;
|
|
83
|
+
const byteLength = result.data.length;
|
|
84
|
+
|
|
85
|
+
// Do not cache oversized individual items exceeding 25% of max cache capacity
|
|
86
|
+
if (byteLength > this.maxBytes * 0.25) return;
|
|
87
|
+
|
|
88
|
+
if (this.entries.has(key)) {
|
|
89
|
+
const existing = this.entries.get(key);
|
|
90
|
+
this.totalBytes -= existing.data.length;
|
|
91
|
+
this.entries.delete(key);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Evict least recently used entries if size or count limits are hit
|
|
95
|
+
while (
|
|
96
|
+
(this.entries.size >= this.maxEntries || this.totalBytes + byteLength > this.maxBytes) &&
|
|
97
|
+
this.entries.size > 0
|
|
98
|
+
) {
|
|
99
|
+
const oldestKey = this.entries.keys().next().value;
|
|
100
|
+
const oldestItem = this.entries.get(oldestKey);
|
|
101
|
+
this.totalBytes -= oldestItem.data.length;
|
|
102
|
+
this.entries.delete(oldestKey);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
this.entries.set(key, {
|
|
106
|
+
...result,
|
|
107
|
+
data: Buffer.from(result.data),
|
|
108
|
+
cachedAt: Date.now(),
|
|
109
|
+
});
|
|
110
|
+
this.totalBytes += byteLength;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Clears all cached entries and resets statistics.
|
|
115
|
+
*/
|
|
116
|
+
clear() {
|
|
117
|
+
this.entries.clear();
|
|
118
|
+
this.totalBytes = 0;
|
|
119
|
+
this.hits = 0;
|
|
120
|
+
this.misses = 0;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Returns current cache statistics.
|
|
125
|
+
* @returns {{ size: number, totalBytes: number, hits: number, misses: number, hitRate: number }}
|
|
126
|
+
*/
|
|
127
|
+
stats() {
|
|
128
|
+
const total = this.hits + this.misses;
|
|
129
|
+
return {
|
|
130
|
+
size: this.entries.size,
|
|
131
|
+
totalBytes: this.totalBytes,
|
|
132
|
+
hits: this.hits,
|
|
133
|
+
misses: this.misses,
|
|
134
|
+
hitRate: total > 0 ? Number((this.hits / total).toFixed(3)) : 0,
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const defaultCache = new ConversionCache();
|
|
140
|
+
|
|
141
|
+
module.exports = {
|
|
142
|
+
computeCacheKey,
|
|
143
|
+
ConversionCache,
|
|
144
|
+
defaultCache,
|
|
145
|
+
};
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { ZapwebpError } = require('@zapwebp/shared');
|
|
4
|
+
const { getSharp, getResvg, validateSvg, svgDimensions, checkDimensions, MAX_PIXELS } = require('../index');
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Decodes input image bytes into uncompressed RGBA pixel bytes.
|
|
8
|
+
*
|
|
9
|
+
* @param {Uint8Array|Buffer} input - Input image bytes
|
|
10
|
+
* @param {string} format - Input format
|
|
11
|
+
* @param {object} [options]
|
|
12
|
+
* @returns {Promise<import('../types').RawImage>}
|
|
13
|
+
*/
|
|
14
|
+
async function decode(input, format, options = {}) {
|
|
15
|
+
const data = Buffer.isBuffer(input) ? input : Buffer.from(input.buffer, input.byteOffset, input.byteLength);
|
|
16
|
+
const fmt = String(format || '').toLowerCase();
|
|
17
|
+
let source = data;
|
|
18
|
+
|
|
19
|
+
if (fmt === 'svg') {
|
|
20
|
+
const svg = validateSvg(data);
|
|
21
|
+
const dims = svgDimensions(svg);
|
|
22
|
+
const width = dims.width || 2048;
|
|
23
|
+
const height = dims.height || 2048;
|
|
24
|
+
checkDimensions(width, height);
|
|
25
|
+
const ResvgClass = getResvg();
|
|
26
|
+
source = new ResvgClass(svg, { fitTo: { mode: 'original' }, background: 'rgba(0, 0, 0, 0)' }).render().asPng();
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const pipeline = getSharp()(source, {
|
|
30
|
+
limitInputPixels: MAX_PIXELS,
|
|
31
|
+
pages: 1,
|
|
32
|
+
animated: false,
|
|
33
|
+
failOn: 'error',
|
|
34
|
+
}).ensureAlpha();
|
|
35
|
+
|
|
36
|
+
const { data: raw, info } = await pipeline.raw().toBuffer({ resolveWithObject: true });
|
|
37
|
+
checkDimensions(info.width, info.height);
|
|
38
|
+
|
|
39
|
+
let hasAlpha = false;
|
|
40
|
+
for (let i = 3; i < raw.length; i += 4) {
|
|
41
|
+
if (raw[i] < 255) {
|
|
42
|
+
hasAlpha = true;
|
|
43
|
+
break;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
return {
|
|
48
|
+
data: new Uint8Array(raw.buffer, raw.byteOffset, raw.byteLength),
|
|
49
|
+
width: info.width,
|
|
50
|
+
height: info.height,
|
|
51
|
+
channels: 4,
|
|
52
|
+
hasAlpha,
|
|
53
|
+
format: fmt,
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
module.exports = {
|
|
58
|
+
decode,
|
|
59
|
+
};
|
|
60
|
+
|