@hussmartinez/image-sdk 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,12 +1,23 @@
1
- import { $ as imageLimitDefinitions, A as onlyFields, B as createPlan, C as checkFilter, D as createImageReducer, E as checkOutput, F as DEVELOP_ADJUSTMENTS, G as placement, H as MAX_PIXEL_RATIO, I as FILTER_PRESETS, K as createImageProcessor, L as FULL_SIZE, M as MAX_METADATA_LENGTH, N as NO_METADATA, O as invalid, Q as checkOutputLimits, R as NEUTRAL_DEVELOP, S as checkDevelop, T as checkOrientation, U as backingSize, V as createImageRenderer, W as fittedView, X as PER_FILE_LIMITS, Y as OUTPUT_LIMITS, Z as checkFileLimits, _ as outputSize, a as compositionDeltaToSource, b as checkCrop, c as fitAspect, d as nudgeCropOnScreen, et as imageLimits, g as orientedSize, h as cropRect, i as aspectRatio, j as EMPTY_KEEPABLE_METADATA, k as isRecord, l as handleInSource, m as compositionToSource, n as createImageSession, nt as isImageError, o as cropInComposition, p as compositionSize, q as createImageEngine, r as ASPECT_PRESETS, s as dragHandle, t as imageMessages, tt as ImageError, u as moveCrop, v as sourceToComposition, w as checkMetadata, x as checkCropInSource, y as Invalid, z as UPRIGHT } from "./shared/core-BWNmXDlB.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-DKUm3jGZ.js";
2
2
  // src/core/format/plan-document.ts
3
3
  var IMAGE_PLAN_FORMAT = "hm-image-plan";
4
- var IMAGE_PLAN_VERSION = 1;
4
+ var IMAGE_PLAN_VERSION = 3;
5
+ var V1_FIELDS = [
6
+ "format",
7
+ "version",
8
+ "sources",
9
+ "base",
10
+ "output",
11
+ "metadata"
12
+ ];
5
13
  var DOCUMENT_FIELDS = [
6
14
  "format",
7
15
  "version",
8
16
  "sources",
9
17
  "base",
18
+ "layers",
19
+ "redactions",
20
+ "animation",
10
21
  "output",
11
22
  "metadata"
12
23
  ];
@@ -86,6 +97,35 @@ function readBase(value, sources) {
86
97
  filter: checkFilter(value.filter)
87
98
  };
88
99
  }
100
+ function migrateFromV1(value) {
101
+ required(value, V1_FIELDS, "a document");
102
+ return {
103
+ ...value,
104
+ version: 2,
105
+ layers: [],
106
+ redactions: [],
107
+ animation: null
108
+ };
109
+ }
110
+ function readLayers(value, sources, version) {
111
+ if (!Array.isArray(value)) malformed("layers is a list");
112
+ if (value.length > 1024) malformed(`a document holds at most ${MAX_PLAN_ITEMS} layers`);
113
+ const sourceSize = (id) => Object.hasOwn(sources, id) ? sources[id] : void 0;
114
+ return value.map((layer) => checkLayer(layer, sourceSize, version));
115
+ }
116
+ function readRedactions(value) {
117
+ if (!Array.isArray(value)) malformed("redactions is a list");
118
+ if (value.length > 1024) malformed(`a document holds at most ${MAX_PLAN_ITEMS} redactions`);
119
+ return value.map(checkRedaction);
120
+ }
121
+ function checkItems(layers, redactions) {
122
+ const keys = /* @__PURE__ */ new Set();
123
+ for (const { key } of [...layers, ...redactions]) {
124
+ if (keys.has(key)) invalid("duplicate-key", `two items have the key "${key}"`);
125
+ keys.add(key);
126
+ }
127
+ if (keys.size > 1024) invalid("too-many-layers", `a document holds at most ${MAX_PLAN_ITEMS} layers and redactions together`);
128
+ }
89
129
  function read(value) {
90
130
  if (!isRecord(value)) malformed("a document is an object");
91
131
  const { format, version } = value;
@@ -94,18 +134,27 @@ function read(value) {
94
134
  format: IMAGE_PLAN_FORMAT,
95
135
  reason: "unknown-format"
96
136
  } });
97
- if (Number.isSafeInteger(version) && version > 1) 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: {
98
138
  format: IMAGE_PLAN_FORMAT,
99
139
  reason: "unknown-format-version"
100
140
  } });
101
- if (version !== 1) malformed("version is 1");
102
- required(value, DOCUMENT_FIELDS, "a document");
103
- const sources = readSources(value.sources);
141
+ if (version !== 1 && version !== 2 && version !== 3) malformed("version is 1, 2 or 3");
142
+ const document = version === 1 ? migrateFromV1(value) : value;
143
+ required(document, DOCUMENT_FIELDS, "a document");
144
+ const { layers, redactions, animation } = document;
145
+ const sources = readSources(document.sources);
146
+ if (animation !== null) malformed("animation is null");
147
+ const readLayerList = readLayers(layers, sources, version === 3 ? 3 : 2);
148
+ const readRedactionList = readRedactions(redactions);
149
+ checkItems(readLayerList, readRedactionList);
104
150
  return {
105
151
  plan: {
106
- base: readBase(value.base, sources),
107
- output: checkOutput(value.output),
108
- metadata: checkMetadata(value.metadata)
152
+ base: readBase(document.base, sources),
153
+ layers: readLayerList,
154
+ redactions: readRedactionList,
155
+ animation: null,
156
+ output: checkOutput(document.output),
157
+ metadata: checkMetadata(document.metadata)
109
158
  },
110
159
  sources
111
160
  };
@@ -127,7 +176,7 @@ function toImagePlanDocument(plan, sources) {
127
176
  if (!Object.hasOwn(sources, base.source)) throw new TypeError(`The sources don't include ${base.source}, which the base uses.`);
128
177
  return {
129
178
  format: IMAGE_PLAN_FORMAT,
130
- version: 1,
179
+ version: 3,
131
180
  sources: Object.fromEntries(Object.entries(sources).map(([id, { width, height, asset }]) => [id, asset === void 0 ? {
132
181
  width,
133
182
  height
@@ -143,6 +192,9 @@ function toImagePlanDocument(plan, sources) {
143
192
  develop: { ...base.develop },
144
193
  filter: base.filter === null ? null : { ...base.filter }
145
194
  },
195
+ layers: plan.layers.map((layer) => structuredClone(layer)),
196
+ redactions: plan.redactions.map((redaction) => ({ ...redaction })),
197
+ animation: null,
146
198
  output: { ...output },
147
199
  metadata: {
148
200
  title: metadata.title,
@@ -152,6 +204,21 @@ function toImagePlanDocument(plan, sources) {
152
204
  }
153
205
  };
154
206
  }
155
- export { ASPECT_PRESETS, DEVELOP_ADJUSTMENTS, EMPTY_KEEPABLE_METADATA, FILTER_PRESETS, FULL_SIZE, IMAGE_PLAN_FORMAT, IMAGE_PLAN_VERSION, ImageError, MAX_METADATA_LENGTH, MAX_PIXEL_RATIO, NEUTRAL_DEVELOP, NO_METADATA, OUTPUT_LIMITS, PER_FILE_LIMITS, UPRIGHT, aspectRatio, backingSize, checkFileLimits, checkOutputLimits, compositionDeltaToSource, compositionSize, compositionToSource, createImageEngine, createImageProcessor, createImageReducer, createImageRenderer, createImageSession, createPlan, cropInComposition, cropRect, dragHandle, fitAspect, fittedView, handleInSource, imageLimitDefinitions, imageLimits, imageMessages, isImageError, moveCrop, nudgeCropOnScreen, orientedSize, outputSize, placement, readImagePlanDocument, sourceToComposition, toImagePlanDocument };
207
+ // src/core/ports/plan-support.ts
208
+ function checkPlanSupport(plan, supported) {
209
+ const used = {
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"),
212
+ redactions: !(Array.isArray(plan.redactions) && plan.redactions.length === 0),
213
+ animation: plan.animation !== null
214
+ };
215
+ for (const part of [
216
+ "layers",
217
+ "drawings",
218
+ "redactions",
219
+ "animation"
220
+ ]) if (used[part] && !supported.includes(part)) throw new ImageError("UNSUPPORTED_PLAN", `This renderer can't draw the plan's ${part}.`, { details: { reason: part } });
221
+ }
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 };
156
223
 
157
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"],"sourcesContent":["import { ImageError } from \"../errors/image-error.js\";\nimport type { ImageBase, ImageDevelop, ImagePlan } 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\";\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 = 1;\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 1, which\n * `formats/hm-image-plan/v1.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; and, as for commands, `crop-outside-source`,\n * `invalid-orientation`, `invalid-output`, `metadata-too-long`,\n * `unknown-adjustment`, `invalid-level`, `unknown-preset` and\n * `invalid-strength`.\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\nconst DOCUMENT_FIELDS = [\"format\", \"version\", \"sources\", \"base\", \"output\", \"metadata\"];\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\nfunction read(value: unknown): {\n plan: ImagePlan;\n sources: Record<string, ImagePlanDocumentSource>;\n} {\n if (!isRecord<ImagePlanDocument>(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 !== IMAGE_PLAN_VERSION) malformed(\"version is 1\");\n required(value, DOCUMENT_FIELDS, \"a document\");\n const sources = readSources(value.sources);\n return {\n plan: {\n base: readBase(value.base, sources),\n output: checkOutput(value.output),\n metadata: checkMetadata(value.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, and its crop must fit inside it. Unknown fields\n * are refused, never dropped.\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 output: { ...output },\n metadata: {\n title: metadata.title,\n description: metadata.description,\n artist: metadata.artist,\n copyright: metadata.copyright,\n },\n };\n}\n"],"mappings":";;AAsBA,IAAa,oBAAoB;AAQjC,IAA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S,OAAO,OAAO,EAAE,GAAG,KAAK,KAAK;GACjD,aAAa,EAAE,GAAG,KAAK,YAAY;GACnC,SAAS,EAAE,GAAG,KAAK,QAAQ;GAC3B,QAAQ,KAAK,WAAW,OAAO,OAAO,EAAE,GAAG,KAAK,OAAO;EACzD;EACA,QAAQ,EAAE,GAAG,OAAO;EACpB,UAAU;GACR,OAAO,SAAS;GAChB,aAAa,SAAS;GACtB,QAAQ,SAAS;GACjB,WAAW,SAAS;EACtB;CACF;AACF"}
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,IAAM,eAAe;CAAC;CAAS;CAAa;AAAM;AAElD,IAAM,WAAW;AACjB,IAAM,aAAa;AAEnB,SAAS,UAAU,SAAwB;CACzC,OAAO,QAAQ,qBAAqB,OAAO;AAC7C;AAEA,IAAM,WAAW,OAAgB,QAC/B,OAAO,cAAc,KAAK,KAAM,SAAoB;AAEtD,SAAS,SAAS,OAAe,QAA2B,MAAoB;CAC9E,WAAW,OAAO,QAAQ,IAAI;CAC9B,KAAK,MAAM,QAAQ,QACjB,IAAI,CAAC,OAAO,OAAO,OAAO,IAAI,GAAG,UAAU,GAAG,K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,KAAK,KAAK,OAAO,WAAW;EAE/D,UACE,MAAM,QAAQ,KAAK,MAAM,KACzB,KAAK,OAAO,MAAM,UAAU,OAAO,SAAS,aAAa,OAAO,SAAS,OAAO;EAClF,YAAY,EAAE,MAAM,QAAQ,KAAK,UAAU,KAAK,KAAK,WAAW,WAAW;EAC3E,WAAW,KAAK,cAAc;CAChC;CACA,KAAK,MAAM,QAAQ;EAAC;EAAU;EAAY;EAAc;CAAW,GACjE,IAAI,KAAK,SAAS,CAAC,UAAU,SAAS,IAAI,GACxC,MAAM,IAAI,WAAW,oBAAoB,uCAAuC,KAAK,IAAI,EACvF,SAAS,EAAE,QAAQ,KAAK,EAC1B,CAAC;AAGP"}
@@ -0,0 +1,30 @@
1
+ // src/workers/render.worker.ts?worker&inline
2
+ var jsContent = "function e(){try{return process.env.NODE_ENV!==`production`}catch{return!1}}function t(t){e()&&console.warn(`[@hussmartinez/sdk-core] ${t}`)}var n=/* @__PURE__ */ Symbol.for(`@hussmartinez/sdk-core`),r={},i=!1;function a(){return`0.4.4`}function o(){if(!i&&(i=!0,typeof process<`u`&&process.env.NODE_ENV!==`production`)){let e=globalThis,i=e[n]??/* @__PURE__ */ new Map;e[n]=i,i.set(r,a()),i.size>1&&t(`${i.size} copies of @hussmartinez/sdk-core are in use (${[...i.values()].join(`, `)}). \\`instanceof SdkError\\` fails for errors from another copy, so use \\`isSdkError\\`, and each copy keeps its own caches. Install a single version: \\`npm ls @hussmartinez/sdk-core\\` shows where each comes from, and every SDK, \\`@hussmartinez/ui\\` and your application should use the same minor version.`)}}var s=/* @__PURE__ */ Symbol.for(`@hussmartinez/sdk-core/SdkError`),c=class extends Error{name=`SdkError`;code;constructor(e,t,n={}){super(t,`cause`in n?{cause:n.cause}:void 0),o(),this.code=e,Object.defineProperty(this,s,{value:!0}),n.details!==void 0&&(this.details=n.details)}};function l(e,t){if(typeof e!=`object`||!e)return!1;let n=e;return(e instanceof c||n[s]===!0)&&typeof n.code==`string`&&typeof n.message==`string`&&(t===void 0||n.code===t)}var u=1<<20;function d(e,t,n){if(!Number.isSafeInteger(t)||t<n)throw RangeError(`The ${e} must be an integer of at least ${n}, not ${String(t)}.`)}function f(e,t={}){let n=t.windowSize??u;d(`window size`,n,1);let r=e.size,i=0,a=/* @__PURE__ */ new Uint8Array;return{size:r,async bytes(t,o){d(`offset`,t,0),d(`length`,o,0);let s=Math.min(t,r),c=Math.min(r,s+o);if(s<i||c>i+a.length){let t=Math.min(r,s+Math.max(o,n));a=new Uint8Array(await e.slice(s,t).arrayBuffer()),i=s}return a.subarray(s-i,c-i)}}}var p=8,m=16,h=`UNKNOWN`;function g(e,t={}){let n=t.includeStack??!1,r=ee(t.maxDepth),i=/* @__PURE__ */ new Set,a=(e,t)=>{i.add(e);let o=_(e),s=n&&b(e)?e.stack:void 0;return typeof s==`string`&&(o.stack=s),b(e)&&`cause`in e&&t<r&&!i.has(e.cause)&&(o.cause=a(e.cause,t+1)),o};return a(e,0)}function _(e){if(l(e)){let t={name:e.name,code:e.code,message:e.message},n=v(e.details);return n!==void 0&&(t.details=n),t}if(b(e)&&typeof e.message==`string`){let t=typeof e.name==`string`?e.name:`Error`;return{name:`SdkError`,code:h,message:e.message,details:{originalName:t}}}return typeof e==`string`?{name:`SdkError`,code:h,message:e,details:{thrownType:`string`}}:{name:`SdkError`,code:h,message:`A value that isn't an Error was thrown.`,details:{thrownType:e===null?`null`:typeof e}}}function v(e){if(!x(e))return;let t=y(e,0);return x(t)?t:void 0}function y(e,t){if(e===null||typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Number.isFinite(e)?e:void 0;if(!(t>=m)){if(Array.isArray(e))return e.flatMap(e=>{let n=y(e,t+1);return n===void 0?[]:[n]});if(x(e)){let n={};for(let[r,i]of Object.entries(e)){let e=y(i,t+1);e!==void 0&&(n[r]=e)}return n}}}function b(e){return typeof e==`object`&&!!e}function x(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ee(e){if(e===void 0)return p;if(!Number.isInteger(e)||e<0)throw RangeError(`maxDepth must be a non-negative integer, received ${e}.`);return e}var S={maxFileSize:{code:`FILE_TOO_LARGE`,unit:`bytes`,default:1e8,warning:5e7},maxFiles:{code:`TOO_MANY_FILES`,unit:`count`,default:20},maxDecodedSize:{code:`DECODED_SIZE_TOO_LARGE`,unit:`bytes`,default:5e8},maxProcessingTime:{code:`PROCESSING_TIME_EXCEEDED`,unit:`milliseconds`,default:12e4}};function te(e,t={}){let n=t.errorClass??c;for(let[t,n]of Object.entries(e))C(`${t}.default`,n.default),n.warning!==void 0&&C(`${t}.warning`,n.warning);return{definitions:e,resolve(t={}){let r={};for(let[t,n]of Object.entries(e))r[t]={maximum:n.default,warning:n.warning??1/0};for(let[e,n]of Object.entries(t)){let t=Object.hasOwn(r,e)?r[e]:void 0;if(t===void 0)throw TypeError(`\"${e}\" isn't a file policy limit. Known limits: ${Object.keys(r).join(`, `)}.`);r[e]=ne(e,t,n)}let i=(t,n)=>{let i=Object.hasOwn(r,t)?r[t]:void 0,a=Object.hasOwn(e,t)?e[t]:void 0;if(i===void 0||a===void 0)throw TypeError(`\"${t}\" isn't a file policy limit.`);if(typeof n!=`number`||Number.isNaN(n)||n<0)throw RangeError(`The value checked against ${t} must be a non-negative number, received ${String(n)}.`);return{resolved:i,definition:a,actual:n}},a=(e,t)=>{let r=i(e,t),{maximum:a}=r.resolved,{code:o,unit:s}=r.definition;return new n(o,`${e} is ${a} ${s}, but the value is ${r.actual}.`,{details:{limit:e,maximum:a,actual:r.actual,unit:s}})};return{limits:r,check(e,t){let{resolved:n}=i(e,t);if(t>n.maximum)throw a(e,t);return t>=n.warning?`warning`:void 0},error:(e,t)=>a(e,t)}}}}function ne(e,t,n){if(typeof n==`number`)return C(e,n),{...t,maximum:n};if(typeof n!=`object`||!n)throw TypeError(`The setting for ${e} must be a number or { maximum, warning }.`);let{maximum:r=t.maximum,warning:i=t.warning,...a}=n,o=Object.keys(a);if(o.length>0)throw TypeError(`The setting for ${e} has unknown keys: ${o.join(`, `)}.`);return C(`${e}.maximum`,r),C(`${e}.warning`,i),{maximum:r,warning:i}}function C(e,t){if(typeof t!=`number`||Number.isNaN(t)||t<=0)throw RangeError(`${e} must be a positive number or Infinity, received ${String(t)}.`)}[...Array.from({length:12},(e,t)=>`F${t+1}`)];var re=`hm-rpc`;function w(e){return{protocol:re,version:1,...e}}function ie(e){if(typeof e!=`object`||!e)return;let t=e;if(t.protocol!==`hm-rpc`||typeof t.version!=`number`)return;let n=Number.isSafeInteger(t.id);switch(t.type){case`ready`:return t;case`call`:return n&&typeof t.method==`string`?t:void 0;case`cancel`:case`progress`:case`result`:return n?t:void 0;case`error`:return n?t:void 0;case`crash`:return t;default:return}}function ae(e,t){let n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Map,i=e=>{if(typeof e!=`object`||!e)return e;if(r.has(e))return r.get(e);if(ArrayBuffer.isView(e)){let i=se(e)?e:ce(e);return t&&i===e&&n.add(e.buffer),r.set(e,i),i}return ue(e)?(t&&n.add(e),r.set(e,e),e):Array.isArray(e)?a(e,()=>[],(e,t)=>{t.forEach((t,n)=>{e[n]=i(t)})}):e instanceof Map?a(e,()=>/* @__PURE__ */ new Map,(e,t)=>{for(let[n,r]of t)e.set(i(n),i(r))}):e instanceof Set?a(e,()=>/* @__PURE__ */ new Set,(e,t)=>{for(let n of t)e.add(i(n))}):T(e)?a(e,()=>({}),(e,t)=>{for(let[n,r]of Object.entries(t))e[n]=i(r)}):(r.set(e,e),e)},a=(e,t,n)=>{let i=t();return r.set(e,i),n(i,e),E(e,i)?(r.set(e,e),e):i};return{value:i(e),transferables:[...n]}}function oe(e,t,n){if(n.length===0)e(t,[]);else try{e(t,n)}catch{e(t,[])}}function se(e){return e.buffer instanceof ArrayBuffer&&e.byteOffset===0&&e.byteLength===e.buffer.byteLength}function ce(e){let t=new Uint8Array(e.buffer,e.byteOffset,e.byteLength).slice();if(e instanceof DataView)return new DataView(t.buffer);let n=e.constructor;return new n(t.buffer)}var le=[`ArrayBuffer`,`MessagePort`,`ImageBitmap`,`OffscreenCanvas`,`ReadableStream`,`WritableStream`,`TransformStream`,`VideoFrame`,`AudioData`];function ue(e){let t=globalThis;return le.some(n=>{let r=t[n];return typeof r==`function`&&e instanceof r})}function T(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function E(e,t){if(Array.isArray(e)){let n=t;return e.length===n.length&&e.every((e,t)=>e===n[t])}if(e instanceof Map){let n=[...t];return[...e].every(([e,t],r)=>n[r]?.[0]===e&&n[r]?.[1]===t)}if(e instanceof Set){let n=[...t];return[...e].every((e,t)=>n[t]===e)}let n=t;return Object.entries(e).every(([e,t])=>n[e]===t)}function de(e,t={}){let n=t.scope??globalThis,r=t.includeStack??!1,i=/* @__PURE__ */ new Map,a=(e,t=[])=>{n.postMessage(e,t)},o=(e,t)=>{a(w({type:`error`,id:e,error:g(t,{includeStack:r})}))},s=(e,t,r)=>{let i=ae(r,!0);try{oe((e,t)=>n.postMessage(e,t),w({type:`result`,id:e,output:i.value}),i.transferables)}catch(n){o(e,new c(`WORKER_DATA_NOT_CLONEABLE`,`The result of \"${t}\" can't be sent to the page.`,{cause:n,details:{method:t}}))}},l=t=>{let{id:n,method:r}=t,l=Object.hasOwn(e,r)?e[r]:void 0;if(typeof l!=`function`){o(n,new c(`WORKER_METHOD_NOT_FOUND`,`The worker has no method \"${r}\".`,{details:{method:r}}));return}let u=new AbortController;i.set(n,u);let d={signal:u.signal,progress:e=>{i.get(n)===u&&a(w({type:`progress`,id:n,value:e}))}};Promise.resolve().then(()=>l.call(e,t.input,d)).then(e=>{i.delete(n),s(n,r,e)},e=>{i.delete(n),o(n,e)})},u=e=>{a(w({type:`crash`,error:g(e,{includeStack:r})}))};n.addEventListener(`message`,e=>{let t=ie(e.data);t!==void 0&&t.version===1&&(t.type===`call`?l(t):t.type===`cancel`&&i.get(t.id)?.abort())}),n.addEventListener(`error`,e=>{let t=e;u(t.error??Error(t.message))}),n.addEventListener(`unhandledrejection`,e=>{u(e.reason)}),a(w({type:`ready`,...t.packageVersion===void 0?{}:{packageVersion:t.packageVersion}}))}var D=class extends c{name=`ImageError`};const O=/* @__PURE__ */ te({...S,maxDecodedSize:{...S.maxDecodedSize,default:1e9,warning:4e8},maxImagePixels:{code:`IMAGE_TOO_LARGE`,unit:`pixels`,default:5e7,warning:24e6},maxImageDimension:{code:`IMAGE_DIMENSION_TOO_LARGE`,unit:`pixels`,default:16384},maxFrames:{code:`TOO_MANY_FRAMES`,unit:`count`,default:300,warning:100},maxSessionSize:{code:`SESSION_TOO_LARGE`,unit:`bytes`,default:1e9,warning:5e8},maxLayers:{code:`TOO_MANY_LAYERS`,unit:`count`,default:256},maxDrawingPoints:{code:`TOO_MANY_POINTS`,unit:`count`,default:2e5,warning:1e5}},{errorClass:D}),fe=[`maxFileSize`,`maxImageDimension`,`maxImagePixels`,`maxFrames`,`maxDecodedSize`];function pe(e,t,n){let{width:r,height:i}=n.oriented,a={maxFileSize:t,maxImageDimension:Math.max(r,i),maxImagePixels:r*i,maxFrames:n.frames,maxDecodedSize:n.decodedPixelBound*4};return fe.filter(t=>e.check(t,a[t])===`warning`)}function me(e,t){e.check(`maxImageDimension`,Math.max(t.width,t.height)),e.check(`maxImagePixels`,t.width*t.height)}function k(e){let t=Math.min(e.pixelRatio,4);return{width:Math.max(1,Math.round(e.width*t)),height:Math.max(1,Math.round(e.height*t))}}function he(e,t){let n=t.inset??0,r=Math.min((t.width-2*n)/e.width,(t.height-2*n)/e.height),i=Math.max(0,r)*t.zoom,a=e.width*i,o=e.height*i;return{x:(t.width-a)/2+t.pan.x,y:(t.height-o)/2+t.pan.y,width:a,height:o,scale:i}}function A(e,t){let n={layers:!(Array.isArray(e.layers)&&e.layers.length===0),drawings:Array.isArray(e.layers)&&e.layers.some(e=>e?.kind===`drawing`||e?.kind===`arrow`),redactions:!(Array.isArray(e.redactions)&&e.redactions.length===0),animation:e.animation!==null};for(let e of[`layers`,`drawings`,`redactions`,`animation`])if(n[e]&&!t.includes(e))throw new D(`UNSUPPORTED_PLAN`,`This renderer can't draw the plan's ${e}.`,{details:{reason:e}})}const ge=Object.freeze({location:!1,camera:!1,timestamps:!1,thumbnail:!1,colourProfile:!1,other:!1}),_e=Object.freeze({title:``,description:``,artist:``,copyright:``}),ve=2e3;function ye(e,t){if(e.length<=t)return!1;let n=0;for(let r of e)if(n+=1,n>t)return!0;return!1}function j(e,t){return new D(`INVALID_IMAGE`,`Invalid ${e}: ${t}.`,{details:{format:e,problem:t}})}async function M(e,t,n,r,i){if(n+r>e.size)throw j(t,`${i} ends past the end of the file`);return e.bytes(n,r)}function N(e,t){return(e[t]??0)<<8|(e[t+1]??0)}function P(e,t){return((e[t]??0)<<24|(e[t+1]??0)<<16|(e[t+2]??0)<<8|(e[t+3]??0))>>>0}function F(e,t,n){let r=``;for(let i=t;i<t+n&&i<e.length;i+=1)r+=String.fromCharCode(e[i]??0);return r}function be(e,t){return t.every((t,n)=>e[n]===t)}function I(e,t){return(e[t]??0)|(e[t+1]??0)<<8}function L(e,t){return(e[t]??0)|(e[t+1]??0)<<8|(e[t+2]??0)<<16}function R(e,t){return((e[t]??0)|(e[t+1]??0)<<8|(e[t+2]??0)<<16|(e[t+3]??0)<<24)>>>0}function xe(e,t){return R(e,t)|0}const Se=/* @__PURE__ */ new Set([12,40,52,56,108,124]);function Ce(e){return F(e,0,2)===`BM`}async function we(e){let t=await M(e,`bmp`,0,18,`the file header`),n=R(t,10),r=R(t,14);if(!Se.has(r))throw j(`bmp`,`the DIB header size is unknown`);let i=await M(e,`bmp`,14,r,`the DIB header`),a,o,s;if(r===12?(a=I(i,4),o=I(i,6),s=I(i,10)):(a=xe(i,4),o=Math.abs(xe(i,8)),s=I(i,14)),I(i,r===12?8:12)!==1)throw j(`bmp`,`the plane count isn't 1`);if(a<1||o<1||a>2147483647||o>2147483647)throw j(`bmp`,`the dimensions are out of range`);if(![1,4,8,16,24,32].includes(s))throw j(`bmp`,`the bit depth is unsupported`);if(n<14+r||n>=e.size)throw j(`bmp`,`the pixel data starts outside the file`);let c=r===124&&[1279872587,1296188740].includes(R(i,56)),l={width:a,height:o};return{format:`bmp`,stored:l,oriented:l,orientation:1,frames:1,hasAlpha:s===32,decodedPixelBound:a*o,metadata:{...ge,colourProfile:c},keepable:_e}}function Te(e){let t=F(e,0,6);return t===`GIF87a`||t===`GIF89a`}async function Ee(e,t){let n=t;for(;;){let t=(await M(e,`gif`,n,1,`a data sub-block`))[0]??0;if(n+=1,t===0)return n;if(n+t>e.size)throw j(`gif`,`a data sub-block ends past the end of the file`);n+=t}}async function De(e){let t=await M(e,`gif`,0,13,`the logical screen descriptor`),n=I(t,6),r=I(t,8);if(n<1||r<1)throw j(`gif`,`the logical screen has no pixels`);let i=t[10]??0,a=13+(i&128?3*2**((i&7)+1):0),o=0,s=!1,c=!1;for(let t=0;;t+=1){if(t>=1e6)throw j(`gif`,`the file has too many blocks`);let i=(await M(e,`gif`,a,1,`a block`))[0];if(i===59)break;if(i===33){let t=(await M(e,`gif`,a+1,1,`an extension label`))[0];if(t===249){let t=await M(e,`gif`,a+2,6,`a graphic control extension`);if(t[0]!==4)throw j(`gif`,`a graphic control extension is the wrong size`);if((t[1]??0)&1&&(s=!0),((t[1]??0)>>>2&7)>3)throw j(`gif`,`a frame uses a reserved disposal method`)}else if(t===255){let t=F(await M(e,`gif`,a+2,12,`an application extension`),1,11);t!==`NETSCAPE2.0`&&t!==`ANIMEXTS1.0`&&(c=!0)}else t===254&&(c=!0);a=await Ee(e,a+2)}else if(i===44){let t=await M(e,`gif`,a,10,`an image descriptor`),i=I(t,1),s=I(t,3),c=I(t,5),l=I(t,7);if(c<1||l<1||i+c>n||s+l>r)throw j(`gif`,`a frame doesn't fit inside the logical screen`);let u=t[9]??0;a+=10+(u&128?3*2**((u&7)+1):0);let d=(await M(e,`gif`,a,1,`an LZW minimum code size`))[0]??0;if(d<2||d>8)throw j(`gif`,`a frame's LZW minimum code size is out of range`);a=await Ee(e,a+1),o+=1}else throw j(`gif`,`an unknown block`)}if(o===0)throw j(`gif`,`there are no frames`);let l={width:n,height:r};return{format:`gif`,stored:l,oriented:l,orientation:1,frames:o,hasAlpha:s,decodedPixelBound:o*n*r,metadata:{...ge,other:c},keepable:_e}}function Oe(e,t){return t>=5?{width:e.height,height:e.width}:e}function z(e,t){return e??{x:0,y:0,width:t.width,height:t.height}}function ke(e,t){let{width:n,height:r}=z(e.base.crop,t);return e.base.orientation.rotate%180==0?{width:n,height:r}:{width:r,height:n}}function Ae(e,t){let n=e.kind===`scale`?e.scale:Math.min(1,e.width/t.width,e.height/t.height);return{width:Math.max(1,Math.round(t.width*n)),height:Math.max(1,Math.round(t.height*n))}}function je(e,t,n){let r=e.x-t.x,i=e.y-t.y,{width:a,height:o}=t,s;switch(n.rotate){case 90:s={x:o-i,y:r};break;case 180:s={x:a-r,y:o-i};break;case 270:s={x:i,y:a-r};break;default:s={x:r,y:i}}let c=n.rotate%180==0?{width:a,height:o}:{width:o,height:a};return{x:n.flipX?c.width-s.x:s.x,y:n.flipY?c.height-s.y:s.y}}function Me(){return{orientation:1,location:!1,camera:!1,timestamps:!1,thumbnail:!1,other:!1,title:``,description:``,artist:``,copyright:``}}function Ne(e){try{return new TextDecoder(`utf-8`,{fatal:!0}).decode(e)}catch{return new TextDecoder(`latin1`).decode(e)}}const Pe=/* @__PURE__ */ new Set([271,272,42033,42035,42036,42037,37500]),Fe=/* @__PURE__ */ new Set([306,36867,36868,36880,36881,36882]),Ie=/* @__PURE__ */ new Set([34665,34853,40965,513,514]),Le={1:1,2:1,3:2,4:4,5:8,6:1,7:1,8:2,9:4,10:8,11:4,12:8};function Re(e,t){let n=Me();if(e.length<8)throw j(t,`the EXIF block is too short`);let r=e[0]===73&&e[1]===73;if(!r&&(e[0]!==77||e[1]!==77))throw j(t,`the EXIF byte order is unknown`);let i=t=>r?(e[t]??0)|(e[t+1]??0)<<8:(e[t]??0)<<8|(e[t+1]??0),a=t=>(r?(e[t]??0)|(e[t+1]??0)<<8|(e[t+2]??0)<<16|(e[t+3]??0)<<24:(e[t]??0)<<24|(e[t+1]??0)<<16|(e[t+2]??0)<<8|(e[t+3]??0))>>>0;if(i(2)!==42)throw j(t,`the EXIF block isn't TIFF`);let o=(n,r,i,o)=>{let s=r*(Le[n]??1),c=s<=4?i:a(i);if(c+s>e.length)throw j(t,`an EXIF value ends past the block`);let l=e.subarray(c,c+s),u=(o?new TextDecoder(`utf-16le`).decode(l):Ne(l)).replace(/\\0+$/,``);return ye(u,2e3)?[...u].slice(0,ve).join(``):u},s=/* @__PURE__ */ new Set,c=[{offset:a(4),kind:`main`}];for(;c.length>0;){let{offset:r,kind:l}=c.shift();if(r===0)continue;if(s.has(r))throw j(t,`EXIF directories loop`);if(s.size>=8)throw j(t,`the EXIF block has too many directories`);if(s.add(r),r+2>e.length)throw j(t,`an EXIF directory starts past the block`);let u=i(r);if(u>1e3||r+2+u*12+4>e.length)throw j(t,`an EXIF directory ends past the block`);l===`gps`&&u>0&&(n.location=!0);for(let e=0;e<u;e+=1){let t=r+2+e*12,s=i(t),u=i(t+2),d=a(t+4),f=t+8;if(l!==`gps`){if(s===274&&l===`main`){let e=i(f);n.orientation=e>=1&&e<=8?e:1}else s===34665?c.push({offset:a(f),kind:`exif`}):s===34853?(n.location=!0,c.push({offset:a(f),kind:`gps`})):l===`next`?n.thumbnail=!0:s===270&&u===2?n.description=o(u,d,f,!1):s===315&&u===2?n.artist=o(u,d,f,!1):s===33432&&u===2?n.copyright=o(u,d,f,!1):s===40091&&(u===1||u===7)?n.title=o(1,d,f,!0):Pe.has(s)?n.camera=!0:Fe.has(s)?n.timestamps=!0:Ie.has(s)||(n.other=!0)}}l===`main`?c.push({offset:a(r+2+u*12),kind:`next`}):l===`next`&&(n.thumbnail=!0)}return n}const ze=/* @__PURE__ */ new Set([`avif`,`avis`,`avio`,`heic`,`heix`,`heim`,`heis`,`hevc`,`hevx`,`mif1`,`mif2`,`msf1`]),Be=/* @__PURE__ */ new Set([`avif`,`avis`,`avio`]),Ve=/* @__PURE__ */ new Set([`av01`,`hvc1`]),He=/* @__PURE__ */ new Set([`urn:mpeg:mpegB:cicp:systems:auxiliary:alpha`,`urn:mpeg:hevc:2015:auxid:1`]),Ue=/* @__PURE__ */ new Set([`dimg`,`auxl`,`thmb`]),We=4096;function Ge(e){return F(e,4,4)===`ftyp`&&ze.has(F(e,8,4))}function Ke(e,t){return P(e,t)*2**32+P(e,t+4)}function B(e,t,n,r){let i=(t,n)=>{if(t.at+n>r)throw j(e,`a box is shorter than its fields`)},a={at:n,end:r,u8(){return i(a,1),a.at+=1,t[a.at-1]??0},u16(){return i(a,2),a.at+=2,N(t,a.at-2)},u32(){return i(a,4),a.at+=4,P(t,a.at-4)},uint(n){if(n===0)return 0;if(n===4)return a.u32();if(n===8)return i(a,8),a.at+=8,Ke(t,a.at-8);throw j(e,`a field has an unsupported size`)},fourcc(){return i(a,4),a.at+=4,F(t,a.at-4,4)},string(){let n=t.subarray(a.at,r).indexOf(0);if(n<0)throw j(e,`a string isn't terminated inside its box`);let i=F(t,a.at,n);return a.at+=n+1,i}};return a}function V(e,t,n,r){let i=[],a=n;for(;a<r;){if(i.length>=We)throw j(e,`a box holds too many boxes`);if(a+8>r)throw j(e,`a box header ends past its parent`);let n=P(t,a),o=8;if(n===1){if(a+16>r)throw j(e,`a box header ends past its parent`);n=Ke(t,a+8),o=16}else n===0&&(n=r-a);if(n<o||a+n>r)throw j(e,`a box ends past its parent`);i.push({type:F(t,a+4,4),start:a+o,end:a+n}),a+=n}return i}function H(e,t,n){let r=t.filter(e=>e.type===n);if(r.length>1)throw j(e,`a box that may appear once appears twice`);return r[0]}const qe=[[1,[1,0,0,1]],[2,[-1,0,0,1]],[3,[-1,0,0,-1]],[4,[1,0,0,-1]],[5,[0,1,1,0]],[6,[0,-1,1,0]],[7,[0,-1,-1,0]],[8,[0,1,-1,0]]];function Je(e){return qe.find(([t])=>t===e)?.[1]??[1,0,0,1]}function Ye(e,t){let[n=0,r=0,i=0,a=0]=Je(t),[o=0,s=0,c=0,l=0]=Je(e),u=[n*o+r*c,n*s+r*l,i*o+a*c,i*s+a*l];return qe.find(([,e])=>e.every((e,t)=>e===u[t]))?.[0]??1}function Xe(e,t,n){let r=n=>{let r=t.u32(),i=t.u32();if(i===0)throw j(e,`a clean aperture divides by zero`);return(n?r|0:r)/i},i=r(!1),a=r(!1),o=r(!0),s=r(!0);if(!Number.isInteger(i)||!Number.isInteger(a)||i<1||a<1)throw j(e,`a clean aperture isn't a whole number of pixels`);let c=(n.width-i)/2+o,l=(n.height-a)/2+s;if(c<0||l<0||c+i>n.width||l+a>n.height)throw j(e,`a clean aperture lies outside the image`);return{width:i,height:a}}const Ze=[1,8,3,6];async function Qe(e){let t=P(await M(e,`heif`,0,8,`the ftyp box`),0);if(t<16||t>4096)throw j(`heif`,`the ftyp box has an invalid size`);let n=await M(e,`heif`,8,t-8,`the ftyp box`),r=[F(n,0,4)];for(let e=8;e+4<=n.length;e+=4)r.push(F(n,e,4));let i=r.some(e=>Be.has(e))?`avif`:`heif`,a,o=t;for(let t=0;o<e.size;t+=1){if(t>=1024)throw j(i,`the file has too many boxes`);let n=await M(e,i,o,8,`a box header`),r=P(n,0),s=8;if(r===1?(r=Ke(await M(e,i,o+8,8,`a box header`),0),s=16):r===0&&(r=e.size-o),r<s||o+r>e.size)throw j(i,`a box ends past the end of the file`);let c=F(n,4,4);if(c===`moov`)throw new D(`UNSUPPORTED_FORMAT`,`Image sequences in ${i} aren't supported.`,{details:{format:i}});if(c===`meta`){if(a!==void 0)throw j(i,`there are two meta boxes`);a={start:o+s,end:o+r}}o+=r}if(a===void 0)throw j(i,`there's no meta box`);if(a.end-a.start>4194304)throw j(i,`the meta box is too large`);let s=await M(e,i,a.start,a.end-a.start,`the meta box`),c=V(i,s,4,s.length),l=H(i,c,`hdlr`),u=l&&B(i,s,l.start+8,l.end);if(u===void 0||u.fourcc()!==`pict`)throw j(i,`the meta box isn't for a picture`);let d=H(i,c,`pitm`);if(d===void 0)throw j(i,`there's no primary item`);let f=B(i,s,d.start,d.end),p=f.u8();f.at+=3;let m=p===0?f.u16():f.u32(),h=/* @__PURE__ */ new Map,g=H(i,c,`iinf`);if(g===void 0)throw j(i,`there's no item information`);let _=B(i,s,g.start,g.end),v=_.u8();_.at+=3;let y=v===0?_.u16():_.u32(),b=V(i,s,_.at,g.end).filter(e=>e.type===`infe`);if(b.length!==y)throw j(i,`the item count doesn't match the item entries`);for(let e of b){let t=B(i,s,e.start,e.end),n=t.u8();t.at+=3;let r;if(n<2)r={id:t.u16(),type:``};else{let e=n===2?t.u16():t.u32();t.u16(),r={id:e,type:t.fourcc()}}if(h.has(r.id))throw j(i,`two items share an ID`);h.set(r.id,r)}let x=h.get(m);if(x===void 0)throw j(i,`the primary item isn't declared`);if(x.type!==`grid`&&!Ve.has(x.type))throw new D(`UNSUPPORTED_FORMAT`,`The ${i} file's primary image type isn't supported.`,{details:{format:i}});let ee=[],S=H(i,c,`iref`);if(S!==void 0){let e=s[S.start]??0;for(let t of V(i,s,S.start+4,S.end)){let n=B(i,s,t.start,t.end),r=e===0?n.u16():n.u32(),a=n.u16(),o=[];for(let t=0;t<a;t+=1)o.push(e===0?n.u16():n.u32());ee.push({type:t.type,from:r,to:o})}}let te=H(i,c,`iprp`);if(te===void 0)throw j(i,`there are no item properties`);let ne=V(i,s,te.start,te.end),C=H(i,ne,`ipco`);if(C===void 0)throw j(i,`there's no property container`);let re=V(i,s,C.start,C.end),w=/* @__PURE__ */ new Map;for(let e of ne.filter(e=>e.type===`ipma`)){let t=B(i,s,e.start,e.end),n=t.u8();t.u16();let r=(t.u8()&1)==1,a=t.u32();if(a>We)throw j(i,`too many property associations`);for(let e=0;e<a;e+=1){let e=n<1?t.u16():t.u32();if(w.has(e))throw j(i,`an item's properties are associated twice`);let a=[],o=t.u8();for(let e=0;e<o;e+=1){let e=r?t.u16()&32767:t.u8()&127;if(e===0)continue;let n=re[e-1];if(n===void 0)throw j(i,`an item refers to a property that doesn't exist`);a.push(n)}w.set(e,a)}}let ie=(e,t)=>(w.get(e)??[]).filter(e=>e.type===t),ae=e=>{let t=ie(e,`ispe`),n=t[0];if(n===void 0||t.length>1)throw j(i,`an image item has no single ispe`);let r=B(i,s,n.start+4,n.end),a={width:r.u32(),height:r.u32()};if(a.width<1||a.height<1)throw j(i,`an image item has no pixels`);return a},oe=H(i,c,`idat`),se=/* @__PURE__ */ new Map,ce=H(i,c,`iloc`);if(ce!==void 0){let t=B(i,s,ce.start,ce.end),n=t.u8();if(t.at+=3,n>2)throw j(i,`the item location version is unknown`);let r=t.u8(),a=t.u8(),o=r>>>4,c=r&15,l=a>>>4,u=n===0?0:a&15,d=n<2?t.u16():t.u32();if(d>We)throw j(i,`too many item locations`);for(let r=0;r<d;r+=1){let r=n<2?t.u16():t.u32(),a=n===0?0:t.u16()&15;t.u16();let s=t.uint(l),d=t.u16(),f=[];for(let n=0;n<d;n+=1){t.uint(u);let n=s+t.uint(o),r=t.uint(c),l=a===0?e.size:a===1?(oe?.end??0)-(oe?.start??0):1/0,d=r===0?l-n:r;if(n+d>l||d<0)throw j(i,`an item's data lies outside the file`);f.push({offset:n,length:d})}if(se.has(r))throw j(i,`an item is located twice`);se.set(r,{method:a,extents:f})}}let le=async(t,n)=>{let r=se.get(t);if(r===void 0)throw j(i,`an item's data has no location`);let a=r.extents.reduce((e,t)=>e+t.length,0);if(a>n)throw j(i,`an item's data is too large`);let o=[];for(let t of r.extents)if(r.method===0)o.push(await e.bytes(t.offset,t.length));else if(r.method===1&&oe!==void 0){let e=oe.start+t.offset;o.push(s.subarray(e,e+t.length))}else throw j(i,`an item's data is stored in a way the probe doesn't read`);let c=new Uint8Array(a),l=0;for(let e of o)c.set(e,l),l+=e.length;return c},ue=ee.filter(e=>Ue.has(e.type)),T=/* @__PURE__ */ new Set([m]);for(let e=[m];e.length>0;){let t=e.pop()??m;for(let n of ue){let r=n.from===t?n.to:n.to.includes(t)?[n.from]:[];for(let t of r){if(!h.has(t))throw j(i,`a reference names an item that isn't declared`);T.has(t)||(T.add(t),e.push(t))}}}let E=new Map([...T].map(e=>[e,0])),de=ue.filter(e=>T.has(e.from));for(let e of de)for(let t of e.to)E.set(t,(E.get(t)??0)+1);let O=[...E].filter(([,e])=>e===0).map(([e])=>e),fe=0;for(;O.length>0;){let e=O.pop()??0;fe+=1;for(let t of de)if(t.from===e)for(let e of t.to){let t=(E.get(e)??0)-1;E.set(e,t),t===0&&O.push(e)}}if(fe!==T.size)throw j(i,`item references form a cycle`);let pe=0;for(let e of T){let t=ae(e);pe+=t.width*t.height,h.get(e)?.type===`grid`&&await me(e,t)}async function me(e,t){let n=ee.filter(t=>t.type===`dimg`&&t.from===e),r=n[0]?.to??[];if(n.length!==1||r.length===0)throw j(i,`a grid doesn't name its tiles once`);if(r.length>1024)throw j(i,`a grid has too many tiles`);let a=await le(e,64),o=B(i,a,0,a.length);if(o.u8()!==0)throw j(i,`the grid version is unknown`);let s=(o.u8()&1)==1,c=o.u8()+1,l=o.u8()+1,u=s?{width:o.u32(),height:o.u32()}:{width:o.u16(),height:o.u16()};if(c*l!==r.length)throw j(i,`a grid's tile count doesn't match its rows and columns`);if(u.width!==t.width||u.height!==t.height)throw j(i,`a grid's output differs from its ispe`);let d;for(let e of r){if(!Ve.has(h.get(e)?.type??``))throw j(i,`a grid tile isn't a coded image`);let t=ae(e);if(d!==void 0&&(t.width!==d.width||t.height!==d.height))throw j(i,`a grid's tiles differ in size`);d=t}if(d===void 0||t.width>l*d.width||t.height>c*d.height)throw j(i,`a grid's output doesn't fit its tiles`)}let k=ae(m),he=k,A=1,ge=!1;for(let e of w.get(m)??[])if(e.type===`clap`){if(ge||he!==k)throw j(i,`a clean aperture follows a transformation`);he=Xe(i,B(i,s,e.start,e.end),k)}else if(e.type===`irot`){ge=!0;let t=B(i,s,e.start,e.end);A=Ye(A,Ze[t.u8()&3]??1)}else if(e.type===`imir`){ge=!0;let t=B(i,s,e.start,e.end);A=Ye(A,t.u8()&1?2:4)}let _e=e=>ee.filter(t=>t.type===e&&t.to.includes(m)),ve=_e(`auxl`).some(e=>ie(e.from,`auxC`).some(e=>{let t=B(i,s,e.start+4,e.end);return He.has(t.string())})),ye=ie(m,`colr`).some(e=>{let t=B(i,s,e.start,e.end).fourcc();return t===`prof`||t===`rICC`}),N=Me(),be=[...h.values()].find(e=>e.type===`Exif`);if(be!==void 0){let e=await le(be.id,1048576);if(e.length<4||4+P(e,0)>e.length)throw j(i,`the EXIF item's header offset is out of range`);Object.assign(N,Re(e.subarray(4+P(e,0)),i))}let I=N.other||[...h.values()].some(e=>e.type===`mime`||e.type===`uri `);return{format:i,stored:he,oriented:Oe(he,A),orientation:A,frames:1,hasAlpha:ve,decodedPixelBound:pe,metadata:{location:N.location,camera:N.camera,timestamps:N.timestamps,thumbnail:N.thumbnail||_e(`thmb`).length>0,colourProfile:ye,other:I},keepable:{title:N.title,description:N.description,artist:N.artist,copyright:N.copyright}}}const $e=[255,216,255];function et(e){return e>=192&&e<=207&&e!==196&&e!==200&&e!==204}async function tt(e){let t=2,n,r=!1,i=Me(),a=!1,o=!1;for(let s=0;!r;s+=1){if(s>=1e4)throw j(`jpeg`,`the file has too many segments`);let c=await M(e,`jpeg`,t,2,`a marker`);if(c[0]!==255)throw j(`jpeg`,`a marker is missing`);let l=c[1]??0;if(l===255){t+=1;continue}if(l===216||l===217||l>=208&&l<=215||l===1){if(l===217)throw j(`jpeg`,`the image ends before its first scan`);t+=2;continue}let u=N(await M(e,`jpeg`,t+2,2,`a segment length`),0);if(u<2)throw j(`jpeg`,`a segment length is out of range`);let d=t+4,f=u-2;if(d+f>e.size)throw j(`jpeg`,`a segment ends past the end of the file`);if(et(l)){if(n!==void 0)throw j(`jpeg`,`there's more than one frame header before the scan`);if(f<6)throw j(`jpeg`,`the frame header is too short`);let t=await e.bytes(d,f),r=N(t,1),i=N(t,3),a=t[5]??0;if(r===0)throw j(`jpeg`,`the height is only defined after the scan`);if(i===0||a<1||a>4||f<6+a*3)throw j(`jpeg`,`the frame header is invalid`);n={width:i,height:r,components:a}}else if(l===218){if(n===void 0)throw j(`jpeg`,`the scan comes before a frame header`);r=!0}else if(l===225&&f>=6){if(F(await e.bytes(d,Math.min(f,64)),0,6)===`Exif\\0\\0`){if(a)i.other=!0;else{a=!0;let t=Re((await e.bytes(d,f)).subarray(6),`jpeg`);Object.assign(i,t)}}else i.other=!0}else l===226&&f>=12?F(await e.bytes(d,12),0,12)===`ICC_PROFILE\\0`?o=!0:i.other=!0:(l>=227&&l<=239||l===254)&&(i.other=!0);t=d+f}let s={width:n?.width??0,height:n?.height??0};return{format:`jpeg`,stored:s,oriented:Oe(s,i.orientation),orientation:i.orientation,frames:1,hasAlpha:!1,decodedPixelBound:s.width*s.height,metadata:{location:i.location,camera:i.camera,timestamps:i.timestamps,thumbnail:i.thumbnail,colourProfile:o,other:i.other},keepable:{title:i.title,description:i.description,artist:i.artist,copyright:i.copyright}}}const nt=[137,80,78,71,13,10,26,10],rt=2**31-1,it={Title:`title`,Description:`description`,Author:`artist`,Copyright:`copyright`};async function at(e){let t=8,n=0,r=0,i=!1,a,o=0,s=!1,c=!1,l=Me(),u=!1;for(let d=0;!c;d+=1){if(d>=1e5)throw j(`png`,`the file has too many chunks`);let f=await M(e,`png`,t,8,`a chunk header`),p=P(f,0),m=F(f,4,4);if(p>2147483647)throw j(`png`,`a chunk length is out of range`);let h=t+8;if(h+p+4>e.size)throw j(`png`,`a chunk ends past the end of the file`);if(d===0&&m!==`IHDR`)throw j(`png`,`IHDR isn't the first chunk`);let g=async()=>{if(p>1048576)throw j(`png`,`the ${m} chunk is too large`);return e.bytes(h,p)};switch(m){case`IHDR`:{if(d!==0||p!==13)throw j(`png`,`IHDR is repeated or the wrong size`);let e=await g();if(n=P(e,0),r=P(e,4),n<1||r<1||n>rt||r>rt)throw j(`png`,`the dimensions are out of range`);let t=e[9];i=t===4||t===6;break}case`acTL`:if(s||a!==void 0||p!==8)throw j(`png`,`acTL is misplaced, repeated or the wrong size`);if(a=P(await g(),0),a<1)throw j(`png`,`acTL declares no frames`);break;case`fcTL`:{if(p!==26)throw j(`png`,`an fcTL is the wrong size`);let e=await g(),t=P(e,4),i=P(e,8),a=P(e,12),s=P(e,16);if(t<1||i<1||a+t>n||s+i>r)throw j(`png`,`a frame doesn't fit inside the image`);o+=1;break}case`IDAT`:s=!0;break;case`tRNS`:i=!0;break;case`iCCP`:case`sRGB`:case`cICP`:u||=m!==`sRGB`;break;case`tIME`:l.timestamps=!0;break;case`eXIf`:{let e=Re(await g(),`png`);Object.assign(l,{...e,orientation:s?l.orientation:e.orientation,title:l.title||e.title,description:l.description||e.description,artist:l.artist||e.artist,copyright:l.copyright||e.copyright});break}case`tEXt`:case`iTXt`:case`zTXt`:{let e=await g(),t=e.indexOf(0),n=F(e,0,t<0?Math.min(e.length,79):t),r=it[n];if(r===void 0)l.other=!0;else if(m===`tEXt`&&t>=0)l[r]=new TextDecoder(`latin1`).decode(e.subarray(t+1)).slice(0,ve);else if(m===`iTXt`&&t>=0&&e[t+1]===0){let n=t+3;for(let t=0;t<2&&n<e.length;n+=1)e[n]===0&&(t+=1);l[r]=new TextDecoder().decode(e.subarray(n)).slice(0,ve)}else l.other=!0;break}case`IEND`:c=!0}t=h+p+4}if(!s)throw j(`png`,`there's no image data`);if(a!==void 0&&o!==a)throw j(`png`,`acTL's frame count doesn't match the frames`);let d=a??1,f={width:n,height:r};return{format:`png`,stored:f,oriented:Oe(f,l.orientation),orientation:l.orientation,frames:d,hasAlpha:i,decodedPixelBound:d*n*r,metadata:{location:l.location,camera:l.camera,timestamps:l.timestamps,thumbnail:l.thumbnail,colourProfile:u,other:l.other},keepable:{title:l.title,description:l.description,artist:l.artist,copyright:l.copyright}}}function ot(e){return F(e,0,4)===`RIFF`&&F(e,8,4)===`WEBP`}async function st(e){let t=8+R(await M(e,`webp`,0,12,`the RIFF header`),4);if(t>e.size||t<20)throw j(`webp`,`the RIFF size doesn't match the file`);let n=0,r=0,i=!1,a,o=!1,s=0,c=Me(),l=!1,u=12;for(let d=0;u<t;d+=1){if(d>=1e5)throw j(`webp`,`the file has too many chunks`);let f=await M(e,`webp`,u,8,`a chunk header`),p=F(f,0,4),m=R(f,4),h=u+8;if(h+m>t)throw j(`webp`,`a chunk ends past the RIFF data`);if(d===0&&p!==`VP8 `&&p!==`VP8L`&&p!==`VP8X`)throw j(`webp`,`the first chunk isn't an image header`);switch(p){case`VP8X`:{if(d!==0||m<10)throw j(`webp`,`VP8X is misplaced or too short`);let t=await e.bytes(h,10),o=t[0]??0;i=!!(o&16),a={animated:!!(o&2)},n=L(t,4)+1,r=L(t,7)+1;break}case`VP8 `:if(d===0&&(o=!0),o||a!==void 0&&!a.animated){if(m<10)throw j(`webp`,`the VP8 frame header is too short`);let t=await e.bytes(h,10);if(t[3]!==157||t[4]!==1||t[5]!==42)throw j(`webp`,`the VP8 start code is missing`);let i=((t[6]??0)|(t[7]??0)<<8)&16383,a=((t[8]??0)|(t[9]??0)<<8)&16383;if(o)n=i,r=a;else if(i!==n||a!==r)throw j(`webp`,`the bitstream's size differs from the canvas`);s=1}break;case`VP8L`:if(d===0&&(o=!0),o||a!==void 0&&!a.animated){if(m<5)throw j(`webp`,`the VP8L header is too short`);let t=await e.bytes(h,5);if(t[0]!==47)throw j(`webp`,`the VP8L signature is missing`);let a=R(t,1),c=(a&16383)+1,l=(a>>>14&16383)+1;if(o)n=c,r=l,i=(a>>>28&1)==1;else if(c!==n||l!==r)throw j(`webp`,`the bitstream's size differs from the canvas`);s=1}break;case`ANMF`:{if(a?.animated!==!0)throw j(`webp`,`an animation frame without the animation flag`);if(m<16)throw j(`webp`,`an ANMF header is too short`);let t=await e.bytes(h,16),i=L(t,0)*2,o=L(t,3)*2,c=L(t,6)+1,l=L(t,9)+1;if(i+c>n||o+l>r)throw j(`webp`,`a frame doesn't fit inside the canvas`);s+=1;break}case`EXIF`:{if(m>1048576)throw j(`webp`,`the EXIF chunk is too large`);let t=await e.bytes(h,m),n=F(t,0,6)===`Exif\\0\\0`?t.subarray(6):t;Object.assign(c,Re(n,`webp`));break}case`ICCP`:l=!0;break;case`XMP `:c.other=!0}u=h+m+m%2}if(a?.animated===!0&&s===0)throw j(`webp`,`an animation without frames`);if(s===0||n<1||r<1)throw j(`webp`,`there's no image data`);let d={width:n,height:r};return{format:`webp`,stored:d,oriented:d,orientation:1,frames:s,hasAlpha:i,decodedPixelBound:s*n*r,metadata:{location:c.location,camera:c.camera,timestamps:c.timestamps,thumbnail:c.thumbnail,colourProfile:l,other:c.other},keepable:{title:c.title,description:c.description,artist:c.artist,copyright:c.copyright}}}async function ct(e){let t=await lt(e);return t.orientation===1?t:{...t,decodedPixelBound:t.decodedPixelBound+t.oriented.width*t.oriented.height}}async function lt(e){let t=await e.bytes(0,16);if(be(t,nt))return at(e);if(be(t,$e))return tt(e);if(ot(t))return st(e);if(Te(t))return De(e);if(Ge(t))return Qe(e);if(Ce(t))return we(e);throw new D(`UNSUPPORTED_FORMAT`,`The file isn't an image format the SDK reads.`,{details:{format:`unknown`}})}function ut(e,{width:t,height:n}){switch(e){case 2:return[-1,0,0,1,t,0];case 3:return[-1,0,0,-1,t,n];case 4:return[1,0,0,-1,0,n];case 5:return[0,1,1,0,0,0];case 6:return[0,1,-1,0,n,0];case 7:return[0,-1,-1,0,n,t];case 8:return[0,-1,1,0,0,t];default:return[1,0,0,1,0,0]}}function dt(e,t){let n={width:e.width,height:e.height},r=Oe(n,t),i=new OffscreenCanvas(r.width,r.height),a=i.getContext(`2d`);if(!a)throw e.close(),Error(`The worker has no 2D canvas.`);return a.setTransform(...ut(t,n)),a.drawImage(e,0,0),e.close(),i.transferToImageBitmap()}const ft=[[255,0,0],[0,255,0],[0,0,255],[255,255,0]];function pt(e){let[t,n,r,i]=ut(e,{width:0,height:0}),a=[[-1,-1],[1,-1],[-1,1],[1,1]],o=[];return a.forEach(([e,s],c)=>{let l=a.findIndex(([a,o])=>a===t*e+r*s&&o===n*e+i*s);o[l]=c}),o}const mt=(e,t)=>t.every((t,n)=>Math.abs((e[n]??NaN)-t)<=64);function ht(e,t,n){for(let r of[1,2,3,4,5,6,7,8]){let i=Oe(n,r);if(i.width===e.width&&i.height===e.height&&pt(r).every((e,n)=>mt(t[n]??[],ft[e]??[])))return r}}function gt(e){let{width:t,height:n}=e,r=new OffscreenCanvas(t,n).getContext(`2d`,{willReadFrequently:!0});if(!r)throw Error(`The worker has no 2D canvas.`);return r.drawImage(e,0,0),[[t/4,n/4],[3*t/4,n/4],[t/4,3*n/4],[3*t/4,3*n/4]].map(([e=0,t=0])=>Array.from(r.getImageData(Math.floor(e),Math.floor(t),1,1).data))}const _t={width:48,height:32};function vt(){let e=new OffscreenCanvas(_t.width,_t.height),t=e.getContext(`2d`);if(!t)throw Error(`The worker has no 2D canvas.`);return ft.forEach(([e,n,r],i)=>{t.fillStyle=`rgb(${e} ${n} ${r})`,t.fillRect(i%2*24,Math.floor(i/2)*16,24,16)}),e}function yt(e){return Uint8Array.of(77,77,0,42,0,0,0,8,0,1,1,18,0,3,0,0,0,1,0,e,0,0,0,0,0,0)}const bt=Array.from({length:256},(e,t)=>{let n=t;for(let e=0;e<8;e+=1)n=n&1?3988292384^n>>>1:n>>>1;return n>>>0});function xt(e){let t=4294967295;for(let n of e)t=(bt[(t^n)&255]??0)^t>>>8;return(t^4294967295)>>>0}const St=(e,t)=>Array.from({length:t},(n,r)=>e>>>8*(t-1-r)&255);async function Ct(){let e=new Uint8Array(await(await vt().convertToBlob()).arrayBuffer()),t=Uint8Array.of(101,88,73,102,...yt(7)),n=Uint8Array.of(...St(t.length-4,4),...t,...St(xt(t),4));return new Blob([e.slice(0,33),n,e.slice(33)],{type:`image/png`})}function wt(e){return e[2]===255&&e[3]===224?4+((e[4]??0)<<8|(e[5]??0)):2}async function Tt(){let e=new Uint8Array(await(await vt().convertToBlob({type:`image/jpeg`,quality:1})).arrayBuffer()),t=Uint8Array.of(69,120,105,102,0,0,...yt(7)),n=Uint8Array.of(255,225,...St(t.length+2,2),...t),r=wt(e);return new Blob([e.slice(0,r),n,e.slice(r)],{type:`image/jpeg`})}const Et=e=>Uint8Array.from(atob(e),e=>e.charCodeAt(0));async function Dt(e){switch(e){case`jpeg`:return Tt();case`png`:return Ct();case`avif`:return new Blob([Et(`AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUEAAAD/bWV0YQAAAAAAAAAhaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAAAAAAAOcGl0bQAAAAAAAQAAAB5pbG9jAAAAAEQAAAEAAQAAAAEAAAEnAAAAcgAAAChpaW5mAAAAAAABAAAAGmluZmUCAAAAAAEAAGF2MDFDb2xvcgAAAAB+aXBycAAAAF1pcGNvAAAAFGlzcGUAAAAAAAAAMAAAACAAAAAQcGl4aQAAAAADCAgIAAAADGF2MUOBIAAAAAAAE2NvbHJuY2x4AAEADQAAgAAAAAlpcm90AQAAAAlpbWlyAAAAABlpcG1hAAAAAAAAAAEAAQYBAoMEhYYAAAB6bWRhdBIACgg4FS/7CAhoATJkRAAA66GyTOByOdAYkRkr4m7XruCgkx+mYn1Qgy/LhM4TZqjxnONsI9XbAWAHGMpcPWGmUkXOiY7S7v9FNX7P7LNof17If68icGW/sP+HwSL0D+g3eqOYaSrFfjiDyX15CtJnQA==`)]);case`heif`:return new Blob([Et(`AAAAHGZ0eXBoZWljAAAAAG1pZjFoZWljbWlhZgAAAYdtZXRhAAAAAAAAACFoZGxyAAAAAAAAAABwaWN0AAAAAAAAAAAAAAAAAAAAACJpbG9jAAAAAERAAAEAAQAAAAABqwABAAAAAAAAAWgAAAAjaWluZgAAAAAAAQAAABVpbmZlAgAAAAABAABodmMxAAAAAA5waXRtAAAAAAABAAABB2lwcnAAAADmaXBjbwAAAHZodmNDAQNwAAAAkAAAAAAAHvAA/P34+AAADwNgAAEAGEABDAH//wNwAAADAJAAAAMAAAMAHroCQGEAAQAqQgEBA3AAAAMAkAAAAwAAAwAeoCCBBZbq5Ka5uAhoMCAAAAMDIAAAAwAhYgABAAZEAcFzwIkAAAATY29scm5jbHgAAQANAAaAAAAAFGlzcGUAAAAAAAAAQAAAAEAAAAAoY2xhcAAAADAAAAABAAAAIAAAAAH////wAAAAAv///+AAAAACAAAAEHBpeGkAAAAAAwgICAAAAAlpcm90AwAAABlpcG1hAAAAAAAAAAEAAQaBAgMFhIYAAAFwbWRhdAAAAWQoAa8GOFr3tt/M4H//+Vpvof3rcAh8Eib+lqP/9+gf/+RCoo6DBnp3DS7HVjpEKagkLLToAgLPf0gsRJBgcTX4smMnA56A3yusdiX58OB/cyikP5RcP/+9DOaSLzxpbfDIZx/2MvdnwDvv9lSv0freK1OdDW2Ic4mjihv4Uz//vczuufFs///BqPj3RM/C9DmybAdK2pHa/WML+n/ofh5OM4ta2QwoyoH3+alRlUJmOn32ErQy0y2l9of783mHK5kj3qBIVLt5C1BsgYvxBJJJhajHb4IsPzEa+wCUZ5YPLfyZ/uW52rOVP02LJknTKZhyZSGGlQM61gCojEG7/8aeNtxBJSuYa9zi2C0FUTZ4EDzXcIldzBDOZRRifvUNh8tXulTFvZTGIysgw+2l3qZ2NW5kvuf+S5yWynAG/xw+MPF+8sAgASh/Fw7rEV3MEM5lFGJ+9Q2Hy1eE3LPWi21NT3jguA==`)]);default:return}}async function Ot(e){let t=await Dt(e);if(!t)return`unknown`;let n=await ct(f(t)),r=await createImageBitmap(t,{imageOrientation:`from-image`});try{let e=ht(r,gt(r),n.stored);return n.orientation!==1&&e===n.orientation?`applied`:e===1?`not applied`:`unknown`}finally{r.close()}}const kt=/* @__PURE__ */ new Map;function At(e,t=Ot){let n=kt.get(e);return n||(n=t(e).catch(()=>(kt.delete(e),`unknown`)),kt.set(e,n)),n}const jt={decode:e=>createImageBitmap(e,{imageOrientation:`from-image`,premultiplyAlpha:`none`,colorSpaceConversion:`default`}),calibrate:At},Mt=(e,t)=>new D(`DECODE_FAILED`,`The browser couldn't decode the image.`,{details:{format:e.format,problem:t}});async function Nt(e,t,n=jt){let r;try{r=await n.decode(e)}catch(e){throw new D(`DECODE_FAILED`,`The browser couldn't decode the image.`,{details:{format:t.format},cause:e})}if(t.orientation!==1){let e=await n.calibrate(t.format);if(e===`unknown`)throw r.close(),Mt(t,`this browser's orientation handling is unknown`);if(e===`not applied`)try{r=dt(r,t.orientation)}catch(e){throw new D(`DECODE_FAILED`,`The browser couldn't decode the image.`,{details:{format:t.format,problem:`the worker couldn't orient it`},cause:e})}}if(r.width!==t.oriented.width||r.height!==t.oriented.height)throw r.close(),new D(`INVALID_IMAGE`,`The image decoded to another size than its header declares.`,{details:{format:t.format,problem:`the decoded size differs from the probe`}});return r}const Pt=e=>new TextEncoder().encode(e),U=e=>Uint8Array.from(e,e=>e.charCodeAt(0)&255),W=e=>[e>>>8&255,e&255],G=e=>[...W(e>>>16),...W(e&65535)];function K(e){let t=new Uint8Array(e.reduce((e,t)=>e+t.length,0)),n=0;for(let r of e)t.set(r,n),n+=r.length;return t}const Ft=e=>Object.values(e).some(e=>e!==``);function It(e){let t=[];if(e.description&&t.push({tag:270,type:2,value:K([Pt(e.description),[0]])}),e.artist&&t.push({tag:315,type:2,value:K([Pt(e.artist),[0]])}),e.copyright&&t.push({tag:33432,type:2,value:K([Pt(e.copyright),[0]])}),e.title){let n=[];for(let t=0;t<e.title.length;t+=1){let r=e.title.charCodeAt(t);n.push(r&255,r>>>8)}n.push(0,0),t.push({tag:40091,type:1,value:Uint8Array.from(n)})}let n=8+(2+t.length*12+4),r=[...W(t.length)],i=[];for(let{tag:e,type:a,value:o}of t)r.push(...W(e),...W(a),...G(o.length)),o.length<=4?r.push(...o,...Array(4-o.length).fill(0)):(r.push(...G(n)),i.push(o),n+=o.length+o.length%2,o.length%2&&i.push(Uint8Array.of(0)));return r.push(...G(0)),K([U(`MM`),W(42),G(8),r,...i])}function Lt(e,t){let n=[e.subarray(0,2)],r=2,i=!1,a=()=>{if(i||!Ft(t))return;i=!0;let e=K([U(`Exif\\0\\0`),It(t)]);n.push(K([[255,225,...W(e.length+2)],e]))};for(;r+4<=e.length&&e[r]===255;){let t=e[r+1]??0;if(!(t>=224&&t<=239)&&t!==254)break;let i=(e[r+2]??0)<<8|(e[r+3]??0),a=e.subarray(r,r+2+i);t===224&&String.fromCharCode(...a.subarray(4,9))===`JFIF\\0`&&n.push(a),r+=2+i}return a(),n.push(e.subarray(r)),K(n)}const Rt=Array.from({length:256},(e,t)=>{let n=t;for(let e=0;e<8;e+=1)n=n&1?3988292384^n>>>1:n>>>1;return n>>>0});function zt(e,t){let n=K([U(e),t]),r=4294967295;for(let e of n)r=(Rt[(r^e)&255]??0)^r>>>8;return K([G(t.length),n,G((r^4294967295)>>>0)])}const Bt=/* @__PURE__ */ new Set([`IHDR`,`PLTE`,`tRNS`,`IDAT`,`IEND`]),Vt={title:`Title`,description:`Description`,artist:`Author`,copyright:`Copyright`};function Ht(e,t){let n=[e.subarray(0,8)],r=8;for(;r+12<=e.length;){let i=((e[r]??0)<<24|(e[r+1]??0)<<16|(e[r+2]??0)<<8|(e[r+3]??0))>>>0,a=String.fromCharCode(...e.subarray(r+4,r+8)),o=r+12+i;if(Bt.has(a)&&n.push(e.subarray(r,o)),a===`IHDR`)for(let[e,r]of Object.entries(Vt)){let i=t[e];i&&n.push(zt(`iTXt`,K([U(r),[0,0,0,0,0],Pt(i)])))}r=o}return K(n)}function Ut(e){let t=[],n=12;for(;n+8<=e.length;){let r=String.fromCharCode(...e.subarray(n,n+4)),i=((e[n+4]??0)|(e[n+5]??0)<<8|(e[n+6]??0)<<16|(e[n+7]??0)<<24)>>>0,a=n+8+i+i%2,o=e.slice(n,a);r===`VP8X`?(o[8]=(o[8]??0)&-45,t.push(o)):(r===`VP8 `||r===`VP8L`||r===`ALPH`||r===`ANIM`||r===`ANMF`)&&t.push(o),n=a}let r=K([U(`WEBP`),...t]),i=r.length;return K([U(`RIFF`),[i&255,i>>>8&255,i>>>16&255,i>>>24],r])}const Wt=Object.freeze({temperature:0,tint:0,exposure:0,highlights:0,shadows:0,contrast:0,saturation:0,vibrance:0});Object.freeze({rotate:0,flipX:!1,flipY:!1}),Object.freeze({kind:`scale`,scale:1});const Gt=.2126,Kt=.7152,qt=.0722,Jt=[Gt,Kt,qt],q=(e,t)=>[[0,e],[255,t]],Yt={vivid:{develop:{contrast:20,saturation:35,vibrance:25}},warm:{develop:{temperature:35,tint:5,vibrance:10}},cool:{develop:{temperature:-35,tint:-5}},fade:{develop:{contrast:-30,shadows:25},curves:[q(30,240),q(30,240),q(30,240)]},mono:{mono:Jt},noir:{develop:{contrast:50,shadows:-20},mono:Jt},sepia:{mono:Jt,curves:[q(40,255),q(20,235),q(0,190)]}},Xt=2**20,Zt=e=>Math.round(e*Xt)/Xt,Qt=e=>e<=.04045?e/12.92:((e+.055)/1.055)**2.4,$t=e=>e<=.0031308?e*12.92:1.055*e**(1/2.4)-.055,J=4095,en=Float32Array.from({length:256},(e,t)=>Zt(Qt(t/255))),Y=Float32Array.from({length:4096},(e,t)=>Zt(Qt(t/J))),X=Float32Array.from({length:4096},(e,t)=>Zt($t(t/J))),tn=Float64Array.from(Y,e=>e>0?1/e:0),nn=e=>Math.min(1,Math.max(0,e)),rn=e=>Math.round(nn(e)*J),an=e=>Math.round(nn(e)*255),on=(e,t)=>t===0?e:nn(e+t*(e*e*(3-2*e)-e)),Z=e=>[e(0),e(1),e(2)];function sn(e){let t=Zt(2**(e.exposure/50)),n=e.temperature/100,r=e.tint/100,i=[(1+.2*n)*t,(1-.2*r)*t,(1-.2*n)*t],[a,o,s]=Z(e=>Float32Array.from(en,t=>X[rn(t*i[e])])),c=e.contrast/100,l=e.highlights/100*.25,u=e.shadows/100*.25,d=e.saturation/100,f=e.vibrance/100,p=l!==0||u!==0,m=d!==0||f!==0,h=(e,t,n,r)=>{let i=a[e],h=o[t],g=s[n];if(p){let e=Gt*i+Kt*h+qt*g,t=(e-.5)*2;t=Math.min(1,Math.max(0,t));let n=e*2;n=Math.min(1,Math.max(0,n));let r=l*t*t*(3-2*t)+u*(1-n*n*(3-2*n));i+=r,h+=r,g+=r,i=Math.min(1,Math.max(0,i)),h=Math.min(1,Math.max(0,h)),g=Math.min(1,Math.max(0,g))}if(c!==0&&(i+=c*(i*i*(3-2*i)-i),h+=c*(h*h*(3-2*h)-h),g+=c*(g*g*(3-2*g)-g),i=Math.min(1,Math.max(0,i)),h=Math.min(1,Math.max(0,h)),g=Math.min(1,Math.max(0,g))),m){let e=i*J+.5|0,t=h*J+.5|0,n=g*J+.5|0,r=Y[e],a=Y[t],o=Y[n],s=Gt*r+Kt*a+qt*o,c=1+d;if(f!==0){let r=Math.max(e,Math.max(t,n)),i=r>0?(Y[r]-Y[Math.min(e,Math.min(t,n))])*tn[r]:0;c+=f*(1-i)}i=s+(r-s)*c,h=s+(a-s)*c,g=s+(o-s)*c,i=X[Math.min(1,Math.max(0,i))*J+.5|0],h=X[Math.min(1,Math.max(0,h))*J+.5|0],g=X[Math.min(1,Math.max(0,g))*J+.5|0]}r[0]=i,r[1]=h,r[2]=g},[g,_,v]=Z(e=>Uint16Array.from([a,o,s][e],e=>rn(on(e,c))));return{perChannel:p||m?void 0:Z(e=>Uint8Array.from([a,o,s][e],e=>an(on(e,c)))),run:p?h:(e,t,n,r)=>{let i=g[e],a=_[t],o=v[n],s=Y[i],c=Y[a],l=Y[o],u=Gt*s+Kt*c+qt*l,p=1+d;if(f!==0){let e=Math.max(i,Math.max(a,o)),t=e>0?(Y[e]-Y[Math.min(i,Math.min(a,o))])*tn[e]:0;p+=f*(1-t)}let m=u+(s-u)*p,h=u+(c-u)*p,y=u+(l-u)*p;m=X[Math.min(1,Math.max(0,m))*J+.5|0],h=X[Math.min(1,Math.max(0,h))*J+.5|0],y=X[Math.min(1,Math.max(0,y))*J+.5|0],r[0]=m,r[1]=h,r[2]=y}}}function cn(e){return Uint8Array.from({length:256},(t,n)=>{for(let t=1;t<e.length;t+=1){let[r,i]=e[t-1]??[0,0],[a,o]=e[t]??[255,255];if(n<=a)return Math.round(i+(o-i)*(n-r)/(a-r||1))}return e.at(-1)?.[1]??n})}const ln=e=>Object.values(e).every(e=>e===0);function un(e,t){return!ln(e)||t!==null&&t.strength>0}const dn=e=>new Uint8Array(e.buffer,e.byteOffset,e.length),Q=Uint8Array.from({length:256},(e,t)=>t);function fn(e,t){let n=ln(e)?void 0:sn(e),r=t===null||t.strength===0?void 0:Yt[t.preset],i=(t?.strength??0)/100,a=r?.develop?sn({...Wt,...r.develop}):void 0,o=r?.curves?Z(e=>cn(r.curves?.[e]??[])):[Q,Q,Q],s=r?.mono,c=r?.curves!==void 0,l=/* @__PURE__ */ new Float64Array(3),u=r!==void 0&&s===void 0&&(!a||a.perChannel)?Z(e=>Uint8Array.from(Q,t=>{let n=a?.perChannel?.[e][t]??t,r=o[e][n]??n;return Math.round(t+(r-t)*i)})):void 0,d=n?n.perChannel:[Q,Q,Q];if(d&&(!r||u)){let[e,t,n]=Z(e=>Uint8Array.from(d[e],t=>u?u[e][t]??t:t));return r=>{let i=dn(r);for(let r=0;r<i.length;r+=4)i[r]=e[i[r]??0]??0,i[r+1]=t[i[r+1]??0]??0,i[r+2]=n[i[r+2]??0]??0}}return e=>{let t=dn(e);for(let e=0;e<t.length;e+=4){let f=t[e]??0,p=t[e+1]??0,m=t[e+2]??0;if(d?(f=d[0][f]??0,p=d[1][p]??0,m=d[2][m]??0):n&&(n.run(f,p,m,l),f=l[0]*255+.5|0,p=l[1]*255+.5|0,m=l[2]*255+.5|0),u)f=u[0][f]??f,p=u[1][p]??p,m=u[2][m]??m;else if(r){let e,t,n;if(a?.perChannel?(e=(a.perChannel[0][f]??0)/255,t=(a.perChannel[1][p]??0)/255,n=(a.perChannel[2][m]??0)/255):a?(a.run(f,p,m,l),e=l[0]??0,t=l[1]??0,n=l[2]??0):(e=f/255,t=p/255,n=m/255),s){let r=s[0]*e+s[1]*t+s[2]*n;e=r,t=r,n=r}let r=e*255+.5|0,u=t*255+.5|0,d=n*255+.5|0;c&&(r=o[0][r],u=o[1][u],d=o[2][d]),f=f+(r-f)*i+.5|0,p=p+(u-p)*i+.5|0,m=m+(d-m)*i+.5|0}t[e]=f,t[e+1]=p,t[e+2]=m}}}function pn(e,t,n){let r=t.x-e.x,i=t.y-e.y,a=Math.hypot(r,i);if(!(a>0))throw RangeError(`An arrow's ends differ.`);let o=r/a,s=i/a,c=s,l=-o,u=Math.min(4*n,a),d=u/2,f=Math.min(n/2,d),p={x:t.x-o*u,y:t.y-s*u},m=(e,t)=>({x:e.x+c*t||0,y:e.y+l*t||0});return[m(e,f),m(e,-f),m(p,-f),m(p,-d),{x:t.x,y:t.y},m(p,d),m(p,f)]}function mn(e,t){let[n,r,i,a,o,s]=e,[c,l,u,d,f,p]=t;return[c*n+u*r,l*n+d*r,c*i+u*a,l*i+d*a,c*o+u*s+f,l*o+d*s+p]}function hn(e,t,n){let r=t.rotate%180==0?{width:e.width,height:e.height}:{width:e.height,height:e.width},i=n.width/r.width,a=n.height/r.height,o=(n,r)=>{let o=je({x:n,y:r},e,t);return{x:o.x*i,y:o.y*a}},s=o(0,0),c=o(1,0),l=o(0,1);return[c.x-s.x,c.y-s.y,l.x-s.x,l.y-s.y,s.x,s.y]}function gn(e){let t=e.rotation*Math.PI/1800,n=e.rotation%900==0?e.rotation/900%4:-1,r=n>=0?[1,0,-1,0][n]:Math.cos(t),i=n>=0?[0,1,0,-1][n]:Math.sin(t),a=e=>e===0?0:-e,o=e.flipX?a(r):r,s=e.flipX?a(i):i,c=a(i),l=r;return[o,s,c,l,e.x+e.width/2-(o*e.width+c*e.height)/2,e.y+e.height/2-(s*e.width+l*e.height)/2]}function _n(e,t,n,r){return mn(gn(e),hn(t,n,r))}function vn(e){let[t,n,r,i,a,o]=e,s=t*i-n*r;return[i/s,-n/s,-r/s,t/s,(r*o-i*a)/s,(n*a-t*o)/s]}function yn(e,t){let n=[t.width/e.width,0,0,t.height/e.height,t.x,t.y];return mn(vn(gn(e)),n)}function bn(e,t){let[n,r,i,a,o,s]=e;return{x:n*t.x+i*t.y+o,y:r*t.x+a*t.y+s}}function xn(e,t,n,r,i,a){let o=Math.max(0,...e.map(e=>e.width));if(!(o>0)||!(t>0))return null;let s=Math.min(r.width/o,r.height/(t*e.length)),c=(r.height-t*e.length*s)/2,l=i===`center`?.5:+(i===`start`===a);return{scale:s,lines:e.map((e,i)=>({x:(r.width-e.width*s)*l,baseline:c+(i*t+n)*s}))}}function Sn(e){for(let t of e){if(Cn.test(t))return!0;if(wn.test(t))return!1}return!1}const Cn=/[֐-ࣿיִ-﷿ﹰ-\\u{10800}-\\u{10FFF}\\u{1E800}-\\u{1EFFF}]/u,wn=/\\p{L}/u;function Tn(e){return Math.max(8,Math.ceil(Math.max(e.width,e.height)/12))}function En(e,t,n){let r=[e];for(let i=e+n;i<e+t;i+=n)r.push(i);return r.push(e+t),r}function Dn(e,t){let n=[];for(let r=0;r+1<t.length;r+=1){let i=t[r],a=t[r+1]-i;if(!(a<=0))for(let t=0;t+1<e.length;t+=1){let r=e[t],o=e[t+1]-r;o>0&&n.push({x:r,y:i,width:o,height:a})}}return n}const On=(e,t,n)=>Math.min(n,Math.max(t,e));function kn(e,t){let n=Tn(e),r=(e,t,n)=>e.map(e=>On(e,t,n));return Dn(r(En(e.x,e.width,n),t.x,t.x+t.width),r(En(e.y,e.height,n),t.y,t.y+t.height))}function An(e,t,n){let r=t.rotate%180!=0,i=r?{width:e.height,height:e.width}:{width:e.width,height:e.height},a=n.width/i.width,o=n.height/i.height,s=(n,r)=>{let i=je({x:n,y:r},e,t);return{x:i.x*a,y:i.y*o}};return{turned:r,fromX:t=>r?s(t,e.y).y:s(t,e.y).x,fromY:t=>r?s(e.x,t).x:s(e.x,t).y}}function jn(e,t){let n=[...e].sort((e,t)=>e-t),r=n.length-1,i=0;return n.map((e,n)=>(i=Math.max(i,On(n===0?Math.floor(e):n===r?Math.ceil(e):Math.round(e),0,t)),i))}function Mn(e,t,n,r){let{turned:i,fromX:a,fromY:o}=An(t,n,r),s=[a(e.x),a(e.x+e.width)],c=[o(e.y),o(e.y+e.height)],[l,u]=jn(i?c:s,r.width),[d,f]=jn(i?s:c,r.height);return u<=l||f<=d?null:{x:l,y:d,width:u-l,height:f-d}}function Nn(e,t,n,r){let i=Tn(e),{turned:a,fromX:o,fromY:s}=An(t,n,r),c=En(e.x,e.width,i).map(o),l=En(e.y,e.height,i).map(s);return Dn(jn(a?l:c,r.width),jn(a?c:l,r.height))}function Pn(){return new Promise(e=>{let t=new MessageChannel;t.port1.onmessage=()=>{t.port1.close(),e()},t.port2.postMessage(void 0)})}async function Fn(e){if(e&&(await Pn(),e.aborted))throw e.reason}const In=4e6;function Ln(e,t){let n=Math.max(e.x,t.x),r=Math.max(e.y,t.y),i=Math.min(e.x+e.width,t.x+t.width),a=Math.min(e.y+e.height,t.y+t.height);return i>n&&a>r?{x:n,y:r,width:i-n,height:a-r}:null}function Rn(e,t,n){e.save(),e.setTransform(1,0,0,1,0,0),e.globalAlpha=1,e.globalCompositeOperation=`source-over`,e.fillStyle=n,e.fillRect(t.x,t.y,t.width,t.height),e.restore()}const zn=/* @__PURE__ */ new WeakMap,$=/* @__PURE__ */ new WeakMap;function Bn(e){let t=zn.get(e);t&&(t.canvas.width=0),zn.delete(e);for(let t of $.get(e)?.values()??[])t.canvas.width=0;$.delete(e)}const Vn={x:-1e9,y:-1e9,width:2e9,height:2e9};function Hn(e,t){return[[t.x,t.y],[t.x+t.width,t.y],[t.x+t.width,t.y+t.height],[t.x,t.y+t.height]].map(([t,n])=>bn(e,{x:t,y:n}))}function Un(e,t){let n=e.map(e=>e.x),r=e.map(e=>e.y),i=Math.floor(Math.min(...n)),a=Math.floor(Math.min(...r));return Ln({x:i,y:a,width:Math.ceil(Math.max(...n))-i,height:Math.ceil(Math.max(...r))-a},t)}async function Wn(e,t,n,r,i){let a=Un(Hn(t,n),r);if(!a)return[0,0,0,0];let o=vn(t),s=Math.max(1,Math.floor(In/(a.width*4))),c=[0,0,0,0],l=0;for(let t=0;t<a.height;t+=s){await Fn(i);let r=Math.min(s,a.height-t),{data:u}=e.getImageData(a.x,a.y+t,a.width,r,{colorSpace:`srgb`});for(let e=0;e<r;e+=1)for(let r=0;r<a.width;r+=1){let i=bn(o,{x:a.x+r+.5,y:a.y+t+e+.5});if(i.x<n.x||i.x>=n.x+n.width||i.y<n.y||i.y>=n.y+n.height)continue;let s=(e*a.width+r)*4,d=u[s+3];c[0]+=u[s]*d,c[1]+=u[s+1]*d,c[2]+=u[s+2]*d,c[3]+=d,l+=1}}let[u=0,d=0,f=0,p=0]=c;return p>0&&l>0?[Math.round(u/p),Math.round(d/p),Math.round(f/p),Math.round(p/l)]:[0,0,0,0]}async function Gn(e,t,n,r){let i={x:0,y:0,width:e.width,height:e.height},a=z(t.crop,e),o=yn(t,a),s=Un(Hn(gn(t),{x:0,y:0,width:t.width,height:t.height}),Vn),c=n.redactions.filter(e=>s!==null&&Ln(e,s)!==null),l=$.get(e);if(c.length===0)return l?.delete(t.key),e;let{x:u,y:d,width:f,height:p,rotation:m,flipX:h}=t,g=JSON.stringify([c,u,d,f,p,m,h,a]),_=l?.get(t.key);if(_?.key===g)return _.canvas;let v=new OffscreenCanvas(e.width,e.height),y=v.getContext(`2d`,{colorSpace:`srgb`,willReadFrequently:Zn(c)});if(!y)throw Error(`The worker has no 2D canvas.`);y.imageSmoothingEnabled=!1,y.drawImage(e,0,0);for(let e of c){let t=e.mode===`solid`?e.colour:await Wn(y,o,e,i,r).then(([e,t,n])=>`rgb(${e} ${t} ${n})`);y.save(),y.setTransform(...o),y.fillStyle=t,y.fillRect(e.x,e.y,e.width,e.height),y.restore()}if(r?.aborted)throw v.width=0,r.reason;let b=l??/* @__PURE__ */ new Map;return b.set(t.key,{key:g,canvas:v}),$.set(e,b),v}function Kn(e,t){let n=$.get(e);if(n)for(let e of[...n.keys()])t.has(e)||n.delete(e)}async function qn(e,t,n){let r={x:0,y:0,width:e.width,height:e.height},i=z(t.base.crop,e),a=t.redactions.filter(e=>Ln(e,r)!==null);if(a.length===0)return e;let o=JSON.stringify([a,i]),s=zn.get(e);if(s?.key===o)return s.canvas;let c=new OffscreenCanvas(e.width,e.height),l=c.getContext(`2d`,{colorSpace:`srgb`,willReadFrequently:a.some(e=>e.mode===`pixelate`)});if(!l)throw Error(`The worker has no 2D canvas.`);l.imageSmoothingEnabled=!1,l.drawImage(e,0,0);for(let e of a){let t=Ln(e,r);if(e.mode===`solid`)Rn(l,t,e.colour);else{let r=kn(e,i),a=await Jn(l,r,n);Rn(l,t,`#000000`),a.forEach((e,t)=>{Yn(l,r[t],e)})}}if(n?.aborted)throw c.width=0,n.reason;return zn.set(e,{key:o,canvas:c}),c}async function Jn(e,t,n){let r=[];for(let{x:i,y:a,width:o,height:s}of t){await Fn(n);let t=Math.max(1,Math.floor(In/(o*4))),c=[0,0,0,0];for(let n=0;n<s;n+=t){let{data:r}=e.getImageData(i,a+n,o,Math.min(t,s-n),{colorSpace:`srgb`});for(let e=0;e<r.length;e+=4){let t=r[e+3];c[0]+=r[e]*t,c[1]+=r[e+1]*t,c[2]+=r[e+2]*t,c[3]+=t}}let[l=0,u=0,d=0,f=0]=c;r.push(f>0?[Math.round(l/f),Math.round(u/f),Math.round(d/f),Math.round(f/(o*s))]:[0,0,0,0])}return r}function Yn(e,{x:t,y:n,width:r,height:i},a){let o=Math.max(1,Math.floor(In/(r*4))),s=e.createImageData(r,Math.min(o,i));for(let e=0;e<s.data.length;e+=4)s.data.set(a,e);for(let a=0;a<i;a+=o)e.putImageData(s,t,n+a,0,0,r,Math.min(o,i-a))}async function Xn(e,t,n,r,i){let a=z(t.base.crop,n),{orientation:o}=t.base;for(let n of t.redactions)if(n.mode===`solid`){let t=Mn(n,a,o,r);t&&Rn(e,t,n.colour)}else{let t=Nn(n,a,o,r);(await Jn(e,t,i)).forEach((n,r)=>{Yn(e,t[r],n)})}}function Zn(e){return e.some(e=>e.mode===`pixelate`)}function Qn(e,t){let{width:n,height:r,shape:i,fill:a,stroke:o}=t,s=o?Math.min(o.width,n/2,r/2):0;a!==null&&(e.fillStyle=a,i===`rectangle`?e.fillRect(0,0,n,r):(e.beginPath(),e.ellipse(n/2,r/2,n/2,r/2,0,0,Math.PI*2),e.fill())),o!==null&&(e.strokeStyle=o.colour,e.lineWidth=s,e.lineJoin=`miter`,i===`rectangle`?e.strokeRect(s/2,s/2,n-s,r-s):(e.beginPath(),e.ellipse(n/2,r/2,(n-s)/2,(r-s)/2,0,0,Math.PI*2),e.stroke()))}function $n(e,t){if(t.text===``)return;let n=t.text.split(`\n`);e.font=`${t.bold?`bold `:``}100px ${t.font}`;let r=Sn(t.text);e.direction=r?`rtl`:`ltr`,e.textAlign=`left`,e.textBaseline=`alphabetic`;let i=e.measureText(`Mg`),a=i.fontBoundingBoxAscent??i.actualBoundingBoxAscent,o=i.fontBoundingBoxDescent??i.actualBoundingBoxDescent,s=xn(n.map(t=>({width:e.measureText(t).width})),a+o,a,t,t.align,r);s&&(e.fillStyle=t.colour,n.forEach((t,n)=>{let r=s.lines[n];r&&t!==``&&(e.save(),e.translate(r.x,r.baseline),e.scale(s.scale,s.scale),e.fillText(t,0,0),e.restore())}))}async function er(e,t,n,r,i){let a=r(t.source);if(!a)throw TypeError(`There's no source with the id \"${t.source}\".`);let o=await Gn(a,t,n,i),s=z(t.crop,a);e.imageSmoothingEnabled=!0,e.imageSmoothingQuality=`high`,e.drawImage(o,s.x,s.y,s.width,s.height,0,0,t.width,t.height)}function tr(e,t){e.translate(t.x,t.y),e.lineJoin=`round`,e.lineCap=`round`;for(let n of t.strokes){e.strokeStyle=n.colour,e.fillStyle=n.colour,e.lineWidth=n.width,e.beginPath();let t=[],r=NaN,i=NaN;for(let a of n.runs){let n=a[0],o=a[1],s=n===r&&o===i;if(a.length===2)s||t.push(n,o),r=NaN;else{s||e.moveTo(n,o);for(let t=2;t+1<a.length;t+=2)e.lineTo(a[t],a[t+1]);r=a[a.length-2],i=a[a.length-1]}}if(e.stroke(),t.length>0){e.beginPath();for(let r=0;r<t.length;r+=2){let i=t[r],a=t[r+1];e.moveTo(i+n.width/2,a),e.arc(i,a,n.width/2,0,Math.PI*2)}e.fill()}}}function nr(e,t){let n=pn(t.from,t.to,t.width);e.fillStyle=t.colour,e.beginPath(),n.forEach((t,n)=>{n===0?e.moveTo(t.x,t.y):e.lineTo(t.x,t.y)}),e.closePath(),e.fill()}async function rr(e,t,n,r,i,a){let o=z(t.base.crop,n),s;for(let n of t.layers){if(!n.visible||n.opacity===0)continue;await Fn(a);let c=e;if(n.opacity<100){if(!s){let e=new OffscreenCanvas(r.width,r.height).getContext(`2d`,{colorSpace:`srgb`});if(!e)throw Error(`The worker has no 2D canvas.`);s=e}s.setTransform(1,0,0,1,0,0),s.clearRect(0,0,r.width,r.height),c=s}c.save(),n.kind===`drawing`||n.kind===`arrow`?(c.setTransform(...hn(o,t.base.orientation,r)),n.kind===`drawing`?tr(c,n):nr(c,n)):(c.setTransform(..._n(n,o,t.base.orientation,r)),n.kind===`shape`?Qn(c,n):n.kind===`text`?$n(c,n):await er(c,n,t,i,a)),c.restore(),c!==e&&(e.save(),e.setTransform(1,0,0,1,0,0),e.globalAlpha=n.opacity/100,e.drawImage(c.canvas,0,0),e.restore())}s&&(s.canvas.width=0);let c=new Set(t.layers.map(e=>e.key));for(let e of new Set(t.layers.flatMap(e=>e.kind===`image`?[e.source]:[]))){let t=i(e);t&&Kn(t,c)}}function ir(e,t){return Ae(e.output,ke(e,t))}async function ar(e,t,n,r,i=()=>void 0){let{develop:a,filter:o}=t.base,s=un(a,o),c=z(t.base.crop,e),l=ke(t,e),u=Ae(t.output,l),d=new OffscreenCanvas(u.width,u.height),f=d.getContext(`2d`,{colorSpace:`srgb`,alpha:!n,willReadFrequently:s||Zn(t.redactions)});if(!f)throw Error(`The worker has no 2D canvas.`);n&&(f.fillStyle=`#ffffff`,f.fillRect(0,0,u.width,u.height));let p=u.width/l.width,m=u.height/l.height;f.imageSmoothingEnabled=p!==1||m!==1,f.imageSmoothingQuality=`high`,f.scale(p,m);let{rotate:h,flipX:g,flipY:_}=t.base.orientation;g&&f.transform(-1,0,0,1,l.width,0),_&&f.transform(1,0,0,-1,0,l.height),h===90&&f.transform(0,1,-1,0,l.width,0),h===180&&f.transform(-1,0,0,-1,l.width,l.height),h===270&&f.transform(0,-1,1,0,0,l.height);let v=await qn(e,t,r);if(f.drawImage(v,c.x,c.y,c.width,c.height,0,0,c.width,c.height),f.setTransform(1,0,0,1,0,0),s){let e=fn(a,o),t=Math.max(1,Math.floor(4e6/(u.width*4)));for(let n=0;n<u.height;n+=t){if(r&&(await Pn(),r.aborted))throw r.reason;let i=f.getImageData(0,n,u.width,Math.min(t,u.height-n),{colorSpace:`srgb`});e(i.data),f.putImageData(i,0,n)}}return await rr(f,t,e,u,i,r),await Xn(f,t,e,u,r),d}const or={png:`image/png`,jpeg:`image/jpeg`,webp:`image/webp`};async function sr(e,t,n,r,i){let a=or[n.type],o=await ar(e,t,n.type===`jpeg`,r,i),s=await o.convertToBlob({type:a,...n.type===`png`?{}:{quality:n.quality??.92}});if(o.width=0,o.height=0,r?.aborted)throw r.reason;if(s.type!==a)throw new D(`UNSUPPORTED_FORMAT`,`This browser can't encode the requested format.`,{details:{format:n.type}});let c=new Uint8Array(await s.arrayBuffer()),l=n.type===`jpeg`?Lt(c,t.metadata):n.type===`png`?Ht(c,t.metadata):Ut(c);return new Blob([l.slice()],{type:a})}async function cr(e,t,n,r,i,a){let o=ke(n,t),{width:s,height:c}=k(r),l=Math.min(r.pixelRatio,4),u=he(o,r),d=u.scale*l,f=Math.min(1,d),p=await ar(t,{...n,output:{kind:`scale`,scale:f}},!1,i,a);if(i?.aborted)throw p.width=0,i.reason;let{canvas:m}=e;(m.width!==s||m.height!==c)&&(m.width=s,m.height=c),e.clearRect(0,0,s,c),e.imageSmoothingEnabled=!0,e.imageSmoothingQuality=`high`,e.drawImage(p,u.x*l,u.y*l,u.width*l,u.height*l),p.width=0}function lr(e,t){return e.format===t.format&&e.orientation===t.orientation&&e.frames===t.frames&&e.decodedPixelBound===t.decodedPixelBound&&e.stored.width===t.stored.width&&e.stored.height===t.stored.height&&e.oriented.width===t.oriented.width&&e.oriented.height===t.oriented.height}const ur=[`layers`,`drawings`,`redactions`];function dr(e){let t=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=(e,n,r)=>{me(e,r);for(let r of n.layers){let n=r.kind===`image`?t.get(r.source):void 0;n&&me(e,n)}};de({probe:({file:e})=>ct(f(e)),async register({id:e,file:n,probe:r,limits:i},{signal:a}){if(t.has(e))throw TypeError(`The source id \"${e}\" is already in use.`);let o=await ct(f(n));if(!lr(o,r))throw new D(`INVALID_IMAGE`,`The probe doesn't describe this file.`,{details:{format:o.format,problem:`the probe describes another file`}});pe(O.resolve(i),n.size,o);let s=await Nt(n,o);if(a.aborted)throw s.close(),a.reason;return t.set(e,s),{width:s.width,height:s.height}},thumbnail({id:e,maxSize:n}){let r=t.get(e);if(!r)throw TypeError(`There's no source with the id \"${e}\".`);let i=Math.min(1,n/r.width,n/r.height);return createImageBitmap(r,{resizeWidth:Math.max(1,Math.round(r.width*i)),resizeHeight:Math.max(1,Math.round(r.height*i)),resizeQuality:`high`})},async export({plan:e,format:n,limits:i},{signal:a}){A(e,ur);let o=t.get(e.base.source);if(!o)throw TypeError(`There's no source with the id \"${e.base.source}\".`);let s=O.resolve(i);return me(s,ir(e,o)),e.redactions.length>0&&r(s,e,o),sr(o,e,n,a,e=>t.get(e))},attachCanvas({id:e,canvas:t}){let r=t.getContext(`2d`,{colorSpace:`srgb`});if(!r)throw Error(`The worker has no 2D canvas.`);n.set(e,r)},async render({id:e,plan:i,view:a,limits:o},{signal:s}){A(i,ur),me(O.resolve(o),k(a));let c=n.get(e);if(!c)throw TypeError(`There's no canvas with the id \"${e}\".`);let l=t.get(i.base.source);if(!l)throw TypeError(`There's no source with the id \"${i.base.source}\".`);i.redactions.length>0&&r(O.resolve(o),i,l),await cr(c,l,i,a,s,e=>t.get(e))},detachCanvas({id:e}){let t=n.get(e);t&&(t.canvas.width=0,t.canvas.height=0),n.delete(e)},snapshot({id:e}){let t=n.get(e);if(!t)throw TypeError(`There's no canvas with the id \"${e}\".`);return createImageBitmap(t.canvas)},release({id:e}){let n=t.get(e);n&&Bn(n),n?.close(),t.delete(e)}},{...e,packageVersion:`0.5.0`})}dr();\n";
3
+ var blob = typeof self !== "undefined" && self.Blob && new Blob(["URL.revokeObjectURL(import.meta.url);", jsContent], { type: "text/javascript;charset=utf-8" });
4
+ function WorkerWrapper(options) {
5
+ let objURL;
6
+ try {
7
+ objURL = blob && (self.URL || self.webkitURL).createObjectURL(blob);
8
+ if (!objURL) throw "";
9
+ const worker = new Worker(objURL, {
10
+ type: "module",
11
+ name: options?.name
12
+ });
13
+ worker.addEventListener("error", () => {
14
+ (self.URL || self.webkitURL).revokeObjectURL(objURL);
15
+ });
16
+ return worker;
17
+ } catch (e) {
18
+ return new Worker("data:text/javascript;charset=utf-8," + encodeURIComponent(jsContent), {
19
+ type: "module",
20
+ name: options?.name
21
+ });
22
+ }
23
+ }
24
+ // src/adapters/render-worker/inline-worker.ts
25
+ function createInlineWorker() {
26
+ return new WorkerWrapper({ name: "hm-image-render" });
27
+ }
28
+ export { createInlineWorker };
29
+
30
+ //# sourceMappingURL=inline-worker-BGAoQbIR.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"inline-worker-l_ynDNuS.js","names":["RenderWorker"],"sources":["../../src/adapters/render-worker/inline-worker.ts"],"sourcesContent":["import RenderWorker from \"../../workers/render.worker.ts?worker&inline\";\n\n/** Starts the inlined render worker, from its own lazy chunk. */\nexport function createInlineWorker(): Worker {\n return new RenderWorker({ name: \"hm-image-render\" });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAGA,SAAgB,qBAA6B;CAC3C,OAAO,IAAIA,cAAa,EAAE,MAAM,kBAAkB,CAAC;AACrD"}
1
+ {"version":3,"file":"inline-worker-BGAoQbIR.js","names":["RenderWorker"],"sources":["../../src/adapters/render-worker/inline-worker.ts"],"sourcesContent":["import RenderWorker from \"../../workers/render.worker.ts?worker&inline\";\n\n/** Starts the inlined render worker, from its own lazy chunk. */\nexport function createInlineWorker(): Worker {\n return new RenderWorker({ name: \"hm-image-render\" });\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAGA,SAAgB,qBAA6B;CAC3C,OAAO,IAAIA,cAAa,EAAE,MAAM,kBAAkB,CAAC;AACrD"}