@hussmartinez/image-sdk 0.3.0 → 0.5.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.
@@ -1,1612 +0,0 @@
1
- import { SdkError, applyCommands, coreLimits, createAssetsResolver, createErrorHelpers, createHistory, createStore, createWorkerClient, defineLimits, defineMessages, isSdkError, plural, sdkCoreMessages, withProcessingTime } from "@hussmartinez/sdk-core";
2
- import { uiMessages } from "@hussmartinez/ui";
3
- // src/core/errors/image-error.ts
4
- var ImageError = class extends SdkError {
5
- name = "ImageError";
6
- };
7
- function isImageError(value, code) {
8
- return isSdkError(value, code) && value.name === "ImageError";
9
- }
10
- // src/core/errors/error-helpers.ts
11
- var { adapt: asImageError, abortError, throwIfAborted } = createErrorHelpers(ImageError, {
12
- fallbackCode: "UNKNOWN",
13
- fallbackMessage: "Image processing failed."
14
- });
15
- // src/core/errors/image-limits.ts
16
- var imageLimitDefinitions = {
17
- ...coreLimits,
18
- maxDecodedSize: {
19
- ...coreLimits.maxDecodedSize,
20
- default: 1e9,
21
- warning: 4e8
22
- },
23
- maxImagePixels: {
24
- code: "IMAGE_TOO_LARGE",
25
- unit: "pixels",
26
- default: 5e7,
27
- warning: 24e6
28
- },
29
- maxImageDimension: {
30
- code: "IMAGE_DIMENSION_TOO_LARGE",
31
- unit: "pixels",
32
- default: 16384
33
- },
34
- maxFrames: {
35
- code: "TOO_MANY_FRAMES",
36
- unit: "count",
37
- default: 300,
38
- warning: 100
39
- },
40
- maxSessionSize: {
41
- code: "SESSION_TOO_LARGE",
42
- unit: "bytes",
43
- default: 1e9,
44
- warning: 5e8
45
- },
46
- maxLayers: {
47
- code: "TOO_MANY_LAYERS",
48
- unit: "count",
49
- default: 256
50
- }
51
- };
52
- var imageLimits = /* @__PURE__ */ defineLimits(imageLimitDefinitions, { errorClass: ImageError });
53
- var PER_FILE_LIMITS = [
54
- "maxFileSize",
55
- "maxImageDimension",
56
- "maxImagePixels",
57
- "maxFrames",
58
- "maxDecodedSize"
59
- ];
60
- function checkFileLimits(policy, fileSize, probe) {
61
- const { width, height } = probe.oriented;
62
- const actual = {
63
- maxFileSize: fileSize,
64
- maxImageDimension: Math.max(width, height),
65
- maxImagePixels: width * height,
66
- maxFrames: probe.frames,
67
- maxDecodedSize: probe.decodedPixelBound * 4
68
- };
69
- return PER_FILE_LIMITS.filter((limit) => policy.check(limit, actual[limit]) === "warning");
70
- }
71
- var OUTPUT_LIMITS = ["maxImageDimension", "maxImagePixels"];
72
- function checkOutputLimits(policy, size) {
73
- policy.check("maxImageDimension", Math.max(size.width, size.height));
74
- policy.check("maxImagePixels", size.width * size.height);
75
- }
76
- // src/adapters/worker-lifecycle.ts
77
- function createWorkerLifecycle(clearSources, submitted) {
78
- let current;
79
- let sequence = 0;
80
- let terminal = false;
81
- let destroyed = false;
82
- const listeners = /* @__PURE__ */ new Set();
83
- const invalidated = () => new ImageError("WORKER_TERMINATED", "Recreate the image engine before reopening the image.", { details: { reason: "engine-invalidated" } });
84
- const check = (generation) => {
85
- if (destroyed) throw new Error("The image engine has been destroyed.");
86
- if (terminal || generation && (generation.closed || generation !== current)) throw invalidated();
87
- };
88
- return {
89
- check,
90
- current: () => current,
91
- getSnapshot: () => terminal,
92
- subscribe(listener) {
93
- const notify = () => listener();
94
- listeners.add(notify);
95
- return () => {
96
- listeners.delete(notify);
97
- };
98
- },
99
- destroy() {
100
- destroyed = true;
101
- listeners.clear();
102
- clearSources();
103
- },
104
- wrap(worker) {
105
- check();
106
- const generation = {
107
- number: ++sequence,
108
- closed: false,
109
- ownsResources: false
110
- };
111
- current = generation;
112
- return {
113
- postMessage(message, transfer) {
114
- check(generation);
115
- const call = message;
116
- if (call?.type === "call" && (call.method === "register" || call.method === "attachCanvas")) generation.ownsResources = true;
117
- if (call?.type === "call" && call.method === "register" && typeof call.input?.id === "string") submitted(call.input.id, generation);
118
- worker.postMessage(message, transfer);
119
- },
120
- addEventListener(type, listener) {
121
- worker.addEventListener(type, listener);
122
- },
123
- removeEventListener(type, listener) {
124
- worker.removeEventListener(type, listener);
125
- },
126
- terminate() {
127
- if (generation.closed) return;
128
- generation.closed = true;
129
- try {
130
- if (current !== generation) return;
131
- clearSources();
132
- if (destroyed || !generation.ownsResources || terminal) return;
133
- terminal = true;
134
- const notified = [...listeners];
135
- queueMicrotask(() => {
136
- if (destroyed) return;
137
- for (const listener of notified) {
138
- if (!listeners.has(listener)) continue;
139
- try {
140
- listener();
141
- } catch {}
142
- }
143
- });
144
- } finally {
145
- worker.terminate();
146
- }
147
- }
148
- };
149
- }
150
- };
151
- }
152
- function closeRejectedResult(value) {
153
- if (value && typeof value === "object" && "close" in value && typeof value.close === "function") try {
154
- value.close();
155
- } catch {}
156
- }
157
- // src/adapters/image-engine.ts
158
- var ENGINE_INTERNALS = Symbol("hm-image-engine");
159
- function engineInternals(engine) {
160
- return engine[ENGINE_INTERNALS];
161
- }
162
- function createImageEngine(options = {}) {
163
- const asset = options.assetsUrl === void 0 ? void 0 : createAssetsResolver(options.assetsUrl);
164
- let workerUrl;
165
- return createEngine({
166
- loadWorker: asset ? async () => () => {
167
- workerUrl = asset("image/render.worker.js");
168
- return new Worker(workerUrl, {
169
- type: "module",
170
- name: "hm-image-render"
171
- });
172
- } : async () => (await import("../lazy/inline-worker-l_ynDNuS.js")).createInlineWorker,
173
- version: "0.3.0",
174
- get asset() {
175
- return workerUrl ?? "inline";
176
- }
177
- });
178
- }
179
- function createEngine(environment) {
180
- let startWorker;
181
- let destroyed = false;
182
- const ids = /* @__PURE__ */ new Map();
183
- const lifecycle = createWorkerLifecycle(() => ids.clear(), (id, generation) => {
184
- const reservation = ids.get(id);
185
- if (reservation) reservation.generation = generation;
186
- });
187
- const client = createWorkerClient({
188
- createWorker: () => {
189
- if (!startWorker) throw new ImageError("WORKER_START_FAILED", "The render worker hasn't loaded.");
190
- return lifecycle.wrap(startWorker());
191
- },
192
- errorClasses: { ImageError },
193
- idleTimeout: 0,
194
- cancelTimeout: 3e4,
195
- packageVersion: environment.version,
196
- get workerAsset() {
197
- return environment.asset ?? "inline";
198
- }
199
- });
200
- async function ready() {
201
- if (destroyed) throw new Error("The image engine has been destroyed.");
202
- startWorker ??= await environment.loadWorker();
203
- }
204
- const call = async (method, input, options) => {
205
- lifecycle.check();
206
- throwIfAborted(options?.signal);
207
- await ready();
208
- lifecycle.check();
209
- const pending = client.call(method, input, options);
210
- const generation = lifecycle.current();
211
- const result = await pending.catch((error) => {
212
- throw error instanceof TypeError ? error : asImageError(error);
213
- });
214
- try {
215
- lifecycle.check(generation);
216
- } catch (error) {
217
- closeRejectedResult(result);
218
- throw error;
219
- }
220
- return result;
221
- };
222
- const prepare = async () => {
223
- lifecycle.check();
224
- await ready();
225
- lifecycle.check();
226
- const pending = client.start();
227
- const generation = lifecycle.current();
228
- try {
229
- await pending;
230
- } catch (error) {
231
- throw asImageError(error);
232
- }
233
- lifecycle.check(generation);
234
- if (!generation) throw new Error("The worker did not create a generation.");
235
- return generation;
236
- };
237
- const callOptions = (options) => options?.signal ? { signal: options.signal } : {};
238
- return {
239
- [ENGINE_INTERNALS]: {
240
- call,
241
- prepare,
242
- check: lifecycle.check,
243
- getSnapshot: lifecycle.getSnapshot,
244
- subscribe: lifecycle.subscribe,
245
- has: (id) => ids.get(id)?.registered === true
246
- },
247
- probe(file, options) {
248
- return call("probe", { file }, callOptions(options));
249
- },
250
- async register(id, file, probe, options) {
251
- lifecycle.check();
252
- if (ids.has(id)) throw new TypeError(`The source id "${id}" is already in use.`);
253
- const reservation = {
254
- registered: false,
255
- released: false
256
- };
257
- ids.set(id, reservation);
258
- try {
259
- const size = await call("register", {
260
- id,
261
- file,
262
- probe,
263
- limits: Object.fromEntries(PER_FILE_LIMITS.map((limit) => [limit, (options?.filePolicy ?? imageLimits.resolve()).limits[limit].maximum]))
264
- }, callOptions(options));
265
- lifecycle.check(reservation.generation);
266
- if (reservation.released) throw new TypeError("The source was released during registration.");
267
- reservation.registered = true;
268
- options?.onProgress?.(1);
269
- lifecycle.check(reservation.generation);
270
- return {
271
- id,
272
- format: probe.format,
273
- width: size.width,
274
- height: size.height,
275
- frames: 1,
276
- hasAlpha: probe.hasAlpha,
277
- decodedBytes: size.width * size.height * 4
278
- };
279
- } catch (error) {
280
- if (ids.get(id) === reservation) ids.delete(id);
281
- if ((options?.signal?.aborted || reservation.released) && reservation.generation && !reservation.generation.closed && !destroyed && !lifecycle.getSnapshot()) call("release", { id }).catch(() => void 0);
282
- throw error;
283
- }
284
- },
285
- async thumbnail(id, maxSize, options) {
286
- lifecycle.check();
287
- if (!ids.get(id)?.registered) throw new TypeError(`There's no source with the id "${id}".`);
288
- if (!(maxSize >= 1)) throw new RangeError("maxSize must be at least 1.");
289
- return call("thumbnail", {
290
- id,
291
- maxSize
292
- }, callOptions(options));
293
- },
294
- async release(id) {
295
- const reservation = ids.get(id);
296
- if (!reservation) return;
297
- if (!reservation.registered) {
298
- reservation.released = true;
299
- return;
300
- }
301
- ids.delete(id);
302
- if (destroyed || lifecycle.getSnapshot() || reservation.generation?.closed) return;
303
- await call("release", { id });
304
- },
305
- async destroy() {
306
- if (destroyed) return;
307
- destroyed = true;
308
- lifecycle.destroy();
309
- client.destroy();
310
- }
311
- };
312
- }
313
- // src/adapters/image-processor.ts
314
- var FORMATS = /* @__PURE__ */ new Set([
315
- "png",
316
- "jpeg",
317
- "webp"
318
- ]);
319
- function createImageProcessor(engine) {
320
- const internals = engineInternals(engine);
321
- if (!internals) throw new TypeError("createImageProcessor needs an engine from createImageEngine.");
322
- let destroyed = false;
323
- return {
324
- async export(job, options) {
325
- if (destroyed) throw new Error("The image processor has been destroyed.");
326
- const { plan, format } = job;
327
- if (!FORMATS.has(format.type)) throw new TypeError(`"${String(format.type)}" isn't an export format.`);
328
- if (format.type !== "png" && format.quality !== void 0) {
329
- if (!(format.quality >= 0 && format.quality <= 1)) throw new RangeError("quality must be from 0 to 1.");
330
- }
331
- internals.check();
332
- if (!internals.has(plan.base.source)) throw new TypeError(`There's no source with the id "${plan.base.source}".`);
333
- const signal = options?.signal;
334
- throwIfAborted(signal);
335
- const policy = options?.filePolicy ?? imageLimits.resolve();
336
- try {
337
- const blob = await internals.call("export", {
338
- plan,
339
- format,
340
- limits: Object.fromEntries(OUTPUT_LIMITS.map((limit) => [limit, policy.limits[limit].maximum]))
341
- }, signal ? { signal } : {});
342
- options?.onProgress?.(1);
343
- internals.check();
344
- return blob;
345
- } catch (error) {
346
- if (error instanceof TypeError) throw error;
347
- throw asImageError(error);
348
- }
349
- },
350
- async destroy() {
351
- destroyed = true;
352
- }
353
- };
354
- }
355
- // src/core/ports/image-renderer.ts
356
- var MAX_PIXEL_RATIO = 4;
357
- function backingSize(view) {
358
- const ratio = Math.min(view.pixelRatio, 4);
359
- return {
360
- width: Math.max(1, Math.round(view.width * ratio)),
361
- height: Math.max(1, Math.round(view.height * ratio))
362
- };
363
- }
364
- function fittedView(width, height, pixelRatio = 1) {
365
- return {
366
- width,
367
- height,
368
- pixelRatio,
369
- zoom: 1,
370
- pan: {
371
- x: 0,
372
- y: 0
373
- }
374
- };
375
- }
376
- function placement(composition, view) {
377
- const inset = view.inset ?? 0;
378
- const fit = Math.min((view.width - 2 * inset) / composition.width, (view.height - 2 * inset) / composition.height);
379
- const scale = Math.max(0, fit) * view.zoom;
380
- const width = composition.width * scale;
381
- const height = composition.height * scale;
382
- return {
383
- x: (view.width - width) / 2 + view.pan.x,
384
- y: (view.height - height) / 2 + view.pan.y,
385
- width,
386
- height,
387
- scale
388
- };
389
- }
390
- // src/adapters/image-renderer.ts
391
- var RENDERER_INTERNALS = Symbol("hm-image-renderer");
392
- var nextCanvasId = 0;
393
- function checkView(view) {
394
- const positive = (n) => Number.isFinite(n) && n > 0;
395
- if (!positive(view.width) || !positive(view.height) || !positive(view.pixelRatio) || !positive(view.zoom) || !Number.isFinite(view.pan.x) || !Number.isFinite(view.pan.y) || view.inset !== void 0 && !(view.inset >= 0 && 2 * view.inset < Math.min(view.width, view.height))) throw new RangeError("A view needs a positive size, pixel ratio and zoom, a finite pan, and an inset under half its size.");
396
- }
397
- function createImageRenderer(engine) {
398
- const internals = engineInternals(engine);
399
- if (!internals) throw new TypeError("createImageRenderer needs an engine from createImageEngine.");
400
- nextCanvasId += 1;
401
- const id = `preview-${nextCanvasId}`;
402
- let attached = false;
403
- let destroyed = false;
404
- let drawn = 0;
405
- let pending;
406
- let inFlight;
407
- const pump = () => {
408
- if (inFlight || !pending) return;
409
- const request = pending;
410
- pending = void 0;
411
- const controller = new AbortController();
412
- const onAbort = () => controller.abort(request.signal?.reason);
413
- request.signal?.addEventListener("abort", onAbort, { once: true });
414
- inFlight = { controller };
415
- internals.call("render", {
416
- id,
417
- plan: request.plan,
418
- view: request.view,
419
- limits: request.limits
420
- }, { signal: controller.signal }).then(() => {
421
- try {
422
- internals.check();
423
- } catch (error) {
424
- request.reject(error);
425
- return;
426
- }
427
- drawn += 1;
428
- request.resolve("drawn");
429
- }, (error) => {
430
- if (!internals.getSnapshot() && controller.signal.aborted && !request.signal?.aborted && isImageError(error, "ABORTED")) request.resolve("superseded");
431
- else request.reject(error instanceof TypeError ? error : asImageError(error));
432
- }).finally(() => {
433
- request.signal?.removeEventListener("abort", onAbort);
434
- inFlight = void 0;
435
- pump();
436
- });
437
- };
438
- return {
439
- [RENDERER_INTERNALS]: {
440
- snapshot: async () => internals.call("snapshot", { id }),
441
- drawn: () => drawn
442
- },
443
- async attach(canvas) {
444
- if (destroyed) throw new Error("The image renderer has been destroyed.");
445
- internals.check();
446
- if (attached) throw new TypeError("The renderer already has a canvas.");
447
- if (typeof canvas.transferControlToOffscreen !== "function") throw new ImageError("UNSUPPORTED_ENVIRONMENT", "This browser can't draw the preview in a worker.", { details: { feature: "transferControlToOffscreen" } });
448
- try {
449
- const generation = await internals.prepare();
450
- internals.check(generation);
451
- if (destroyed) throw new Error("The image renderer has been destroyed.");
452
- const offscreen = canvas.transferControlToOffscreen();
453
- await internals.call("attachCanvas", {
454
- id,
455
- canvas: offscreen
456
- }, { transfer: true });
457
- internals.check(generation);
458
- if (destroyed) {
459
- await internals.call("detachCanvas", { id });
460
- throw new Error("The image renderer has been destroyed.");
461
- }
462
- attached = true;
463
- } catch (error) {
464
- throw asImageError(error);
465
- }
466
- },
467
- render(plan, view, options) {
468
- if (destroyed) return Promise.reject(/* @__PURE__ */ new Error("The image renderer has been destroyed."));
469
- try {
470
- internals.check();
471
- } catch (error) {
472
- return Promise.reject(error);
473
- }
474
- if (!attached) return Promise.reject(/* @__PURE__ */ new TypeError("Attach a canvas before rendering."));
475
- if (!internals.has(plan.base.source)) return Promise.reject(/* @__PURE__ */ new TypeError(`There's no source with the id "${plan.base.source}".`));
476
- const policy = options?.filePolicy ?? imageLimits.resolve();
477
- try {
478
- checkView(view);
479
- checkOutputLimits(policy, backingSize(view));
480
- throwIfAborted(options?.signal);
481
- } catch (error) {
482
- return Promise.reject(error);
483
- }
484
- const limits = Object.fromEntries(OUTPUT_LIMITS.map((limit) => [limit, policy.limits[limit].maximum]));
485
- return new Promise((resolve, reject) => {
486
- pending?.resolve("superseded");
487
- pending = {
488
- plan,
489
- view,
490
- resolve,
491
- reject,
492
- signal: options?.signal,
493
- limits
494
- };
495
- inFlight?.controller.abort(new DOMException("A later render replaced this one.", "AbortError"));
496
- pump();
497
- });
498
- },
499
- async destroy() {
500
- if (destroyed) return;
501
- destroyed = true;
502
- if (pending) try {
503
- internals.check();
504
- pending.resolve("superseded");
505
- } catch (error) {
506
- pending.reject(error);
507
- }
508
- pending = void 0;
509
- inFlight?.controller.abort(new DOMException("The renderer was destroyed.", "AbortError"));
510
- if (attached && !internals.getSnapshot()) try {
511
- await internals.call("detachCanvas", { id });
512
- } catch {}
513
- }
514
- };
515
- }
516
- // src/core/model/plan.ts
517
- var DEVELOP_ADJUSTMENTS = [
518
- "temperature",
519
- "tint",
520
- "exposure",
521
- "highlights",
522
- "shadows",
523
- "contrast",
524
- "saturation",
525
- "vibrance"
526
- ];
527
- var NEUTRAL_DEVELOP = Object.freeze({
528
- temperature: 0,
529
- tint: 0,
530
- exposure: 0,
531
- highlights: 0,
532
- shadows: 0,
533
- contrast: 0,
534
- saturation: 0,
535
- vibrance: 0
536
- });
537
- var FILTER_PRESETS = [
538
- "vivid",
539
- "warm",
540
- "cool",
541
- "fade",
542
- "mono",
543
- "noir",
544
- "sepia"
545
- ];
546
- var UPRIGHT = Object.freeze({
547
- rotate: 0,
548
- flipX: false,
549
- flipY: false
550
- });
551
- var FULL_SIZE = Object.freeze({
552
- kind: "scale",
553
- scale: 1
554
- });
555
- function createPlan(source) {
556
- return {
557
- base: {
558
- source,
559
- crop: null,
560
- orientation: UPRIGHT,
561
- develop: NEUTRAL_DEVELOP,
562
- filter: null
563
- },
564
- output: FULL_SIZE,
565
- metadata: {
566
- title: "",
567
- description: "",
568
- artist: "",
569
- copyright: ""
570
- }
571
- };
572
- }
573
- function isValidCrop(crop, source) {
574
- const { x, y, width, height } = crop;
575
- return [
576
- x,
577
- y,
578
- width,
579
- height
580
- ].every(Number.isSafeInteger) && x >= 0 && y >= 0 && width >= 1 && height >= 1 && x + width <= source.width && y + height <= source.height;
581
- }
582
- // src/core/model/source.ts
583
- var NO_METADATA = Object.freeze({
584
- location: false,
585
- camera: false,
586
- timestamps: false,
587
- thumbnail: false,
588
- colourProfile: false,
589
- other: false
590
- });
591
- var EMPTY_KEEPABLE_METADATA = Object.freeze({
592
- title: "",
593
- description: "",
594
- artist: "",
595
- copyright: ""
596
- });
597
- var MAX_METADATA_LENGTH = 2e3;
598
- function longerThan(text, max) {
599
- if (text.length <= max) return false;
600
- let count = 0;
601
- for (const _ of text) {
602
- count += 1;
603
- if (count > max) return true;
604
- }
605
- return false;
606
- }
607
- // src/core/operations/commands.ts
608
- var Invalid = class extends Error {
609
- reason;
610
- constructor(reason, message) {
611
- super(message);
612
- this.reason = reason;
613
- }
614
- };
615
- function invalid(reason, message) {
616
- throw new Invalid(reason, message);
617
- }
618
- var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
619
- function onlyFields(value, fields, what) {
620
- for (const name of Object.keys(value)) if (!fields.includes(name)) invalid("malformed-command", `${what} has no field "${name}"`);
621
- }
622
- function allFields(value, fields, what) {
623
- onlyFields(value, fields, what);
624
- for (const name of fields) if (!Object.hasOwn(value, name)) invalid("malformed-command", `${what} needs "${name}"`);
625
- }
626
- var isWhole = (value, min, max = Number.MAX_SAFE_INTEGER) => Number.isSafeInteger(value) && value >= min && value <= max;
627
- function checkCrop(value) {
628
- if (!isRecord(value)) invalid("malformed-command", "a crop is an object");
629
- allFields(value, [
630
- "x",
631
- "y",
632
- "width",
633
- "height"
634
- ], "a crop");
635
- const { x, y, width, height } = value;
636
- if (!isWhole(x, 0) || !isWhole(y, 0) || !isWhole(width, 1) || !isWhole(height, 1)) invalid("malformed-command", "a crop is whole pixels from 0, at least 1 × 1");
637
- return {
638
- x,
639
- y,
640
- width,
641
- height
642
- };
643
- }
644
- function checkCropInSource(crop, source) {
645
- if (!isValidCrop(crop, source)) invalid("crop-outside-source", "a crop must fit inside its source");
646
- }
647
- function checkOrientation(value) {
648
- if (!isRecord(value)) invalid("malformed-command", "an orientation is an object");
649
- allFields(value, [
650
- "rotate",
651
- "flipX",
652
- "flipY"
653
- ], "an orientation");
654
- const { rotate, flipX, flipY } = value;
655
- if (typeof flipX !== "boolean" || typeof flipY !== "boolean") invalid("malformed-command", "an orientation's flips are booleans");
656
- if (![
657
- 0,
658
- 90,
659
- 180,
660
- 270
661
- ].includes(rotate)) invalid("invalid-orientation", "a rotation is 0, 90, 180 or 270 degrees");
662
- return {
663
- rotate,
664
- flipX,
665
- flipY
666
- };
667
- }
668
- function checkOutput(value) {
669
- if (!isRecord(value)) invalid("malformed-command", "an output is an object");
670
- if (value.kind === "scale") {
671
- allFields(value, ["kind", "scale"], "a scale output");
672
- if (typeof value.scale !== "number") invalid("malformed-command", "a scale is a number");
673
- if (!(Number.isFinite(value.scale) && value.scale > 0 && value.scale <= 1)) invalid("invalid-output", "an output scale is more than 0 and at most 1");
674
- return {
675
- kind: "scale",
676
- scale: value.scale
677
- };
678
- }
679
- if (value.kind === "fit") {
680
- allFields(value, [
681
- "kind",
682
- "width",
683
- "height"
684
- ], "a box output");
685
- const { width, height } = value;
686
- if (!Number.isInteger(width) || !Number.isInteger(height)) invalid("malformed-command", "a box's width and height are whole numbers");
687
- if (!isWhole(width, 1) || !isWhole(height, 1)) invalid("invalid-output", "an output box is at least 1 × 1 pixel");
688
- return {
689
- kind: "fit",
690
- width,
691
- height
692
- };
693
- }
694
- return invalid("malformed-command", "an output is either a scale or a box to fit");
695
- }
696
- var METADATA_FIELDS = [
697
- "title",
698
- "description",
699
- "artist",
700
- "copyright"
701
- ];
702
- function checkMetadataValue(field, value) {
703
- if (typeof value !== "string") invalid("malformed-command", `metadata.${field} is text`);
704
- if (longerThan(value, 2e3)) invalid("metadata-too-long", `metadata.${field} has more than ${MAX_METADATA_LENGTH} code points`);
705
- return value;
706
- }
707
- function checkMetadata(value) {
708
- if (!isRecord(value)) invalid("malformed-command", "metadata is an object");
709
- allFields(value, METADATA_FIELDS, "metadata");
710
- return Object.fromEntries(METADATA_FIELDS.map((field) => [field, checkMetadataValue(field, value[field])]));
711
- }
712
- var ADJUSTMENTS = DEVELOP_ADJUSTMENTS;
713
- var PRESETS = FILTER_PRESETS;
714
- function checkDevelop(value, all = false) {
715
- if (!isRecord(value)) invalid("malformed-command", "develop values are an object");
716
- const values = {};
717
- for (const [name, level] of Object.entries(value)) {
718
- if (!ADJUSTMENTS.includes(name)) invalid("unknown-adjustment", `"${name}" isn't a develop adjustment`);
719
- if (typeof level !== "number") invalid("malformed-command", `${name} is a number`);
720
- if (!isWhole(level, -100, 100)) invalid("invalid-level", `${name} is a whole number from -100 to 100`);
721
- values[name] = level;
722
- }
723
- if (all) allFields(value, ADJUSTMENTS, "develop");
724
- return Object.fromEntries(DEVELOP_ADJUSTMENTS.filter((name) => name in values).map((name) => [name, values[name]]));
725
- }
726
- function checkFilter(value) {
727
- if (value === null) return null;
728
- if (!isRecord(value)) invalid("malformed-command", "a filter is an object or null");
729
- allFields(value, ["preset", "strength"], "a filter");
730
- if (typeof value.preset !== "string") invalid("malformed-command", "a filter's preset is text");
731
- if (!PRESETS.includes(value.preset)) invalid("unknown-preset", `a filter's preset is one of ${FILTER_PRESETS.join(", ")}`);
732
- if (typeof value.strength !== "number") invalid("malformed-command", "a filter's strength is a number");
733
- if (!isWhole(value.strength, 0, 100)) invalid("invalid-strength", "a filter's strength is a whole number from 0 to 100");
734
- return {
735
- preset: value.preset,
736
- strength: value.strength
737
- };
738
- }
739
- var COMMAND_FIELDS = {
740
- "image.setCrop": ["type", "crop"],
741
- "image.setOrientation": ["type", "orientation"],
742
- "image.setOutput": ["type", "output"],
743
- "image.setMetadata": [
744
- "type",
745
- "field",
746
- "value"
747
- ],
748
- "image.setDevelop": ["type", "values"],
749
- "image.setFilter": ["type", "filter"]
750
- };
751
- function apply(plan, input, sourceSize) {
752
- if (!isRecord(input)) invalid("malformed-command", "a command is an object");
753
- const { type } = input;
754
- if (typeof type !== "string") invalid("malformed-command", "a command's type is text");
755
- if (!Object.hasOwn(COMMAND_FIELDS, type)) invalid("unknown-command", `"${type}" isn't a command`);
756
- const command = input;
757
- allFields(command, COMMAND_FIELDS[command.type], `${command.type}`);
758
- switch (command.type) {
759
- case "image.setCrop": {
760
- const crop = command.crop === null ? null : checkCrop(command.crop);
761
- if (crop !== null) {
762
- const size = sourceSize(plan.base.source);
763
- if (size === void 0) invalid("unknown-source", `unknown source "${plan.base.source}"`);
764
- checkCropInSource(crop, size);
765
- }
766
- return {
767
- state: {
768
- ...plan,
769
- base: {
770
- ...plan.base,
771
- crop
772
- }
773
- },
774
- inverse: {
775
- type: "image.setCrop",
776
- crop: plan.base.crop
777
- }
778
- };
779
- }
780
- case "image.setOrientation": {
781
- const orientation = checkOrientation(command.orientation);
782
- return {
783
- state: {
784
- ...plan,
785
- base: {
786
- ...plan.base,
787
- orientation
788
- }
789
- },
790
- inverse: {
791
- type: "image.setOrientation",
792
- orientation: plan.base.orientation
793
- }
794
- };
795
- }
796
- case "image.setOutput": {
797
- const output = checkOutput(command.output);
798
- return {
799
- state: {
800
- ...plan,
801
- output
802
- },
803
- inverse: {
804
- type: "image.setOutput",
805
- output: plan.output
806
- }
807
- };
808
- }
809
- case "image.setMetadata": {
810
- const { field } = command;
811
- if (typeof field !== "string") invalid("malformed-command", "a metadata field is text");
812
- if (!METADATA_FIELDS.includes(field)) invalid("unknown-metadata-field", "only title, description, artist and copyright are kept");
813
- const value = checkMetadataValue(field, command.value);
814
- return {
815
- state: {
816
- ...plan,
817
- metadata: {
818
- ...plan.metadata,
819
- [field]: value
820
- }
821
- },
822
- inverse: {
823
- type: "image.setMetadata",
824
- field,
825
- value: plan.metadata[field]
826
- }
827
- };
828
- }
829
- case "image.setDevelop": {
830
- const values = checkDevelop(command.values);
831
- const previous = {};
832
- for (const name of Object.keys(values)) previous[name] = plan.base.develop[name];
833
- return {
834
- state: {
835
- ...plan,
836
- base: {
837
- ...plan.base,
838
- develop: {
839
- ...plan.base.develop,
840
- ...values
841
- }
842
- }
843
- },
844
- inverse: {
845
- type: "image.setDevelop",
846
- values: previous
847
- }
848
- };
849
- }
850
- case "image.setFilter": {
851
- const filter = checkFilter(command.filter);
852
- return {
853
- state: {
854
- ...plan,
855
- base: {
856
- ...plan.base,
857
- filter
858
- }
859
- },
860
- inverse: {
861
- type: "image.setFilter",
862
- filter: plan.base.filter
863
- }
864
- };
865
- }
866
- }
867
- }
868
- function createImageReducer(sourceSize) {
869
- return (plan, command) => {
870
- try {
871
- return apply(plan, command, sourceSize);
872
- } catch (error) {
873
- if (!(error instanceof Invalid)) throw error;
874
- throw new ImageError("INVALID_COMMAND", `Invalid command: ${error.message}.`, { details: { reason: error.reason } });
875
- }
876
- };
877
- }
878
- // src/core/model/geometry.ts
879
- function orientedSize(stored, orientation) {
880
- return orientation >= 5 ? {
881
- width: stored.height,
882
- height: stored.width
883
- } : stored;
884
- }
885
- function cropRect(crop, source) {
886
- return crop ?? {
887
- x: 0,
888
- y: 0,
889
- width: source.width,
890
- height: source.height
891
- };
892
- }
893
- function compositionSize(plan, source) {
894
- const { width, height } = cropRect(plan.base.crop, source);
895
- return plan.base.orientation.rotate % 180 !== 0 ? {
896
- width: height,
897
- height: width
898
- } : {
899
- width,
900
- height
901
- };
902
- }
903
- function outputSize(output, composition) {
904
- const factor = output.kind === "scale" ? output.scale : Math.min(1, output.width / composition.width, output.height / composition.height);
905
- return {
906
- width: Math.max(1, Math.round(composition.width * factor)),
907
- height: Math.max(1, Math.round(composition.height * factor))
908
- };
909
- }
910
- function sourceToComposition(point, crop, orientation) {
911
- const x = point.x - crop.x;
912
- const y = point.y - crop.y;
913
- const { width, height } = crop;
914
- let turned;
915
- switch (orientation.rotate) {
916
- case 90:
917
- turned = {
918
- x: height - y,
919
- y: x
920
- };
921
- break;
922
- case 180:
923
- turned = {
924
- x: width - x,
925
- y: height - y
926
- };
927
- break;
928
- case 270:
929
- turned = {
930
- x: y,
931
- y: width - x
932
- };
933
- break;
934
- default: turned = {
935
- x,
936
- y
937
- };
938
- }
939
- const size = orientation.rotate % 180 === 0 ? {
940
- width,
941
- height
942
- } : {
943
- width: height,
944
- height: width
945
- };
946
- return {
947
- x: orientation.flipX ? size.width - turned.x : turned.x,
948
- y: orientation.flipY ? size.height - turned.y : turned.y
949
- };
950
- }
951
- function compositionToSource(point, crop, orientation) {
952
- const { width, height } = crop;
953
- const size = orientation.rotate % 180 === 0 ? {
954
- width,
955
- height
956
- } : {
957
- width: height,
958
- height: width
959
- };
960
- const x = orientation.flipX ? size.width - point.x : point.x;
961
- const y = orientation.flipY ? size.height - point.y : point.y;
962
- let source;
963
- switch (orientation.rotate) {
964
- case 90:
965
- source = {
966
- x: y,
967
- y: height - x
968
- };
969
- break;
970
- case 180:
971
- source = {
972
- x: width - x,
973
- y: height - y
974
- };
975
- break;
976
- case 270:
977
- source = {
978
- x: width - y,
979
- y: x
980
- };
981
- break;
982
- default: source = {
983
- x,
984
- y
985
- };
986
- }
987
- return {
988
- x: source.x + crop.x,
989
- y: source.y + crop.y
990
- };
991
- }
992
- // src/core/model/crop.ts
993
- var ASPECT_PRESETS = [
994
- "free",
995
- "original",
996
- [1, 1],
997
- [4, 3],
998
- [3, 2],
999
- [16, 9],
1000
- [3, 4],
1001
- [2, 3],
1002
- [9, 16]
1003
- ];
1004
- function aspectRatio(aspect, source) {
1005
- if (aspect === "free") return void 0;
1006
- if (aspect === "original") return source.width / source.height;
1007
- return aspect[0] / aspect[1];
1008
- }
1009
- var wholeCrop = (source) => ({
1010
- x: 0,
1011
- y: 0,
1012
- width: source.width,
1013
- height: source.height
1014
- });
1015
- function fitAspect(within, ratio) {
1016
- if (ratio === void 0) return within;
1017
- let width = within.width;
1018
- let height = Math.round(width / ratio);
1019
- if (height > within.height) {
1020
- height = within.height;
1021
- width = Math.round(height * ratio);
1022
- }
1023
- width = Math.max(1, Math.min(within.width, width));
1024
- height = Math.max(1, Math.min(within.height, height));
1025
- return {
1026
- x: within.x + Math.floor((within.width - width) / 2),
1027
- y: within.y + Math.floor((within.height - height) / 2),
1028
- width,
1029
- height
1030
- };
1031
- }
1032
- function moveCrop(crop, dx, dy, source) {
1033
- return {
1034
- ...crop,
1035
- x: Math.min(source.width - crop.width, Math.max(0, crop.x + Math.round(dx))),
1036
- y: Math.min(source.height - crop.height, Math.max(0, crop.y + Math.round(dy)))
1037
- };
1038
- }
1039
- function dragHandle(crop, handle, dx, dy, source, ratio) {
1040
- let left = crop.x;
1041
- let top = crop.y;
1042
- let right = crop.x + crop.width;
1043
- let bottom = crop.y + crop.height;
1044
- if (handle.includes("w")) left = Math.min(right - 1, Math.max(0, left + dx));
1045
- if (handle.includes("e")) right = Math.max(left + 1, Math.min(source.width, right + dx));
1046
- if (handle.includes("n")) top = Math.min(bottom - 1, Math.max(0, top + dy));
1047
- if (handle.includes("s")) bottom = Math.max(top + 1, Math.min(source.height, bottom + dy));
1048
- left = Math.round(left);
1049
- right = Math.round(right);
1050
- top = Math.round(top);
1051
- bottom = Math.round(bottom);
1052
- if (ratio === void 0) return {
1053
- x: left,
1054
- y: top,
1055
- width: right - left,
1056
- height: bottom - top
1057
- };
1058
- const horizontal = handle.includes("e") || handle.includes("w");
1059
- const vertical = handle.includes("n") || handle.includes("s");
1060
- let width = right - left;
1061
- let height = bottom - top;
1062
- if (horizontal && !vertical) height = width / ratio;
1063
- else if (vertical && !horizontal) width = height * ratio;
1064
- else if (width / height > ratio) width = height * ratio;
1065
- else height = width / ratio;
1066
- const roomRight = handle.includes("w") ? right : source.width - left;
1067
- const roomDown = handle.includes("n") ? bottom : source.height - top;
1068
- const scale = Math.min(1, roomRight / width, roomDown / height);
1069
- width = Math.max(1, Math.round(width * scale));
1070
- height = Math.max(1, Math.round(height * scale));
1071
- const x = handle.includes("w") ? right - width : left;
1072
- let y = handle.includes("n") ? bottom - height : top;
1073
- let cx = x;
1074
- if (vertical && !horizontal) cx = Math.round(crop.x + (crop.width - width) / 2);
1075
- if (horizontal && !vertical) y = Math.round(crop.y + (crop.height - height) / 2);
1076
- return {
1077
- x: Math.min(source.width - width, Math.max(0, cx)),
1078
- y: Math.min(source.height - height, Math.max(0, y)),
1079
- width,
1080
- height
1081
- };
1082
- }
1083
- function cropInComposition(crop, orientation, source) {
1084
- const whole = wholeCrop(source);
1085
- const a = sourceToComposition({
1086
- x: crop.x,
1087
- y: crop.y
1088
- }, whole, orientation);
1089
- const b = sourceToComposition({
1090
- x: crop.x + crop.width,
1091
- y: crop.y + crop.height
1092
- }, whole, orientation);
1093
- return {
1094
- x: Math.min(a.x, b.x),
1095
- y: Math.min(a.y, b.y),
1096
- width: Math.abs(b.x - a.x),
1097
- height: Math.abs(b.y - a.y)
1098
- };
1099
- }
1100
- function compositionDeltaToSource(dx, dy, orientation, source) {
1101
- const whole = wholeCrop(source);
1102
- const origin = compositionToSource({
1103
- x: 0,
1104
- y: 0
1105
- }, whole, orientation);
1106
- const moved = compositionToSource({
1107
- x: dx,
1108
- y: dy
1109
- }, whole, orientation);
1110
- return {
1111
- dx: moved.x - origin.x,
1112
- dy: moved.y - origin.y
1113
- };
1114
- }
1115
- function handleInSource(handle, orientation) {
1116
- const vector = {
1117
- x: 0,
1118
- y: 0
1119
- };
1120
- if (handle.includes("e")) vector.x = 1;
1121
- if (handle.includes("w")) vector.x = -1;
1122
- if (handle.includes("s")) vector.y = 1;
1123
- if (handle.includes("n")) vector.y = -1;
1124
- const unit = compositionDeltaToSource(vector.x, vector.y, orientation, {
1125
- width: 2,
1126
- height: 2
1127
- });
1128
- return `${unit.dy > 0 ? "s" : unit.dy < 0 ? "n" : ""}${unit.dx > 0 ? "e" : unit.dx < 0 ? "w" : ""}`;
1129
- }
1130
- function nudgeCropOnScreen(crop, key, step, resize, orientation, source, ratio) {
1131
- const dx = key === "ArrowLeft" ? -step : key === "ArrowRight" ? step : 0;
1132
- const moved = compositionDeltaToSource(dx, key === "ArrowUp" ? -step : key === "ArrowDown" ? step : 0, orientation, source);
1133
- if (!resize) return moveCrop(crop, moved.dx, moved.dy, source);
1134
- return dragHandle(crop, handleInSource(dx === 0 ? "s" : "e", orientation), moved.dx, moved.dy, source, ratio);
1135
- }
1136
- // src/core/session/session.ts
1137
- var same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
1138
- function commandsBetween(from, to) {
1139
- const commands = [];
1140
- if (!same(from.base.crop, to.base.crop)) commands.push({
1141
- type: "image.setCrop",
1142
- crop: to.base.crop
1143
- });
1144
- if (!same(from.base.orientation, to.base.orientation)) commands.push({
1145
- type: "image.setOrientation",
1146
- orientation: to.base.orientation
1147
- });
1148
- const develop = Object.fromEntries(Object.entries(to.base.develop).filter(([name, value]) => from.base.develop[name] !== value));
1149
- if (Object.keys(develop).length > 0) commands.push({
1150
- type: "image.setDevelop",
1151
- values: develop
1152
- });
1153
- if (!same(from.base.filter, to.base.filter)) commands.push({
1154
- type: "image.setFilter",
1155
- filter: to.base.filter
1156
- });
1157
- if (!same(from.output, to.output)) commands.push({
1158
- type: "image.setOutput",
1159
- output: to.output
1160
- });
1161
- for (const field of Object.keys(to.metadata)) if (from.metadata[field] !== to.metadata[field]) commands.push({
1162
- type: "image.setMetadata",
1163
- field,
1164
- value: to.metadata[field]
1165
- });
1166
- return commands;
1167
- }
1168
- var PRESENCE = [
1169
- "location",
1170
- "camera",
1171
- "timestamps",
1172
- "thumbnail",
1173
- "colourProfile",
1174
- "other"
1175
- ];
1176
- function checkSource(policy, file, probe) {
1177
- const near = checkFileLimits(policy, file.size, probe);
1178
- const bytes = probe.oriented.width * probe.oriented.height * 4;
1179
- if (policy.check("maxSessionSize", bytes) === "warning") near.push("maxSessionSize");
1180
- return near;
1181
- }
1182
- function createImageSession(options) {
1183
- const { engine, processor } = options;
1184
- const policy = imageLimits.resolve(options.filePolicy);
1185
- const history = createHistory();
1186
- let source = null;
1187
- const reducer = createImageReducer((id) => source !== null && source.id === id ? source : void 0);
1188
- let plan = null;
1189
- let opens = 0;
1190
- let opening = 0;
1191
- let exporting = 0;
1192
- let generation = 0;
1193
- let warnings = [];
1194
- let error = null;
1195
- let nextId = 0;
1196
- let destroyed = false;
1197
- const snapshot = () => ({
1198
- status: plan !== null ? "ready" : !destroyed && opening > 0 ? "opening" : "empty",
1199
- plan,
1200
- source,
1201
- canUndo: history.canUndo,
1202
- canRedo: history.canRedo,
1203
- opening: !destroyed && opening > 0,
1204
- exporting: !destroyed && exporting > 0,
1205
- warnings,
1206
- error
1207
- });
1208
- const store = createStore(snapshot());
1209
- const publish = () => store.set(snapshot());
1210
- const emit = (event) => {
1211
- try {
1212
- options.onEvent?.(event);
1213
- } catch {}
1214
- };
1215
- const assertAlive = () => {
1216
- if (destroyed) throw new Error("The image session has been destroyed.");
1217
- };
1218
- const fail = (reason) => {
1219
- error = isImageError(reason) ? reason : asImageError(reason);
1220
- return error;
1221
- };
1222
- const superseded = () => new ImageError("ABORTED", "A later open replaced this one.", { details: { reason: "superseded" } });
1223
- const attempt = (from, commands) => {
1224
- const { state, inverses } = applyCommands(reducer, from, commands);
1225
- if (source) checkOutputLimits(policy, outputSize(state.output, compositionSize(state, source)));
1226
- return {
1227
- state,
1228
- step: {
1229
- commands: [...commands],
1230
- inverses: [...inverses]
1231
- }
1232
- };
1233
- };
1234
- const replay = (direction) => {
1235
- assertAlive();
1236
- const step = direction === "undo" ? history.undo() : history.redo();
1237
- if (!step || plan === null) return false;
1238
- const commands = direction === "undo" ? step.inverses : step.commands;
1239
- try {
1240
- plan = applyCommands(reducer, plan, commands).state;
1241
- } catch (reason) {
1242
- history.restore(direction);
1243
- publish();
1244
- emit({
1245
- type: direction,
1246
- outcome: "failed",
1247
- commands: commands.map((c) => c.type)
1248
- });
1249
- throw fail(reason);
1250
- }
1251
- error = null;
1252
- publish();
1253
- emit({
1254
- type: direction,
1255
- outcome: "done",
1256
- commands: commands.map((c) => c.type)
1257
- });
1258
- return true;
1259
- };
1260
- const executeCommands = (input) => {
1261
- assertAlive();
1262
- const commands = Array.isArray(input) ? input : [input];
1263
- try {
1264
- if (plan === null) throw new ImageError("INVALID_COMMAND", "There's nothing to edit before a file is open.");
1265
- const result = attempt(plan, commands);
1266
- plan = result.state;
1267
- history.push(result.step);
1268
- error = null;
1269
- emit({
1270
- type: "execute",
1271
- outcome: "done",
1272
- commands: commands.map((c) => c.type)
1273
- });
1274
- } catch (reason) {
1275
- emit({
1276
- type: "execute",
1277
- outcome: "failed",
1278
- commands: commands.map((c) => c.type)
1279
- });
1280
- throw fail(reason);
1281
- } finally {
1282
- publish();
1283
- }
1284
- };
1285
- return {
1286
- getSnapshot: () => store.getSnapshot(),
1287
- subscribe: (listener) => store.subscribe(listener),
1288
- async open(file, openOptions = {}) {
1289
- assertAlive();
1290
- opens += 1;
1291
- const ticket = opens;
1292
- nextId += 1;
1293
- const id = `source-${nextId}`;
1294
- let registered = false;
1295
- opening += 1;
1296
- publish();
1297
- try {
1298
- const { probe, near, info } = await withProcessingTime(policy, async (signal) => {
1299
- throwIfAborted(signal);
1300
- policy.check("maxFileSize", file.size);
1301
- const probe = await engine.probe(file, { signal });
1302
- throwIfAborted(signal);
1303
- const near = checkSource(policy, file, probe);
1304
- if (ticket !== opens) throw superseded();
1305
- const info = await engine.register(id, file, probe, {
1306
- filePolicy: policy,
1307
- signal
1308
- });
1309
- registered = true;
1310
- throwIfAborted(signal);
1311
- return {
1312
- probe,
1313
- near,
1314
- info
1315
- };
1316
- }, openOptions);
1317
- assertAlive();
1318
- if (ticket !== opens) throw superseded();
1319
- const previous = source;
1320
- source = {
1321
- ...info,
1322
- fileSize: file.size,
1323
- metadata: probe.metadata,
1324
- keepable: probe.keepable
1325
- };
1326
- plan = createPlan(id);
1327
- history.clear();
1328
- generation += 1;
1329
- warnings = near;
1330
- error = null;
1331
- if (previous) engine.release(previous.id).catch(() => {});
1332
- emit({
1333
- type: "open",
1334
- outcome: "done",
1335
- commands: []
1336
- });
1337
- return source;
1338
- } catch (reason) {
1339
- if (registered && source?.id !== id) await engine.release(id).catch(() => {});
1340
- const failure = isImageError(reason) ? reason : asImageError(reason);
1341
- const cancelled = failure.code === "ABORTED";
1342
- if (!cancelled && !destroyed && ticket === opens) fail(failure);
1343
- emit({
1344
- type: "open",
1345
- outcome: cancelled ? "cancelled" : "failed",
1346
- commands: []
1347
- });
1348
- throw failure;
1349
- } finally {
1350
- opening -= 1;
1351
- if (!destroyed) publish();
1352
- }
1353
- },
1354
- execute: (input) => executeCommands(input),
1355
- applyPlan(next) {
1356
- assertAlive();
1357
- if (plan === null || next.base.source !== plan.base.source) {
1358
- const failure = new ImageError("INVALID_COMMAND", "The plan isn't for the open image.");
1359
- error = failure;
1360
- publish();
1361
- throw failure;
1362
- }
1363
- const commands = commandsBetween(plan, next);
1364
- if (commands.length > 0) executeCommands(commands);
1365
- },
1366
- group(fn) {
1367
- assertAlive();
1368
- return history.group(fn);
1369
- },
1370
- undo: () => replay("undo"),
1371
- redo: () => replay("redo"),
1372
- async export(format, exportOptions = {}) {
1373
- assertAlive();
1374
- const { onProgress } = exportOptions;
1375
- if (plan === null || source === null) throw new ImageError("INVALID_COMMAND", "There's nothing to export before a file is open.");
1376
- const started = generation;
1377
- const exported = plan;
1378
- const from = source;
1379
- exporting += 1;
1380
- publish();
1381
- try {
1382
- const size = outputSize(exported.output, compositionSize(exported, from));
1383
- const blob = await withProcessingTime(policy, async (signal) => {
1384
- throwIfAborted(signal);
1385
- const blob = await processor.export({
1386
- plan: exported,
1387
- format
1388
- }, {
1389
- filePolicy: policy,
1390
- signal,
1391
- ...onProgress ? { onProgress } : {}
1392
- });
1393
- throwIfAborted(signal);
1394
- return blob;
1395
- }, exportOptions);
1396
- if (started !== generation || destroyed) throw new ImageError("ABORTED", "Another file was opened during the export.", { details: { reason: "superseded" } });
1397
- error = null;
1398
- emit({
1399
- type: "export",
1400
- outcome: "done",
1401
- commands: []
1402
- });
1403
- return {
1404
- blob,
1405
- width: size.width,
1406
- height: size.height,
1407
- removed: PRESENCE.filter((kind) => from.metadata[kind]),
1408
- kept: Object.keys(exported.metadata).filter((field) => exported.metadata[field] !== "")
1409
- };
1410
- } catch (reason) {
1411
- const failure = isImageError(reason) ? reason : asImageError(reason);
1412
- const cancelled = failure.code === "ABORTED";
1413
- if (!cancelled && !destroyed && started === generation) fail(failure);
1414
- emit({
1415
- type: "export",
1416
- outcome: cancelled ? "cancelled" : "failed",
1417
- commands: []
1418
- });
1419
- throw failure;
1420
- } finally {
1421
- exporting -= 1;
1422
- if (!destroyed) publish();
1423
- }
1424
- },
1425
- async destroy() {
1426
- if (destroyed) return;
1427
- destroyed = true;
1428
- const held = source;
1429
- source = null;
1430
- plan = null;
1431
- history.clear();
1432
- publish();
1433
- if (held) await engine.release(held.id).catch(() => {});
1434
- }
1435
- };
1436
- }
1437
- // src/messages/en.ts
1438
- var imageMessages = /* @__PURE__ */ defineMessages({
1439
- ...sdkCoreMessages,
1440
- ...uiMessages,
1441
- "editor.engineUnavailable": "Image processing stopped. Reload this page or reopen the editor, then choose the image again. Unsaved edits will be lost unless your application has saved them.",
1442
- "errors.INVALID_IMAGE": "This file isn't a valid image, or it's too damaged to open.",
1443
- "errors.UNSUPPORTED_FORMAT": "This image format isn't supported. Try converting the file to PNG or JPEG, then open it again.",
1444
- "errors.DECODE_FAILED": "This browser can't open this kind of image. Try another browser, or convert the file to PNG or JPEG.",
1445
- "errors.INVALID_COMMAND": "This edit couldn't be made. Please try again.",
1446
- "errors.INVALID_DOCUMENT": "This project is damaged, or it isn't an image project.",
1447
- "errors.IMAGE_TOO_LARGE": "This image has more pixels than the editor can handle. Try a smaller version of it.",
1448
- "errors.IMAGE_DIMENSION_TOO_LARGE": "This image is {actual, number} pixels across, which is over the {maximum, number}-pixel limit.",
1449
- "errors.TOO_MANY_FRAMES": /* @__PURE__ */ plural("maximum", {
1450
- one: "This animation has {actual, number} frames, which is over the {maximum}-frame limit.",
1451
- other: "This animation has {actual, number} frames, which is over the {maximum, number}-frame limit."
1452
- }),
1453
- "errors.SESSION_TOO_LARGE": "The open images would use {actual, fileSize} of memory, which is over the {maximum, fileSize} limit. Close an image, or clear the undo history, and try again.",
1454
- "errors.TOO_MANY_LAYERS": /* @__PURE__ */ plural("maximum", {
1455
- one: "An image can have {maximum} layer. Merge or delete layers, and try again.",
1456
- other: "An image can have up to {maximum, number} layers. Merge or delete layers, and try again."
1457
- }),
1458
- "warnings.maxImagePixels": "This image is large, and may be slow to edit on some devices.",
1459
- "warnings.maxImageDimension": "This image is very wide or tall, and may be slow to edit.",
1460
- "warnings.maxFrames": /* @__PURE__ */ plural("actual", {
1461
- one: "This animation has {actual} frame.",
1462
- other: "This animation has {actual, number} frames, and may be slow to edit and export."
1463
- }),
1464
- "warnings.maxSessionSize": "The open images use {actual, fileSize} of memory. Clearing the undo history frees memory.",
1465
- "warnings.maxLayers": /* @__PURE__ */ plural("actual", {
1466
- one: "This image has {actual} layer.",
1467
- other: "This image has {actual, number} layers, and may be slow to edit and export."
1468
- }),
1469
- "editor.label": "Image editor",
1470
- "editor.preview": "Edited image preview, {width, number} × {height, number}",
1471
- "editor.empty": "Open an image to start editing. It stays on this device.",
1472
- "editor.choose": "Choose an image",
1473
- "editor.dropHint": "or drop it here",
1474
- "editor.opening": "Opening the image…",
1475
- "editor.cancel": "Cancel",
1476
- "editor.opened": "Image opened, {width, number} × {height, number}.",
1477
- "editor.undid": "Undid {action}.",
1478
- "editor.redid": "Redid {action}.",
1479
- "actions.image.setCrop": "crop",
1480
- "actions.image.setOrientation": "rotate or flip",
1481
- "actions.image.setOutput": "size",
1482
- "actions.image.setMetadata": "metadata",
1483
- "actions.image.setDevelop": "adjustment",
1484
- "actions.image.setFilter": "filter",
1485
- "toolbar.label": "Image tools",
1486
- "toolbar.groups.file": "File",
1487
- "toolbar.groups.history": "History",
1488
- "toolbar.groups.orientation": "Rotate",
1489
- "toolbar.groups.zoom": "Zoom",
1490
- "toolbar.groups.other": "More tools",
1491
- "tools.open": "Open image",
1492
- "tools.undo": "Undo",
1493
- "tools.redo": "Redo",
1494
- "tools.rotate-left": "Rotate left",
1495
- "tools.rotate-right": "Rotate right",
1496
- "tools.zoom-in": "Zoom in",
1497
- "tools.zoom-out": "Zoom out",
1498
- "tools.zoom-fit": "Fit to the stage",
1499
- "tools.crop": "Crop",
1500
- "tools.flip-horizontal": "Flip horizontally",
1501
- "tools.flip-vertical": "Flip vertically",
1502
- "toolbar.groups.crop": "Crop",
1503
- "crop.frame": "Crop area",
1504
- "crop.frameDescription": "{width, number} × {height, number} pixels, from {x, number}, {y, number}. Arrow keys move it; with Alt, they resize it; Enter applies and Escape cancels.",
1505
- "crop.size": "{width, number} × {height, number}, from {x, number}, {y, number}",
1506
- "crop.panel": "Crop",
1507
- "crop.x": "Left",
1508
- "crop.y": "Top",
1509
- "crop.width": "Width",
1510
- "crop.height": "Height",
1511
- "crop.aspect": "Aspect ratio",
1512
- "crop.aspects.free": "Free",
1513
- "crop.aspects.original": "Original",
1514
- "crop.aspects.ratio": "{width}:{height}",
1515
- "crop.apply": "Apply crop",
1516
- "crop.cancel": "Cancel",
1517
- "crop.reset": "Whole image",
1518
- "crop.applied": "Cropped to {width, number} × {height, number}.",
1519
- "inspector.label": "Panels",
1520
- "inspector.adjust": "Adjust",
1521
- "inspector.filters": "Filters",
1522
- "inspector.info": "Info",
1523
- "notices.label": "Notices",
1524
- "notices.dismiss": "Dismiss",
1525
- "notices.colourProfile": "This image has a colour profile. Colours outside sRGB will be clipped in the exported file.",
1526
- "info.panel": "Image info",
1527
- "info.size": "Size",
1528
- "info.sizeValue": "{width, number} × {height, number} pixels",
1529
- "info.format": "Format",
1530
- "info.formats.png": "PNG",
1531
- "info.formats.jpeg": "JPEG",
1532
- "info.formats.webp": "WebP",
1533
- "info.formats.gif": "GIF",
1534
- "info.formats.avif": "AVIF",
1535
- "info.formats.heif": "HEIF",
1536
- "info.formats.bmp": "BMP",
1537
- "info.frames": "Frames",
1538
- "info.fileSize": "File size",
1539
- "info.fileSizeValue": "{size, fileSize}",
1540
- "info.metadata": "Metadata in the file",
1541
- "info.metadataNone": "None",
1542
- "info.kept": "Kept on export",
1543
- "info.keptNone": "Nothing",
1544
- "develop.panel": "Adjust",
1545
- "develop.temperature": "Temperature",
1546
- "develop.tint": "Tint",
1547
- "develop.exposure": "Exposure",
1548
- "develop.highlights": "Highlights",
1549
- "develop.shadows": "Shadows",
1550
- "develop.contrast": "Contrast",
1551
- "develop.saturation": "Saturation",
1552
- "develop.vibrance": "Vibrance",
1553
- "develop.reset": "Reset {name}",
1554
- "develop.resetAll": "Reset all",
1555
- "develop.wasReset": "All adjustments reset.",
1556
- "filters.panel": "Filters",
1557
- "filters.label": "Filter",
1558
- "filters.none": "None",
1559
- "filters.vivid": "Vivid",
1560
- "filters.warm": "Warm",
1561
- "filters.cool": "Cool",
1562
- "filters.fade": "Fade",
1563
- "filters.mono": "Mono",
1564
- "filters.noir": "Noir",
1565
- "filters.sepia": "Sepia",
1566
- "filters.strength": "Strength",
1567
- "toolbar.groups.export": "Export",
1568
- "tools.export": "Export",
1569
- "export.title": "Export image",
1570
- "export.description": "The file is made on this device, and nothing is uploaded.",
1571
- "export.format": "Format",
1572
- "export.formats.png": "PNG",
1573
- "export.formats.jpeg": "JPEG",
1574
- "export.formats.webp": "WebP",
1575
- "export.quality": "Quality",
1576
- "export.qualityValue": "{quality, number}%",
1577
- "export.size": "Size",
1578
- "export.sizes.scale": "Scale",
1579
- "export.sizes.fit": "Fit in a box",
1580
- "export.scale": "Scale, in percent",
1581
- "export.fitWidth": "Largest width",
1582
- "export.fitHeight": "Largest height",
1583
- "export.fields": "Details to include",
1584
- "export.fieldsHint": "Only what you fill in is written to the file.",
1585
- "export.field.title": "Title",
1586
- "export.field.description": "Description",
1587
- "export.field.artist": "Artist",
1588
- "export.field.copyright": "Copyright",
1589
- "export.summary": "Summary",
1590
- "export.output": "{width, number} × {height, number} pixels, {format}",
1591
- "export.removed": "Removed from the file",
1592
- "export.removedNone": "The image had no other details to remove.",
1593
- "export.kind.location": "Location",
1594
- "export.kind.camera": "Camera details",
1595
- "export.kind.timestamps": "Dates and times",
1596
- "export.kind.thumbnail": "Embedded thumbnail",
1597
- "export.kind.colourProfile": "Colour profile: colours outside sRGB are clipped",
1598
- "export.kind.other": "Other metadata",
1599
- "export.kept": "Kept in the file",
1600
- "export.confirm": "Export",
1601
- "export.cancel": "Cancel",
1602
- "export.progress": "Exporting the image",
1603
- "export.stop": "Stop exporting",
1604
- "export.cancelled": "Export stopped.",
1605
- "export.done": "Exported a {format} of {size, fileSize}.",
1606
- "export.ready": "{width, number} × {height, number} pixels, {format}, {size, fileSize}",
1607
- "export.download": "Download",
1608
- "export.close": "Done"
1609
- });
1610
- export { imageLimitDefinitions as $, onlyFields as A, createPlan as B, checkFilter as C, createImageReducer as D, checkOutput as E, DEVELOP_ADJUSTMENTS as F, placement as G, MAX_PIXEL_RATIO as H, FILTER_PRESETS as I, engineInternals as J, createImageProcessor as K, FULL_SIZE as L, MAX_METADATA_LENGTH as M, NO_METADATA as N, invalid as O, longerThan as P, checkOutputLimits as Q, NEUTRAL_DEVELOP as R, checkDevelop as S, checkOrientation as T, backingSize as U, createImageRenderer as V, fittedView as W, PER_FILE_LIMITS as X, OUTPUT_LIMITS as Y, checkFileLimits as Z, outputSize as _, compositionDeltaToSource as a, checkCrop as b, fitAspect as c, nudgeCropOnScreen as d, imageLimits as et, wholeCrop as f, orientedSize as g, cropRect as h, aspectRatio as i, EMPTY_KEEPABLE_METADATA as j, isRecord as k, handleInSource as l, compositionToSource as m, createImageSession as n, isImageError as nt, cropInComposition as o, compositionSize as p, createImageEngine as q, ASPECT_PRESETS as r, dragHandle as s, imageMessages as t, ImageError as tt, moveCrop as u, sourceToComposition as v, checkMetadata as w, checkCropInSource as x, Invalid as y, UPRIGHT as z };
1611
-
1612
- //# sourceMappingURL=core-BWNmXDlB.js.map