@hussmartinez/image-sdk 0.4.0 → 0.6.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.
package/dist/index.d.ts CHANGED
@@ -16,6 +16,19 @@ import type { Reducer } from '@hussmartinez/sdk-core';
16
16
  import { SdkCoreErrorCode } from '@hussmartinez/sdk-core';
17
17
  import { SdkError } from '@hussmartinez/sdk-core';
18
18
 
19
+ /**
20
+ * Appends strokes to a drawing layer (ADR 0009, docs/adr/0014): one stroke
21
+ * for each gesture, however many runs it has.
22
+ *
23
+ * @public
24
+ */
25
+ export declare interface AddStrokesCommand {
26
+ readonly type: "image.addStrokes";
27
+ /** The drawing's key. */
28
+ readonly key: string;
29
+ readonly strokes: readonly ImageStroke[];
30
+ }
31
+
19
32
  /**
20
33
  * Where a point goes under a transform.
21
34
  *
@@ -29,6 +42,32 @@ export declare function applyMatrix(matrix: ImageMatrix, point: {
29
42
  readonly y: number;
30
43
  };
31
44
 
45
+ /**
46
+ * The smallest whole-pixel rectangle of the scene that holds an arrow's
47
+ * outline.
48
+ *
49
+ * @public
50
+ */
51
+ export declare function arrowBounds(arrow: Pick<ImageArrowLayer, "from" | "to" | "width">): ImageRect;
52
+
53
+ /**
54
+ * An arrow's outline (docs/adr/0014): seven points of a polygon, in scene
55
+ * pixels, which the renderer fills. Its tip is exactly on `to`. The head is
56
+ * a triangle `4 × width` long and `4 × width` across at its base; the shaft
57
+ * is a rectangle `width` across from `from` to the middle of the head's
58
+ * base. An arrow shorter than its head is all head: the triangle keeps its
59
+ * proportions, as long as the arrow, and the shaft's four points are on its
60
+ * base.
61
+ *
62
+ * In order: the shaft's tail, left then right as the arrow points; the
63
+ * shaft's end on the base, right; the head's right corner; the tip; the
64
+ * head's left corner; the shaft's end on the base, left.
65
+ *
66
+ * @throws `RangeError` when `from` equals `to`: there's no direction.
67
+ * @public
68
+ */
69
+ export declare function arrowOutline(from: ImageScenePoint, to: ImageScenePoint, width: number): ImageScenePoint[];
70
+
32
71
  /**
33
72
  * The crop panel's presets, landscape then portrait (docs/adr/0007).
34
73
  *
@@ -300,6 +339,23 @@ export declare const DEVELOP_ADJUSTMENTS: readonly ["temperature", "tint", "expo
300
339
  */
301
340
  export declare function dragHandle(crop: ImageCrop, handle: CropHandle, dx: number, dy: number, source: ImageSize, ratio?: number): ImageCrop;
302
341
 
342
+ /**
343
+ * The smallest whole-pixel rectangle of the scene that holds everything a
344
+ * drawing draws: its points, and half of each stroke's width around them
345
+ * (docs/adr/0014). The editor places a drawing's frame with it.
346
+ *
347
+ * @public
348
+ */
349
+ export declare function drawingBounds(drawing: Pick<ImageDrawingLayer, "x" | "y" | "strokes">): ImageRect;
350
+
351
+ /**
352
+ * How many points a plan's drawings hold, across every run of every stroke:
353
+ * what `maxDrawingPoints` limits (ADR 0009).
354
+ *
355
+ * @public
356
+ */
357
+ export declare function drawingPoints(plan: Pick<ImagePlan, "layers">): number;
358
+
303
359
  /**
304
360
  * Keepable metadata with every field empty.
305
361
  *
@@ -404,7 +460,26 @@ export declare const IMAGE_PLAN_FORMAT = "hm-image-plan";
404
460
  *
405
461
  * @public
406
462
  */
407
- export declare const IMAGE_PLAN_VERSION = 2;
463
+ export declare const IMAGE_PLAN_VERSION = 3;
464
+
465
+ /**
466
+ * An arrow from one point of the scene to another (ADR 0009,
467
+ * docs/adr/0014). Its head's size follows its width, and its tip is exactly
468
+ * on `to`.
469
+ *
470
+ * @public
471
+ */
472
+ export declare interface ImageArrowLayer extends ImageLayerCommon {
473
+ readonly kind: "arrow";
474
+ /** The tail. */
475
+ readonly from: ImageScenePoint;
476
+ /** The tip. It differs from `from`. */
477
+ readonly to: ImageScenePoint;
478
+ /** `#rrggbb`. */
479
+ readonly colour: string;
480
+ /** The shaft's width, in whole scene pixels: 1 to `MAX_STROKE_WIDTH`. */
481
+ readonly width: number;
482
+ }
408
483
 
409
484
  /**
410
485
  * The crop frame's geometry (docs/adr/0007): pure functions over crops in
@@ -451,6 +526,13 @@ export declare interface ImageBase {
451
526
  readonly filter: ImageFilter | null;
452
527
  }
453
528
 
529
+ /**
530
+ * A layer that has a box: text, a shape or an image.
531
+ *
532
+ * @public
533
+ */
534
+ export declare type ImageBoxedLayer = ImageTextLayer | ImageShapeLayer | ImageImageLayer;
535
+
454
536
  /**
455
537
  * Options every port call accepts.
456
538
  *
@@ -471,7 +553,7 @@ export declare interface ImageCallOptions {
471
553
  *
472
554
  * @public
473
555
  */
474
- export declare type ImageCommand = SetCropCommand | SetOrientationCommand | SetOutputCommand | SetMetadataCommand | SetDevelopCommand | SetFilterCommand | InsertLayersCommand | RemoveLayersCommand | MoveLayersCommand | UpdateLayersCommand | InsertRedactionsCommand | RemoveRedactionsCommand | MoveRedactionsCommand | UpdateRedactionsCommand | ImageInverseCommand;
556
+ export declare type ImageCommand = SetCropCommand | SetOrientationCommand | SetOutputCommand | SetMetadataCommand | SetDevelopCommand | SetFilterCommand | InsertLayersCommand | RemoveLayersCommand | MoveLayersCommand | UpdateLayersCommand | AddStrokesCommand | RemoveStrokesCommand | InsertRedactionsCommand | RemoveRedactionsCommand | MoveRedactionsCommand | UpdateRedactionsCommand | ImageInverseCommand;
475
557
 
476
558
  /**
477
559
  * Why a command was refused, as a stable token: `details.reason` on the
@@ -525,7 +607,7 @@ export declare type ImageCommand = SetCropCommand | SetOrientationCommand | SetO
525
607
  *
526
608
  * @public
527
609
  */
528
- export declare type ImageCommandRejection = "malformed-command" | "unknown-command" | "unknown-source" | "crop-outside-source" | "invalid-orientation" | "invalid-output" | "unknown-metadata-field" | "metadata-too-long" | "unknown-adjustment" | "invalid-level" | "unknown-preset" | "invalid-strength" | "invalid-key" | "duplicate-key" | "invalid-index" | "invalid-order" | "unknown-layer" | "unknown-layer-kind" | "invalid-box" | "invalid-opacity" | "invalid-text" | "text-too-long" | "empty-shape" | "wrong-kind" | "unknown-redaction" | "unknown-redaction-mode" | "invalid-region" | "invalid-colour" | "unexpected-colour" | "missing-colour" | "too-many-layers";
610
+ export declare type ImageCommandRejection = "malformed-command" | "unknown-command" | "unknown-source" | "crop-outside-source" | "invalid-orientation" | "invalid-output" | "unknown-metadata-field" | "metadata-too-long" | "unknown-adjustment" | "invalid-level" | "unknown-preset" | "invalid-strength" | "invalid-key" | "duplicate-key" | "invalid-index" | "invalid-order" | "unknown-layer" | "unknown-layer-kind" | "invalid-box" | "invalid-opacity" | "invalid-text" | "text-too-long" | "empty-shape" | "empty-drawing" | "empty-arrow" | "invalid-points" | "too-many-strokes" | "wrong-kind" | "unknown-redaction" | "unknown-redaction-mode" | "invalid-region" | "invalid-colour" | "unexpected-colour" | "missing-colour" | "too-many-layers";
529
611
 
530
612
  /**
531
613
  * A rectangle in whole pixels of the oriented source: `x` and `y` from its
@@ -576,12 +658,32 @@ export declare interface ImageDevelop {
576
658
  * `invalid-level`, `unknown-preset`, `invalid-strength`, `invalid-key`,
577
659
  * `unknown-redaction-mode`, `invalid-region`, `invalid-colour`,
578
660
  * `unknown-layer-kind`, `invalid-box`, `invalid-opacity`, `invalid-text`,
579
- * `text-too-long`, `empty-shape` and `too-many-layers`. `unknown-source`
580
- * and `crop-outside-source` apply to an image layer too.
661
+ * `text-too-long`, `empty-shape`, `empty-drawing`, `empty-arrow`,
662
+ * `invalid-points` and `too-many-layers`. `unknown-source` and
663
+ * `crop-outside-source` apply to an image layer too. A drawing or an
664
+ * arrow in a document of version 2, which has neither, is
665
+ * `unknown-layer-kind`.
581
666
  *
582
667
  * @public
583
668
  */
584
- export declare type ImageDocumentRejection = "unknown-format" | "unknown-format-version" | "malformed-document" | "unknown-source" | "crop-outside-source" | "invalid-orientation" | "invalid-output" | "metadata-too-long" | "unknown-adjustment" | "invalid-level" | "unknown-preset" | "invalid-strength" | "duplicate-key" | "invalid-key" | "unknown-redaction-mode" | "invalid-region" | "invalid-colour" | "unknown-layer-kind" | "invalid-box" | "invalid-opacity" | "invalid-text" | "text-too-long" | "empty-shape" | "too-many-layers";
669
+ export declare type ImageDocumentRejection = "unknown-format" | "unknown-format-version" | "malformed-document" | "unknown-source" | "crop-outside-source" | "invalid-orientation" | "invalid-output" | "metadata-too-long" | "unknown-adjustment" | "invalid-level" | "unknown-preset" | "invalid-strength" | "duplicate-key" | "invalid-key" | "unknown-redaction-mode" | "invalid-region" | "invalid-colour" | "unknown-layer-kind" | "invalid-box" | "invalid-opacity" | "invalid-text" | "text-too-long" | "empty-shape" | "empty-drawing" | "empty-arrow" | "invalid-points" | "too-many-layers";
670
+
671
+ /**
672
+ * Freehand strokes (ADR 0009, docs/adr/0014). A drawing has an origin and
673
+ * no box: moving it changes its origin, never its points. Its strokes are
674
+ * drawn opaque and the drawing composited as one, so strokes that cross
675
+ * don't darken each other.
676
+ *
677
+ * @public
678
+ */
679
+ export declare interface ImageDrawingLayer extends ImageLayerCommon {
680
+ readonly kind: "drawing";
681
+ /** Its origin, in whole scene pixels. May be negative. */
682
+ readonly x: number;
683
+ readonly y: number;
684
+ /** 1 to `MAX_DRAWING_STROKES` strokes, in the order they're drawn. */
685
+ readonly strokes: readonly ImageStroke[];
686
+ }
585
687
 
586
688
  /**
587
689
  * The port for reading images: probe a file's headers, decode it into a
@@ -705,6 +807,8 @@ export declare class ImageError extends SdkError<ImageErrorCode> {
705
807
  * - `SESSION_TOO_LARGE`: the decoded images the session holds exceed the
706
808
  * `maxSessionSize` limit.
707
809
  * - `TOO_MANY_LAYERS`: the layer plan exceeds the `maxLayers` limit.
810
+ * - `TOO_MANY_POINTS`: the plan's drawings hold more points than the
811
+ * `maxDrawingPoints` limit.
708
812
  *
709
813
  * Limit codes carry `details` with the `limit`, its `maximum`, the `actual`
710
814
  * value and the `unit`. Other codes' `details` name the format involved,
@@ -712,7 +816,7 @@ export declare class ImageError extends SdkError<ImageErrorCode> {
712
816
  *
713
817
  * @public
714
818
  */
715
- export declare type ImageErrorCode = SdkCoreErrorCode | "INVALID_IMAGE" | "UNSUPPORTED_FORMAT" | "DECODE_FAILED" | "INVALID_COMMAND" | "INVALID_DOCUMENT" | "UNSUPPORTED_PLAN" | "IMAGE_TOO_LARGE" | "IMAGE_DIMENSION_TOO_LARGE" | "TOO_MANY_FRAMES" | "SESSION_TOO_LARGE" | "TOO_MANY_LAYERS";
819
+ export declare type ImageErrorCode = SdkCoreErrorCode | "INVALID_IMAGE" | "UNSUPPORTED_FORMAT" | "DECODE_FAILED" | "INVALID_COMMAND" | "INVALID_DOCUMENT" | "UNSUPPORTED_PLAN" | "IMAGE_TOO_LARGE" | "IMAGE_DIMENSION_TOO_LARGE" | "TOO_MANY_FRAMES" | "SESSION_TOO_LARGE" | "TOO_MANY_LAYERS" | "TOO_MANY_POINTS";
716
820
 
717
821
  /**
718
822
  * The file an export produces (ADR 0001). `quality`, from 0 to 1, applies to
@@ -843,7 +947,7 @@ declare interface ImageInsertOptions {
843
947
  *
844
948
  * @public
845
949
  */
846
- export declare type ImageInverseCommand = RestoreLayersCommand | SetLayerOrderCommand | RestoreRedactionsCommand | SetRedactionOrderCommand;
950
+ export declare type ImageInverseCommand = RestoreStrokesCommand | RestoreLayersCommand | SetLayerOrderCommand | RestoreRedactionsCommand | SetRedactionOrderCommand;
847
951
 
848
952
  /**
849
953
  * The metadata fields a user may keep on export (ADR 0005). Empty strings
@@ -859,13 +963,13 @@ export declare interface ImageKeepableMetadata {
859
963
  }
860
964
 
861
965
  /**
862
- * A layer over the base: text, a shape or another image (ADR 0009). Layers
863
- * are drawn bottom to top, in the plan's order, and redactions over all of
864
- * them.
966
+ * A layer over the base: text, a shape, another image, a drawing or an
967
+ * arrow (ADR 0009). Layers are drawn bottom to top, in the plan's order, and
968
+ * redactions over all of them.
865
969
  *
866
970
  * @public
867
971
  */
868
- export declare type ImageLayer = ImageTextLayer | ImageShapeLayer | ImageImageLayer;
972
+ export declare type ImageLayer = ImageBoxedLayer | ImageDrawingLayer | ImageArrowLayer;
869
973
 
870
974
  /**
871
975
  * Where a positioned layer is: a box in whole pixels of the scene, the
@@ -945,6 +1049,7 @@ export declare type ImageLimitDefinitions = typeof imageLimitDefinitions;
945
1049
  * | `maxFrames` | `TOO_MANY_FRAMES` | 300 | 100 |
946
1050
  * | `maxSessionSize` | `SESSION_TOO_LARGE` | 1 GB | 500 MB |
947
1051
  * | `maxLayers` | `TOO_MANY_LAYERS` | 256 | none |
1052
+ * | `maxDrawingPoints` | `TOO_MANY_POINTS` | 200,000 | 100,000 |
948
1053
  *
949
1054
  * Sizes are decimal: 1 MB is 1,000,000 bytes. Decoded sizes count 4 bytes
950
1055
  * per pixel. `maxImagePixels` is the same limit, with the same name, code
@@ -987,6 +1092,12 @@ export declare const imageLimitDefinitions: {
987
1092
  readonly unit: "count";
988
1093
  readonly default: 256;
989
1094
  };
1095
+ readonly maxDrawingPoints: {
1096
+ readonly code: "TOO_MANY_POINTS";
1097
+ readonly unit: "count";
1098
+ readonly default: 200000;
1099
+ readonly warning: 100000;
1100
+ };
990
1101
  readonly maxFileSize: {
991
1102
  readonly code: "FILE_TOO_LARGE";
992
1103
  readonly unit: "bytes";
@@ -1095,6 +1206,7 @@ export declare const imageMessages: {
1095
1206
  readonly one: "An image can have {maximum} layer. Merge or delete layers, and try again.";
1096
1207
  readonly other: "An image can have up to {maximum, number} layers. Merge or delete layers, and try again.";
1097
1208
  };
1209
+ readonly "errors.TOO_MANY_POINTS": "This image's drawings would have {actual, number} points, which is over the limit of {maximum, number}. Remove some strokes, and try again.";
1098
1210
  readonly "warnings.maxImagePixels": "This image is large, and may be slow to edit on some devices.";
1099
1211
  readonly "warnings.maxImageDimension": "This image is very wide or tall, and may be slow to edit.";
1100
1212
  readonly "warnings.maxFrames": {
@@ -1110,6 +1222,7 @@ export declare const imageMessages: {
1110
1222
  readonly one: "This image has {actual} layer.";
1111
1223
  readonly other: "This image has {actual, number} layers, and may be slow to edit and export.";
1112
1224
  };
1225
+ readonly "warnings.maxDrawingPoints": "This image has a lot of drawing, and may be slow to edit and export.";
1113
1226
  readonly "errors.UNKNOWN": "Something went wrong. Please try again.";
1114
1227
  readonly "errors.ABORTED": "The operation was cancelled.";
1115
1228
  readonly "errors.TIMEOUT": "The operation took too long and was stopped.";
@@ -1225,8 +1338,8 @@ export declare interface ImagePlan {
1225
1338
  }
1226
1339
 
1227
1340
  /**
1228
- * The plan as portable JSON: `hm-image-plan` version 2, which
1229
- * `formats/hm-image-plan/v2.schema.json` describes
1341
+ * The plan as portable JSON: `hm-image-plan` version 3, which
1342
+ * `formats/hm-image-plan/v3.schema.json` describes
1230
1343
  * (docs/formats/hm-image-plan.md). Positions are whole pixels of the
1231
1344
  * oriented source, and the base names its source by an id the document
1232
1345
  * lists.
@@ -1252,10 +1365,12 @@ export declare interface ImagePlanDocumentSource extends ImageSize {
1252
1365
 
1253
1366
  /**
1254
1367
  * A part of a plan that a renderer or processor may not know how to draw.
1368
+ * `layers` is any layer; `drawings` is a drawing or an arrow layer, which a
1369
+ * renderer that draws the other kinds may not.
1255
1370
  *
1256
1371
  * @public
1257
1372
  */
1258
- export declare type ImagePlanPart = "layers" | "redactions" | "animation";
1373
+ export declare type ImagePlanPart = "layers" | "drawings" | "redactions" | "animation";
1259
1374
 
1260
1375
  /**
1261
1376
  * A point in pixels, which may be fractional.
@@ -1489,6 +1604,16 @@ export declare type ImageRenderOutcome = "drawn" | "superseded";
1489
1604
  */
1490
1605
  export declare type ImageRotation = 0 | 90 | 180 | 270;
1491
1606
 
1607
+ /**
1608
+ * A point of the scene, in whole pixels.
1609
+ *
1610
+ * @public
1611
+ */
1612
+ export declare interface ImageScenePoint {
1613
+ readonly x: number;
1614
+ readonly y: number;
1615
+ }
1616
+
1492
1617
  /**
1493
1618
  * An image editing session (ADR 0003, ADR 0008): one document, its plan
1494
1619
  * over the source it opened, edited by commands with undo and redo, and
@@ -1722,6 +1847,25 @@ export declare interface ImageSourceInfo {
1722
1847
  readonly decodedBytes: number;
1723
1848
  }
1724
1849
 
1850
+ /**
1851
+ * One stroke of a drawing: what one gesture drew, from the press to the
1852
+ * release (docs/adr/0014). It has more than one run only when it's long.
1853
+ *
1854
+ * @public
1855
+ */
1856
+ export declare interface ImageStroke {
1857
+ /** `#rrggbb`. */
1858
+ readonly colour: string;
1859
+ /** In whole scene pixels: 1 to `MAX_STROKE_WIDTH`. */
1860
+ readonly width: number;
1861
+ /**
1862
+ * 1 to `MAX_STROKE_RUNS` runs, each a polyline `[x0, y0, x1, y1, …]` of 1
1863
+ * to `MAX_RUN_POINTS` points, in whole pixels from the drawing's origin.
1864
+ * A run of one point is a dot.
1865
+ */
1866
+ readonly runs: readonly (readonly number[])[];
1867
+ }
1868
+
1725
1869
  /**
1726
1870
  * Text, drawn as large as fits inside its box, never distorted (ADR 0009).
1727
1871
  * Lines break only at line feeds. Emoji are text.
@@ -1875,7 +2019,7 @@ export declare const LAYER_FONTS: readonly ["sans-serif", "serif", "monospace"];
1875
2019
  *
1876
2020
  * @public
1877
2021
  */
1878
- export declare const LAYER_KINDS: readonly ["text", "shape", "image"];
2022
+ export declare const LAYER_KINDS: readonly ["text", "shape", "image", "drawing", "arrow"];
1879
2023
 
1880
2024
  /**
1881
2025
  * The shapes a shape layer can be.
@@ -1903,6 +2047,13 @@ export declare function layerToOutput(box: ImageLayerBox, crop: ImageCrop, orien
1903
2047
  */
1904
2048
  export declare function layerToScene(box: ImageLayerBox): ImageMatrix;
1905
2049
 
2050
+ /**
2051
+ * The most strokes in a drawing (docs/adr/0014).
2052
+ *
2053
+ * @public
2054
+ */
2055
+ export declare const MAX_DRAWING_STROKES = 1024;
2056
+
1906
2057
  /**
1907
2058
  * The most Unicode code points in a key.
1908
2059
  *
@@ -1949,6 +2100,13 @@ export declare const MAX_PIXEL_RATIO = 4;
1949
2100
  */
1950
2101
  export declare const MAX_PLAN_ITEMS = 1024;
1951
2102
 
2103
+ /**
2104
+ * The most points in one run of a drawing's stroke (docs/adr/0014).
2105
+ *
2106
+ * @public
2107
+ */
2108
+ export declare const MAX_RUN_POINTS = 2000;
2109
+
1952
2110
  /**
1953
2111
  * How far from the scene's origin a position may be, in pixels, either way:
1954
2112
  * four times the longest side `maxImageDimension` allows by default (ADR
@@ -1959,7 +2117,15 @@ export declare const MAX_PLAN_ITEMS = 1024;
1959
2117
  export declare const MAX_SCENE_COORDINATE = 65536;
1960
2118
 
1961
2119
  /**
1962
- * The widest stroke of a shape, in scene pixels.
2120
+ * The most runs in a stroke (docs/adr/0014).
2121
+ *
2122
+ * @public
2123
+ */
2124
+ export declare const MAX_STROKE_RUNS = 64;
2125
+
2126
+ /**
2127
+ * The widest stroke of a shape or a drawing, and the widest arrow's shaft,
2128
+ * in scene pixels.
1963
2129
  *
1964
2130
  * @public
1965
2131
  */
@@ -2078,7 +2244,8 @@ export declare function placement(composition: {
2078
2244
  * inside them, and no two items share a key. Unknown fields are refused, never dropped.
2079
2245
  *
2080
2246
  * A document of an earlier version is migrated, so every version stays
2081
- * readable: version 1 reads as a plan with no layers or redactions.
2247
+ * readable: version 1 reads as a plan with no layers or redactions, and
2248
+ * version 2 as it is, with the kinds of layer it had.
2082
2249
  *
2083
2250
  * @param value - The parsed JSON.
2084
2251
  * @returns The plan, and its sources by id.
@@ -2164,6 +2331,18 @@ export declare interface RemoveRedactionsCommand {
2164
2331
  readonly keys: readonly string[];
2165
2332
  }
2166
2333
 
2334
+ /**
2335
+ * Removes strokes from a drawing layer, by index. A drawing keeps at least
2336
+ * one stroke: to remove the last, remove the layer.
2337
+ *
2338
+ * @public
2339
+ */
2340
+ export declare interface RemoveStrokesCommand {
2341
+ readonly type: "image.removeStrokes";
2342
+ readonly key: string;
2343
+ readonly indexes: readonly number[];
2344
+ }
2345
+
2167
2346
  /**
2168
2347
  * Puts removed layers back, each at its index, by rising index. It's what
2169
2348
  * undoes {@link RemoveLayersCommand}: the reducer applies it, but it isn't
@@ -2194,6 +2373,22 @@ export declare interface RestoreRedactionsCommand {
2194
2373
  }[];
2195
2374
  }
2196
2375
 
2376
+ /**
2377
+ * Puts removed strokes back, each at its index, by rising index. It's what
2378
+ * undoes {@link RemoveStrokesCommand}: the reducer applies it, but it isn't
2379
+ * part of the portable command format (ADR 0009).
2380
+ *
2381
+ * @public
2382
+ */
2383
+ export declare interface RestoreStrokesCommand {
2384
+ readonly type: "image.restoreStrokes";
2385
+ readonly key: string;
2386
+ readonly entries: readonly {
2387
+ readonly at: number;
2388
+ readonly stroke: ImageStroke;
2389
+ }[];
2390
+ }
2391
+
2197
2392
  /**
2198
2393
  * A rectangle of the scene as the composition shows it: through the crop,
2199
2394
  * the rotation and the flips, in composition pixels, without clipping. The
@@ -2316,6 +2511,27 @@ export declare interface SetRedactionOrderCommand {
2316
2511
  readonly keys: readonly string[];
2317
2512
  }
2318
2513
 
2514
+ /**
2515
+ * A pointer's samples as one stroke's `runs` (docs/adr/0014): repeats
2516
+ * dropped, long input cut into runs of at most 2,000 points that share
2517
+ * their end points, and each run simplified by Ramer–Douglas–Peucker with
2518
+ * distance to the segment. The same samples give the same runs in every
2519
+ * engine: every comparison is between whole numbers.
2520
+ *
2521
+ * A tolerance of 0 drops only repeats and points exactly on a segment.
2522
+ *
2523
+ * @param points - `[x0, y0, x1, y1, …]`, in whole pixels from the drawing's
2524
+ * origin: at least one point.
2525
+ * @param tolerance - In whole scene pixels, from 0. The draw tool passes one
2526
+ * screen pixel's worth.
2527
+ * @returns 1 to 64 runs, each `[x0, y0, …]` of 1 to 2,000 points.
2528
+ * @throws `RangeError` for no points, an odd number of coordinates, a
2529
+ * coordinate or a tolerance that isn't a whole number, or more points
2530
+ * than 64 runs hold: a caller's mistake, since samples aren't a file's.
2531
+ * @public
2532
+ */
2533
+ export declare function simplifyStroke(points: readonly number[], tolerance: number): number[][];
2534
+
2319
2535
  /**
2320
2536
  * Maps a point in the cropped source to the composition, through the plan's
2321
2537
  * rotation and then its flips. Points are continuous coordinates, so the
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import { $ as NO_METADATA, A as compositionSize, At as imageLimitDefinitions, B as checkOutput, C as cropInComposition, Ct as createImageProcessor, D as moveCrop, Dt as PER_FILE_LIMITS, E as handleInSource, Et as OUTPUT_LIMITS, F as sourceToComposition, G as Invalid, I as checkDevelop, J as invalid, K as checkCrop, L as checkFilter, M as cropRect, N as orientedSize, Nt as ImageError, O as nudgeCropOnScreen, Ot as checkFileLimits, P as outputSize, Pt as isImageError, Q as MAX_METADATA_LENGTH, R as checkMetadata, S as compositionDeltaToSource, St as placement, T as fitAspect, U as checkLayer, V as createImageReducer, W as checkRedaction, X as onlyFields, Y as isRecord, Z as EMPTY_KEEPABLE_METADATA, _ as sceneToLayerSource, _t as createPlan, a as fitRedactionRegion, at as LAYER_FONTS, b as ASPECT_PRESETS, bt as backingSize, c as redactionBlocksInScene, ct as MAX_KEY_LENGTH, d as applyMatrix, dt as MAX_PLAN_ITEMS, f as fitTextLines, ft as MAX_SCENE_COORDINATE, g as layerToScene, gt as UPRIGHT, h as layerToOutput, ht as REDACTION_MODES, i as compositionRectToScene, it as LAYER_ALIGNMENTS, j as compositionToSource, jt as imageLimits, kt as checkOutputLimits, l as redactionRectInOutput, lt as MAX_LAYER_NAME_LENGTH, m as isRightToLeft, mt as NEUTRAL_DEVELOP, n as createImageSession, nt as FILTER_PRESETS, o as redactionBlockSize, ot as LAYER_KINDS, p as invertMatrix, pt as MAX_STROKE_WIDTH, q as checkCropInSource, rt as FULL_SIZE, s as redactionBlocksInOutput, st as LAYER_SHAPES, t as imageMessages, tt as DEVELOP_ADJUSTMENTS, u as sceneRectToComposition, ut as MAX_LAYER_TEXT_LENGTH, v as sceneToOutput, vt as createImageRenderer, w as dragHandle, wt as createImageEngine, x as aspectRatio, xt as fittedView, y as createImageKey, yt as MAX_PIXEL_RATIO, z as checkOrientation } from "./shared/core-BlFeJWak.js";
1
+ import { $ as invalid, A as fitAspect, At as placement, B as sourceToComposition, C as drawingPoints, Ct as REDACTION_MODES, D as compositionDeltaToSource, Dt as MAX_PIXEL_RATIO, E as aspectRatio, Et as createImageRenderer, F as compositionSize, Ft as PER_FILE_LIMITS, G as checkOutput, H as checkFilter, Ht as isImageError, I as compositionToSource, It as checkFileLimits, J as checkLayer, K as createImageReducer, L as cropRect, Lt as checkOutputLimits, M as moveCrop, Mt as createImageEngine, N as nudgeCropOnScreen, O as cropInComposition, Ot as backingSize, Pt as OUTPUT_LIMITS, Q as checkCropInSource, R as orientedSize, Rt as imageLimitDefinitions, S as drawingBounds, St as NEUTRAL_DEVELOP, T as ASPECT_PRESETS, Tt as createPlan, U as checkMetadata, V as checkDevelop, Vt as ImageError, W as checkOrientation, X as Invalid, Y as checkRedaction, Z as checkCrop, _ as sceneToLayerSource, _t as MAX_PLAN_ITEMS, a as fitRedactionRegion, b as arrowBounds, bt as MAX_STROKE_RUNS, c as redactionBlocksInScene, ct as FULL_SIZE, d as applyMatrix, dt as LAYER_KINDS, et as isRecord, f as fitTextLines, ft as LAYER_SHAPES, g as layerToScene, gt as MAX_LAYER_TEXT_LENGTH, h as layerToOutput, ht as MAX_LAYER_NAME_LENGTH, i as compositionRectToScene, it as NO_METADATA, j as handleInSource, jt as createImageProcessor, k as dragHandle, kt as fittedView, l as redactionRectInOutput, lt as LAYER_ALIGNMENTS, m as isRightToLeft, mt as MAX_KEY_LENGTH, n as createImageSession, nt as EMPTY_KEEPABLE_METADATA, o as redactionBlockSize, ot as DEVELOP_ADJUSTMENTS, p as invertMatrix, pt as MAX_DRAWING_STROKES, rt as MAX_METADATA_LENGTH, s as redactionBlocksInOutput, st as FILTER_PRESETS, t as imageMessages, tt as onlyFields, u as sceneRectToComposition, ut as LAYER_FONTS, v as sceneToOutput, vt as MAX_RUN_POINTS, w as simplifyStroke, wt as UPRIGHT, x as arrowOutline, xt as MAX_STROKE_WIDTH, y as createImageKey, yt as MAX_SCENE_COORDINATE, z as outputSize, zt as imageLimits } from "./shared/core-VHeENp7j.js";
2
2
  // src/core/format/plan-document.ts
3
3
  var IMAGE_PLAN_FORMAT = "hm-image-plan";
4
- var IMAGE_PLAN_VERSION = 2;
4
+ var IMAGE_PLAN_VERSION = 3;
5
5
  var V1_FIELDS = [
6
6
  "format",
7
7
  "version",
@@ -107,11 +107,11 @@ function migrateFromV1(value) {
107
107
  animation: null
108
108
  };
109
109
  }
110
- function readLayers(value, sources) {
110
+ function readLayers(value, sources, version) {
111
111
  if (!Array.isArray(value)) malformed("layers is a list");
112
112
  if (value.length > 1024) malformed(`a document holds at most ${MAX_PLAN_ITEMS} layers`);
113
113
  const sourceSize = (id) => Object.hasOwn(sources, id) ? sources[id] : void 0;
114
- return value.map((layer) => checkLayer(layer, sourceSize));
114
+ return value.map((layer) => checkLayer(layer, sourceSize, version));
115
115
  }
116
116
  function readRedactions(value) {
117
117
  if (!Array.isArray(value)) malformed("redactions is a list");
@@ -134,17 +134,17 @@ function read(value) {
134
134
  format: IMAGE_PLAN_FORMAT,
135
135
  reason: "unknown-format"
136
136
  } });
137
- if (Number.isSafeInteger(version) && version > 2) throw new ImageError("UNSUPPORTED_FORMAT", `This ${IMAGE_PLAN_FORMAT} document is a later version than this release reads.`, { details: {
137
+ if (Number.isSafeInteger(version) && version > 3) throw new ImageError("UNSUPPORTED_FORMAT", `This ${IMAGE_PLAN_FORMAT} document is a later version than this release reads.`, { details: {
138
138
  format: IMAGE_PLAN_FORMAT,
139
139
  reason: "unknown-format-version"
140
140
  } });
141
- if (version !== 1 && version !== 2) malformed("version is 1 or 2");
141
+ if (version !== 1 && version !== 2 && version !== 3) malformed("version is 1, 2 or 3");
142
142
  const document = version === 1 ? migrateFromV1(value) : value;
143
143
  required(document, DOCUMENT_FIELDS, "a document");
144
144
  const { layers, redactions, animation } = document;
145
145
  const sources = readSources(document.sources);
146
146
  if (animation !== null) malformed("animation is null");
147
- const readLayerList = readLayers(layers, sources);
147
+ const readLayerList = readLayers(layers, sources, version === 3 ? 3 : 2);
148
148
  const readRedactionList = readRedactions(redactions);
149
149
  checkItems(readLayerList, readRedactionList);
150
150
  return {
@@ -176,7 +176,7 @@ function toImagePlanDocument(plan, sources) {
176
176
  if (!Object.hasOwn(sources, base.source)) throw new TypeError(`The sources don't include ${base.source}, which the base uses.`);
177
177
  return {
178
178
  format: IMAGE_PLAN_FORMAT,
179
- version: 2,
179
+ version: 3,
180
180
  sources: Object.fromEntries(Object.entries(sources).map(([id, { width, height, asset }]) => [id, asset === void 0 ? {
181
181
  width,
182
182
  height
@@ -208,15 +208,17 @@ function toImagePlanDocument(plan, sources) {
208
208
  function checkPlanSupport(plan, supported) {
209
209
  const used = {
210
210
  layers: !(Array.isArray(plan.layers) && plan.layers.length === 0),
211
+ drawings: Array.isArray(plan.layers) && plan.layers.some((layer) => layer?.kind === "drawing" || layer?.kind === "arrow"),
211
212
  redactions: !(Array.isArray(plan.redactions) && plan.redactions.length === 0),
212
213
  animation: plan.animation !== null
213
214
  };
214
215
  for (const part of [
215
216
  "layers",
217
+ "drawings",
216
218
  "redactions",
217
219
  "animation"
218
220
  ]) if (used[part] && !supported.includes(part)) throw new ImageError("UNSUPPORTED_PLAN", `This renderer can't draw the plan's ${part}.`, { details: { reason: part } });
219
221
  }
220
- export { ASPECT_PRESETS, DEVELOP_ADJUSTMENTS, EMPTY_KEEPABLE_METADATA, FILTER_PRESETS, FULL_SIZE, IMAGE_PLAN_FORMAT, IMAGE_PLAN_VERSION, ImageError, LAYER_ALIGNMENTS, LAYER_FONTS, LAYER_KINDS, LAYER_SHAPES, MAX_KEY_LENGTH, MAX_LAYER_NAME_LENGTH, MAX_LAYER_TEXT_LENGTH, MAX_METADATA_LENGTH, MAX_PIXEL_RATIO, MAX_PLAN_ITEMS, MAX_SCENE_COORDINATE, MAX_STROKE_WIDTH, NEUTRAL_DEVELOP, NO_METADATA, OUTPUT_LIMITS, PER_FILE_LIMITS, REDACTION_MODES, UPRIGHT, applyMatrix, aspectRatio, backingSize, checkFileLimits, checkOutputLimits, checkPlanSupport, compositionDeltaToSource, compositionRectToScene, compositionSize, compositionToSource, createImageEngine, createImageKey, createImageProcessor, createImageReducer, createImageRenderer, createImageSession, createPlan, cropInComposition, cropRect, dragHandle, fitAspect, fitRedactionRegion, fitTextLines, fittedView, handleInSource, imageLimitDefinitions, imageLimits, imageMessages, invertMatrix, isImageError, isRightToLeft, layerToOutput, layerToScene, moveCrop, nudgeCropOnScreen, orientedSize, outputSize, placement, readImagePlanDocument, redactionBlockSize, redactionBlocksInOutput, redactionBlocksInScene, redactionRectInOutput, sceneRectToComposition, sceneToLayerSource, sceneToOutput, sourceToComposition, toImagePlanDocument };
222
+ export { ASPECT_PRESETS, DEVELOP_ADJUSTMENTS, EMPTY_KEEPABLE_METADATA, FILTER_PRESETS, FULL_SIZE, IMAGE_PLAN_FORMAT, IMAGE_PLAN_VERSION, ImageError, LAYER_ALIGNMENTS, LAYER_FONTS, LAYER_KINDS, LAYER_SHAPES, MAX_DRAWING_STROKES, MAX_KEY_LENGTH, MAX_LAYER_NAME_LENGTH, MAX_LAYER_TEXT_LENGTH, MAX_METADATA_LENGTH, MAX_PIXEL_RATIO, MAX_PLAN_ITEMS, MAX_RUN_POINTS, MAX_SCENE_COORDINATE, MAX_STROKE_RUNS, MAX_STROKE_WIDTH, NEUTRAL_DEVELOP, NO_METADATA, OUTPUT_LIMITS, PER_FILE_LIMITS, REDACTION_MODES, UPRIGHT, applyMatrix, arrowBounds, arrowOutline, aspectRatio, backingSize, checkFileLimits, checkOutputLimits, checkPlanSupport, compositionDeltaToSource, compositionRectToScene, compositionSize, compositionToSource, createImageEngine, createImageKey, createImageProcessor, createImageReducer, createImageRenderer, createImageSession, createPlan, cropInComposition, cropRect, dragHandle, drawingBounds, drawingPoints, fitAspect, fitRedactionRegion, fitTextLines, fittedView, handleInSource, imageLimitDefinitions, imageLimits, imageMessages, invertMatrix, isImageError, isRightToLeft, layerToOutput, layerToScene, moveCrop, nudgeCropOnScreen, orientedSize, outputSize, placement, readImagePlanDocument, redactionBlockSize, redactionBlocksInOutput, redactionBlocksInScene, redactionRectInOutput, sceneRectToComposition, sceneToLayerSource, sceneToOutput, simplifyStroke, sourceToComposition, toImagePlanDocument };
221
223
 
222
224
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../src/core/format/plan-document.ts","../src/core/ports/plan-support.ts"],"sourcesContent":["import { ImageError } from \"../errors/image-error.js\";\nimport type { ImageLayer } from \"../model/plan.js\";\nimport {\n type ImageBase,\n type ImageDevelop,\n type ImagePlan,\n type ImageRedaction,\n MAX_PLAN_ITEMS,\n} from \"../model/plan.js\";\nimport type { ImageSize } from \"../model/source.js\";\nimport {\n checkCrop,\n checkCropInSource,\n checkDevelop,\n checkFilter,\n checkMetadata,\n checkOrientation,\n checkOutput,\n Invalid,\n invalid,\n isRecord,\n onlyFields,\n} from \"../operations/commands.js\";\nimport { checkLayer } from \"../operations/layers.js\";\nimport { checkRedaction } from \"../operations/redactions.js\";\n\n/**\n * The name of the plan's portable format (sdk-core ADR 0045).\n *\n * @public\n */\nexport const IMAGE_PLAN_FORMAT = \"hm-image-plan\";\n\n/**\n * The version of {@link IMAGE_PLAN_FORMAT} this release writes, and the\n * latest it reads.\n *\n * @public\n */\nexport const IMAGE_PLAN_VERSION = 2;\n\n/**\n * A content-addressed reference to binary data, such as a source's file\n * (sdk-core ADR 0045). Documents never inline bytes.\n *\n * @public\n */\nexport interface ImageAssetReference {\n /** `sha256:` and the lowercase hex SHA-256 of the bytes. */\n readonly asset: string;\n /** The bytes' media type, such as `image/jpeg`, in lowercase. */\n readonly mediaType: string;\n /** The size of the bytes. */\n readonly size: number;\n}\n\n/**\n * A source, as a plan document records it: its oriented size in pixels,\n * which a crop must fit inside, and, once documents travel with their files,\n * its content.\n *\n * @public\n */\nexport interface ImagePlanDocumentSource extends ImageSize {\n readonly asset?: ImageAssetReference;\n}\n\n/**\n * The plan as portable JSON: `hm-image-plan` version 2, which\n * `formats/hm-image-plan/v2.schema.json` describes\n * (docs/formats/hm-image-plan.md). Positions are whole pixels of the\n * oriented source, and the base names its source by an id the document\n * lists.\n *\n * @public\n */\nexport interface ImagePlanDocument extends ImagePlan {\n readonly format: typeof IMAGE_PLAN_FORMAT;\n readonly version: typeof IMAGE_PLAN_VERSION;\n readonly sources: Readonly<Record<string, ImagePlanDocumentSource>>;\n}\n\n/**\n * Why a plan document was refused, as a stable token: `details.reason` on\n * the error (sdk-core ADR 0045).\n *\n * - With `UNSUPPORTED_FORMAT`: `unknown-format`, a document of another\n * format, and `unknown-format-version`, a later version than this release\n * reads.\n * - With `INVALID_DOCUMENT`: `malformed-document`, a document that isn't\n * shaped as the schema says; `unknown-source`, a base whose source the\n * document doesn't list; `duplicate-key`, a key two items share; and, as\n * for commands, `crop-outside-source`, `invalid-orientation`,\n * `invalid-output`, `metadata-too-long`, `unknown-adjustment`,\n * `invalid-level`, `unknown-preset`, `invalid-strength`, `invalid-key`,\n * `unknown-redaction-mode`, `invalid-region`, `invalid-colour`,\n * `unknown-layer-kind`, `invalid-box`, `invalid-opacity`, `invalid-text`,\n * `text-too-long`, `empty-shape` and `too-many-layers`. `unknown-source`\n * and `crop-outside-source` apply to an image layer too.\n *\n * @public\n */\nexport type ImageDocumentRejection =\n | \"unknown-format\"\n | \"unknown-format-version\"\n | \"malformed-document\"\n | \"unknown-source\"\n | \"crop-outside-source\"\n | \"invalid-orientation\"\n | \"invalid-output\"\n | \"metadata-too-long\"\n | \"unknown-adjustment\"\n | \"invalid-level\"\n | \"unknown-preset\"\n | \"invalid-strength\"\n | \"duplicate-key\"\n | \"invalid-key\"\n | \"unknown-redaction-mode\"\n | \"invalid-region\"\n | \"invalid-colour\"\n | \"unknown-layer-kind\"\n | \"invalid-box\"\n | \"invalid-opacity\"\n | \"invalid-text\"\n | \"text-too-long\"\n | \"empty-shape\"\n | \"too-many-layers\";\n\n/** Version 1's fields: the plan before layers, redactions and animation. */\nconst V1_FIELDS = [\"format\", \"version\", \"sources\", \"base\", \"output\", \"metadata\"];\nconst DOCUMENT_FIELDS = [\n \"format\",\n \"version\",\n \"sources\",\n \"base\",\n \"layers\",\n \"redactions\",\n \"animation\",\n \"output\",\n \"metadata\",\n];\nconst BASE_FIELDS = [\"source\", \"crop\", \"orientation\", \"develop\", \"filter\"];\nconst SOURCE_FIELDS = [\"width\", \"height\", \"asset\"];\nconst ASSET_FIELDS = [\"asset\", \"mediaType\", \"size\"];\n/** The patterns the schema uses too, so both accept the same documents. */\nconst ASSET_ID = /^sha256:[0-9a-f]{64}$/;\nconst MEDIA_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*$/;\n\nfunction malformed(message: string): never {\n return invalid(\"malformed-command\", message);\n}\n\nconst isCount = (value: unknown, min: number): value is number =>\n Number.isSafeInteger(value) && (value as number) >= min;\n\nfunction required(value: object, fields: readonly string[], what: string): void {\n onlyFields(value, fields, what);\n for (const name of fields) {\n if (!Object.hasOwn(value, name)) malformed(`${what} needs \"${name}\"`);\n }\n}\n\nfunction readAsset(value: unknown): ImageAssetReference {\n if (!isRecord<ImageAssetReference>(value)) malformed(\"an asset is an object\");\n required(value, ASSET_FIELDS, \"an asset\");\n const { asset, mediaType, size } = value;\n if (typeof asset !== \"string\" || !ASSET_ID.test(asset)) malformed(\"an asset id is sha256:<hex>\");\n if (typeof mediaType !== \"string\" || mediaType.length > 255 || !MEDIA_TYPE.test(mediaType)) {\n malformed(\"a media type is type/subtype, in lowercase\");\n }\n if (!isCount(size, 0)) malformed(\"an asset's size is a whole number of bytes\");\n return { asset, mediaType, size };\n}\n\nfunction readSources(value: unknown): Record<string, ImagePlanDocumentSource> {\n if (!isRecord<Record<string, unknown>>(value)) malformed(\"sources is an object\");\n // Object.fromEntries keeps ids such as __proto__ as own, ordinary keys.\n return Object.fromEntries(\n Object.entries(value).map(([id, source]) => {\n if (id === \"\") malformed(\"a source id is a non-empty string\");\n if (!isRecord<ImagePlanDocumentSource>(source)) malformed(\"a source is an object\");\n onlyFields(source, SOURCE_FIELDS, \"a source\");\n for (const name of [\"width\", \"height\"]) {\n if (!Object.hasOwn(source, name)) malformed(`a source needs \"${name}\"`);\n }\n const { width, height } = source;\n if (!isCount(width, 1) || !isCount(height, 1)) {\n malformed(\"a source's size is whole pixels, at least 1 × 1\");\n }\n const entry: ImagePlanDocumentSource =\n source.asset === undefined\n ? { width, height }\n : { width, height, asset: readAsset(source.asset) };\n return [id, entry];\n }),\n );\n}\n\nfunction readBase(value: unknown, sources: Record<string, ImagePlanDocumentSource>): ImageBase {\n if (!isRecord<ImageBase>(value)) malformed(\"base is an object\");\n required(value, BASE_FIELDS, \"base\");\n const { source } = value;\n if (typeof source !== \"string\" || source === \"\") malformed(\"base.source is a source id\");\n const size = Object.hasOwn(sources, source) ? sources[source] : undefined;\n if (size === undefined) invalid(\"unknown-source\", `the document doesn't list source ${source}`);\n const crop = value.crop === null ? null : checkCrop(value.crop);\n if (crop !== null) checkCropInSource(crop, size);\n return {\n source,\n crop,\n orientation: checkOrientation(value.orientation),\n develop: checkDevelop(value.develop, true) as ImageDevelop,\n filter: checkFilter(value.filter),\n };\n}\n\n/** A document's fields, before any is checked. */\ntype RawDocument = { readonly [Field in keyof ImagePlanDocument]?: unknown };\n\n/**\n * Version 1 as version 2: a plan with no layers, no redactions and no\n * animation (ADR 0009). It's checked as version 1 first, so a version 1\n * document with a later version's field is refused, not migrated.\n */\nfunction migrateFromV1(value: RawDocument): RawDocument {\n required(value, V1_FIELDS, \"a document\");\n return { ...value, version: 2, layers: [], redactions: [], animation: null };\n}\n\nfunction readLayers(\n value: unknown,\n sources: Record<string, ImagePlanDocumentSource>,\n): ImageLayer[] {\n if (!Array.isArray(value)) malformed(\"layers is a list\");\n if (value.length > MAX_PLAN_ITEMS) malformed(`a document holds at most ${MAX_PLAN_ITEMS} layers`);\n // An image layer's source is one the document lists, as the base's is.\n const sourceSize = (id: string) => (Object.hasOwn(sources, id) ? sources[id] : undefined);\n return value.map((layer) => checkLayer(layer, sourceSize));\n}\n\nfunction readRedactions(value: unknown): ImageRedaction[] {\n if (!Array.isArray(value)) malformed(\"redactions is a list\");\n if (value.length > MAX_PLAN_ITEMS) {\n malformed(`a document holds at most ${MAX_PLAN_ITEMS} redactions`);\n }\n return value.map(checkRedaction);\n}\n\n/** What depends on both lists: no key twice, and no more items than the format holds. */\nfunction checkItems(layers: readonly ImageLayer[], redactions: readonly ImageRedaction[]): void {\n const keys = new Set<string>();\n for (const { key } of [...layers, ...redactions]) {\n if (keys.has(key)) invalid(\"duplicate-key\", `two items have the key \"${key}\"`);\n keys.add(key);\n }\n if (keys.size > MAX_PLAN_ITEMS) {\n invalid(\n \"too-many-layers\",\n `a document holds at most ${MAX_PLAN_ITEMS} layers and redactions together`,\n );\n }\n}\n\nfunction read(value: unknown): {\n plan: ImagePlan;\n sources: Record<string, ImagePlanDocumentSource>;\n} {\n if (!isRecord<RawDocument>(value)) malformed(\"a document is an object\");\n const { format, version } = value;\n if (typeof format !== \"string\") malformed(\"format is text\");\n if (format !== IMAGE_PLAN_FORMAT) {\n throw new ImageError(\"UNSUPPORTED_FORMAT\", `This isn't an ${IMAGE_PLAN_FORMAT} document.`, {\n details: { format: IMAGE_PLAN_FORMAT, reason: \"unknown-format\" },\n });\n }\n if (Number.isSafeInteger(version) && (version as number) > IMAGE_PLAN_VERSION) {\n throw new ImageError(\n \"UNSUPPORTED_FORMAT\",\n `This ${IMAGE_PLAN_FORMAT} document is a later version than this release reads.`,\n { details: { format: IMAGE_PLAN_FORMAT, reason: \"unknown-format-version\" } },\n );\n }\n if (version !== 1 && version !== IMAGE_PLAN_VERSION) malformed(\"version is 1 or 2\");\n const document = version === 1 ? migrateFromV1(value) : value;\n required(document, DOCUMENT_FIELDS, \"a document\");\n const { layers, redactions, animation } = document;\n const sources = readSources(document.sources);\n // The animation arrives with its model, in a later version (ADR 0009).\n if (animation !== null) malformed(\"animation is null\");\n const readLayerList = readLayers(layers, sources);\n const readRedactionList = readRedactions(redactions);\n checkItems(readLayerList, readRedactionList);\n return {\n plan: {\n base: readBase(document.base, sources),\n layers: readLayerList,\n redactions: readRedactionList,\n animation: null,\n output: checkOutput(document.output),\n metadata: checkMetadata(document.metadata),\n },\n sources,\n };\n}\n\n/**\n * Reads a plan document, such as one parsed from JSON, checking it as\n * {@link ImagePlanDocument}'s schema does and more: the base's source must\n * be one the document lists, as must an image layer's, their crops must fit\n * inside them, and no two items share a key. Unknown fields are refused, never dropped.\n *\n * A document of an earlier version is migrated, so every version stays\n * readable: version 1 reads as a plan with no layers or redactions.\n *\n * @param value - The parsed JSON.\n * @returns The plan, and its sources by id.\n * @throws `ImageError` with `UNSUPPORTED_FORMAT` for another format or a\n * later version, and `INVALID_DOCUMENT` for anything else that's wrong,\n * with an {@link ImageDocumentRejection} as `details.reason`.\n * @public\n */\nexport function readImagePlanDocument(value: unknown): {\n readonly plan: ImagePlan;\n readonly sources: Readonly<Record<string, ImagePlanDocumentSource>>;\n} {\n try {\n return read(value);\n } catch (error) {\n if (!(error instanceof Invalid)) throw error;\n const reason = error.reason === \"malformed-command\" ? \"malformed-document\" : error.reason;\n throw new ImageError(\n \"INVALID_DOCUMENT\",\n `Invalid ${IMAGE_PLAN_FORMAT} document: ${error.message}.`,\n { details: { format: IMAGE_PLAN_FORMAT, reason } },\n );\n }\n}\n\n/**\n * Writes a plan as an {@link ImagePlanDocument}, plain JSON-ready data.\n *\n * @param plan - The plan.\n * @param sources - The sources by id, with at least the base's. They're\n * written as given.\n * @throws `TypeError` if the base's source is missing from `sources`.\n * @public\n */\nexport function toImagePlanDocument(\n plan: ImagePlan,\n sources: Readonly<Record<string, ImagePlanDocumentSource>>,\n): ImagePlanDocument {\n const { base, output, metadata } = plan;\n if (!Object.hasOwn(sources, base.source)) {\n throw new TypeError(`The sources don't include ${base.source}, which the base uses.`);\n }\n return {\n format: IMAGE_PLAN_FORMAT,\n version: IMAGE_PLAN_VERSION,\n sources: Object.fromEntries(\n Object.entries(sources).map(([id, { width, height, asset }]) => [\n id,\n asset === undefined ? { width, height } : { width, height, asset: { ...asset } },\n ]),\n ),\n base: {\n source: base.source,\n crop: base.crop === null ? null : { ...base.crop },\n orientation: { ...base.orientation },\n develop: { ...base.develop },\n filter: base.filter === null ? null : { ...base.filter },\n },\n layers: plan.layers.map((layer) => structuredClone(layer)),\n redactions: plan.redactions.map((redaction) => ({ ...redaction })),\n animation: null,\n output: { ...output },\n metadata: {\n title: metadata.title,\n description: metadata.description,\n artist: metadata.artist,\n copyright: metadata.copyright,\n },\n };\n}\n","import { ImageError } from \"../errors/image-error.js\";\nimport type { ImagePlan } from \"../model/plan.js\";\n\n/**\n * A part of a plan that a renderer or processor may not know how to draw.\n *\n * @public\n */\nexport type ImagePlanPart = \"layers\" | \"redactions\" | \"animation\";\n\n/**\n * Refuses a plan that holds something a renderer or processor can't draw\n * (ADR 0009). Nothing may be drawn or exported without a part of its plan:\n * an export that left out a redaction would show what it was meant to hide.\n * Every renderer and processor calls this, with the parts it draws, before\n * it draws anything.\n *\n * @param plan - The plan to draw.\n * @param supported - The parts this renderer or processor draws.\n * @throws `ImageError` with `UNSUPPORTED_PLAN`, and the first part it can't\n * draw as `details.reason`.\n * @public\n */\nexport function checkPlanSupport(plan: ImagePlan, supported: readonly ImagePlanPart[]): void {\n const used: Record<ImagePlanPart, boolean> = {\n // Anything but an empty list or `null` counts, including a value the\n // types don't allow: a plan can come from a host's own storage.\n layers: !(Array.isArray(plan.layers) && plan.layers.length === 0),\n redactions: !(Array.isArray(plan.redactions) && plan.redactions.length === 0),\n animation: plan.animation !== null,\n };\n for (const part of [\"layers\", \"redactions\", \"animation\"] as const) {\n if (used[part] && !supported.includes(part)) {\n throw new ImageError(\"UNSUPPORTED_PLAN\", `This renderer can't draw the plan's ${part}.`, {\n details: { reason: part },\n });\n }\n }\n}\n"],"mappings":";;AA+BA,IAAa,oBAAoB;AAQjC,IAAa,qBAAqB;AA0FlC,IAAM,YAAY;CAAC;CAAU;CAAW;CAAW;CAAQ;CAAU;AAAU;AAC/E,IAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,IAAM,cAAc;CAAC;CAAU;CAAQ;CAAe;CAAW;AAAQ;AACzE,IAAM,gBAAgB;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AK,OAAO,KAAK,UAAU,gBAAgB,KAAK,CAAC;EACzD,YAAY,KAAK,WAAW,KAAK,eAAe,EAAE,GAAG,UAAU,EAAE;EACjE,WAAW;EACX,QAAQ,EAAE,GAAG,OAAO;EACpB,UAAU;GACR,OAAO,SAAS;GAChB,aAAa,SAAS;GACtB,QAAQ,SAAS;GACjB,WAAW,SAAS;EACtB;CACF;AACF;;ACvWA,SAAgB,iBAAiB,MAAiB,WAA2C;CAC3F,MAAM,OAAuC;EAG3C,QAAQ,EAAE,MAAM,QAAQ,KAAK,MAAM,KAAK,KAAK,OAAO,WAAW;EAC/D,YAAY,EAAE,MAAM,QAAQ,KAAK,UAAU,KAAK,KAAK,WAAW,WAAW;EAC3E,WAAW,KAAK,cAAc;CAChC;CACA,KAAK,MAAM,QAAQ;EAAC;EAAU;EAAc;CAAW,GACrD,IAAI,KAAK,SAAS,CAAC,UAAU,SAAS,IAAI,GACxC,MAAM,IAAI,WAAW,oBAAoB,uCAAuC,KAAK,IAAI,EACvF,SAAS,EAAE,QAAQ,KAAK,EAC1B,CAAC;AAGP"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../src/core/format/plan-document.ts","../src/core/ports/plan-support.ts"],"sourcesContent":["import { ImageError } from \"../errors/image-error.js\";\nimport type { ImageLayer } from \"../model/plan.js\";\nimport {\n type ImageBase,\n type ImageDevelop,\n type ImagePlan,\n type ImageRedaction,\n MAX_PLAN_ITEMS,\n} from \"../model/plan.js\";\nimport type { ImageSize } from \"../model/source.js\";\nimport {\n checkCrop,\n checkCropInSource,\n checkDevelop,\n checkFilter,\n checkMetadata,\n checkOrientation,\n checkOutput,\n Invalid,\n invalid,\n isRecord,\n onlyFields,\n} from \"../operations/commands.js\";\nimport { checkLayer } from \"../operations/layers.js\";\nimport { checkRedaction } from \"../operations/redactions.js\";\n\n/**\n * The name of the plan's portable format (sdk-core ADR 0045).\n *\n * @public\n */\nexport const IMAGE_PLAN_FORMAT = \"hm-image-plan\";\n\n/**\n * The version of {@link IMAGE_PLAN_FORMAT} this release writes, and the\n * latest it reads.\n *\n * @public\n */\nexport const IMAGE_PLAN_VERSION = 3;\n\n/**\n * A content-addressed reference to binary data, such as a source's file\n * (sdk-core ADR 0045). Documents never inline bytes.\n *\n * @public\n */\nexport interface ImageAssetReference {\n /** `sha256:` and the lowercase hex SHA-256 of the bytes. */\n readonly asset: string;\n /** The bytes' media type, such as `image/jpeg`, in lowercase. */\n readonly mediaType: string;\n /** The size of the bytes. */\n readonly size: number;\n}\n\n/**\n * A source, as a plan document records it: its oriented size in pixels,\n * which a crop must fit inside, and, once documents travel with their files,\n * its content.\n *\n * @public\n */\nexport interface ImagePlanDocumentSource extends ImageSize {\n readonly asset?: ImageAssetReference;\n}\n\n/**\n * The plan as portable JSON: `hm-image-plan` version 3, which\n * `formats/hm-image-plan/v3.schema.json` describes\n * (docs/formats/hm-image-plan.md). Positions are whole pixels of the\n * oriented source, and the base names its source by an id the document\n * lists.\n *\n * @public\n */\nexport interface ImagePlanDocument extends ImagePlan {\n readonly format: typeof IMAGE_PLAN_FORMAT;\n readonly version: typeof IMAGE_PLAN_VERSION;\n readonly sources: Readonly<Record<string, ImagePlanDocumentSource>>;\n}\n\n/**\n * Why a plan document was refused, as a stable token: `details.reason` on\n * the error (sdk-core ADR 0045).\n *\n * - With `UNSUPPORTED_FORMAT`: `unknown-format`, a document of another\n * format, and `unknown-format-version`, a later version than this release\n * reads.\n * - With `INVALID_DOCUMENT`: `malformed-document`, a document that isn't\n * shaped as the schema says; `unknown-source`, a base whose source the\n * document doesn't list; `duplicate-key`, a key two items share; and, as\n * for commands, `crop-outside-source`, `invalid-orientation`,\n * `invalid-output`, `metadata-too-long`, `unknown-adjustment`,\n * `invalid-level`, `unknown-preset`, `invalid-strength`, `invalid-key`,\n * `unknown-redaction-mode`, `invalid-region`, `invalid-colour`,\n * `unknown-layer-kind`, `invalid-box`, `invalid-opacity`, `invalid-text`,\n * `text-too-long`, `empty-shape`, `empty-drawing`, `empty-arrow`,\n * `invalid-points` and `too-many-layers`. `unknown-source` and\n * `crop-outside-source` apply to an image layer too. A drawing or an\n * arrow in a document of version 2, which has neither, is\n * `unknown-layer-kind`.\n *\n * @public\n */\nexport type ImageDocumentRejection =\n | \"unknown-format\"\n | \"unknown-format-version\"\n | \"malformed-document\"\n | \"unknown-source\"\n | \"crop-outside-source\"\n | \"invalid-orientation\"\n | \"invalid-output\"\n | \"metadata-too-long\"\n | \"unknown-adjustment\"\n | \"invalid-level\"\n | \"unknown-preset\"\n | \"invalid-strength\"\n | \"duplicate-key\"\n | \"invalid-key\"\n | \"unknown-redaction-mode\"\n | \"invalid-region\"\n | \"invalid-colour\"\n | \"unknown-layer-kind\"\n | \"invalid-box\"\n | \"invalid-opacity\"\n | \"invalid-text\"\n | \"text-too-long\"\n | \"empty-shape\"\n | \"empty-drawing\"\n | \"empty-arrow\"\n | \"invalid-points\"\n | \"too-many-layers\";\n\n/** Version 1's fields: the plan before layers, redactions and animation. */\nconst V1_FIELDS = [\"format\", \"version\", \"sources\", \"base\", \"output\", \"metadata\"];\nconst DOCUMENT_FIELDS = [\n \"format\",\n \"version\",\n \"sources\",\n \"base\",\n \"layers\",\n \"redactions\",\n \"animation\",\n \"output\",\n \"metadata\",\n];\nconst BASE_FIELDS = [\"source\", \"crop\", \"orientation\", \"develop\", \"filter\"];\nconst SOURCE_FIELDS = [\"width\", \"height\", \"asset\"];\nconst ASSET_FIELDS = [\"asset\", \"mediaType\", \"size\"];\n/** The patterns the schema uses too, so both accept the same documents. */\nconst ASSET_ID = /^sha256:[0-9a-f]{64}$/;\nconst MEDIA_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*$/;\n\nfunction malformed(message: string): never {\n return invalid(\"malformed-command\", message);\n}\n\nconst isCount = (value: unknown, min: number): value is number =>\n Number.isSafeInteger(value) && (value as number) >= min;\n\nfunction required(value: object, fields: readonly string[], what: string): void {\n onlyFields(value, fields, what);\n for (const name of fields) {\n if (!Object.hasOwn(value, name)) malformed(`${what} needs \"${name}\"`);\n }\n}\n\nfunction readAsset(value: unknown): ImageAssetReference {\n if (!isRecord<ImageAssetReference>(value)) malformed(\"an asset is an object\");\n required(value, ASSET_FIELDS, \"an asset\");\n const { asset, mediaType, size } = value;\n if (typeof asset !== \"string\" || !ASSET_ID.test(asset)) malformed(\"an asset id is sha256:<hex>\");\n if (typeof mediaType !== \"string\" || mediaType.length > 255 || !MEDIA_TYPE.test(mediaType)) {\n malformed(\"a media type is type/subtype, in lowercase\");\n }\n if (!isCount(size, 0)) malformed(\"an asset's size is a whole number of bytes\");\n return { asset, mediaType, size };\n}\n\nfunction readSources(value: unknown): Record<string, ImagePlanDocumentSource> {\n if (!isRecord<Record<string, unknown>>(value)) malformed(\"sources is an object\");\n // Object.fromEntries keeps ids such as __proto__ as own, ordinary keys.\n return Object.fromEntries(\n Object.entries(value).map(([id, source]) => {\n if (id === \"\") malformed(\"a source id is a non-empty string\");\n if (!isRecord<ImagePlanDocumentSource>(source)) malformed(\"a source is an object\");\n onlyFields(source, SOURCE_FIELDS, \"a source\");\n for (const name of [\"width\", \"height\"]) {\n if (!Object.hasOwn(source, name)) malformed(`a source needs \"${name}\"`);\n }\n const { width, height } = source;\n if (!isCount(width, 1) || !isCount(height, 1)) {\n malformed(\"a source's size is whole pixels, at least 1 × 1\");\n }\n const entry: ImagePlanDocumentSource =\n source.asset === undefined\n ? { width, height }\n : { width, height, asset: readAsset(source.asset) };\n return [id, entry];\n }),\n );\n}\n\nfunction readBase(value: unknown, sources: Record<string, ImagePlanDocumentSource>): ImageBase {\n if (!isRecord<ImageBase>(value)) malformed(\"base is an object\");\n required(value, BASE_FIELDS, \"base\");\n const { source } = value;\n if (typeof source !== \"string\" || source === \"\") malformed(\"base.source is a source id\");\n const size = Object.hasOwn(sources, source) ? sources[source] : undefined;\n if (size === undefined) invalid(\"unknown-source\", `the document doesn't list source ${source}`);\n const crop = value.crop === null ? null : checkCrop(value.crop);\n if (crop !== null) checkCropInSource(crop, size);\n return {\n source,\n crop,\n orientation: checkOrientation(value.orientation),\n develop: checkDevelop(value.develop, true) as ImageDevelop,\n filter: checkFilter(value.filter),\n };\n}\n\n/** A document's fields, before any is checked. */\ntype RawDocument = { readonly [Field in keyof ImagePlanDocument]?: unknown };\n\n/**\n * Version 1 as version 2: a plan with no layers, no redactions and no\n * animation (ADR 0009). It's checked as version 1 first, so a version 1\n * document with a later version's field is refused, not migrated.\n */\nfunction migrateFromV1(value: RawDocument): RawDocument {\n required(value, V1_FIELDS, \"a document\");\n return { ...value, version: 2, layers: [], redactions: [], animation: null };\n}\n\nfunction readLayers(\n value: unknown,\n sources: Record<string, ImagePlanDocumentSource>,\n version: 2 | 3,\n): ImageLayer[] {\n if (!Array.isArray(value)) malformed(\"layers is a list\");\n if (value.length > MAX_PLAN_ITEMS) malformed(`a document holds at most ${MAX_PLAN_ITEMS} layers`);\n // An image layer's source is one the document lists, as the base's is.\n const sourceSize = (id: string) => (Object.hasOwn(sources, id) ? sources[id] : undefined);\n // A document has its own version's kinds: a drawing in version 2 is refused, not read.\n return value.map((layer) => checkLayer(layer, sourceSize, version));\n}\n\nfunction readRedactions(value: unknown): ImageRedaction[] {\n if (!Array.isArray(value)) malformed(\"redactions is a list\");\n if (value.length > MAX_PLAN_ITEMS) {\n malformed(`a document holds at most ${MAX_PLAN_ITEMS} redactions`);\n }\n return value.map(checkRedaction);\n}\n\n/** What depends on both lists: no key twice, and no more items than the format holds. */\nfunction checkItems(layers: readonly ImageLayer[], redactions: readonly ImageRedaction[]): void {\n const keys = new Set<string>();\n for (const { key } of [...layers, ...redactions]) {\n if (keys.has(key)) invalid(\"duplicate-key\", `two items have the key \"${key}\"`);\n keys.add(key);\n }\n if (keys.size > MAX_PLAN_ITEMS) {\n invalid(\n \"too-many-layers\",\n `a document holds at most ${MAX_PLAN_ITEMS} layers and redactions together`,\n );\n }\n}\n\nfunction read(value: unknown): {\n plan: ImagePlan;\n sources: Record<string, ImagePlanDocumentSource>;\n} {\n if (!isRecord<RawDocument>(value)) malformed(\"a document is an object\");\n const { format, version } = value;\n if (typeof format !== \"string\") malformed(\"format is text\");\n if (format !== IMAGE_PLAN_FORMAT) {\n throw new ImageError(\"UNSUPPORTED_FORMAT\", `This isn't an ${IMAGE_PLAN_FORMAT} document.`, {\n details: { format: IMAGE_PLAN_FORMAT, reason: \"unknown-format\" },\n });\n }\n if (Number.isSafeInteger(version) && (version as number) > IMAGE_PLAN_VERSION) {\n throw new ImageError(\n \"UNSUPPORTED_FORMAT\",\n `This ${IMAGE_PLAN_FORMAT} document is a later version than this release reads.`,\n { details: { format: IMAGE_PLAN_FORMAT, reason: \"unknown-format-version\" } },\n );\n }\n if (version !== 1 && version !== 2 && version !== IMAGE_PLAN_VERSION) {\n malformed(\"version is 1, 2 or 3\");\n }\n // Version 2 as version 3 changes only the version (ADR 0009): it's read\n // with version 2's layer kinds, so it can't hold a later version's.\n const document = version === 1 ? migrateFromV1(value) : value;\n required(document, DOCUMENT_FIELDS, \"a document\");\n const { layers, redactions, animation } = document;\n const sources = readSources(document.sources);\n // The animation arrives with its model, in a later version (ADR 0009).\n if (animation !== null) malformed(\"animation is null\");\n const readLayerList = readLayers(layers, sources, version === IMAGE_PLAN_VERSION ? 3 : 2);\n const readRedactionList = readRedactions(redactions);\n checkItems(readLayerList, readRedactionList);\n return {\n plan: {\n base: readBase(document.base, sources),\n layers: readLayerList,\n redactions: readRedactionList,\n animation: null,\n output: checkOutput(document.output),\n metadata: checkMetadata(document.metadata),\n },\n sources,\n };\n}\n\n/**\n * Reads a plan document, such as one parsed from JSON, checking it as\n * {@link ImagePlanDocument}'s schema does and more: the base's source must\n * be one the document lists, as must an image layer's, their crops must fit\n * inside them, and no two items share a key. Unknown fields are refused, never dropped.\n *\n * A document of an earlier version is migrated, so every version stays\n * readable: version 1 reads as a plan with no layers or redactions, and\n * version 2 as it is, with the kinds of layer it had.\n *\n * @param value - The parsed JSON.\n * @returns The plan, and its sources by id.\n * @throws `ImageError` with `UNSUPPORTED_FORMAT` for another format or a\n * later version, and `INVALID_DOCUMENT` for anything else that's wrong,\n * with an {@link ImageDocumentRejection} as `details.reason`.\n * @public\n */\nexport function readImagePlanDocument(value: unknown): {\n readonly plan: ImagePlan;\n readonly sources: Readonly<Record<string, ImagePlanDocumentSource>>;\n} {\n try {\n return read(value);\n } catch (error) {\n if (!(error instanceof Invalid)) throw error;\n const reason = error.reason === \"malformed-command\" ? \"malformed-document\" : error.reason;\n throw new ImageError(\n \"INVALID_DOCUMENT\",\n `Invalid ${IMAGE_PLAN_FORMAT} document: ${error.message}.`,\n { details: { format: IMAGE_PLAN_FORMAT, reason } },\n );\n }\n}\n\n/**\n * Writes a plan as an {@link ImagePlanDocument}, plain JSON-ready data.\n *\n * @param plan - The plan.\n * @param sources - The sources by id, with at least the base's. They're\n * written as given.\n * @throws `TypeError` if the base's source is missing from `sources`.\n * @public\n */\nexport function toImagePlanDocument(\n plan: ImagePlan,\n sources: Readonly<Record<string, ImagePlanDocumentSource>>,\n): ImagePlanDocument {\n const { base, output, metadata } = plan;\n if (!Object.hasOwn(sources, base.source)) {\n throw new TypeError(`The sources don't include ${base.source}, which the base uses.`);\n }\n return {\n format: IMAGE_PLAN_FORMAT,\n version: IMAGE_PLAN_VERSION,\n sources: Object.fromEntries(\n Object.entries(sources).map(([id, { width, height, asset }]) => [\n id,\n asset === undefined ? { width, height } : { width, height, asset: { ...asset } },\n ]),\n ),\n base: {\n source: base.source,\n crop: base.crop === null ? null : { ...base.crop },\n orientation: { ...base.orientation },\n develop: { ...base.develop },\n filter: base.filter === null ? null : { ...base.filter },\n },\n layers: plan.layers.map((layer) => structuredClone(layer)),\n redactions: plan.redactions.map((redaction) => ({ ...redaction })),\n animation: null,\n output: { ...output },\n metadata: {\n title: metadata.title,\n description: metadata.description,\n artist: metadata.artist,\n copyright: metadata.copyright,\n },\n };\n}\n","import { ImageError } from \"../errors/image-error.js\";\nimport type { ImagePlan } from \"../model/plan.js\";\n\n/**\n * A part of a plan that a renderer or processor may not know how to draw.\n * `layers` is any layer; `drawings` is a drawing or an arrow layer, which a\n * renderer that draws the other kinds may not.\n *\n * @public\n */\nexport type ImagePlanPart = \"layers\" | \"drawings\" | \"redactions\" | \"animation\";\n\n/**\n * Refuses a plan that holds something a renderer or processor can't draw\n * (ADR 0009). Nothing may be drawn or exported without a part of its plan:\n * an export that left out a redaction would show what it was meant to hide.\n * Every renderer and processor calls this, with the parts it draws, before\n * it draws anything.\n *\n * @param plan - The plan to draw.\n * @param supported - The parts this renderer or processor draws.\n * @throws `ImageError` with `UNSUPPORTED_PLAN`, and the first part it can't\n * draw as `details.reason`.\n * @public\n */\nexport function checkPlanSupport(plan: ImagePlan, supported: readonly ImagePlanPart[]): void {\n const used: Record<ImagePlanPart, boolean> = {\n // Anything but an empty list or `null` counts, including a value the\n // types don't allow: a plan can come from a host's own storage.\n layers: !(Array.isArray(plan.layers) && plan.layers.length === 0),\n // Drawings and arrows, the kinds format version 3 added (docs/adr/0014).\n drawings:\n Array.isArray(plan.layers) &&\n plan.layers.some((layer) => layer?.kind === \"drawing\" || layer?.kind === \"arrow\"),\n redactions: !(Array.isArray(plan.redactions) && plan.redactions.length === 0),\n animation: plan.animation !== null,\n };\n for (const part of [\"layers\", \"drawings\", \"redactions\", \"animation\"] as const) {\n if (used[part] && !supported.includes(part)) {\n throw new ImageError(\"UNSUPPORTED_PLAN\", `This renderer can't draw the plan's ${part}.`, {\n details: { reason: part },\n });\n }\n }\n}\n"],"mappings":";;AA+BA,IAAa,oBAAoB;AAQjC,IAAa,qBAAqB;AAgGlC,IAAM,YAAY;CAAC;CAAU;CAAW;CAAW;CAAQ;CAAU;AAAU;AAC/E,IAAM,kBAAkB;CACtB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,IAAM,cAAc;CAAC;CAAU;CAAQ;CAAe;CAAW;AAAQ;AACzE,IAAM,gBAAgB;CAAC;CAAS;CAAU;AAAO;AACjD,I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