@myrialabs/clopen 0.3.16 → 0.3.17
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/backend/files/image-processing.ts +396 -0
- package/backend/ws/files/image-edit.ts +158 -0
- package/backend/ws/files/index.ts +4 -0
- package/backend/ws/files/read.ts +10 -2
- package/dist/assets/{main-CYVFcz-a.js → main-CHTThSzD.js} +252 -252
- package/dist/assets/main-Dzb_5CtR.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +11 -9
- package/shared/constants/binary-extensions.ts +25 -6
- package/shared/types/filesystem/index.ts +81 -0
- package/dist/assets/main-DrFILAEB.css +0 -1
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Image Processing
|
|
3
|
+
*
|
|
4
|
+
* Applies an `ImageEditRecipe` to an image on disk using sharp and returns the
|
|
5
|
+
* encoded result as a Buffer. The client editor only ever sends a small
|
|
6
|
+
* declarative recipe — the full-resolution original is read here so quality is
|
|
7
|
+
* never bounded by what the browser downscaled for preview.
|
|
8
|
+
*
|
|
9
|
+
* Geometry is deterministic: for static images we fully bake rotate/flip into a
|
|
10
|
+
* raw intermediate buffer first, so the crop rectangle always maps to the
|
|
11
|
+
* orientation the user cropped against (sharp's single-pipeline op ordering is
|
|
12
|
+
* not call-order, so we stage it ourselves). Animated images (GIF/WebP) are
|
|
13
|
+
* processed in a single `{ animated: true }` pass to preserve their frames.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import sharp from 'sharp';
|
|
17
|
+
import type { Sharp } from 'sharp';
|
|
18
|
+
|
|
19
|
+
import type { ImageEditRecipe, ImageEditRegion, ImageEditStroke } from '$shared/types/filesystem';
|
|
20
|
+
import { validateFileSize } from './file-size-limit';
|
|
21
|
+
|
|
22
|
+
export interface ProcessedImage {
|
|
23
|
+
data: Buffer;
|
|
24
|
+
format: string;
|
|
25
|
+
width: number;
|
|
26
|
+
height: number;
|
|
27
|
+
size: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Clamp a value into [min, max], rounding to an integer. */
|
|
31
|
+
function clampInt(value: number, min: number, max: number): number {
|
|
32
|
+
return Math.max(min, Math.min(max, Math.round(value)));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Apply the color/tone adjustments shared by both processing paths. */
|
|
36
|
+
function applyColor(pipeline: Sharp, recipe: ImageEditRecipe): Sharp {
|
|
37
|
+
let p = pipeline;
|
|
38
|
+
if (recipe.background) {
|
|
39
|
+
// Composite any transparency onto a solid colour (e.g. for JPEG export).
|
|
40
|
+
p = p.flatten({ background: recipe.background });
|
|
41
|
+
}
|
|
42
|
+
if (recipe.grayscale) {
|
|
43
|
+
p = p.grayscale();
|
|
44
|
+
}
|
|
45
|
+
const brightness = recipe.brightness ?? 1;
|
|
46
|
+
const saturation = recipe.saturation ?? 1;
|
|
47
|
+
const hue = Math.round(recipe.hue ?? 0);
|
|
48
|
+
if (brightness !== 1 || saturation !== 1 || hue !== 0) {
|
|
49
|
+
p = p.modulate({ brightness, saturation, hue });
|
|
50
|
+
}
|
|
51
|
+
if (recipe.contrast != null && recipe.contrast !== 1) {
|
|
52
|
+
// Linear contrast around the 128 midpoint: out = slope*in + intercept.
|
|
53
|
+
p = p.linear(recipe.contrast, -(128 * recipe.contrast) + 128);
|
|
54
|
+
}
|
|
55
|
+
if (recipe.sepia) {
|
|
56
|
+
// Standard sepia matrix (matches the CSS `sepia(1)` filter).
|
|
57
|
+
p = p.recomb([
|
|
58
|
+
[0.393, 0.769, 0.189],
|
|
59
|
+
[0.349, 0.686, 0.168],
|
|
60
|
+
[0.272, 0.534, 0.131]
|
|
61
|
+
]);
|
|
62
|
+
}
|
|
63
|
+
if (recipe.invert) {
|
|
64
|
+
p = p.negate({ alpha: false });
|
|
65
|
+
}
|
|
66
|
+
if (recipe.blur != null && recipe.blur > 0) {
|
|
67
|
+
p = p.blur(Math.max(0.3, recipe.blur));
|
|
68
|
+
}
|
|
69
|
+
return p;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** True when the recipe applies any geometry, color, region or annotation change. */
|
|
73
|
+
function hasEdits(recipe: ImageEditRecipe): boolean {
|
|
74
|
+
return (
|
|
75
|
+
!!recipe.crop ||
|
|
76
|
+
!!recipe.resize ||
|
|
77
|
+
!!recipe.rotate ||
|
|
78
|
+
!!recipe.flipH ||
|
|
79
|
+
!!recipe.flipV ||
|
|
80
|
+
(recipe.brightness != null && recipe.brightness !== 1) ||
|
|
81
|
+
(recipe.saturation != null && recipe.saturation !== 1) ||
|
|
82
|
+
(recipe.contrast != null && recipe.contrast !== 1) ||
|
|
83
|
+
(recipe.hue != null && recipe.hue !== 0) ||
|
|
84
|
+
(recipe.blur != null && recipe.blur > 0) ||
|
|
85
|
+
!!recipe.grayscale ||
|
|
86
|
+
!!recipe.sepia ||
|
|
87
|
+
!!recipe.invert ||
|
|
88
|
+
(recipe.regions?.length ?? 0) > 0 ||
|
|
89
|
+
(recipe.annotations?.length ?? 0) > 0
|
|
90
|
+
);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Build a composite layer that blurs or pixelates one region of the oriented image. */
|
|
94
|
+
async function buildRegionComposite(
|
|
95
|
+
orientedBuf: Buffer,
|
|
96
|
+
region: ImageEditRegion,
|
|
97
|
+
imgWidth: number,
|
|
98
|
+
imgHeight: number
|
|
99
|
+
): Promise<{ input: Buffer; left: number; top: number }> {
|
|
100
|
+
const r = boundCrop(
|
|
101
|
+
{ left: region.left, top: region.top, width: region.width, height: region.height },
|
|
102
|
+
imgWidth,
|
|
103
|
+
imgHeight
|
|
104
|
+
);
|
|
105
|
+
const strength = Math.max(1, Math.min(100, region.strength || 1));
|
|
106
|
+
let img = sharp(orientedBuf).extract(r);
|
|
107
|
+
if (region.type === 'blur') {
|
|
108
|
+
img = img.blur(Math.max(0.3, strength / 3));
|
|
109
|
+
} else {
|
|
110
|
+
// Mosaic: downscale with nearest-neighbour, then scale back up.
|
|
111
|
+
const factor = Math.max(2, Math.round(strength / 3));
|
|
112
|
+
const dw = Math.max(1, Math.round(r.width / factor));
|
|
113
|
+
const dh = Math.max(1, Math.round(r.height / factor));
|
|
114
|
+
img = img
|
|
115
|
+
.resize(dw, dh, { kernel: 'nearest' })
|
|
116
|
+
.resize(r.width, r.height, { kernel: 'nearest' });
|
|
117
|
+
}
|
|
118
|
+
return { input: await img.png().toBuffer(), left: r.left, top: r.top };
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** Render freehand strokes to an SVG overlay sized to the oriented image. */
|
|
122
|
+
function buildAnnotationSvg(strokes: ImageEditStroke[], width: number, height: number): string {
|
|
123
|
+
const lines = strokes
|
|
124
|
+
.map((s) => {
|
|
125
|
+
const color = /^#[0-9a-fA-F]{3,8}$/.test(s.color) ? s.color : '#ef4444';
|
|
126
|
+
const w = Math.max(1, Math.min(400, s.size || 4));
|
|
127
|
+
const opacity = Math.max(0, Math.min(1, s.opacity ?? 1));
|
|
128
|
+
const pts = s.points
|
|
129
|
+
.filter((p) => Number.isFinite(p.x) && Number.isFinite(p.y))
|
|
130
|
+
.map((p) => `${Math.round(p.x)},${Math.round(p.y)}`)
|
|
131
|
+
.join(' ');
|
|
132
|
+
if (!pts) return '';
|
|
133
|
+
return `<polyline points="${pts}" fill="none" stroke="${color}" stroke-width="${w}" stroke-opacity="${opacity}" stroke-linecap="round" stroke-linejoin="round"/>`;
|
|
134
|
+
})
|
|
135
|
+
.join('');
|
|
136
|
+
return `<svg xmlns="http://www.w3.org/2000/svg" width="${width}" height="${height}">${lines}</svg>`;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Encode the pipeline into the requested output format.
|
|
141
|
+
*
|
|
142
|
+
* `compress` opt-in (per format):
|
|
143
|
+
* - off → preserve quality: lossless for PNG/WebP, high quality otherwise. The
|
|
144
|
+
* caller copies the original byte-for-byte when there are no other edits, so
|
|
145
|
+
* this path only runs when geometry/color/format actually changed.
|
|
146
|
+
* - on → efficient codecs that shrink files at visually-equivalent quality:
|
|
147
|
+
* mozjpeg for JPEG, palette quantization for PNG (in encodeToBuffer),
|
|
148
|
+
* efficient lossy WebP/AVIF.
|
|
149
|
+
*/
|
|
150
|
+
function encode(pipeline: Sharp, output: ImageEditRecipe['output'], fast = false): Sharp {
|
|
151
|
+
const compress = output.compress ?? false;
|
|
152
|
+
const quality = output.quality ?? 80;
|
|
153
|
+
switch (output.format) {
|
|
154
|
+
case 'png':
|
|
155
|
+
// Lossy PNG (palette quantization) is handled in encodeToBuffer; here
|
|
156
|
+
// we always produce the lossless variant. `fast` trades a little size
|
|
157
|
+
// accuracy for speed (used by the live estimate on large images).
|
|
158
|
+
return pipeline.png({ compressionLevel: fast ? 6 : 9, effort: fast ? 1 : 10 });
|
|
159
|
+
case 'jpeg':
|
|
160
|
+
// mozjpeg = trellis quantization + optimized Huffman + progressive.
|
|
161
|
+
return pipeline.jpeg({ quality: compress ? quality : 95, mozjpeg: true });
|
|
162
|
+
case 'webp':
|
|
163
|
+
return output.lossless || !compress
|
|
164
|
+
? pipeline.webp({ lossless: true, effort: fast ? 0 : 6 })
|
|
165
|
+
: pipeline.webp({ quality, effort: fast ? 0 : 6, smartSubsample: true });
|
|
166
|
+
case 'gif':
|
|
167
|
+
return pipeline.gif({ dither: 1 });
|
|
168
|
+
case 'avif':
|
|
169
|
+
// Off = preserve quality (near-lossless); on = the requested quality.
|
|
170
|
+
// Keep the two clearly apart so toggling compression changes the size.
|
|
171
|
+
// AVIF effort is the slowest knob — drop it hard for the estimate.
|
|
172
|
+
return pipeline.avif({ quality: compress ? (output.quality ?? 80) : 92, effort: fast ? 0 : 4 });
|
|
173
|
+
default: {
|
|
174
|
+
// Exhaustiveness guard — unreachable for valid recipes.
|
|
175
|
+
const never: never = output.format;
|
|
176
|
+
throw new Error(`Unsupported output format: ${String(never)}`);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Apply a recipe to the image at `sourcePath` and return the encoded result.
|
|
183
|
+
* Throws if the source is not a decodable image or the output exceeds the
|
|
184
|
+
* configured file-size limit.
|
|
185
|
+
*/
|
|
186
|
+
export async function processImageEdit(
|
|
187
|
+
sourcePath: string,
|
|
188
|
+
recipe: ImageEditRecipe,
|
|
189
|
+
fast = false
|
|
190
|
+
): Promise<ProcessedImage> {
|
|
191
|
+
const srcMeta = await sharp(sourcePath, { animated: true }).metadata();
|
|
192
|
+
if (!srcMeta.width || !srcMeta.height) {
|
|
193
|
+
throw new Error('Source file is not a readable image');
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Nothing to do: not compressing, no edits, and the format is unchanged →
|
|
197
|
+
// return the original bytes verbatim so an untouched file stays identical.
|
|
198
|
+
const compress = recipe.output.compress ?? false;
|
|
199
|
+
if (!compress && !hasEdits(recipe) && srcMeta.format === recipe.output.format) {
|
|
200
|
+
const data = Buffer.from(await Bun.file(sourcePath).arrayBuffer());
|
|
201
|
+
validateFileSize(data.length);
|
|
202
|
+
return {
|
|
203
|
+
data,
|
|
204
|
+
format: srcMeta.format ?? recipe.output.format,
|
|
205
|
+
width: srcMeta.width,
|
|
206
|
+
height: srcMeta.height,
|
|
207
|
+
size: data.length
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const animated = (srcMeta.pages ?? 1) > 1;
|
|
212
|
+
const rotate = recipe.rotate ?? 0;
|
|
213
|
+
|
|
214
|
+
let pipeline: Sharp;
|
|
215
|
+
|
|
216
|
+
if (animated) {
|
|
217
|
+
// Single pass keeps every frame. sharp applies extract/resize per frame.
|
|
218
|
+
let p = sharp(sourcePath, { animated: true });
|
|
219
|
+
if (rotate) p = p.rotate(rotate);
|
|
220
|
+
if (recipe.flipV) p = p.flip();
|
|
221
|
+
if (recipe.flipH) p = p.flop();
|
|
222
|
+
if (recipe.crop) {
|
|
223
|
+
p = p.extract(boundCrop(recipe.crop, srcMeta.width, srcMeta.height));
|
|
224
|
+
}
|
|
225
|
+
if (recipe.resize) {
|
|
226
|
+
p = p.resize(Math.round(recipe.resize.width), Math.round(recipe.resize.height), { fit: 'fill' });
|
|
227
|
+
}
|
|
228
|
+
pipeline = applyColor(p, recipe);
|
|
229
|
+
} else {
|
|
230
|
+
// The browser decodes images with EXIF orientation applied, so the editor's
|
|
231
|
+
// coordinates live in that space. EXIF-oriented dimensions are derived from
|
|
232
|
+
// metadata (orientation 5–8 swap W/H) so the common no-rotation path never
|
|
233
|
+
// has to fully decode a large image just to estimate its size.
|
|
234
|
+
const exifSwap = (srcMeta.orientation ?? 1) >= 5;
|
|
235
|
+
const baseW = exifSwap ? srcMeta.height : srcMeta.width;
|
|
236
|
+
const baseH = exifSwap ? srcMeta.width : srcMeta.height;
|
|
237
|
+
|
|
238
|
+
const quarterTurn = rotate === 90 || rotate === 270;
|
|
239
|
+
const orientedWidth = quarterTurn ? baseH : baseW;
|
|
240
|
+
const orientedHeight = quarterTurn ? baseW : baseH;
|
|
241
|
+
|
|
242
|
+
const regions = recipe.regions ?? [];
|
|
243
|
+
const annotations = recipe.annotations ?? [];
|
|
244
|
+
|
|
245
|
+
// Decode the EXIF-auto-oriented source into a raw buffer. Only used when a
|
|
246
|
+
// rotation/flip must be baked (so crop maps after rotation) or overlays are
|
|
247
|
+
// composited — the plain path below stays lazy.
|
|
248
|
+
const decodeOrientedRaw = async () => {
|
|
249
|
+
const { data, info } = await sharp(sourcePath)
|
|
250
|
+
.rotate()
|
|
251
|
+
.ensureAlpha()
|
|
252
|
+
.raw()
|
|
253
|
+
.toBuffer({ resolveWithObject: true });
|
|
254
|
+
return sharp(data, { raw: { width: info.width, height: info.height, channels: info.channels } });
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
if (regions.length > 0 || annotations.length > 0) {
|
|
258
|
+
// Bake orientation + color first, then composite blur/pixelate regions
|
|
259
|
+
// and freehand strokes in oriented space, then crop/resize/encode.
|
|
260
|
+
let oriented = (await decodeOrientedRaw()).rotate(rotate);
|
|
261
|
+
if (recipe.flipV) oriented = oriented.flip();
|
|
262
|
+
if (recipe.flipH) oriented = oriented.flop();
|
|
263
|
+
oriented = applyColor(oriented, recipe);
|
|
264
|
+
const orientedBuf = await oriented.png().toBuffer();
|
|
265
|
+
|
|
266
|
+
// Composite layers must fit the *actual* baked buffer, which can differ
|
|
267
|
+
// from the metadata-derived oriented size by a sub-pixel after EXIF
|
|
268
|
+
// auto-orient + rotate. Measure the real dimensions and size every
|
|
269
|
+
// layer against them, or sharp rejects them ("same dimensions or smaller").
|
|
270
|
+
const bakedMeta = await sharp(orientedBuf).metadata();
|
|
271
|
+
const ow = bakedMeta.width ?? orientedWidth;
|
|
272
|
+
const oh = bakedMeta.height ?? orientedHeight;
|
|
273
|
+
|
|
274
|
+
const composites: { input: Buffer; left: number; top: number }[] = [];
|
|
275
|
+
for (const region of regions) {
|
|
276
|
+
composites.push(await buildRegionComposite(orientedBuf, region, ow, oh));
|
|
277
|
+
}
|
|
278
|
+
if (annotations.length > 0) {
|
|
279
|
+
// Rasterize the overlay to an exact-size PNG first. Compositing a raw
|
|
280
|
+
// SVG buffer can be rejected ("same dimensions or smaller") when
|
|
281
|
+
// librsvg rounds the raster up by a sub-pixel versus the base.
|
|
282
|
+
const svg = buildAnnotationSvg(annotations, ow, oh);
|
|
283
|
+
const svgPng = await sharp(Buffer.from(svg))
|
|
284
|
+
.resize(ow, oh, { fit: 'fill' })
|
|
285
|
+
.png()
|
|
286
|
+
.toBuffer();
|
|
287
|
+
composites.push({ input: svgPng, left: 0, top: 0 });
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// Flatten the composites into the base BEFORE cropping/resizing. sharp
|
|
291
|
+
// orders pipeline ops internally (extract/resize run before composite),
|
|
292
|
+
// so chaining .composite().extract() on one pipeline would crop the base
|
|
293
|
+
// first and then reject the full-size overlay. Baking to a buffer pins
|
|
294
|
+
// the overlay to the full oriented frame it was authored against.
|
|
295
|
+
const compositedBuf =
|
|
296
|
+
composites.length > 0
|
|
297
|
+
? await sharp(orientedBuf).composite(composites).png().toBuffer()
|
|
298
|
+
: orientedBuf;
|
|
299
|
+
|
|
300
|
+
let p = sharp(compositedBuf);
|
|
301
|
+
if (recipe.crop) {
|
|
302
|
+
p = p.extract(boundCrop(recipe.crop, ow, oh));
|
|
303
|
+
}
|
|
304
|
+
if (recipe.resize) {
|
|
305
|
+
p = p.resize(Math.round(recipe.resize.width), Math.round(recipe.resize.height), { fit: 'fill' });
|
|
306
|
+
}
|
|
307
|
+
// Color already baked above.
|
|
308
|
+
pipeline = p;
|
|
309
|
+
} else if (rotate || recipe.flipH || recipe.flipV) {
|
|
310
|
+
// Bake EXIF + user orientation into a raw buffer so the crop coordinates
|
|
311
|
+
// (expressed against the oriented preview) map exactly — sharp's single
|
|
312
|
+
// pipeline does not honor rotate-before-extract call order.
|
|
313
|
+
let pre = (await decodeOrientedRaw()).rotate(rotate);
|
|
314
|
+
if (recipe.flipV) pre = pre.flip();
|
|
315
|
+
if (recipe.flipH) pre = pre.flop();
|
|
316
|
+
const { data, info } = await pre.raw().toBuffer({ resolveWithObject: true });
|
|
317
|
+
let p = sharp(data, { raw: { width: info.width, height: info.height, channels: info.channels } });
|
|
318
|
+
if (recipe.crop) {
|
|
319
|
+
p = p.extract(boundCrop(recipe.crop, orientedWidth, orientedHeight));
|
|
320
|
+
}
|
|
321
|
+
if (recipe.resize) {
|
|
322
|
+
p = p.resize(Math.round(recipe.resize.width), Math.round(recipe.resize.height), { fit: 'fill' });
|
|
323
|
+
}
|
|
324
|
+
pipeline = applyColor(p, recipe);
|
|
325
|
+
} else {
|
|
326
|
+
// No rotation/flip: stay lazy. `.rotate()` auto-orients via EXIF before
|
|
327
|
+
// extract, so crop coordinates still map to the displayed image.
|
|
328
|
+
let p = sharp(sourcePath).rotate();
|
|
329
|
+
if (recipe.crop) {
|
|
330
|
+
p = p.extract(boundCrop(recipe.crop, orientedWidth, orientedHeight));
|
|
331
|
+
}
|
|
332
|
+
if (recipe.resize) {
|
|
333
|
+
p = p.resize(Math.round(recipe.resize.width), Math.round(recipe.resize.height), { fit: 'fill' });
|
|
334
|
+
}
|
|
335
|
+
pipeline = applyColor(p, recipe);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
const { data, info } = await encodeToBuffer(pipeline, recipe.output, fast);
|
|
340
|
+
|
|
341
|
+
// Guard against producing an output larger than the admin file-size limit.
|
|
342
|
+
validateFileSize(data.length);
|
|
343
|
+
|
|
344
|
+
return {
|
|
345
|
+
data,
|
|
346
|
+
format: info.format,
|
|
347
|
+
width: info.width,
|
|
348
|
+
height: info.height,
|
|
349
|
+
size: data.length
|
|
350
|
+
};
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
/**
|
|
354
|
+
* Encode to a Buffer. For lossy PNG we render both palette-quantized and
|
|
355
|
+
* lossless variants and keep the smaller one — palette quantization shrinks
|
|
356
|
+
* photographic PNGs dramatically but can *grow* smooth/continuous-tone images,
|
|
357
|
+
* so "compress" must never increase the size.
|
|
358
|
+
*/
|
|
359
|
+
async function encodeToBuffer(
|
|
360
|
+
pipeline: Sharp,
|
|
361
|
+
output: ImageEditRecipe['output'],
|
|
362
|
+
fast = false
|
|
363
|
+
): Promise<{ data: Buffer; info: { format: string; width: number; height: number } }> {
|
|
364
|
+
if (output.format === 'png' && (output.compress ?? false) && !output.lossless) {
|
|
365
|
+
const quality = output.quality ?? 80;
|
|
366
|
+
// Estimate path: a single fast palette encode instead of the dual
|
|
367
|
+
// palette/lossless comparison (which is too slow on large images).
|
|
368
|
+
if (fast) {
|
|
369
|
+
return pipeline
|
|
370
|
+
.png({ palette: true, quality, dither: 1, effort: 1, compressionLevel: 6 })
|
|
371
|
+
.toBuffer({ resolveWithObject: true });
|
|
372
|
+
}
|
|
373
|
+
const [palette, lossless] = await Promise.all([
|
|
374
|
+
pipeline
|
|
375
|
+
.clone()
|
|
376
|
+
.png({ palette: true, quality, dither: 1, effort: 10, compressionLevel: 9 })
|
|
377
|
+
.toBuffer({ resolveWithObject: true }),
|
|
378
|
+
pipeline.clone().png({ compressionLevel: 9, effort: 10 }).toBuffer({ resolveWithObject: true })
|
|
379
|
+
]);
|
|
380
|
+
return palette.data.length <= lossless.data.length ? palette : lossless;
|
|
381
|
+
}
|
|
382
|
+
return encode(pipeline, output, fast).toBuffer({ resolveWithObject: true });
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** Clamp a crop rectangle so it always sits within the image bounds. */
|
|
386
|
+
function boundCrop(
|
|
387
|
+
crop: NonNullable<ImageEditRecipe['crop']>,
|
|
388
|
+
imgWidth: number,
|
|
389
|
+
imgHeight: number
|
|
390
|
+
): { left: number; top: number; width: number; height: number } {
|
|
391
|
+
const left = clampInt(crop.left, 0, Math.max(0, imgWidth - 1));
|
|
392
|
+
const top = clampInt(crop.top, 0, Math.max(0, imgHeight - 1));
|
|
393
|
+
const width = clampInt(crop.width, 1, imgWidth - left);
|
|
394
|
+
const height = clampInt(crop.height, 1, imgHeight - top);
|
|
395
|
+
return { left, top, width, height };
|
|
396
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Files Image Edit Operation
|
|
3
|
+
*
|
|
4
|
+
* Applies a declarative `ImageEditRecipe` (crop/resize/rotate/flip/filters/
|
|
5
|
+
* compression) to an image on disk with sharp and writes the result either back
|
|
6
|
+
* over the original or to a new copy.
|
|
7
|
+
*
|
|
8
|
+
* The recipe is small JSON and the source is read server-side from disk, so no
|
|
9
|
+
* large binary crosses the wire in either direction — this fits the existing
|
|
10
|
+
* WS-http router rather than the streaming HTTP upload route.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { t } from 'elysia';
|
|
14
|
+
import { stat as fsStat } from 'node:fs/promises';
|
|
15
|
+
|
|
16
|
+
import { createRouter } from '$shared/utils/ws-server';
|
|
17
|
+
import { debug } from '$shared/utils/logger';
|
|
18
|
+
import type { ImageEditRecipe } from '$shared/types/filesystem';
|
|
19
|
+
import { processImageEdit } from '../../files/image-processing';
|
|
20
|
+
import { requireFilePathAccess } from './path-access';
|
|
21
|
+
|
|
22
|
+
const cropSchema = t.Object({
|
|
23
|
+
left: t.Number(),
|
|
24
|
+
top: t.Number(),
|
|
25
|
+
width: t.Number(),
|
|
26
|
+
height: t.Number()
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
const recipeSchema = t.Object({
|
|
30
|
+
crop: t.Optional(cropSchema),
|
|
31
|
+
resize: t.Optional(t.Object({ width: t.Number(), height: t.Number() })),
|
|
32
|
+
rotate: t.Optional(
|
|
33
|
+
t.Union([t.Literal(0), t.Literal(90), t.Literal(180), t.Literal(270)])
|
|
34
|
+
),
|
|
35
|
+
flipH: t.Optional(t.Boolean()),
|
|
36
|
+
flipV: t.Optional(t.Boolean()),
|
|
37
|
+
brightness: t.Optional(t.Number()),
|
|
38
|
+
saturation: t.Optional(t.Number()),
|
|
39
|
+
contrast: t.Optional(t.Number()),
|
|
40
|
+
hue: t.Optional(t.Number()),
|
|
41
|
+
blur: t.Optional(t.Number()),
|
|
42
|
+
grayscale: t.Optional(t.Boolean()),
|
|
43
|
+
sepia: t.Optional(t.Boolean()),
|
|
44
|
+
invert: t.Optional(t.Boolean()),
|
|
45
|
+
background: t.Optional(t.String()),
|
|
46
|
+
regions: t.Optional(
|
|
47
|
+
t.Array(
|
|
48
|
+
t.Object({
|
|
49
|
+
type: t.Union([t.Literal('blur'), t.Literal('pixelate')]),
|
|
50
|
+
left: t.Number(),
|
|
51
|
+
top: t.Number(),
|
|
52
|
+
width: t.Number(),
|
|
53
|
+
height: t.Number(),
|
|
54
|
+
strength: t.Number()
|
|
55
|
+
})
|
|
56
|
+
)
|
|
57
|
+
),
|
|
58
|
+
annotations: t.Optional(
|
|
59
|
+
t.Array(
|
|
60
|
+
t.Object({
|
|
61
|
+
color: t.String(),
|
|
62
|
+
size: t.Number(),
|
|
63
|
+
opacity: t.Optional(t.Number()),
|
|
64
|
+
points: t.Array(t.Object({ x: t.Number(), y: t.Number() }))
|
|
65
|
+
})
|
|
66
|
+
)
|
|
67
|
+
),
|
|
68
|
+
output: t.Object({
|
|
69
|
+
format: t.Union([
|
|
70
|
+
t.Literal('png'),
|
|
71
|
+
t.Literal('jpeg'),
|
|
72
|
+
t.Literal('webp'),
|
|
73
|
+
t.Literal('gif'),
|
|
74
|
+
t.Literal('avif')
|
|
75
|
+
]),
|
|
76
|
+
compress: t.Optional(t.Boolean()),
|
|
77
|
+
quality: t.Optional(t.Number()),
|
|
78
|
+
lossless: t.Optional(t.Boolean())
|
|
79
|
+
})
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
export const imageEditHandler = createRouter()
|
|
83
|
+
// Dry-run: apply the recipe and report the resulting byte size without
|
|
84
|
+
// writing anything — drives the editor's live "Result size" readout, so it
|
|
85
|
+
// matches the real save exactly (same codec) instead of a browser estimate.
|
|
86
|
+
.http('files:estimate-image', {
|
|
87
|
+
data: t.Object({
|
|
88
|
+
sourcePath: t.String(),
|
|
89
|
+
recipe: recipeSchema
|
|
90
|
+
}),
|
|
91
|
+
response: t.Object({
|
|
92
|
+
size: t.Number(),
|
|
93
|
+
width: t.Number(),
|
|
94
|
+
height: t.Number()
|
|
95
|
+
})
|
|
96
|
+
}, async ({ data, conn }) => {
|
|
97
|
+
const sourcePath = await requireFilePathAccess(conn, data.sourcePath);
|
|
98
|
+
// Fast mode: lower encoder effort so the live estimate stays responsive
|
|
99
|
+
// on very large images / upscales. The real save uses full effort.
|
|
100
|
+
const result = await processImageEdit(sourcePath, data.recipe as ImageEditRecipe, true);
|
|
101
|
+
return { size: result.size, width: result.width, height: result.height };
|
|
102
|
+
})
|
|
103
|
+
|
|
104
|
+
.http('files:edit-image', {
|
|
105
|
+
data: t.Object({
|
|
106
|
+
sourcePath: t.String(),
|
|
107
|
+
targetPath: t.String(),
|
|
108
|
+
// true = write over targetPath even if it exists; false = refuse if it exists.
|
|
109
|
+
overwrite: t.Boolean(),
|
|
110
|
+
recipe: recipeSchema,
|
|
111
|
+
// Optimistic concurrency token: the disk mtime the editor based its
|
|
112
|
+
// source on. Only checked when overwriting an existing file.
|
|
113
|
+
baseModified: t.Optional(t.String())
|
|
114
|
+
}),
|
|
115
|
+
response: t.Object({
|
|
116
|
+
message: t.String(),
|
|
117
|
+
path: t.String(),
|
|
118
|
+
size: t.Number(),
|
|
119
|
+
width: t.Number(),
|
|
120
|
+
height: t.Number(),
|
|
121
|
+
modified: t.String()
|
|
122
|
+
})
|
|
123
|
+
}, async ({ data, conn }) => {
|
|
124
|
+
const sourcePath = await requireFilePathAccess(conn, data.sourcePath);
|
|
125
|
+
const targetPath = await requireFilePathAccess(conn, data.targetPath);
|
|
126
|
+
|
|
127
|
+
const targetStat = await fsStat(targetPath).catch(() => null);
|
|
128
|
+
|
|
129
|
+
if (data.overwrite) {
|
|
130
|
+
// Refuse to clobber a version newer than the one the editor loaded.
|
|
131
|
+
if (targetStat && data.baseModified && targetStat.mtime.toISOString() !== data.baseModified) {
|
|
132
|
+
throw new Error('FILE_CONFLICT: file changed on disk since it was opened in the editor');
|
|
133
|
+
}
|
|
134
|
+
} else if (targetStat) {
|
|
135
|
+
throw new Error('File already exists');
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const recipe = data.recipe as ImageEditRecipe;
|
|
139
|
+
debug.log('file', 'Edit image operation:', {
|
|
140
|
+
sourcePath,
|
|
141
|
+
targetPath,
|
|
142
|
+
overwrite: data.overwrite,
|
|
143
|
+
format: recipe.output.format
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
const result = await processImageEdit(sourcePath, recipe);
|
|
147
|
+
await Bun.write(targetPath, result.data);
|
|
148
|
+
|
|
149
|
+
const stats = await fsStat(targetPath);
|
|
150
|
+
return {
|
|
151
|
+
message: data.overwrite ? 'Image saved successfully' : 'Image saved as a new file',
|
|
152
|
+
path: targetPath,
|
|
153
|
+
size: result.size,
|
|
154
|
+
width: result.width,
|
|
155
|
+
height: result.height,
|
|
156
|
+
modified: stats.mtime.toISOString()
|
|
157
|
+
};
|
|
158
|
+
});
|
|
@@ -13,6 +13,7 @@
|
|
|
13
13
|
import { createRouter } from '$shared/utils/ws-server';
|
|
14
14
|
import { readHandler } from './read';
|
|
15
15
|
import { writeHandler } from './write';
|
|
16
|
+
import { imageEditHandler } from './image-edit';
|
|
16
17
|
import { fileSearchHandler } from './search';
|
|
17
18
|
import { watchHandler } from './watch';
|
|
18
19
|
import { filesStateHandler } from './state';
|
|
@@ -24,6 +25,9 @@ export const filesRouter = createRouter()
|
|
|
24
25
|
// Write Operations (HTTP)
|
|
25
26
|
.merge(writeHandler)
|
|
26
27
|
|
|
28
|
+
// Image Edit Operation (HTTP)
|
|
29
|
+
.merge(imageEditHandler)
|
|
30
|
+
|
|
27
31
|
// Search Operations (HTTP)
|
|
28
32
|
.merge(fileSearchHandler)
|
|
29
33
|
|
package/backend/ws/files/read.ts
CHANGED
|
@@ -218,7 +218,11 @@ export const readHandler = createRouter()
|
|
|
218
218
|
}),
|
|
219
219
|
response: t.Object({
|
|
220
220
|
content: t.String(), // Base64 encoded binary content
|
|
221
|
-
contentType: t.String()
|
|
221
|
+
contentType: t.String(),
|
|
222
|
+
// Disk mtime + size — used by the image editor as an optimistic
|
|
223
|
+
// concurrency token and to report compression savings.
|
|
224
|
+
modified: t.Optional(t.String()),
|
|
225
|
+
size: t.Optional(t.Number())
|
|
222
226
|
})
|
|
223
227
|
}, async ({ data, conn }) => {
|
|
224
228
|
const path = await requireFilePathAccess(conn, data.path);
|
|
@@ -239,8 +243,12 @@ export const readHandler = createRouter()
|
|
|
239
243
|
// Detect content type
|
|
240
244
|
const contentType = file.type || 'application/octet-stream';
|
|
241
245
|
|
|
246
|
+
const stats = await file.stat();
|
|
247
|
+
|
|
242
248
|
return {
|
|
243
249
|
content: base64,
|
|
244
|
-
contentType
|
|
250
|
+
contentType,
|
|
251
|
+
modified: stats.mtime.toISOString(),
|
|
252
|
+
size: stats.size
|
|
245
253
|
};
|
|
246
254
|
});
|