@hussmartinez/image-sdk 0.3.0 → 0.4.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,5 +1,4 @@
1
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
2
  // src/core/errors/image-error.ts
4
3
  var ImageError = class extends SdkError {
5
4
  name = "ImageError";
@@ -169,8 +168,8 @@ function createImageEngine(options = {}) {
169
168
  type: "module",
170
169
  name: "hm-image-render"
171
170
  });
172
- } : async () => (await import("../lazy/inline-worker-l_ynDNuS.js")).createInlineWorker,
173
- version: "0.3.0",
171
+ } : async () => (await import("../lazy/inline-worker-DsBNkr8Q.js")).createInlineWorker,
172
+ version: "0.4.0",
174
173
  get asset() {
175
174
  return workerUrl ?? "inline";
176
175
  }
@@ -329,7 +328,8 @@ function createImageProcessor(engine) {
329
328
  if (!(format.quality >= 0 && format.quality <= 1)) throw new RangeError("quality must be from 0 to 1.");
330
329
  }
331
330
  internals.check();
332
- if (!internals.has(plan.base.source)) throw new TypeError(`There's no source with the id "${plan.base.source}".`);
331
+ const missing = [plan.base.source, ...layerSources(plan)].find((id) => !internals.has(id));
332
+ if (missing !== void 0) throw new TypeError(`There's no source with the id "${missing}".`);
333
333
  const signal = options?.signal;
334
334
  throwIfAborted(signal);
335
335
  const policy = options?.filePolicy ?? imageLimits.resolve();
@@ -352,6 +352,9 @@ function createImageProcessor(engine) {
352
352
  }
353
353
  };
354
354
  }
355
+ function layerSources(plan) {
356
+ return Array.isArray(plan.layers) ? plan.layers.flatMap((layer) => layer.kind === "image" ? [layer.source] : []) : [];
357
+ }
355
358
  // src/core/ports/image-renderer.ts
356
359
  var MAX_PIXEL_RATIO = 4;
357
360
  function backingSize(view) {
@@ -472,7 +475,8 @@ function createImageRenderer(engine) {
472
475
  return Promise.reject(error);
473
476
  }
474
477
  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}".`));
478
+ const missing = [plan.base.source, ...layerSources(plan)].find((id) => !internals.has(id));
479
+ if (missing !== void 0) return Promise.reject(/* @__PURE__ */ new TypeError(`There's no source with the id "${missing}".`));
476
480
  const policy = options?.filePolicy ?? imageLimits.resolve();
477
481
  try {
478
482
  checkView(view);
@@ -543,6 +547,29 @@ var FILTER_PRESETS = [
543
547
  "noir",
544
548
  "sepia"
545
549
  ];
550
+ var MAX_PLAN_ITEMS = 1024;
551
+ var MAX_KEY_LENGTH = 64;
552
+ var MAX_SCENE_COORDINATE = 65536;
553
+ var REDACTION_MODES = ["solid", "pixelate"];
554
+ var MAX_LAYER_TEXT_LENGTH = 1e3;
555
+ var MAX_LAYER_NAME_LENGTH = 100;
556
+ var MAX_STROKE_WIDTH = 1024;
557
+ var LAYER_FONTS = [
558
+ "sans-serif",
559
+ "serif",
560
+ "monospace"
561
+ ];
562
+ var LAYER_ALIGNMENTS = [
563
+ "start",
564
+ "center",
565
+ "end"
566
+ ];
567
+ var LAYER_SHAPES = ["rectangle", "ellipse"];
568
+ var LAYER_KINDS = [
569
+ "text",
570
+ "shape",
571
+ "image"
572
+ ];
546
573
  var UPRIGHT = Object.freeze({
547
574
  rotate: 0,
548
575
  flipX: false,
@@ -561,6 +588,9 @@ function createPlan(source) {
561
588
  develop: NEUTRAL_DEVELOP,
562
589
  filter: null
563
590
  },
591
+ layers: [],
592
+ redactions: [],
593
+ animation: null,
564
594
  output: FULL_SIZE,
565
595
  metadata: {
566
596
  title: "",
@@ -604,7 +634,7 @@ function longerThan(text, max) {
604
634
  }
605
635
  return false;
606
636
  }
607
- // src/core/operations/commands.ts
637
+ // src/core/operations/checks.ts
608
638
  var Invalid = class extends Error {
609
639
  reason;
610
640
  constructor(reason, message) {
@@ -644,6 +674,372 @@ function checkCrop(value) {
644
674
  function checkCropInSource(crop, source) {
645
675
  if (!isValidCrop(crop, source)) invalid("crop-outside-source", "a crop must fit inside its source");
646
676
  }
677
+ // src/core/operations/keyed-list.ts
678
+ function checkKey(value) {
679
+ if (typeof value !== "string") invalid("malformed-command", "a key is text");
680
+ if (value === "" || longerThan(value, 64)) invalid("invalid-key", `a key has 1 to 64 code points`);
681
+ return value;
682
+ }
683
+ function checkList(value, what) {
684
+ if (!Array.isArray(value)) invalid("malformed-command", `${what} is a list`);
685
+ if (value.length === 0) invalid("malformed-command", `${what} has at least one item`);
686
+ return value;
687
+ }
688
+ function checkKeys(value) {
689
+ const keys = checkList(value, "keys").map(checkKey);
690
+ if (new Set(keys).size !== keys.length) invalid("malformed-command", "a key is listed twice");
691
+ return keys;
692
+ }
693
+ function checkIndex(value, max) {
694
+ if (!isWhole(value, 0)) invalid("malformed-command", "an index is a whole number from 0");
695
+ if (value > max) invalid("invalid-index", `an index is from 0 to ${max}`);
696
+ return value;
697
+ }
698
+ function indexes(list, keys, names) {
699
+ return keys.map((key) => {
700
+ const index = list.findIndex((item) => item.key === key);
701
+ if (index < 0) invalid(names.unknown, `there's no ${names.item} "${key}"`);
702
+ return index;
703
+ });
704
+ }
705
+ function checkUnused(keys, taken) {
706
+ const seen = new Set(taken);
707
+ for (const key of keys) {
708
+ if (seen.has(key)) invalid("duplicate-key", `the key "${key}" is already used`);
709
+ seen.add(key);
710
+ }
711
+ }
712
+ function insertItems(list, at, items, taken) {
713
+ const index = checkIndex(at, list.length);
714
+ const keys = items.map((item) => item.key);
715
+ checkUnused(keys, taken);
716
+ return {
717
+ list: [
718
+ ...list.slice(0, index),
719
+ ...items,
720
+ ...list.slice(index)
721
+ ],
722
+ keys
723
+ };
724
+ }
725
+ function removeItems(list, keys, names) {
726
+ const removed = new Set(indexes(list, checkKeys(keys), names));
727
+ const entries = [];
728
+ list.forEach((item, at) => {
729
+ if (removed.has(at)) entries.push({
730
+ at,
731
+ item
732
+ });
733
+ });
734
+ return {
735
+ list: list.filter((_, at) => !removed.has(at)),
736
+ entries
737
+ };
738
+ }
739
+ function restoreItems(list, entries, taken) {
740
+ const keys = entries.map(({ item }) => item.key);
741
+ checkUnused(keys, taken);
742
+ const next = [...list];
743
+ let last = -1;
744
+ for (const { at, item } of entries) {
745
+ const index = checkIndex(at, next.length);
746
+ if (index <= last) invalid("invalid-index", "restored items are listed by rising index");
747
+ last = index;
748
+ next.splice(index, 0, item);
749
+ }
750
+ return {
751
+ list: next,
752
+ keys
753
+ };
754
+ }
755
+ function moveItems(list, keys, to, names) {
756
+ const moving = new Set(indexes(list, checkKeys(keys), names));
757
+ const moved = list.filter((_, at) => moving.has(at));
758
+ const rest = list.filter((_, at) => !moving.has(at));
759
+ const index = checkIndex(to, rest.length);
760
+ return {
761
+ list: [
762
+ ...rest.slice(0, index),
763
+ ...moved,
764
+ ...rest.slice(index)
765
+ ],
766
+ order: list.map((item) => item.key)
767
+ };
768
+ }
769
+ function orderItems(list, keys, names) {
770
+ const order = indexes(list, checkKeys(keys), names);
771
+ if (order.length !== list.length) invalid("invalid-order", "an order lists every key once");
772
+ return {
773
+ list: order.map((at) => list[at]),
774
+ order: list.map((item) => item.key)
775
+ };
776
+ }
777
+ function updateItems(list, updates, names, patch) {
778
+ const entries = checkList(updates, "updates").map((update) => {
779
+ if (!isRecord(update)) invalid("malformed-command", "an update is an object");
780
+ allFields(update, ["key", "props"], "an update");
781
+ return {
782
+ key: checkKey(update.key),
783
+ props: update.props
784
+ };
785
+ });
786
+ const keys = entries.map(({ key }) => key);
787
+ if (new Set(keys).size !== keys.length) invalid("duplicate-key", "a key is updated twice");
788
+ const at = indexes(list, keys, names);
789
+ const next = [...list];
790
+ return {
791
+ list: next,
792
+ previous: entries.map(({ key, props }, i) => {
793
+ const index = at[i];
794
+ const patched = patch(next[index], props);
795
+ next[index] = patched.item;
796
+ return {
797
+ key,
798
+ props: patched.previous
799
+ };
800
+ })
801
+ };
802
+ }
803
+ // src/core/operations/redactions.ts
804
+ var REDACTION_NAMES = {
805
+ unknown: "unknown-redaction",
806
+ item: "redaction"
807
+ };
808
+ var MODES = REDACTION_MODES;
809
+ var REGION = [
810
+ "x",
811
+ "y",
812
+ "width",
813
+ "height"
814
+ ];
815
+ var PROPS = [
816
+ "mode",
817
+ ...REGION,
818
+ "colour"
819
+ ];
820
+ var COLOUR = /^#[0-9a-f]{6}$/;
821
+ function checkColour(value) {
822
+ if (typeof value !== "string") invalid("malformed-command", "a colour is text");
823
+ if (!COLOUR.test(value)) invalid("invalid-colour", "a colour is #rrggbb, in lower case");
824
+ return value;
825
+ }
826
+ function checkRedaction(value) {
827
+ if (!isRecord(value)) invalid("malformed-command", "a redaction is an object");
828
+ const { mode } = value;
829
+ if (typeof mode !== "string") invalid("malformed-command", "a redaction's mode is text");
830
+ if (!MODES.includes(mode)) invalid("unknown-redaction-mode", `a redaction's mode is one of ${REDACTION_MODES.join(", ")}`);
831
+ const solid = mode === "solid";
832
+ allFields(value, [
833
+ "key",
834
+ "mode",
835
+ ...REGION,
836
+ ...solid ? ["colour"] : []
837
+ ], "a redaction");
838
+ const key = checkKey(value["key"]);
839
+ const { x, y, width, height } = value;
840
+ if (![
841
+ x,
842
+ y,
843
+ width,
844
+ height
845
+ ].every(Number.isInteger)) invalid("malformed-command", "a redaction's region is whole pixels");
846
+ if (!isWhole(x, -65536, 65536) || !isWhole(y, -65536, 65536) || !isWhole(width, 1, 65536) || !isWhole(height, 1, 65536)) invalid("invalid-region", `a redaction's region is at least 1 × 1, within ${MAX_SCENE_COORDINATE} pixels of the scene's origin`);
847
+ return solid ? {
848
+ key,
849
+ mode: "solid",
850
+ x,
851
+ y,
852
+ width,
853
+ height,
854
+ colour: checkColour(value["colour"])
855
+ } : {
856
+ key,
857
+ mode: "pixelate",
858
+ x,
859
+ y,
860
+ width,
861
+ height
862
+ };
863
+ }
864
+ function patchRedaction(item, props) {
865
+ if (!isRecord(props)) invalid("malformed-command", "an update's props are an object");
866
+ onlyFields(props, PROPS, "a redaction's props");
867
+ const merged = { ...item };
868
+ const previous = {};
869
+ const before = item;
870
+ for (const name of PROPS) {
871
+ if (!Object.hasOwn(props, name)) continue;
872
+ merged[name] = props[name];
873
+ if (Object.hasOwn(before, name)) previous[name] = before[name];
874
+ }
875
+ if (merged["mode"] === "pixelate") {
876
+ if (Object.hasOwn(props, "colour")) invalid("unexpected-colour", "a pixelated redaction has no colour");
877
+ if (item.mode === "solid") previous["colour"] = item.colour;
878
+ delete merged["colour"];
879
+ } else if (merged["mode"] === "solid" && !Object.hasOwn(merged, "colour")) invalid("missing-colour", "a redaction set to solid needs a colour in the same update");
880
+ return {
881
+ item: checkRedaction(merged),
882
+ previous
883
+ };
884
+ }
885
+ // src/core/operations/layers.ts
886
+ var LAYER_NAMES = {
887
+ unknown: "unknown-layer",
888
+ item: "layer"
889
+ };
890
+ var COMMON = [
891
+ "key",
892
+ "kind",
893
+ "name",
894
+ "visible",
895
+ "opacity"
896
+ ];
897
+ var BOX = [
898
+ "x",
899
+ "y",
900
+ "width",
901
+ "height",
902
+ "rotation",
903
+ "flipX"
904
+ ];
905
+ var OWN = {
906
+ text: [
907
+ "text",
908
+ "font",
909
+ "bold",
910
+ "colour",
911
+ "align"
912
+ ],
913
+ shape: [
914
+ "shape",
915
+ "fill",
916
+ "stroke"
917
+ ],
918
+ image: ["source", "crop"]
919
+ };
920
+ var KINDS = LAYER_KINDS;
921
+ var ANY_OWN = new Set(Object.values(OWN).flat());
922
+ var FORBIDDEN_IN_TEXT = /[\u0000-\u0009\u000B-\u001F\u007F‪-‮⁦-⁩]/u;
923
+ function checkText(value, max, what) {
924
+ if (typeof value !== "string") invalid("malformed-command", `${what} is text`);
925
+ if (longerThan(value, max)) invalid("text-too-long", `${what} has at most ${max} code points`);
926
+ if (FORBIDDEN_IN_TEXT.test(value)) invalid("invalid-text", `${what} can't hold control characters other than a line feed, or bidirectional controls`);
927
+ return value;
928
+ }
929
+ function checkOneOf(value, options, what) {
930
+ if (typeof value !== "string" || !options.includes(value)) invalid("malformed-command", `${what} is one of ${options.join(", ")}`);
931
+ return value;
932
+ }
933
+ function checkBoolean(value, what) {
934
+ if (typeof value !== "boolean") invalid("malformed-command", `${what} is true or false`);
935
+ return value;
936
+ }
937
+ function checkLayer(value, sourceSize) {
938
+ if (!isRecord(value)) invalid("malformed-command", "a layer is an object");
939
+ const { kind } = value;
940
+ if (typeof kind !== "string") invalid("malformed-command", "a layer's kind is text");
941
+ if (!KINDS.includes(kind)) invalid("unknown-layer-kind", `a layer's kind is one of ${LAYER_KINDS.join(", ")}`);
942
+ const own = OWN[kind];
943
+ allFields(value, [
944
+ ...COMMON,
945
+ ...BOX,
946
+ ...own
947
+ ], `a ${kind} layer`);
948
+ const key = checkKey(value["key"]);
949
+ const name = checkText(value["name"], 100, "a layer's name");
950
+ const visible = checkBoolean(value["visible"], "a layer's visible");
951
+ const { opacity, x, y, width, height, rotation } = value;
952
+ if (![
953
+ opacity,
954
+ x,
955
+ y,
956
+ width,
957
+ height,
958
+ rotation
959
+ ].every(Number.isInteger)) invalid("malformed-command", "a layer's opacity and box are whole numbers");
960
+ if (!isWhole(opacity, 0, 100)) invalid("invalid-opacity", "a layer's opacity is from 0 to 100");
961
+ if (!isWhole(x, -65536, 65536) || !isWhole(y, -65536, 65536) || !isWhole(width, 1, 65536) || !isWhole(height, 1, 65536) || !isWhole(rotation, 0, 3599)) invalid("invalid-box", `a layer's box is at least 1 × 1, within ${MAX_SCENE_COORDINATE} pixels of the scene's origin, turned by 0 to 3599 tenths of a degree`);
962
+ const common = {
963
+ key,
964
+ name,
965
+ visible,
966
+ opacity,
967
+ x,
968
+ y,
969
+ width,
970
+ height,
971
+ rotation,
972
+ flipX: checkBoolean(value["flipX"], "a layer's flipX")
973
+ };
974
+ if (kind === "text") return {
975
+ ...common,
976
+ kind,
977
+ text: checkText(value["text"], MAX_LAYER_TEXT_LENGTH, "a layer's text"),
978
+ font: checkOneOf(value["font"], LAYER_FONTS, "a layer's font"),
979
+ bold: checkBoolean(value["bold"], "a layer's bold"),
980
+ colour: checkColour(value["colour"]),
981
+ align: checkOneOf(value["align"], LAYER_ALIGNMENTS, "a layer's align")
982
+ };
983
+ if (kind === "shape") {
984
+ const shape = checkOneOf(value["shape"], LAYER_SHAPES, "a layer's shape");
985
+ const fill = value["fill"] === null ? null : checkColour(value["fill"]);
986
+ let stroke = null;
987
+ if (value["stroke"] !== null) {
988
+ const given = value["stroke"];
989
+ if (!isRecord(given)) invalid("malformed-command", "a stroke is an object or null");
990
+ allFields(given, ["colour", "width"], "a stroke");
991
+ if (!isWhole(given.width, 1, 1024)) invalid("malformed-command", `a stroke's width is from 1 to ${MAX_STROKE_WIDTH} pixels`);
992
+ stroke = {
993
+ colour: checkColour(given.colour),
994
+ width: given.width
995
+ };
996
+ }
997
+ if (fill === null && stroke === null) invalid("empty-shape", "a shape has a fill or a stroke");
998
+ return {
999
+ ...common,
1000
+ kind,
1001
+ shape,
1002
+ fill,
1003
+ stroke
1004
+ };
1005
+ }
1006
+ const source = value["source"];
1007
+ if (typeof source !== "string" || source === "") invalid("malformed-command", "an image layer's source is a source id");
1008
+ const size = sourceSize(source);
1009
+ if (size === void 0) invalid("unknown-source", `unknown source "${source}"`);
1010
+ const crop = value["crop"] === null ? null : checkCrop(value["crop"]);
1011
+ if (crop !== null) checkCropInSource(crop, size);
1012
+ return {
1013
+ ...common,
1014
+ kind: "image",
1015
+ source,
1016
+ crop
1017
+ };
1018
+ }
1019
+ function patchLayer(item, props, sourceSize) {
1020
+ if (!isRecord(props)) invalid("malformed-command", "an update's props are an object");
1021
+ const allowed = /* @__PURE__ */ new Set([
1022
+ ...COMMON.slice(2),
1023
+ ...BOX,
1024
+ ...OWN[item.kind]
1025
+ ]);
1026
+ const before = item;
1027
+ const merged = { ...item };
1028
+ const previous = {};
1029
+ for (const name of Object.keys(props)) {
1030
+ if (!allowed.has(name)) {
1031
+ if (ANY_OWN.has(name)) invalid("wrong-kind", `a ${item.kind} layer has no "${name}"`);
1032
+ invalid("malformed-command", `a layer's props have no field "${name}"`);
1033
+ }
1034
+ merged[name] = props[name];
1035
+ previous[name] = before[name];
1036
+ }
1037
+ return {
1038
+ item: checkLayer(merged, sourceSize),
1039
+ previous
1040
+ };
1041
+ }
1042
+ // src/core/operations/commands.ts
647
1043
  function checkOrientation(value) {
648
1044
  if (!isRecord(value)) invalid("malformed-command", "an orientation is an object");
649
1045
  allFields(value, [
@@ -746,8 +1142,76 @@ var COMMAND_FIELDS = {
746
1142
  "value"
747
1143
  ],
748
1144
  "image.setDevelop": ["type", "values"],
749
- "image.setFilter": ["type", "filter"]
1145
+ "image.setFilter": ["type", "filter"],
1146
+ "image.insertLayers": [
1147
+ "type",
1148
+ "at",
1149
+ "layers"
1150
+ ],
1151
+ "image.removeLayers": ["type", "keys"],
1152
+ "image.moveLayers": [
1153
+ "type",
1154
+ "keys",
1155
+ "to"
1156
+ ],
1157
+ "image.updateLayers": ["type", "updates"],
1158
+ "image.restoreLayers": ["type", "entries"],
1159
+ "image.setLayerOrder": ["type", "keys"],
1160
+ "image.insertRedactions": [
1161
+ "type",
1162
+ "at",
1163
+ "redactions"
1164
+ ],
1165
+ "image.removeRedactions": ["type", "keys"],
1166
+ "image.moveRedactions": [
1167
+ "type",
1168
+ "keys",
1169
+ "to"
1170
+ ],
1171
+ "image.updateRedactions": ["type", "updates"],
1172
+ "image.restoreRedactions": ["type", "entries"],
1173
+ "image.setRedactionOrder": ["type", "keys"]
750
1174
  };
1175
+ function planKeys(plan) {
1176
+ return new Set([...plan.layers, ...plan.redactions].map((item) => item.key));
1177
+ }
1178
+ function checkRoom(plan, added) {
1179
+ if (plan.layers.length + plan.redactions.length + added > 1024) invalid("too-many-layers", `a plan holds at most ${MAX_PLAN_ITEMS} layers and redactions together`);
1180
+ }
1181
+ function checkLayers(value, sourceSize) {
1182
+ if (!Array.isArray(value)) invalid("malformed-command", "layers is a list");
1183
+ if (value.length === 0) invalid("malformed-command", "layers has at least one item");
1184
+ return value.map((layer) => checkLayer(layer, sourceSize));
1185
+ }
1186
+ function checkLayerEntries(value, sourceSize) {
1187
+ if (!Array.isArray(value)) invalid("malformed-command", "entries is a list");
1188
+ if (value.length === 0) invalid("malformed-command", "entries has at least one item");
1189
+ return value.map((entry) => {
1190
+ if (!isRecord(entry)) invalid("malformed-command", "an entry is an object");
1191
+ allFields(entry, ["at", "layer"], "an entry");
1192
+ return {
1193
+ at: entry.at,
1194
+ item: checkLayer(entry.layer, sourceSize)
1195
+ };
1196
+ });
1197
+ }
1198
+ function checkRedactions(value) {
1199
+ if (!Array.isArray(value)) invalid("malformed-command", "redactions is a list");
1200
+ if (value.length === 0) invalid("malformed-command", "redactions has at least one item");
1201
+ return value.map(checkRedaction);
1202
+ }
1203
+ function checkRedactionEntries(value) {
1204
+ if (!Array.isArray(value)) invalid("malformed-command", "entries is a list");
1205
+ if (value.length === 0) invalid("malformed-command", "entries has at least one item");
1206
+ return value.map((entry) => {
1207
+ if (!isRecord(entry)) invalid("malformed-command", "an entry is an object");
1208
+ allFields(entry, ["at", "redaction"], "an entry");
1209
+ return {
1210
+ at: entry.at,
1211
+ item: checkRedaction(entry.redaction)
1212
+ };
1213
+ });
1214
+ }
751
1215
  function apply(plan, input, sourceSize) {
752
1216
  if (!isRecord(input)) invalid("malformed-command", "a command is an object");
753
1217
  const { type } = input;
@@ -863,6 +1327,176 @@ function apply(plan, input, sourceSize) {
863
1327
  }
864
1328
  };
865
1329
  }
1330
+ case "image.insertLayers": {
1331
+ const layers = checkLayers(command.layers, sourceSize);
1332
+ const { list, keys } = insertItems(plan.layers, command.at, layers, planKeys(plan));
1333
+ checkRoom(plan, layers.length);
1334
+ return {
1335
+ state: {
1336
+ ...plan,
1337
+ layers: list
1338
+ },
1339
+ inverse: {
1340
+ type: "image.removeLayers",
1341
+ keys
1342
+ }
1343
+ };
1344
+ }
1345
+ case "image.removeLayers": {
1346
+ const { list, entries } = removeItems(plan.layers, command.keys, LAYER_NAMES);
1347
+ return {
1348
+ state: {
1349
+ ...plan,
1350
+ layers: list
1351
+ },
1352
+ inverse: {
1353
+ type: "image.restoreLayers",
1354
+ entries: entries.map(({ at, item }) => ({
1355
+ at,
1356
+ layer: item
1357
+ }))
1358
+ }
1359
+ };
1360
+ }
1361
+ case "image.restoreLayers": {
1362
+ const entries = checkLayerEntries(command.entries, sourceSize);
1363
+ const { list, keys } = restoreItems(plan.layers, entries, planKeys(plan));
1364
+ checkRoom(plan, entries.length);
1365
+ return {
1366
+ state: {
1367
+ ...plan,
1368
+ layers: list
1369
+ },
1370
+ inverse: {
1371
+ type: "image.removeLayers",
1372
+ keys
1373
+ }
1374
+ };
1375
+ }
1376
+ case "image.moveLayers": {
1377
+ const { list, order } = moveItems(plan.layers, command.keys, command.to, LAYER_NAMES);
1378
+ return {
1379
+ state: {
1380
+ ...plan,
1381
+ layers: list
1382
+ },
1383
+ inverse: {
1384
+ type: "image.setLayerOrder",
1385
+ keys: order
1386
+ }
1387
+ };
1388
+ }
1389
+ case "image.setLayerOrder": {
1390
+ const { list, order } = orderItems(plan.layers, command.keys, LAYER_NAMES);
1391
+ return {
1392
+ state: {
1393
+ ...plan,
1394
+ layers: list
1395
+ },
1396
+ inverse: {
1397
+ type: "image.setLayerOrder",
1398
+ keys: order
1399
+ }
1400
+ };
1401
+ }
1402
+ case "image.updateLayers": {
1403
+ const { list, previous } = updateItems(plan.layers, command.updates, LAYER_NAMES, (item, props) => patchLayer(item, props, sourceSize));
1404
+ return {
1405
+ state: {
1406
+ ...plan,
1407
+ layers: list
1408
+ },
1409
+ inverse: {
1410
+ type: "image.updateLayers",
1411
+ updates: previous
1412
+ }
1413
+ };
1414
+ }
1415
+ case "image.insertRedactions": {
1416
+ const redactions = checkRedactions(command.redactions);
1417
+ const { list, keys } = insertItems(plan.redactions, command.at, redactions, planKeys(plan));
1418
+ checkRoom(plan, redactions.length);
1419
+ return {
1420
+ state: {
1421
+ ...plan,
1422
+ redactions: list
1423
+ },
1424
+ inverse: {
1425
+ type: "image.removeRedactions",
1426
+ keys
1427
+ }
1428
+ };
1429
+ }
1430
+ case "image.removeRedactions": {
1431
+ const { list, entries } = removeItems(plan.redactions, command.keys, REDACTION_NAMES);
1432
+ return {
1433
+ state: {
1434
+ ...plan,
1435
+ redactions: list
1436
+ },
1437
+ inverse: {
1438
+ type: "image.restoreRedactions",
1439
+ entries: entries.map(({ at, item }) => ({
1440
+ at,
1441
+ redaction: item
1442
+ }))
1443
+ }
1444
+ };
1445
+ }
1446
+ case "image.restoreRedactions": {
1447
+ const entries = checkRedactionEntries(command.entries);
1448
+ const { list, keys } = restoreItems(plan.redactions, entries, planKeys(plan));
1449
+ checkRoom(plan, entries.length);
1450
+ return {
1451
+ state: {
1452
+ ...plan,
1453
+ redactions: list
1454
+ },
1455
+ inverse: {
1456
+ type: "image.removeRedactions",
1457
+ keys
1458
+ }
1459
+ };
1460
+ }
1461
+ case "image.moveRedactions": {
1462
+ const { list, order } = moveItems(plan.redactions, command.keys, command.to, REDACTION_NAMES);
1463
+ return {
1464
+ state: {
1465
+ ...plan,
1466
+ redactions: list
1467
+ },
1468
+ inverse: {
1469
+ type: "image.setRedactionOrder",
1470
+ keys: order
1471
+ }
1472
+ };
1473
+ }
1474
+ case "image.setRedactionOrder": {
1475
+ const { list, order } = orderItems(plan.redactions, command.keys, REDACTION_NAMES);
1476
+ return {
1477
+ state: {
1478
+ ...plan,
1479
+ redactions: list
1480
+ },
1481
+ inverse: {
1482
+ type: "image.setRedactionOrder",
1483
+ keys: order
1484
+ }
1485
+ };
1486
+ }
1487
+ case "image.updateRedactions": {
1488
+ const { list, previous } = updateItems(plan.redactions, command.updates, REDACTION_NAMES, patchRedaction);
1489
+ return {
1490
+ state: {
1491
+ ...plan,
1492
+ redactions: list
1493
+ },
1494
+ inverse: {
1495
+ type: "image.updateRedactions",
1496
+ updates: previous
1497
+ }
1498
+ };
1499
+ }
866
1500
  }
867
1501
  }
868
1502
  function createImageReducer(sourceSize) {
@@ -1133,7 +1767,350 @@ function nudgeCropOnScreen(crop, key, step, resize, orientation, source, ratio)
1133
1767
  if (!resize) return moveCrop(crop, moved.dx, moved.dy, source);
1134
1768
  return dragHandle(crop, handleInSource(dx === 0 ? "s" : "e", orientation), moved.dx, moved.dy, source, ratio);
1135
1769
  }
1770
+ // src/core/model/keys.ts
1771
+ function createImageKey(used) {
1772
+ for (;;) {
1773
+ const bytes = globalThis.crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
1774
+ const key = Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1775
+ if (!used?.has(key)) return key;
1776
+ }
1777
+ }
1778
+ // src/core/model/layer-geometry.ts
1779
+ function then(first, second) {
1780
+ const [a1, b1, c1, d1, e1, f1] = first;
1781
+ const [a2, b2, c2, d2, e2, f2] = second;
1782
+ return [
1783
+ a2 * a1 + c2 * b1,
1784
+ b2 * a1 + d2 * b1,
1785
+ a2 * c1 + c2 * d1,
1786
+ b2 * c1 + d2 * d1,
1787
+ a2 * e1 + c2 * f1 + e2,
1788
+ b2 * e1 + d2 * f1 + f2
1789
+ ];
1790
+ }
1791
+ function sceneToOutput(crop, orientation, output) {
1792
+ const composition = orientation.rotate % 180 !== 0 ? {
1793
+ width: crop.height,
1794
+ height: crop.width
1795
+ } : {
1796
+ width: crop.width,
1797
+ height: crop.height
1798
+ };
1799
+ const scaleX = output.width / composition.width;
1800
+ const scaleY = output.height / composition.height;
1801
+ const at = (x, y) => {
1802
+ const point = sourceToComposition({
1803
+ x,
1804
+ y
1805
+ }, crop, orientation);
1806
+ return {
1807
+ x: point.x * scaleX,
1808
+ y: point.y * scaleY
1809
+ };
1810
+ };
1811
+ const origin = at(0, 0);
1812
+ const alongX = at(1, 0);
1813
+ const alongY = at(0, 1);
1814
+ return [
1815
+ alongX.x - origin.x,
1816
+ alongX.y - origin.y,
1817
+ alongY.x - origin.x,
1818
+ alongY.y - origin.y,
1819
+ origin.x,
1820
+ origin.y
1821
+ ];
1822
+ }
1823
+ function layerToScene(box) {
1824
+ const radians = box.rotation * Math.PI / 1800;
1825
+ const quarter = box.rotation % 900 === 0 ? box.rotation / 900 % 4 : -1;
1826
+ const cos = quarter >= 0 ? [
1827
+ 1,
1828
+ 0,
1829
+ -1,
1830
+ 0
1831
+ ][quarter] : Math.cos(radians);
1832
+ const sin = quarter >= 0 ? [
1833
+ 0,
1834
+ 1,
1835
+ 0,
1836
+ -1
1837
+ ][quarter] : Math.sin(radians);
1838
+ const negative = (value) => value === 0 ? 0 : -value;
1839
+ const a = box.flipX ? negative(cos) : cos;
1840
+ const b = box.flipX ? negative(sin) : sin;
1841
+ const c = negative(sin);
1842
+ const d = cos;
1843
+ return [
1844
+ a,
1845
+ b,
1846
+ c,
1847
+ d,
1848
+ box.x + box.width / 2 - (a * box.width + c * box.height) / 2,
1849
+ box.y + box.height / 2 - (b * box.width + d * box.height) / 2
1850
+ ];
1851
+ }
1852
+ function layerToOutput(box, crop, orientation, output) {
1853
+ return then(layerToScene(box), sceneToOutput(crop, orientation, output));
1854
+ }
1855
+ function invertMatrix(matrix) {
1856
+ const [a, b, c, d, e, f] = matrix;
1857
+ const determinant = a * d - b * c;
1858
+ return [
1859
+ d / determinant,
1860
+ -b / determinant,
1861
+ -c / determinant,
1862
+ a / determinant,
1863
+ (c * f - d * e) / determinant,
1864
+ (b * e - a * f) / determinant
1865
+ ];
1866
+ }
1867
+ function sceneToLayerSource(box, crop) {
1868
+ const boxToSource = [
1869
+ crop.width / box.width,
1870
+ 0,
1871
+ 0,
1872
+ crop.height / box.height,
1873
+ crop.x,
1874
+ crop.y
1875
+ ];
1876
+ return then(invertMatrix(layerToScene(box)), boxToSource);
1877
+ }
1878
+ function applyMatrix(matrix, point) {
1879
+ const [a, b, c, d, e, f] = matrix;
1880
+ return {
1881
+ x: a * point.x + c * point.y + e,
1882
+ y: b * point.x + d * point.y + f
1883
+ };
1884
+ }
1885
+ function fitTextLines(lines, lineHeight, ascent, box, align, rightToLeft) {
1886
+ const widest = Math.max(0, ...lines.map((line) => line.width));
1887
+ if (!(widest > 0) || !(lineHeight > 0)) return null;
1888
+ const scale = Math.min(box.width / widest, box.height / (lineHeight * lines.length));
1889
+ const top = (box.height - lineHeight * lines.length * scale) / 2;
1890
+ const side = align === "center" ? .5 : align === "start" === rightToLeft ? 1 : 0;
1891
+ return {
1892
+ scale,
1893
+ lines: lines.map((line, index) => ({
1894
+ x: (box.width - line.width * scale) * side,
1895
+ baseline: top + (index * lineHeight + ascent) * scale
1896
+ }))
1897
+ };
1898
+ }
1899
+ function isRightToLeft(text) {
1900
+ for (const character of text) {
1901
+ if (RIGHT_TO_LEFT.test(character)) return true;
1902
+ if (LEFT_TO_RIGHT.test(character)) return false;
1903
+ }
1904
+ return false;
1905
+ }
1906
+ var RIGHT_TO_LEFT = /[֐-ࣿיִ-﷿ﹰ-\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}]/u;
1907
+ var LEFT_TO_RIGHT = /\p{L}/u;
1908
+ // src/core/model/redaction-geometry.ts
1909
+ var MIN_BLOCK = 8;
1910
+ var MAX_BLOCKS = 12;
1911
+ function redactionBlockSize(region) {
1912
+ return Math.max(MIN_BLOCK, Math.ceil(Math.max(region.width, region.height) / MAX_BLOCKS));
1913
+ }
1914
+ function boundaries(start, length, block) {
1915
+ const edges = [start];
1916
+ for (let at = start + block; at < start + length; at += block) edges.push(at);
1917
+ edges.push(start + length);
1918
+ return edges;
1919
+ }
1920
+ function cells(xs, ys) {
1921
+ const rects = [];
1922
+ for (let row = 0; row + 1 < ys.length; row += 1) {
1923
+ const y = ys[row];
1924
+ const height = ys[row + 1] - y;
1925
+ if (height <= 0) continue;
1926
+ for (let column = 0; column + 1 < xs.length; column += 1) {
1927
+ const x = xs[column];
1928
+ const width = xs[column + 1] - x;
1929
+ if (width > 0) rects.push({
1930
+ x,
1931
+ y,
1932
+ width,
1933
+ height
1934
+ });
1935
+ }
1936
+ }
1937
+ return rects;
1938
+ }
1939
+ var clamp$1 = (value, min, max) => Math.min(max, Math.max(min, value));
1940
+ function redactionBlocksInScene(region, within) {
1941
+ const block = redactionBlockSize(region);
1942
+ const clip = (edges, min, max) => edges.map((edge) => clamp$1(edge, min, max));
1943
+ return cells(clip(boundaries(region.x, region.width, block), within.x, within.x + within.width), clip(boundaries(region.y, region.height, block), within.y, within.y + within.height));
1944
+ }
1945
+ function toOutput(crop, orientation, output) {
1946
+ const turned = orientation.rotate % 180 !== 0;
1947
+ const composition = turned ? {
1948
+ width: crop.height,
1949
+ height: crop.width
1950
+ } : {
1951
+ width: crop.width,
1952
+ height: crop.height
1953
+ };
1954
+ const scaleX = output.width / composition.width;
1955
+ const scaleY = output.height / composition.height;
1956
+ const at = (x, y) => {
1957
+ const point = sourceToComposition({
1958
+ x,
1959
+ y
1960
+ }, crop, orientation);
1961
+ return {
1962
+ x: point.x * scaleX,
1963
+ y: point.y * scaleY
1964
+ };
1965
+ };
1966
+ return {
1967
+ turned,
1968
+ fromX: (value) => turned ? at(value, crop.y).y : at(value, crop.y).x,
1969
+ fromY: (value) => turned ? at(crop.x, value).x : at(crop.x, value).y
1970
+ };
1971
+ }
1972
+ function outputEdges(values, size) {
1973
+ const sorted = [...values].sort((a, b) => a - b);
1974
+ const last = sorted.length - 1;
1975
+ let previous = 0;
1976
+ return sorted.map((value, index) => {
1977
+ previous = Math.max(previous, clamp$1(index === 0 ? Math.floor(value) : index === last ? Math.ceil(value) : Math.round(value), 0, size));
1978
+ return previous;
1979
+ });
1980
+ }
1981
+ function redactionRectInOutput(region, crop, orientation, output) {
1982
+ const { turned, fromX, fromY } = toOutput(crop, orientation, output);
1983
+ const alongX = [fromX(region.x), fromX(region.x + region.width)];
1984
+ const alongY = [fromY(region.y), fromY(region.y + region.height)];
1985
+ const [left, right] = outputEdges(turned ? alongY : alongX, output.width);
1986
+ const [top, bottom] = outputEdges(turned ? alongX : alongY, output.height);
1987
+ if (right <= left || bottom <= top) return null;
1988
+ return {
1989
+ x: left,
1990
+ y: top,
1991
+ width: right - left,
1992
+ height: bottom - top
1993
+ };
1994
+ }
1995
+ function redactionBlocksInOutput(region, crop, orientation, output) {
1996
+ const block = redactionBlockSize(region);
1997
+ const { turned, fromX, fromY } = toOutput(crop, orientation, output);
1998
+ const alongX = boundaries(region.x, region.width, block).map(fromX);
1999
+ const alongY = boundaries(region.y, region.height, block).map(fromY);
2000
+ return cells(outputEdges(turned ? alongY : alongX, output.width), outputEdges(turned ? alongX : alongY, output.height));
2001
+ }
2002
+ function between(a, b) {
2003
+ const x = Math.min(a.x, b.x);
2004
+ const y = Math.min(a.y, b.y);
2005
+ return {
2006
+ x,
2007
+ y,
2008
+ width: Math.max(a.x, b.x) - x,
2009
+ height: Math.max(a.y, b.y) - y
2010
+ };
2011
+ }
2012
+ function sceneRectToComposition(rect, crop, orientation) {
2013
+ return between(sourceToComposition({
2014
+ x: rect.x,
2015
+ y: rect.y
2016
+ }, crop, orientation), sourceToComposition({
2017
+ x: rect.x + rect.width,
2018
+ y: rect.y + rect.height
2019
+ }, crop, orientation));
2020
+ }
2021
+ function compositionRectToScene(rect, crop, orientation) {
2022
+ return between(compositionToSource({
2023
+ x: rect.x,
2024
+ y: rect.y
2025
+ }, crop, orientation), compositionToSource({
2026
+ x: rect.x + rect.width,
2027
+ y: rect.y + rect.height
2028
+ }, crop, orientation));
2029
+ }
2030
+ function fitRedactionRegion(rect) {
2031
+ const limit = MAX_SCENE_COORDINATE;
2032
+ const x = clamp$1(Math.floor(rect.x), -limit, limit - 1);
2033
+ const y = clamp$1(Math.floor(rect.y), -limit, limit - 1);
2034
+ const right = clamp$1(Math.ceil(rect.x + rect.width), x + 1, limit);
2035
+ const bottom = clamp$1(Math.ceil(rect.y + rect.height), y + 1, limit);
2036
+ return {
2037
+ x,
2038
+ y,
2039
+ width: right - x,
2040
+ height: bottom - y
2041
+ };
2042
+ }
2043
+ // src/core/model/layer-placement.ts
2044
+ var QUARTERS = [
2045
+ 0,
2046
+ 900,
2047
+ 1800,
2048
+ 2700
2049
+ ];
2050
+ var clamp = (value, min, max) => Math.min(max, Math.max(min, value));
2051
+ function newLayerBox(plan, source, seen) {
2052
+ const crop = cropRect(plan.base.crop, source);
2053
+ const { orientation } = plan.base;
2054
+ const composition = compositionSize(plan, source);
2055
+ const width = clamp(Math.round(seen.width), 1, MAX_SCENE_COORDINATE);
2056
+ const height = clamp(Math.round(seen.height), 1, MAX_SCENE_COORDINATE);
2057
+ const asSeen = (rotation, flipX) => {
2058
+ const [a, , , d] = layerToOutput({
2059
+ x: 0,
2060
+ y: 0,
2061
+ width,
2062
+ height,
2063
+ rotation,
2064
+ flipX
2065
+ }, crop, orientation, composition);
2066
+ return a > .5 && d > .5;
2067
+ };
2068
+ const flipX = !QUARTERS.some((rotation) => asSeen(rotation, false));
2069
+ const rotation = QUARTERS.find((quarter) => asSeen(quarter, flipX)) ?? 0;
2070
+ const centre = compositionToSource({
2071
+ x: composition.width / 2,
2072
+ y: composition.height / 2
2073
+ }, crop, orientation);
2074
+ return {
2075
+ x: Math.round(centre.x - width / 2) || 0,
2076
+ y: Math.round(centre.y - height / 2) || 0,
2077
+ width,
2078
+ height,
2079
+ rotation,
2080
+ flipX
2081
+ };
2082
+ }
2083
+ function fittedImageSize(plan, source, image) {
2084
+ const { width, height } = compositionSize(plan, source);
2085
+ const scale = Math.min(1, width / 2 / image.width, height / 2 / image.height);
2086
+ return {
2087
+ width: image.width * scale,
2088
+ height: image.height * scale
2089
+ };
2090
+ }
1136
2091
  // src/core/session/session.ts
2092
+ function sourcesIn(command) {
2093
+ const of = (layer) => layer.kind === "image" && typeof layer.source === "string" ? [layer.source] : [];
2094
+ switch (command.type) {
2095
+ case "image.insertLayers": return command.layers.flatMap(of);
2096
+ case "image.restoreLayers": return command.entries.flatMap(({ layer }) => of(layer));
2097
+ case "image.updateLayers": return command.updates.flatMap(({ props }) => typeof props["source"] === "string" ? [props["source"]] : []);
2098
+ default: return [];
2099
+ }
2100
+ }
2101
+ var sourcesOf = (plan) => plan.layers.flatMap((layer) => layer.kind === "image" ? [layer.source] : []);
2102
+ function defaultLayer(source, plan, base) {
2103
+ return {
2104
+ key: createImageKey(new Set([...plan.layers, ...plan.redactions].map((item) => item.key))),
2105
+ kind: "image",
2106
+ name: "",
2107
+ visible: true,
2108
+ opacity: 100,
2109
+ ...newLayerBox(plan, base, fittedImageSize(plan, base, source)),
2110
+ source: source.id,
2111
+ crop: null
2112
+ };
2113
+ }
1137
2114
  var same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
1138
2115
  function commandsBetween(from, to) {
1139
2116
  const commands = [];
@@ -1163,6 +2140,28 @@ function commandsBetween(from, to) {
1163
2140
  field,
1164
2141
  value: to.metadata[field]
1165
2142
  });
2143
+ if (!same(from.layers, to.layers)) {
2144
+ if (from.layers.length > 0) commands.push({
2145
+ type: "image.removeLayers",
2146
+ keys: from.layers.map((layer) => layer.key)
2147
+ });
2148
+ if (to.layers.length > 0) commands.push({
2149
+ type: "image.insertLayers",
2150
+ at: 0,
2151
+ layers: to.layers
2152
+ });
2153
+ }
2154
+ if (!same(from.redactions, to.redactions)) {
2155
+ if (from.redactions.length > 0) commands.push({
2156
+ type: "image.removeRedactions",
2157
+ keys: from.redactions.map((redaction) => redaction.key)
2158
+ });
2159
+ if (to.redactions.length > 0) commands.push({
2160
+ type: "image.insertRedactions",
2161
+ at: 0,
2162
+ redactions: to.redactions
2163
+ });
2164
+ }
1166
2165
  return commands;
1167
2166
  }
1168
2167
  var PRESENCE = [
@@ -1173,9 +2172,10 @@ var PRESENCE = [
1173
2172
  "colourProfile",
1174
2173
  "other"
1175
2174
  ];
2175
+ var decodedBytes = (probe) => probe.oriented.width * probe.oriented.height * 4;
1176
2176
  function checkSource(policy, file, probe) {
1177
2177
  const near = checkFileLimits(policy, file.size, probe);
1178
- const bytes = probe.oriented.width * probe.oriented.height * 4;
2178
+ const bytes = decodedBytes(probe);
1179
2179
  if (policy.check("maxSessionSize", bytes) === "warning") near.push("maxSessionSize");
1180
2180
  return near;
1181
2181
  }
@@ -1184,11 +2184,15 @@ function createImageSession(options) {
1184
2184
  const policy = imageLimits.resolve(options.filePolicy);
1185
2185
  const history = createHistory();
1186
2186
  let source = null;
1187
- const reducer = createImageReducer((id) => source !== null && source.id === id ? source : void 0);
2187
+ const extras = /* @__PURE__ */ new Map();
2188
+ const exports = /* @__PURE__ */ new Set();
2189
+ const sourceOf = (id) => source?.id === id ? source : extras.get(id);
2190
+ const reducer = createImageReducer(sourceOf);
1188
2191
  let plan = null;
1189
2192
  let opens = 0;
1190
2193
  let opening = 0;
1191
2194
  let exporting = 0;
2195
+ let inserting = 0;
1192
2196
  let generation = 0;
1193
2197
  let warnings = [];
1194
2198
  let error = null;
@@ -1198,8 +2202,11 @@ function createImageSession(options) {
1198
2202
  status: plan !== null ? "ready" : !destroyed && opening > 0 ? "opening" : "empty",
1199
2203
  plan,
1200
2204
  source,
2205
+ sources: source ? [source, ...extras.values()] : [],
1201
2206
  canUndo: history.canUndo,
1202
2207
  canRedo: history.canRedo,
2208
+ historyTrimmed: history.trimmed,
2209
+ inserting: !destroyed && inserting > 0,
1203
2210
  opening: !destroyed && opening > 0,
1204
2211
  exporting: !destroyed && exporting > 0,
1205
2212
  warnings,
@@ -1220,9 +2227,57 @@ function createImageSession(options) {
1220
2227
  return error;
1221
2228
  };
1222
2229
  const superseded = () => new ImageError("ABORTED", "A later open replaced this one.", { details: { reason: "superseded" } });
2230
+ const referenced = (dropped = 0) => {
2231
+ const ids = /* @__PURE__ */ new Set();
2232
+ for (const held of [plan, ...exports]) if (held) for (const id of sourcesOf(held)) ids.add(id);
2233
+ const gone = new Set(history.dropOrder.slice(0, dropped));
2234
+ for (const step of history.steps) {
2235
+ if (gone.has(step)) continue;
2236
+ for (const command of [...step.commands, ...step.inverses]) for (const id of sourcesIn(command)) ids.add(id);
2237
+ }
2238
+ return ids;
2239
+ };
2240
+ const releaseUnreferenced = () => {
2241
+ const kept = referenced();
2242
+ for (const id of [...extras.keys()]) {
2243
+ if (kept.has(id)) continue;
2244
+ extras.delete(id);
2245
+ engine.release(id).catch(() => {});
2246
+ }
2247
+ };
2248
+ const heldBytes = (without = /* @__PURE__ */ new Set()) => {
2249
+ let bytes = source?.decodedBytes ?? 0;
2250
+ for (const [id, extra] of extras) if (!without.has(id)) bytes += extra.decodedBytes;
2251
+ return bytes;
2252
+ };
2253
+ const fits = (bytes) => {
2254
+ try {
2255
+ return policy.check("maxSessionSize", bytes);
2256
+ } catch {
2257
+ return false;
2258
+ }
2259
+ };
2260
+ const makeRoom = (bytes) => {
2261
+ const warned = (outcome) => outcome === "warning" ? ["maxSessionSize"] : [];
2262
+ const now = fits(heldBytes() + bytes);
2263
+ if (now !== false) return warned(now);
2264
+ for (let dropped = 1; dropped <= history.dropOrder.length; dropped += 1) {
2265
+ const kept = referenced(dropped);
2266
+ const freed = new Set([...extras.keys()].filter((id) => !kept.has(id)));
2267
+ const after = fits(heldBytes(freed) + bytes);
2268
+ if (after === false) continue;
2269
+ history.drop(dropped);
2270
+ releaseUnreferenced();
2271
+ return warned(after);
2272
+ }
2273
+ policy.check("maxSessionSize", heldBytes() + bytes);
2274
+ return [];
2275
+ };
1223
2276
  const attempt = (from, commands) => {
1224
2277
  const { state, inverses } = applyCommands(reducer, from, commands);
1225
2278
  if (source) checkOutputLimits(policy, outputSize(state.output, compositionSize(state, source)));
2279
+ const items = state.layers.length + state.redactions.length;
2280
+ if (items > from.layers.length + from.redactions.length) policy.check("maxLayers", items);
1226
2281
  return {
1227
2282
  state,
1228
2283
  step: {
@@ -1249,6 +2304,7 @@ function createImageSession(options) {
1249
2304
  throw fail(reason);
1250
2305
  }
1251
2306
  error = null;
2307
+ releaseUnreferenced();
1252
2308
  publish();
1253
2309
  emit({
1254
2310
  type: direction,
@@ -1266,6 +2322,7 @@ function createImageSession(options) {
1266
2322
  plan = result.state;
1267
2323
  history.push(result.step);
1268
2324
  error = null;
2325
+ releaseUnreferenced();
1269
2326
  emit({
1270
2327
  type: "execute",
1271
2328
  outcome: "done",
@@ -1329,6 +2386,7 @@ function createImageSession(options) {
1329
2386
  warnings = near;
1330
2387
  error = null;
1331
2388
  if (previous) engine.release(previous.id).catch(() => {});
2389
+ releaseUnreferenced();
1332
2390
  emit({
1333
2391
  type: "open",
1334
2392
  outcome: "done",
@@ -1351,11 +2409,88 @@ function createImageSession(options) {
1351
2409
  if (!destroyed) publish();
1352
2410
  }
1353
2411
  },
2412
+ async insertImage(file, insertOptions = {}) {
2413
+ assertAlive();
2414
+ if (plan === null || source === null) throw new ImageError("INVALID_COMMAND", "There's no image to add a layer to yet.");
2415
+ const started = generation;
2416
+ nextId += 1;
2417
+ const id = `source-${nextId}`;
2418
+ let registered = false;
2419
+ let held = false;
2420
+ inserting += 1;
2421
+ publish();
2422
+ try {
2423
+ const { probe, info } = await withProcessingTime(policy, async (signal) => {
2424
+ throwIfAborted(signal);
2425
+ policy.check("maxFileSize", file.size);
2426
+ const probe = await engine.probe(file, { signal });
2427
+ throwIfAborted(signal);
2428
+ checkFileLimits(policy, file.size, probe);
2429
+ const info = await engine.register(id, file, probe, {
2430
+ filePolicy: policy,
2431
+ signal
2432
+ });
2433
+ registered = true;
2434
+ throwIfAborted(signal);
2435
+ return {
2436
+ probe,
2437
+ info
2438
+ };
2439
+ }, insertOptions);
2440
+ assertAlive();
2441
+ if (started !== generation || plan === null || source === null) throw superseded();
2442
+ const near = checkFileLimits(policy, file.size, probe);
2443
+ if (policy.check("maxFiles", extras.size + 2) === "warning") near.push("maxFiles");
2444
+ near.push(...makeRoom(info.decodedBytes));
2445
+ const added = {
2446
+ ...info,
2447
+ fileSize: file.size,
2448
+ metadata: probe.metadata,
2449
+ keepable: probe.keepable
2450
+ };
2451
+ extras.set(id, added);
2452
+ held = true;
2453
+ try {
2454
+ const placed = insertOptions.place?.(added, plan) ?? {
2455
+ type: "image.insertLayers",
2456
+ at: plan.layers.length,
2457
+ layers: [defaultLayer(added, plan, source)]
2458
+ };
2459
+ const commands = Array.isArray(placed) ? placed : [placed];
2460
+ if (!commands.some((command) => sourcesIn(command).includes(id))) throw new ImageError("INVALID_COMMAND", "The commands don't add the image to the plan.");
2461
+ executeCommands(commands);
2462
+ } finally {
2463
+ releaseUnreferenced();
2464
+ }
2465
+ warnings = near;
2466
+ emit({
2467
+ type: "insert",
2468
+ outcome: "done",
2469
+ commands: []
2470
+ });
2471
+ return added;
2472
+ } catch (reason) {
2473
+ if (registered && !held) await engine.release(id).catch(() => {});
2474
+ const failure = isImageError(reason) ? reason : asImageError(reason);
2475
+ const cancelled = failure.code === "ABORTED";
2476
+ if (!cancelled && !destroyed && started === generation) fail(failure);
2477
+ emit({
2478
+ type: "insert",
2479
+ outcome: cancelled ? "cancelled" : "failed",
2480
+ commands: []
2481
+ });
2482
+ throw failure;
2483
+ } finally {
2484
+ inserting -= 1;
2485
+ if (!destroyed) publish();
2486
+ }
2487
+ },
1354
2488
  execute: (input) => executeCommands(input),
1355
2489
  applyPlan(next) {
1356
2490
  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.");
2491
+ const shaped = Array.isArray(next.redactions) && Array.isArray(next.layers) && next.animation === null;
2492
+ if (plan === null || !shaped || next.base.source !== plan.base.source) {
2493
+ const failure = new ImageError("INVALID_COMMAND", shaped ? "The plan isn't for the open image." : "The plan needs layers, redactions and animation, as createPlan gives them.");
1359
2494
  error = failure;
1360
2495
  publish();
1361
2496
  throw failure;
@@ -1377,6 +2512,7 @@ function createImageSession(options) {
1377
2512
  const exported = plan;
1378
2513
  const from = source;
1379
2514
  exporting += 1;
2515
+ exports.add(exported);
1380
2516
  publish();
1381
2517
  try {
1382
2518
  const size = outputSize(exported.output, compositionSize(exported, from));
@@ -1419,31 +2555,35 @@ function createImageSession(options) {
1419
2555
  throw failure;
1420
2556
  } finally {
1421
2557
  exporting -= 1;
1422
- if (!destroyed) publish();
2558
+ exports.delete(exported);
2559
+ if (!destroyed) {
2560
+ releaseUnreferenced();
2561
+ publish();
2562
+ }
1423
2563
  }
1424
2564
  },
1425
2565
  async destroy() {
1426
2566
  if (destroyed) return;
1427
2567
  destroyed = true;
1428
- const held = source;
2568
+ const held = [...source ? [source.id] : [], ...extras.keys()];
1429
2569
  source = null;
2570
+ extras.clear();
1430
2571
  plan = null;
1431
2572
  history.clear();
1432
2573
  publish();
1433
- if (held) await engine.release(held.id).catch(() => {});
2574
+ await Promise.all(held.map((id) => engine.release(id).catch(() => {})));
1434
2575
  }
1435
2576
  };
1436
2577
  }
1437
2578
  // src/messages/en.ts
1438
2579
  var imageMessages = /* @__PURE__ */ defineMessages({
1439
2580
  ...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
2581
  "errors.INVALID_IMAGE": "This file isn't a valid image, or it's too damaged to open.",
1443
2582
  "errors.UNSUPPORTED_FORMAT": "This image format isn't supported. Try converting the file to PNG or JPEG, then open it again.",
1444
2583
  "errors.DECODE_FAILED": "This browser can't open this kind of image. Try another browser, or convert the file to PNG or JPEG.",
1445
2584
  "errors.INVALID_COMMAND": "This edit couldn't be made. Please try again.",
1446
2585
  "errors.INVALID_DOCUMENT": "This project is damaged, or it isn't an image project.",
2586
+ "errors.UNSUPPORTED_PLAN": "This image has edits this version can't show. Update the application and try again.",
1447
2587
  "errors.IMAGE_TOO_LARGE": "This image has more pixels than the editor can handle. Try a smaller version of it.",
1448
2588
  "errors.IMAGE_DIMENSION_TOO_LARGE": "This image is {actual, number} pixels across, which is over the {maximum, number}-pixel limit.",
1449
2589
  "errors.TOO_MANY_FRAMES": /* @__PURE__ */ plural("maximum", {
@@ -1465,148 +2605,8 @@ var imageMessages = /* @__PURE__ */ defineMessages({
1465
2605
  "warnings.maxLayers": /* @__PURE__ */ plural("actual", {
1466
2606
  one: "This image has {actual} layer.",
1467
2607
  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"
2608
+ })
1609
2609
  });
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 };
2610
+ export { NO_METADATA as $, compositionSize as A, imageLimitDefinitions as At, checkOutput as B, cropInComposition as C, createImageProcessor as Ct, moveCrop as D, PER_FILE_LIMITS as Dt, handleInSource as E, OUTPUT_LIMITS as Et, sourceToComposition as F, Invalid as G, FORBIDDEN_IN_TEXT as H, checkDevelop as I, invalid as J, checkCrop as K, checkFilter as L, cropRect as M, asImageError as Mt, orientedSize as N, ImageError as Nt, nudgeCropOnScreen as O, checkFileLimits as Ot, outputSize as P, isImageError as Pt, MAX_METADATA_LENGTH as Q, checkMetadata as R, compositionDeltaToSource as S, placement as St, fitAspect as T, engineInternals as Tt, checkLayer as U, createImageReducer as V, checkRedaction as W, onlyFields as X, isRecord as Y, EMPTY_KEEPABLE_METADATA as Z, sceneToLayerSource as _, createPlan as _t, fitRedactionRegion as a, LAYER_FONTS as at, ASPECT_PRESETS as b, backingSize as bt, redactionBlocksInScene as c, MAX_KEY_LENGTH as ct, applyMatrix as d, MAX_PLAN_ITEMS as dt, longerThan as et, fitTextLines as f, MAX_SCENE_COORDINATE as ft, layerToScene as g, UPRIGHT as gt, layerToOutput as h, REDACTION_MODES as ht, compositionRectToScene as i, LAYER_ALIGNMENTS as it, compositionToSource as j, imageLimits as jt, wholeCrop as k, checkOutputLimits as kt, redactionRectInOutput as l, MAX_LAYER_NAME_LENGTH as lt, isRightToLeft as m, NEUTRAL_DEVELOP as mt, createImageSession as n, FILTER_PRESETS as nt, redactionBlockSize as o, LAYER_KINDS as ot, invertMatrix as p, MAX_STROKE_WIDTH as pt, checkCropInSource as q, newLayerBox as r, FULL_SIZE as rt, redactionBlocksInOutput as s, LAYER_SHAPES as st, imageMessages as t, DEVELOP_ADJUSTMENTS as tt, sceneRectToComposition as u, MAX_LAYER_TEXT_LENGTH as ut, sceneToOutput as v, createImageRenderer as vt, dragHandle as w, createImageEngine as wt, aspectRatio as x, fittedView as xt, createImageKey as y, MAX_PIXEL_RATIO as yt, checkOrientation as z };
1611
2611
 
1612
- //# sourceMappingURL=core-BWNmXDlB.js.map
2612
+ //# sourceMappingURL=core-BlFeJWak.js.map