@hussmartinez/image-sdk 0.1.0 → 0.3.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/README.md +98 -9
- package/dist/assets/image/render.worker.js +1 -1
- package/dist/element.d.ts +32 -2
- package/dist/element.js +2 -2
- package/dist/index.d.ts +41 -3
- package/dist/index.js +1 -1
- package/dist/lazy/{inline-worker-BVCwAPZU.js → inline-worker-l_ynDNuS.js} +2 -2
- package/dist/lazy/{inline-worker-BVCwAPZU.js.map → inline-worker-l_ynDNuS.js.map} +1 -1
- package/dist/react.d.ts +85 -2
- package/dist/react.js +1 -1
- package/dist/shared/{core-cKo2m54U.js → core-BWNmXDlB.js} +271 -79
- package/dist/shared/core-BWNmXDlB.js.map +1 -0
- package/dist/shared/{editor-Dv5EU2YJ.js → editor-CJXEK6MY.js} +262 -75
- package/dist/shared/editor-CJXEK6MY.js.map +1 -0
- package/dist/styles.css +126 -19
- package/package.json +8 -7
- package/dist/shared/core-cKo2m54U.js.map +0 -1
- package/dist/shared/editor-Dv5EU2YJ.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"core-cKo2m54U.js","names":[],"sources":["../../src/core/errors/image-error.ts","../../src/core/errors/error-helpers.ts","../../src/core/errors/image-limits.ts","../../src/adapters/image-engine.ts","../../src/adapters/image-processor.ts","../../src/core/ports/image-renderer.ts","../../src/adapters/image-renderer.ts","../../src/core/model/plan.ts","../../src/core/model/source.ts","../../src/core/operations/commands.ts","../../src/core/model/geometry.ts","../../src/core/model/crop.ts","../../src/core/session/session.ts","../../src/messages/en.ts"],"sourcesContent":["import { isSdkError, type SdkCoreErrorCode, SdkError } from \"@hussmartinez/sdk-core\";\n\n/**\n * Error codes of `@hussmartinez/image-sdk`: sdk-core's own codes, such as\n * `ABORTED`, `WORKER_CRASHED` and `FILE_TOO_LARGE`, plus the image SDK's\n * (ADR 0001, ADR 0004). They never change meaning once released.\n *\n * - `INVALID_IMAGE`: the file is malformed, its headers claim more than its\n * data can carry or less than its decoder would produce, or its decoded\n * size differs from what its headers declare.\n * - `UNSUPPORTED_FORMAT`: the format isn't recognised, its bound can't be\n * read, or the browser can't encode the requested export format.\n * `details.format` names it.\n * - `DECODE_FAILED`: the browser couldn't decode a file the SDK probed,\n * usually because it lacks the format. `details.format` names it.\n * - `INVALID_COMMAND`: an edit command doesn't apply to the plan, such as a\n * crop outside its source. `details.reason` says why, as a stable token\n * (`ImageCommandRejection`).\n * - `INVALID_DOCUMENT`: a plan document, such as a saved project, isn't\n * valid in its format. `details.reason` says why (`ImageDocumentRejection`).\n * A document of another format, or a later version, is `UNSUPPORTED_FORMAT`\n * instead, with `details.reason` `unknown-format` or `unknown-format-version`.\n * - `IMAGE_TOO_LARGE`: an image, a frame, the canvas or the export exceeds\n * the `maxImagePixels` limit.\n * - `IMAGE_DIMENSION_TOO_LARGE`: a width or height exceeds the\n * `maxImageDimension` limit.\n * - `TOO_MANY_FRAMES`: an animation exceeds the `maxFrames` limit.\n * - `SESSION_TOO_LARGE`: the decoded images the session holds exceed the\n * `maxSessionSize` limit.\n * - `TOO_MANY_LAYERS`: the layer plan exceeds the `maxLayers` limit.\n *\n * Limit codes carry `details` with the `limit`, its `maximum`, the `actual`\n * value and the `unit`. Other codes' `details` name the format involved,\n * and a `reason`, never data from the file.\n *\n * @public\n */\nexport type ImageErrorCode =\n | SdkCoreErrorCode\n | \"INVALID_IMAGE\"\n | \"UNSUPPORTED_FORMAT\"\n | \"DECODE_FAILED\"\n | \"INVALID_COMMAND\"\n | \"INVALID_DOCUMENT\"\n | \"IMAGE_TOO_LARGE\"\n | \"IMAGE_DIMENSION_TOO_LARGE\"\n | \"TOO_MANY_FRAMES\"\n | \"SESSION_TOO_LARGE\"\n | \"TOO_MANY_LAYERS\";\n\n/**\n * The error `@hussmartinez/image-sdk` throws and rejects with, with a stable\n * `code`, structured `details` and the underlying error as `cause`. Show\n * users the text for its code from {@link imageMessages}, never its\n * `message`, which is for developers and may contain text from the file.\n *\n * @example\n * ```ts\n * try {\n * await session.open(file);\n * } catch (error) {\n * if (isImageError(error, \"DECODE_FAILED\")) {\n * suggestConvertingToPng();\n * } else {\n * show(messages.error(error));\n * }\n * }\n * ```\n *\n * @public\n */\nexport class ImageError extends SdkError<ImageErrorCode> {\n /** Always `\"ImageError\"`, which survives minification and worker boundaries. */\n override readonly name = \"ImageError\";\n}\n\n/**\n * Checks whether a value is an {@link ImageError}, optionally with a given\n * code.\n *\n * Unlike `instanceof`, it recognises errors from another copy of this\n * package or another realm, and errors rebuilt after crossing a worker\n * boundary.\n *\n * @param value - Any thrown value.\n * @param code - When given, the error must also have this code.\n * @public\n */\nexport function isImageError<Code extends ImageErrorCode = ImageErrorCode>(\n value: unknown,\n code?: Code,\n): value is ImageError & { readonly code: Code } {\n return isSdkError(value, code) && value.name === \"ImageError\";\n}\n","import { createErrorHelpers } from \"@hussmartinez/sdk-core\";\nimport { ImageError } from \"./image-error.js\";\n\n/**\n * The SDK's error helpers, from sdk-core's `createErrorHelpers` (sdk-core\n * ADR 0034):\n *\n * - `asImageError` makes any failure an `ImageError`, as every port promises:\n * an `ImageError` as it is, another `SdkError` with its code, details and\n * message, and anything else as `UNKNOWN`, keeping the original as `cause`;\n * - `abortError` is the error an aborted call rejects with: an `SdkError`\n * reason adapted, so a file policy's `PROCESSING_TIME_EXCEEDED` keeps its\n * code, `TIMEOUT` for a timeout, and `ABORTED` otherwise;\n * - `throwIfAborted` throws `abortError` if the signal has aborted.\n *\n * @internal\n */\nexport const {\n adapt: asImageError,\n abortError,\n throwIfAborted,\n} = createErrorHelpers(ImageError, {\n fallbackCode: \"UNKNOWN\",\n fallbackMessage: \"Image processing failed.\",\n});\n","import {\n coreLimits,\n defineLimits,\n type FilePolicy,\n type FilePolicyOverrides,\n type Limits,\n} from \"@hussmartinez/sdk-core\";\nimport type { ImageProbe } from \"../model/source.js\";\nimport { ImageError } from \"./image-error.js\";\n\n/**\n * The image SDK's limit definitions: sdk-core's core limits with image\n * defaults, plus five for images (ADR 0004).\n *\n * | Limit | Code | Default maximum | Default warning |\n * |---|---|---|---|\n * | `maxFileSize` | `FILE_TOO_LARGE` | 100 MB | 50 MB |\n * | `maxFiles` | `TOO_MANY_FILES` | 20 | none |\n * | `maxDecodedSize` | `DECODED_SIZE_TOO_LARGE` | 1 GB | 400 MB |\n * | `maxProcessingTime` | `PROCESSING_TIME_EXCEEDED` | 120 s | none |\n * | `maxImagePixels` | `IMAGE_TOO_LARGE` | 50 megapixels | 24 megapixels |\n * | `maxImageDimension` | `IMAGE_DIMENSION_TOO_LARGE` | 16,384 pixels | none |\n * | `maxFrames` | `TOO_MANY_FRAMES` | 300 | 100 |\n * | `maxSessionSize` | `SESSION_TOO_LARGE` | 1 GB | 500 MB |\n * | `maxLayers` | `TOO_MANY_LAYERS` | 256 | none |\n *\n * Sizes are decimal: 1 MB is 1,000,000 bytes. Decoded sizes count 4 bytes\n * per pixel. `maxImagePixels` is the same limit, with the same name, code\n * and unit, as `pdf-sdk`'s. `maxImageDimension` is a side length, in pixels.\n *\n * @public\n */\nexport const imageLimitDefinitions = {\n ...coreLimits,\n maxDecodedSize: { ...coreLimits.maxDecodedSize, default: 1_000_000_000, warning: 400_000_000 },\n maxImagePixels: {\n code: \"IMAGE_TOO_LARGE\",\n unit: \"pixels\",\n default: 50_000_000,\n warning: 24_000_000,\n },\n maxImageDimension: { code: \"IMAGE_DIMENSION_TOO_LARGE\", unit: \"pixels\", default: 16_384 },\n maxFrames: { code: \"TOO_MANY_FRAMES\", unit: \"count\", default: 300, warning: 100 },\n maxSessionSize: {\n code: \"SESSION_TOO_LARGE\",\n unit: \"bytes\",\n default: 1_000_000_000,\n warning: 500_000_000,\n },\n maxLayers: { code: \"TOO_MANY_LAYERS\", unit: \"count\", default: 256 },\n} as const;\n\n/**\n * The type of {@link imageLimitDefinitions}.\n *\n * @public\n */\nexport type ImageLimitDefinitions = typeof imageLimitDefinitions;\n\n/**\n * The names of the image SDK's limits.\n *\n * @public\n */\nexport type ImageLimitName = keyof ImageLimitDefinitions;\n\n/**\n * A host's `filePolicy`: a new maximum, or `{ maximum, warning }`, for any of\n * the image SDK's limits. `Infinity` disables a maximum, which removes a\n * protection against hostile files, or disables a warning. Unknown limit\n * names throw `TypeError` when the policy is resolved.\n *\n * @example\n * ```ts\n * // Large scans: raise the pixel and decoded sizes together.\n * const filePolicy: ImageFilePolicyOverrides = {\n * maxImagePixels: 100_000_000,\n * maxDecodedSize: { maximum: 2e9, warning: 800e6 },\n * };\n * ```\n *\n * @public\n */\nexport type ImageFilePolicyOverrides = FilePolicyOverrides<ImageLimitDefinitions>;\n\n/**\n * A resolved file policy for the image SDK. Violations throw\n * {@link ImageError}.\n *\n * @public\n */\nexport type ImageFilePolicy = FilePolicy<ImageLimitDefinitions>;\n\n/**\n * The image SDK's limits, ready to resolve a host's `filePolicy`. Violations\n * are thrown as {@link ImageError}, with `details` naming the limit.\n *\n * @example\n * ```ts\n * const policy = imageLimits.resolve(props.filePolicy);\n * policy.check(\"maxImagePixels\", width * height); // throws ImageError(\"IMAGE_TOO_LARGE\") above 50 megapixels\n * ```\n *\n * @public\n */\nexport const imageLimits: Limits<ImageLimitDefinitions> = /* @__PURE__ */ defineLimits(\n imageLimitDefinitions,\n { errorClass: ImageError },\n);\n\n/**\n * The limits that apply to one file on its own, which the engine checks\n * against its own probe before it decodes anything (ADR 0004).\n *\n * @public\n */\nexport const PER_FILE_LIMITS = [\n \"maxFileSize\",\n \"maxImageDimension\",\n \"maxImagePixels\",\n \"maxFrames\",\n \"maxDecodedSize\",\n] as const satisfies readonly ImageLimitName[];\n\n/**\n * Checks one probed file against a policy's per-file limits, in the order\n * of {@link PER_FILE_LIMITS}, and throws the first violation as an\n * `ImageError` with the limit's code (ADR 0004). Returns the limits whose\n * warning threshold the file reaches.\n *\n * @public\n */\nexport function checkFileLimits(\n policy: ImageFilePolicy,\n fileSize: number,\n probe: ImageProbe,\n): ImageLimitName[] {\n const { width, height } = probe.oriented;\n const actual: Record<(typeof PER_FILE_LIMITS)[number], number> = {\n maxFileSize: fileSize,\n maxImageDimension: Math.max(width, height),\n maxImagePixels: width * height,\n maxFrames: probe.frames,\n maxDecodedSize: probe.decodedPixelBound * 4,\n };\n return PER_FILE_LIMITS.filter((limit) => policy.check(limit, actual[limit]) === \"warning\");\n}\n\n/**\n * The limits an export's output canvas is checked against before it's\n * allocated: its longest side and its pixels (ADR 0004).\n *\n * @public\n */\nexport const OUTPUT_LIMITS = [\n \"maxImageDimension\",\n \"maxImagePixels\",\n] as const satisfies readonly ImageLimitName[];\n\n/**\n * Checks an export's output size against a policy before its canvas is\n * allocated, and throws the first violation as an `ImageError` with the\n * limit's code (ADR 0004).\n *\n * @public\n */\nexport function checkOutputLimits(\n policy: ImageFilePolicy,\n size: { readonly width: number; readonly height: number },\n): void {\n policy.check(\"maxImageDimension\", Math.max(size.width, size.height));\n policy.check(\"maxImagePixels\", size.width * size.height);\n}\n","import {\n createWorkerClient,\n resolveAssetsBase,\n type WorkerClient,\n type WorkerLike,\n} from \"@hussmartinez/sdk-core\";\nimport { abortError, asImageError, throwIfAborted } from \"../core/errors/error-helpers.js\";\nimport { ImageError } from \"../core/errors/image-error.js\";\nimport { imageLimits, PER_FILE_LIMITS } from \"../core/errors/image-limits.js\";\nimport type { ImageProbe, ImageSourceInfo, ImageThumbnail } from \"../core/model/source.js\";\nimport type { ImageEngine } from \"../core/ports/image-engine.js\";\nimport type { ImageCallOptions, ImageRegisterOptions } from \"../core/ports/options.js\";\nimport type { RenderWorkerContract } from \"./render-worker/contract.js\";\n\n/**\n * Options for {@link createImageEngine}.\n *\n * @public\n */\nexport interface ImageEngineOptions {\n /**\n * Where the application serves the package's `dist/assets/` directory, to\n * load the render worker from its own origin instead of a `blob:` URL. The\n * worker is then `image/render.worker.js` there, and a Content Security\n * Policy needs `worker-src 'self'` and no `blob:` (docs/adr/0002). Copy\n * `dist/assets` again after every upgrade: a worker from another version\n * is refused with `WORKER_START_FAILED`. By default the worker is inlined.\n */\n readonly assetsUrl?: string | URL;\n}\n\n/**\n * What a processor needs from the engine whose render worker it shares\n * (docs/adr/0002): its client, once the worker has loaded, and which sources\n * it holds.\n *\n * @internal\n */\nexport interface EngineInternals {\n readonly client: () => Promise<WorkerClient<RenderWorkerContract>>;\n readonly has: (id: string) => boolean;\n}\n\n/** Where an engine made by {@link createImageEngine} keeps its internals. */\nexport const ENGINE_INTERNALS: unique symbol = Symbol(\"hm-image-engine\");\n\n/**\n * The internals of an engine made by {@link createImageEngine}, or\n * `undefined` for any other engine.\n *\n * @internal\n */\nexport function engineInternals(engine: ImageEngine): EngineInternals | undefined {\n return (engine as { [ENGINE_INTERNALS]?: EngineInternals })[ENGINE_INTERNALS];\n}\n\n/** What the engine needs from its environment, replaceable in tests. */\nexport interface EngineEnvironment {\n /** Loads the worker's code, on the first call, and returns how to start it. */\n readonly loadWorker: () => Promise<() => WorkerLike>;\n /** The version the worker must report: this package's. */\n readonly version: string;\n /** Where the worker comes from, for the version error's details. */\n readonly asset?: string;\n}\n\n/**\n * Creates the SDK's image engine (docs/adr/0001, docs/adr/0002,\n * docs/adr/0005). It probes files in its render worker with the SDK's own\n * readers, and decodes them there with `createImageBitmap`, upright: where\n * the browser doesn't apply a format's orientation, as its one-time\n * calibration shows, the worker applies it itself. Every decode must have\n * the probe's oriented size exactly. The worker holds the sources until\n * they're released or the engine is destroyed.\n *\n * Nothing starts until the first call. By default the worker is inlined,\n * which needs `worker-src blob:` in a Content Security Policy; with\n * `assetsUrl` it loads from your own origin, which needs `worker-src 'self'`\n * instead. Either way it makes no requests of its own.\n *\n * @example\n * ```ts\n * const engine = createImageEngine();\n * const probe = await engine.probe(file);\n * policy.check(\"maxImagePixels\", probe.oriented.width * probe.oriented.height);\n * const source = await engine.register(\"photo\", file, probe);\n * ```\n *\n * @public\n */\nexport function createImageEngine(options: ImageEngineOptions = {}): ImageEngine {\n const base = options.assetsUrl === undefined ? undefined : resolveAssetsBase(options.assetsUrl);\n const selfHosted = base === undefined ? undefined : `${base}image/render.worker.js`;\n return createEngine({\n loadWorker: selfHosted\n ? async () => () => new Worker(selfHosted, { type: \"module\", name: \"hm-image-render\" })\n : async () => (await import(\"./render-worker/inline-worker.js\")).createInlineWorker,\n version: __IMAGE_SDK_VERSION__,\n ...(selfHosted ? { asset: selfHosted } : {}),\n });\n}\n\n/**\n * The engine, with its environment passed in.\n *\n * @internal\n */\nexport function createEngine(\n environment: EngineEnvironment,\n): ImageEngine & { readonly [ENGINE_INTERNALS]: EngineInternals } {\n let startWorker: (() => WorkerLike) | undefined;\n let destroyed = false;\n /** Sources the worker holds, or is decoding, by id. */\n const ids = new Set<string>();\n\n const client: WorkerClient<RenderWorkerContract> = createWorkerClient<RenderWorkerContract>({\n createWorker: () => {\n if (!startWorker) {\n throw new ImageError(\"WORKER_START_FAILED\", \"The render worker hasn't loaded.\");\n }\n return startWorker();\n },\n errorClasses: { ImageError },\n // The worker holds the sources, so it lives as long as the engine, and a\n // cancelled decode may finish rather than take the sources with it.\n idleTimeout: 0,\n cancelTimeout: 30_000,\n // A crashed worker has lost every source.\n onCrash: () => ids.clear(),\n // A self-hosted worker copied before an upgrade speaks the same protocol\n // but runs older code: sdk-core refuses it before any call, with\n // WORKER_START_FAILED and the asset and both versions (ADR 0038).\n packageVersion: environment.version,\n workerAsset: environment.asset ?? \"inline\",\n });\n\n async function ready(): Promise<void> {\n if (destroyed) throw new Error(\"The image engine has been destroyed.\");\n startWorker ??= await environment.loadWorker();\n }\n\n async function run<T>(signal: AbortSignal | undefined, work: () => Promise<T>): Promise<T> {\n throwIfAborted(signal);\n try {\n await ready();\n return await work();\n } catch (error) {\n if (error instanceof TypeError) throw error;\n if (signal?.aborted) throw abortError(signal);\n throw asImageError(error);\n }\n }\n\n const callOptions = (options: ImageCallOptions | undefined) =>\n options?.signal ? { signal: options.signal } : {};\n\n return {\n [ENGINE_INTERNALS]: {\n client: async () => {\n await ready();\n return client;\n },\n has: (id) => ids.has(id),\n },\n\n probe(file: Blob, options?: ImageCallOptions): Promise<ImageProbe> {\n return run(options?.signal, () => client.call(\"probe\", { file }, callOptions(options)));\n },\n\n async register(\n id: string,\n file: Blob,\n probe: ImageProbe,\n options?: ImageRegisterOptions,\n ): Promise<ImageSourceInfo> {\n if (destroyed) throw new Error(\"The image engine has been destroyed.\");\n if (ids.has(id)) throw new TypeError(`The source id \"${id}\" is already in use.`);\n ids.add(id);\n try {\n const size = await run(options?.signal, () =>\n client.call(\n \"register\",\n {\n id,\n file,\n probe,\n // The maxima cross to the worker, which checks them against its\n // own probe (docs/adr/0004).\n limits: Object.fromEntries(\n PER_FILE_LIMITS.map((limit) => [\n limit,\n (options?.filePolicy ?? imageLimits.resolve()).limits[limit].maximum,\n ]),\n ) as Record<(typeof PER_FILE_LIMITS)[number], number>,\n },\n callOptions(options),\n ),\n );\n options?.onProgress?.(1);\n return {\n id,\n format: probe.format,\n width: size.width,\n height: size.height,\n // Animations open as their first frame until the GIF decoder lands\n // (docs/adr/0001).\n frames: 1,\n hasAlpha: probe.hasAlpha,\n decodedBytes: size.width * size.height * 4,\n };\n } catch (error) {\n ids.delete(id);\n // A cancelled decode may still finish in the worker; release it.\n if (options?.signal?.aborted && !destroyed) {\n client.call(\"release\", { id }).catch(() => undefined);\n }\n throw error;\n }\n },\n\n async thumbnail(\n id: string,\n maxSize: number,\n options?: ImageCallOptions,\n ): Promise<ImageThumbnail> {\n if (!ids.has(id)) throw new TypeError(`There's no source with the id \"${id}\".`);\n if (!(maxSize >= 1)) throw new RangeError(\"maxSize must be at least 1.\");\n return run(options?.signal, () =>\n client.call(\"thumbnail\", { id, maxSize }, callOptions(options)),\n );\n },\n\n async release(id: string): Promise<void> {\n if (!ids.delete(id) || destroyed) return;\n await run(undefined, () => client.call(\"release\", { id }));\n },\n\n async destroy(): Promise<void> {\n if (destroyed) return;\n destroyed = true;\n ids.clear();\n client.destroy();\n },\n };\n}\n","import { abortError, asImageError, throwIfAborted } from \"../core/errors/error-helpers.js\";\nimport { imageLimits, OUTPUT_LIMITS } from \"../core/errors/image-limits.js\";\nimport type { ImageEngine } from \"../core/ports/image-engine.js\";\nimport type { ImageExportJob, ImageProcessor } from \"../core/ports/image-processor.js\";\nimport type { ImageExportOptions } from \"../core/ports/options.js\";\nimport { engineInternals } from \"./image-engine.js\";\n\nconst FORMATS = new Set([\"png\", \"jpeg\", \"webp\"]);\n\n/**\n * Creates the SDK's image processor over an engine from\n * {@link createImageEngine}, sharing its render worker, where the sources\n * are (docs/adr/0002). An export renders the plan at its output size in an\n * sRGB canvas, after checking that size against the file policy, encodes\n * it with the browser's encoder, and keeps nothing of the result but the\n * image data and the fields the user kept: title, description, artist and\n * copyright, as EXIF in JPEG and `iTXt` in PNG. WebP exports carry no\n * metadata. The encoded type is checked: a browser that can't encode the\n * requested format fails with `UNSUPPORTED_FORMAT` (docs/adr/0001,\n * docs/adr/0005).\n *\n * @example\n * ```ts\n * const engine = createImageEngine();\n * const processor = createImageProcessor(engine);\n * const blob = await processor.export({ plan, format: { type: \"jpeg\", quality: 0.9 } });\n * ```\n *\n * @throws `TypeError` for an engine that `createImageEngine` didn't make.\n * @public\n */\nexport function createImageProcessor(engine: ImageEngine): ImageProcessor {\n const internals = engineInternals(engine);\n if (!internals) {\n throw new TypeError(\"createImageProcessor needs an engine from createImageEngine.\");\n }\n let destroyed = false;\n return {\n async export(job: ImageExportJob, options?: ImageExportOptions): Promise<Blob> {\n if (destroyed) throw new Error(\"The image processor has been destroyed.\");\n const { plan, format } = job;\n if (!FORMATS.has(format.type)) {\n throw new TypeError(`\"${String(format.type)}\" isn't an export format.`);\n }\n if (format.type !== \"png\" && format.quality !== undefined) {\n if (!(format.quality >= 0 && format.quality <= 1)) {\n throw new RangeError(\"quality must be from 0 to 1.\");\n }\n }\n if (!internals.has(plan.base.source)) {\n throw new TypeError(`There's no source with the id \"${plan.base.source}\".`);\n }\n const signal = options?.signal;\n throwIfAborted(signal);\n const policy = options?.filePolicy ?? imageLimits.resolve();\n try {\n const client = await internals.client();\n const blob = await client.call(\n \"export\",\n {\n plan,\n format,\n limits: Object.fromEntries(\n OUTPUT_LIMITS.map((limit) => [limit, policy.limits[limit].maximum]),\n ) as Record<(typeof OUTPUT_LIMITS)[number], number>,\n },\n signal ? { signal } : {},\n );\n options?.onProgress?.(1);\n return blob;\n } catch (error) {\n if (error instanceof TypeError) throw error;\n if (signal?.aborted) throw abortError(signal);\n throw asImageError(error);\n }\n },\n\n async destroy(): Promise<void> {\n destroyed = true;\n },\n };\n}\n","import type { ImageFilePolicy } from \"../errors/image-limits.js\";\nimport type { ImagePlan } from \"../model/plan.js\";\nimport type { ImageCallOptions } from \"./options.js\";\n\n/**\n * The highest device pixel ratio the preview draws at. A larger ratio is\n * drawn at this one: no display needs more, and it bounds the canvas a\n * runaway layout can ask for.\n *\n * @public\n */\nexport const MAX_PIXEL_RATIO = 4;\n\n/**\n * Where and how the preview is shown: the stage's size in CSS pixels, the\n * device pixel ratio, and the zoom and pan. At zoom 1 the composition fits\n * the stage; the pan moves it, in CSS pixels. The view isn't part of the\n * document (ADR 0003).\n *\n * @public\n */\nexport interface ImageView {\n readonly width: number;\n readonly height: number;\n /**\n * Device pixels per CSS pixel, such as `devicePixelRatio`. Ratios above\n * {@link MAX_PIXEL_RATIO} are drawn at it.\n */\n readonly pixelRatio: number;\n /** 1 fits the composition inside the stage; 2 is twice that. */\n readonly zoom: number;\n readonly pan: { readonly x: number; readonly y: number };\n /**\n * CSS pixels the fitted composition keeps clear inside each edge of the\n * stage, such as room for the crop frame's handles, which would otherwise\n * be cut off where the image meets the stage's edge. 0 when omitted.\n */\n readonly inset?: number;\n}\n\n/**\n * Options for a render.\n *\n * @public\n */\nexport interface ImageRenderOptions extends ImageCallOptions {\n /**\n * The limits the preview canvas's backing size, the view's size times its\n * pixel ratio, is checked against before the canvas is resized:\n * `maxImageDimension` and `maxImagePixels` (ADR 0004). The defaults of\n * `imageLimits` when omitted.\n */\n readonly filePolicy?: ImageFilePolicy;\n}\n\n/**\n * What became of one `render` call: `drawn`, or `superseded` when a later\n * call replaced it before it was drawn (ADR 0002).\n *\n * @public\n */\nexport type ImageRenderOutcome = \"drawn\" | \"superseded\";\n\n/**\n * The port for the preview (ADR 0002): a canvas on the page, drawn by the\n * engine's render worker through the same renderer as every export, so what\n * the editor shows is what the file will contain. Renders are coalesced:\n * when plans arrive faster than they're drawn, only the latest is drawn, and\n * a render in progress stops at its next strip.\n *\n * @public\n */\nexport interface ImageRenderer {\n /**\n * Hands a canvas to the render worker, once per canvas. The page can't\n * draw into or read it afterwards. Without `transferControlToOffscreen`\n * it rejects with `UNSUPPORTED_ENVIRONMENT`.\n */\n attach(canvas: HTMLCanvasElement): Promise<void>;\n /**\n * Draws a plan into the attached canvas for a view. It resolves `drawn`\n * when this plan is on screen, or `superseded` when a later call replaced\n * it. A plan whose source isn't registered is a `TypeError`. A view whose\n * backing size is over `filePolicy`'s limits rejects with the limit's code\n * before anything is drawn, and the canvas keeps its previous frame.\n */\n render(\n plan: ImagePlan,\n view: ImageView,\n options?: ImageRenderOptions,\n ): Promise<ImageRenderOutcome>;\n /** Releases the canvas in the worker. Pending renders resolve `superseded`, and later calls throw. */\n destroy(): Promise<void>;\n}\n\n/**\n * The size of the preview canvas's backing store for a view: its size times\n * its pixel ratio, at most {@link MAX_PIXEL_RATIO}, in whole pixels.\n *\n * @public\n */\nexport function backingSize(view: ImageView): { readonly width: number; readonly height: number } {\n const ratio = Math.min(view.pixelRatio, MAX_PIXEL_RATIO);\n return {\n width: Math.max(1, Math.round(view.width * ratio)),\n height: Math.max(1, Math.round(view.height * ratio)),\n };\n}\n\n/**\n * The view for a stage of this size: fitted, centred, at this ratio.\n *\n * @public\n */\nexport function fittedView(width: number, height: number, pixelRatio = 1): ImageView {\n return { width, height, pixelRatio, zoom: 1, pan: { x: 0, y: 0 } };\n}\n\n/**\n * Where a composition of this size is shown on the stage for a view, in the\n * stage's CSS pixels: fitted, zoomed, centred and panned. The renderer draws\n * there, and the editor's crop frame and handles are placed with it, so the\n * DOM over the canvas lines up with its pixels (ADR 0002).\n *\n * @public\n */\nexport function placement(\n composition: { readonly width: number; readonly height: number },\n view: ImageView,\n): {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n readonly scale: number;\n} {\n const inset = view.inset ?? 0;\n const fit = Math.min(\n (view.width - 2 * inset) / composition.width,\n (view.height - 2 * inset) / composition.height,\n );\n const scale = Math.max(0, fit) * view.zoom;\n const width = composition.width * scale;\n const height = composition.height * scale;\n return {\n x: (view.width - width) / 2 + view.pan.x,\n y: (view.height - height) / 2 + view.pan.y,\n width,\n height,\n scale,\n };\n}\n","import { abortError, asImageError, throwIfAborted } from \"../core/errors/error-helpers.js\";\nimport { ImageError } from \"../core/errors/image-error.js\";\nimport { checkOutputLimits, imageLimits, OUTPUT_LIMITS } from \"../core/errors/image-limits.js\";\nimport type { ImagePlan } from \"../core/model/plan.js\";\nimport type { ImageEngine } from \"../core/ports/image-engine.js\";\nimport {\n backingSize,\n type ImageRenderer,\n type ImageRenderOptions,\n type ImageRenderOutcome,\n type ImageView,\n} from \"../core/ports/image-renderer.js\";\nimport { engineInternals } from \"./image-engine.js\";\n\n/** What tests reach of a renderer from {@link createImageRenderer}. */\nexport interface RendererInternals {\n /** A copy of the preview's pixels: the page can't read a transferred canvas. */\n readonly snapshot: () => Promise<ImageBitmap>;\n /** How many renders the worker has drawn, for the coalescing tests. */\n readonly drawn: () => number;\n}\n\n/** Where a renderer made by {@link createImageRenderer} keeps its internals. */\nexport const RENDERER_INTERNALS: unique symbol = Symbol(\"hm-image-renderer\");\n\n/**\n * The internals of a renderer made by {@link createImageRenderer}.\n *\n * @internal\n */\nexport function rendererInternals(renderer: ImageRenderer): RendererInternals | undefined {\n return (renderer as { [RENDERER_INTERNALS]?: RendererInternals })[RENDERER_INTERNALS];\n}\n\nlet nextCanvasId = 0;\n\ninterface Request {\n readonly plan: ImagePlan;\n readonly view: ImageView;\n readonly resolve: (outcome: ImageRenderOutcome) => void;\n readonly reject: (error: unknown) => void;\n readonly signal: AbortSignal | undefined;\n readonly limits: Readonly<Record<(typeof OUTPUT_LIMITS)[number], number>>;\n}\n\nfunction checkView(view: ImageView): void {\n const positive = (n: number) => Number.isFinite(n) && n > 0;\n if (\n !positive(view.width) ||\n !positive(view.height) ||\n !positive(view.pixelRatio) ||\n !positive(view.zoom) ||\n !Number.isFinite(view.pan.x) ||\n !Number.isFinite(view.pan.y) ||\n (view.inset !== undefined &&\n !(view.inset >= 0 && 2 * view.inset < Math.min(view.width, view.height)))\n ) {\n throw new RangeError(\n \"A view needs a positive size, pixel ratio and zoom, a finite pan, and an inset under half its size.\",\n );\n }\n}\n\n/**\n * Creates the SDK's preview renderer over an engine from\n * `createImageEngine`, sharing its render worker, where the sources are\n * (docs/adr/0002). The canvas is transferred to the worker once, and every\n * frame is drawn there by the same renderer as the export.\n *\n * Renders are coalesced, latest first: while one is being drawn, newer\n * calls replace the waiting one, which resolves `superseded`, and the one\n * being drawn is cancelled at its next strip. So a slider drag that sends\n * many plans ends with one final render of the last.\n *\n * @example\n * ```ts\n * const renderer = createImageRenderer(engine);\n * await renderer.attach(canvas);\n * await renderer.render(plan, fittedView(stage.clientWidth, stage.clientHeight, devicePixelRatio));\n * ```\n *\n * @throws `TypeError` for an engine that `createImageEngine` didn't make.\n * @public\n */\nexport function createImageRenderer(engine: ImageEngine): ImageRenderer {\n const internals = engineInternals(engine);\n if (!internals) {\n throw new TypeError(\"createImageRenderer needs an engine from createImageEngine.\");\n }\n nextCanvasId += 1;\n const id = `preview-${nextCanvasId}`;\n let attached = false;\n let destroyed = false;\n let drawn = 0;\n let pending: Request | undefined;\n let inFlight: { readonly controller: AbortController } | undefined;\n\n const pump = () => {\n if (inFlight || !pending) return;\n const request = pending;\n pending = undefined;\n const controller = new AbortController();\n const onAbort = () => controller.abort(request.signal?.reason);\n request.signal?.addEventListener(\"abort\", onAbort, { once: true });\n inFlight = { controller };\n internals\n .client()\n .then((client) =>\n client.call(\n \"render\",\n { id, plan: request.plan, view: request.view, limits: request.limits },\n { signal: controller.signal },\n ),\n )\n .then(\n () => {\n drawn += 1;\n request.resolve(\"drawn\");\n },\n (error: unknown) => {\n if (request.signal?.aborted) request.reject(abortError(request.signal));\n else if (controller.signal.aborted) request.resolve(\"superseded\");\n else request.reject(error instanceof TypeError ? error : asImageError(error));\n },\n )\n .finally(() => {\n request.signal?.removeEventListener(\"abort\", onAbort);\n inFlight = undefined;\n pump();\n });\n };\n\n const renderer: ImageRenderer & { readonly [RENDERER_INTERNALS]: RendererInternals } = {\n [RENDERER_INTERNALS]: {\n snapshot: async () => (await internals.client()).call(\"snapshot\", { id }),\n drawn: () => drawn,\n },\n\n async attach(canvas: HTMLCanvasElement): Promise<void> {\n if (destroyed) throw new Error(\"The image renderer has been destroyed.\");\n if (attached) throw new TypeError(\"The renderer already has a canvas.\");\n if (typeof canvas.transferControlToOffscreen !== \"function\") {\n throw new ImageError(\n \"UNSUPPORTED_ENVIRONMENT\",\n \"This browser can't draw the preview in a worker.\",\n {\n details: { feature: \"transferControlToOffscreen\" },\n },\n );\n }\n const offscreen = canvas.transferControlToOffscreen();\n try {\n const client = await internals.client();\n await client.call(\"attachCanvas\", { id, canvas: offscreen }, { transfer: true });\n attached = true;\n } catch (error) {\n throw asImageError(error);\n }\n },\n\n render(\n plan: ImagePlan,\n view: ImageView,\n options?: ImageRenderOptions,\n ): Promise<ImageRenderOutcome> {\n if (destroyed) return Promise.reject(new Error(\"The image renderer has been destroyed.\"));\n if (!attached) return Promise.reject(new TypeError(\"Attach a canvas before rendering.\"));\n if (!internals.has(plan.base.source)) {\n return Promise.reject(\n new TypeError(`There's no source with the id \"${plan.base.source}\".`),\n );\n }\n const policy = options?.filePolicy ?? imageLimits.resolve();\n try {\n checkView(view);\n // A runaway layout can't size the canvas past the limits; the\n // current frame stays (docs/adr/0004).\n checkOutputLimits(policy, backingSize(view));\n throwIfAborted(options?.signal);\n } catch (error) {\n return Promise.reject(error);\n }\n const limits = Object.fromEntries(\n OUTPUT_LIMITS.map((limit) => [limit, policy.limits[limit].maximum]),\n ) as Request[\"limits\"];\n return new Promise<ImageRenderOutcome>((resolve, reject) => {\n pending?.resolve(\"superseded\");\n pending = { plan, view, resolve, reject, signal: options?.signal, limits };\n // The render being drawn is stale now: stop it at its next strip.\n inFlight?.controller.abort(\n new DOMException(\"A later render replaced this one.\", \"AbortError\"),\n );\n pump();\n });\n },\n\n async destroy(): Promise<void> {\n if (destroyed) return;\n destroyed = true;\n pending?.resolve(\"superseded\");\n pending = undefined;\n inFlight?.controller.abort(new DOMException(\"The renderer was destroyed.\", \"AbortError\"));\n if (attached) {\n try {\n await (await internals.client()).call(\"detachCanvas\", { id });\n } catch {\n // The engine may already be destroyed, with its worker.\n }\n }\n },\n };\n return renderer;\n}\n","import type { ImageKeepableMetadata, ImageSize } from \"./source.js\";\n\n/**\n * A rectangle in whole pixels of the oriented source: `x` and `y` from its\n * top left, `width` and `height` at least 1 (ADR 0003).\n *\n * @public\n */\nexport interface ImageCrop {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * A quarter-turn rotation, clockwise, in degrees.\n *\n * @public\n */\nexport type ImageRotation = 0 | 90 | 180 | 270;\n\n/**\n * The plan's own rotation and flips, applied after the crop. They're user\n * edits, separate from the file's EXIF orientation, which decoding has\n * already applied (ADR 0005).\n *\n * @public\n */\nexport interface ImageOrientation {\n readonly rotate: ImageRotation;\n /** Mirrors left to right, after the rotation. */\n readonly flipX: boolean;\n /** Mirrors top to bottom, after the rotation. */\n readonly flipY: boolean;\n}\n\n/**\n * The base's tonal and colour adjustments (ADR 0006). Each is an integer\n * from -100 to 100, where 0 is unchanged, applied in this order.\n *\n * @public\n */\nexport interface ImageDevelop {\n /** Warmer (positive) or cooler (negative). */\n readonly temperature: number;\n /** Toward magenta (positive) or green (negative). */\n readonly tint: number;\n /** In fiftieths of a stop: 100 is two stops brighter. */\n readonly exposure: number;\n readonly highlights: number;\n readonly shadows: number;\n readonly contrast: number;\n readonly saturation: number;\n /** Saturation weighted toward the least saturated colours. */\n readonly vibrance: number;\n}\n\n/**\n * The names of the develop adjustments, in the order they're applied.\n *\n * @public\n */\nexport const DEVELOP_ADJUSTMENTS = [\n \"temperature\",\n \"tint\",\n \"exposure\",\n \"highlights\",\n \"shadows\",\n \"contrast\",\n \"saturation\",\n \"vibrance\",\n] as const satisfies readonly (keyof ImageDevelop)[];\n\n/**\n * Every adjustment at 0: the base as it was decoded.\n *\n * @public\n */\nexport const NEUTRAL_DEVELOP: ImageDevelop = Object.freeze({\n temperature: 0,\n tint: 0,\n exposure: 0,\n highlights: 0,\n shadows: 0,\n contrast: 0,\n saturation: 0,\n vibrance: 0,\n});\n\n/**\n * The filter presets (ADR 0006). Names are part of the document format:\n * presets are only ever added.\n *\n * @public\n */\nexport const FILTER_PRESETS = [\"vivid\", \"warm\", \"cool\", \"fade\", \"mono\", \"noir\", \"sepia\"] as const;\n\n/**\n * A filter preset's name.\n *\n * @public\n */\nexport type ImageFilterPreset = (typeof FILTER_PRESETS)[number];\n\n/**\n * A filter preset and its strength, an integer from 0 (no effect) to 100.\n *\n * @public\n */\nexport interface ImageFilter {\n readonly preset: ImageFilterPreset;\n readonly strength: number;\n}\n\n/**\n * The image being edited: a source, its crop and orientation, and its\n * develop adjustments and filter.\n *\n * @public\n */\nexport interface ImageBase {\n /** The id of a registered source. */\n readonly source: string;\n /** The crop, or `null` for the whole image. */\n readonly crop: ImageCrop | null;\n readonly orientation: ImageOrientation;\n readonly develop: ImageDevelop;\n /** The filter, or `null` for none. */\n readonly filter: ImageFilter | null;\n}\n\n/**\n * The export's size: the composition scaled by a factor up to 1, or fitted\n * inside a box without enlarging it.\n *\n * @public\n */\nexport type ImageOutput =\n | { readonly kind: \"scale\"; readonly scale: number }\n | { readonly kind: \"fit\"; readonly width: number; readonly height: number };\n\n/**\n * The session's document: a description of the edits over an immutable\n * source, rendered to pixels only for display and export (ADR 0003).\n *\n * @public\n */\nexport interface ImagePlan {\n readonly base: ImageBase;\n readonly output: ImageOutput;\n /** The fields the user chose to keep on export. Never a location (ADR 0005). */\n readonly metadata: ImageKeepableMetadata;\n}\n\n/**\n * No rotation and no flips.\n *\n * @public\n */\nexport const UPRIGHT: ImageOrientation = Object.freeze({ rotate: 0, flipX: false, flipY: false });\n\n/**\n * The export at full size.\n *\n * @public\n */\nexport const FULL_SIZE: ImageOutput = Object.freeze({ kind: \"scale\", scale: 1 });\n\n/**\n * The plan for a newly opened source: the whole image, upright, undeveloped\n * and unfiltered, at full size, keeping no metadata.\n *\n * @public\n */\nexport function createPlan(source: string): ImagePlan {\n return {\n base: { source, crop: null, orientation: UPRIGHT, develop: NEUTRAL_DEVELOP, filter: null },\n output: FULL_SIZE,\n metadata: { title: \"\", description: \"\", artist: \"\", copyright: \"\" },\n };\n}\n\n/**\n * Whether a crop is valid for a source of the given oriented size: whole\n * pixels, at least 1 × 1, and inside the source.\n *\n * @internal\n */\nexport function isValidCrop(crop: ImageCrop, source: ImageSize): boolean {\n const { x, y, width, height } = crop;\n return (\n [x, y, width, height].every(Number.isSafeInteger) &&\n x >= 0 &&\n y >= 0 &&\n width >= 1 &&\n height >= 1 &&\n x + width <= source.width &&\n y + height <= source.height\n );\n}\n","/**\n * The formats the probe recognises, by their signature bytes (ADR 0001).\n *\n * @public\n */\nexport type ImageFormat = \"png\" | \"jpeg\" | \"webp\" | \"gif\" | \"avif\" | \"heif\" | \"bmp\";\n\n/**\n * An EXIF orientation, 1 to 8: how the stored pixels must be turned to be\n * upright. 1 means they already are (ADR 0005).\n *\n * @public\n */\nexport type ExifOrientation = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;\n\n/**\n * A width and a height, in whole pixels.\n *\n * @public\n */\nexport interface ImageSize {\n readonly width: number;\n readonly height: number;\n}\n\n/**\n * Which kinds of metadata a file carries, as presence flags, never values,\n * so the editor can say what an export removes (ADR 0005).\n *\n * @public\n */\nexport interface ImageMetadataPresence {\n readonly location: boolean;\n readonly camera: boolean;\n readonly timestamps: boolean;\n readonly thumbnail: boolean;\n readonly colourProfile: boolean;\n /** Any other field, such as maker notes or unknown tags. */\n readonly other: boolean;\n}\n\n/**\n * The metadata fields a user may keep on export (ADR 0005). Empty strings\n * mean the field isn't written.\n *\n * @public\n */\nexport interface ImageKeepableMetadata {\n readonly title: string;\n readonly description: string;\n readonly artist: string;\n readonly copyright: string;\n}\n\n/**\n * What the probe learned about a file before anything decodes it (ADR 0001,\n * ADR 0004, ADR 0005). Limits are checked against it.\n *\n * @public\n */\nexport interface ImageProbe {\n readonly format: ImageFormat;\n /** The size of the stored pixels, before orientation. */\n readonly stored: ImageSize;\n /** The upright size, after orientation: the size the decoder must return. */\n readonly oriented: ImageSize;\n /** The EXIF or `irot`/`imir` orientation; 1 when there's none. */\n readonly orientation: ExifOrientation;\n /** 1 for a still image, otherwise the number of frames the probe walked. */\n readonly frames: number;\n readonly hasAlpha: boolean;\n /**\n * The most pixels the decoder can produce for the file: frames × the\n * oriented size for most formats, and for AVIF and HEIF the sum over every\n * item decoded with the primary, such as grid tiles and auxiliary planes.\n * A file with an orientation counts one more oriented frame, which the\n * worker needs when it applies the orientation itself (ADR 0005).\n * Never a count declared by one header (ADR 0001).\n */\n readonly decodedPixelBound: number;\n readonly metadata: ImageMetadataPresence;\n /** The keepable fields the file carries, length-limited, shown only as text. */\n readonly keepable: ImageKeepableMetadata;\n}\n\n/**\n * A source the session holds, without its pixels: what the snapshot shows\n * (ADR 0003). Its size is the oriented size.\n *\n * @public\n */\nexport interface ImageSourceInfo {\n readonly id: string;\n readonly format: ImageFormat;\n readonly width: number;\n readonly height: number;\n readonly frames: number;\n readonly hasAlpha: boolean;\n /** The bytes the decoded source takes in the worker: frames × width × height × 4. */\n readonly decodedBytes: number;\n}\n\n/**\n * A small rendering of a source for lists and frame strips. An `ImageBitmap`\n * is one; tests can supply their own. Close it when it's no longer shown.\n *\n * @public\n */\nexport interface ImageThumbnail {\n readonly width: number;\n readonly height: number;\n close(): void;\n}\n\n/**\n * Metadata presence with nothing present.\n *\n * @public\n */\nexport const NO_METADATA: ImageMetadataPresence = Object.freeze({\n location: false,\n camera: false,\n timestamps: false,\n thumbnail: false,\n colourProfile: false,\n other: false,\n});\n\n/**\n * Keepable metadata with every field empty.\n *\n * @public\n */\nexport const EMPTY_KEEPABLE_METADATA: ImageKeepableMetadata = Object.freeze({\n title: \"\",\n description: \"\",\n artist: \"\",\n copyright: \"\",\n});\n\n/**\n * The longest a kept metadata value may be, in Unicode code points, as JSON\n * Schema and every language count them (ADR 0005, sdk-core ADR 0045).\n *\n * @public\n */\nexport const MAX_METADATA_LENGTH = 2_000;\n\n/**\n * Whether text has more than `max` Unicode code points: the length JSON\n * Schema's `maxLength` and other languages count, where JavaScript's\n * `length` counts UTF-16 units (sdk-core ADR 0045). It stops counting at\n * `max + 1`.\n *\n * @internal\n */\nexport function longerThan(text: string, max: number): boolean {\n // Every code point is one or two UTF-16 units.\n if (text.length <= max) return false;\n let count = 0;\n for (const _ of text) {\n count += 1;\n if (count > max) return true;\n }\n return false;\n}\n","import type { Reducer } from \"@hussmartinez/sdk-core\";\nimport { ImageError } from \"../errors/image-error.js\";\nimport {\n DEVELOP_ADJUSTMENTS,\n FILTER_PRESETS,\n type ImageCrop,\n type ImageDevelop,\n type ImageFilter,\n type ImageOrientation,\n type ImageOutput,\n type ImagePlan,\n isValidCrop,\n} from \"../model/plan.js\";\nimport {\n type ImageKeepableMetadata,\n type ImageSize,\n longerThan,\n MAX_METADATA_LENGTH,\n} from \"../model/source.js\";\n\n/**\n * Sets or removes the base's crop, in whole pixels of the oriented source.\n *\n * @public\n */\nexport interface SetCropCommand {\n readonly type: \"image.setCrop\";\n readonly crop: ImageCrop | null;\n}\n\n/**\n * Sets the base's rotation and flips.\n *\n * @public\n */\nexport interface SetOrientationCommand {\n readonly type: \"image.setOrientation\";\n readonly orientation: ImageOrientation;\n}\n\n/**\n * Sets the export's size.\n *\n * @public\n */\nexport interface SetOutputCommand {\n readonly type: \"image.setOutput\";\n readonly output: ImageOutput;\n}\n\n/**\n * Sets one metadata field to keep on export. An empty value keeps nothing.\n *\n * @public\n */\nexport interface SetMetadataCommand {\n readonly type: \"image.setMetadata\";\n readonly field: keyof ImageKeepableMetadata;\n readonly value: string;\n}\n\n/**\n * Sets some of the base's develop adjustments; the others keep their values\n * (ADR 0006).\n *\n * @public\n */\nexport interface SetDevelopCommand {\n readonly type: \"image.setDevelop\";\n readonly values: Partial<ImageDevelop>;\n}\n\n/**\n * Sets the base's filter preset and strength, or removes it with `null`.\n *\n * @public\n */\nexport interface SetFilterCommand {\n readonly type: \"image.setFilter\";\n readonly filter: ImageFilter | null;\n}\n\n/**\n * Every edit to an {@link ImagePlan}: plain, structured-cloneable data\n * (ADR 0003). Feature pull requests add their own commands to this union.\n *\n * @public\n */\nexport type ImageCommand =\n | SetCropCommand\n | SetOrientationCommand\n | SetOutputCommand\n | SetMetadataCommand\n | SetDevelopCommand\n | SetFilterCommand;\n\n/**\n * Why a command was refused, as a stable token: `details.reason` on the\n * `INVALID_COMMAND` error (sdk-core ADR 0045).\n *\n * - `malformed-command`: not shaped as the `hm-image-command` schema says,\n * such as a missing field, a field of the wrong type, an unknown field, or\n * a crop that isn't whole pixels of at least 1 × 1.\n * - `unknown-command`: a `type` the reducer doesn't know.\n * - `unknown-source`: a crop for a plan whose source isn't registered.\n * - `crop-outside-source`: a crop that doesn't fit inside its source.\n * - `invalid-orientation`: a rotation other than 0, 90, 180 or 270.\n * - `invalid-output`: a scale outside (0, 1], or a box under 1 pixel.\n * - `unknown-metadata-field`: a field other than title, description, artist\n * and copyright.\n * - `metadata-too-long`: a value over `MAX_METADATA_LENGTH` code points.\n * - `unknown-adjustment`: a develop value that isn't an adjustment.\n * - `invalid-level`: a develop value that isn't a whole number from -100 to 100.\n * - `unknown-preset`: a filter that isn't one of `FILTER_PRESETS`.\n * - `invalid-strength`: a filter strength that isn't a whole number from 0 to 100.\n *\n * @public\n */\nexport type ImageCommandRejection =\n | \"malformed-command\"\n | \"unknown-command\"\n | \"unknown-source\"\n | \"crop-outside-source\"\n | \"invalid-orientation\"\n | \"invalid-output\"\n | \"unknown-metadata-field\"\n | \"metadata-too-long\"\n | \"unknown-adjustment\"\n | \"invalid-level\"\n | \"unknown-preset\"\n | \"invalid-strength\";\n\n/**\n * A refusal while checking a command or a document, which the reducer and\n * the plan reader turn into their own codes.\n *\n * @internal\n */\nexport class Invalid extends Error {\n readonly reason: string;\n constructor(reason: string, message: string) {\n super(message);\n this.reason = reason;\n }\n}\n\n/** @internal */\nexport function invalid(reason: string, message: string): never {\n throw new Invalid(reason, message);\n}\n\n/** Whether a value is a plain object: not `null`, and not a list. @internal */\nexport const isRecord = <T>(value: unknown): value is T =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Refuses a field the object's type doesn't have, as the schemas do with\n * `additionalProperties: false`, rather than dropping it.\n *\n * @internal\n */\nexport function onlyFields(value: object, fields: readonly string[], what: string): void {\n for (const name of Object.keys(value)) {\n if (!fields.includes(name)) invalid(\"malformed-command\", `${what} has no field \"${name}\"`);\n }\n}\n\n/** Requires every field, as the schemas' `required` does. */\nfunction allFields(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)) invalid(\"malformed-command\", `${what} needs \"${name}\"`);\n }\n}\n\nconst isWhole = (value: unknown, min: number, max = Number.MAX_SAFE_INTEGER): value is number =>\n Number.isSafeInteger(value) && (value as number) >= min && (value as number) <= max;\n\n/**\n * A crop's shape: whole pixels from 0, at least 1 × 1. Whether it fits its\n * source depends on the source, which a schema can't see.\n *\n * @internal\n */\nexport function checkCrop(value: unknown): ImageCrop {\n if (!isRecord<ImageCrop>(value)) invalid(\"malformed-command\", \"a crop is an object\");\n allFields(value, [\"x\", \"y\", \"width\", \"height\"], \"a crop\");\n const { x, y, width, height } = value;\n if (!isWhole(x, 0) || !isWhole(y, 0) || !isWhole(width, 1) || !isWhole(height, 1)) {\n invalid(\"malformed-command\", \"a crop is whole pixels from 0, at least 1 × 1\");\n }\n return { x, y, width, height };\n}\n\n/** @internal */\nexport function checkCropInSource(crop: ImageCrop, source: ImageSize): void {\n if (!isValidCrop(crop, source)) {\n invalid(\"crop-outside-source\", \"a crop must fit inside its source\");\n }\n}\n\n/** @internal */\nexport function checkOrientation(value: unknown): ImageOrientation {\n if (!isRecord<ImageOrientation>(value))\n invalid(\"malformed-command\", \"an orientation is an object\");\n allFields(value, [\"rotate\", \"flipX\", \"flipY\"], \"an orientation\");\n const { rotate, flipX, flipY } = value;\n if (typeof flipX !== \"boolean\" || typeof flipY !== \"boolean\") {\n invalid(\"malformed-command\", \"an orientation's flips are booleans\");\n }\n if (![0, 90, 180, 270].includes(rotate)) {\n invalid(\"invalid-orientation\", \"a rotation is 0, 90, 180 or 270 degrees\");\n }\n return { rotate, flipX, flipY };\n}\n\n/** @internal */\nexport function checkOutput(value: unknown): ImageOutput {\n if (!isRecord<ImageOutput>(value)) invalid(\"malformed-command\", \"an output is an object\");\n if (value.kind === \"scale\") {\n allFields(value, [\"kind\", \"scale\"], \"a scale output\");\n if (typeof value.scale !== \"number\") invalid(\"malformed-command\", \"a scale is a number\");\n if (!(Number.isFinite(value.scale) && value.scale > 0 && value.scale <= 1)) {\n invalid(\"invalid-output\", \"an output scale is more than 0 and at most 1\");\n }\n return { kind: \"scale\", scale: value.scale };\n }\n if (value.kind === \"fit\") {\n allFields(value, [\"kind\", \"width\", \"height\"], \"a box output\");\n const { width, height } = value;\n if (!Number.isInteger(width) || !Number.isInteger(height)) {\n invalid(\"malformed-command\", \"a box's width and height are whole numbers\");\n }\n if (!isWhole(width, 1) || !isWhole(height, 1)) {\n invalid(\"invalid-output\", \"an output box is at least 1 × 1 pixel\");\n }\n return { kind: \"fit\", width, height };\n }\n return invalid(\"malformed-command\", \"an output is either a scale or a box to fit\");\n}\n\nconst METADATA_FIELDS: readonly (keyof ImageKeepableMetadata)[] = [\n \"title\",\n \"description\",\n \"artist\",\n \"copyright\",\n];\n\n/** @internal */\nexport function checkMetadataValue(field: string, value: unknown): string {\n if (typeof value !== \"string\") invalid(\"malformed-command\", `metadata.${field} is text`);\n if (longerThan(value, MAX_METADATA_LENGTH)) {\n invalid(\n \"metadata-too-long\",\n `metadata.${field} has more than ${MAX_METADATA_LENGTH} code points`,\n );\n }\n return value;\n}\n\n/** @internal */\nexport function checkMetadata(value: unknown): ImageKeepableMetadata {\n if (!isRecord<ImageKeepableMetadata>(value))\n invalid(\"malformed-command\", \"metadata is an object\");\n allFields(value, METADATA_FIELDS, \"metadata\");\n return Object.fromEntries(\n METADATA_FIELDS.map((field) => [field, checkMetadataValue(field, value[field])]),\n ) as unknown as ImageKeepableMetadata;\n}\n\nconst ADJUSTMENTS: readonly string[] = DEVELOP_ADJUSTMENTS;\nconst PRESETS: readonly string[] = FILTER_PRESETS;\n\n/** Develop values: some adjustments, or with `all`, every one. @internal */\nexport function checkDevelop(value: unknown, all = false): Partial<ImageDevelop> {\n if (!isRecord<Record<string, unknown>>(value)) {\n invalid(\"malformed-command\", \"develop values are an object\");\n }\n const values: Partial<Record<keyof ImageDevelop, number>> = {};\n for (const [name, level] of Object.entries(value)) {\n if (!ADJUSTMENTS.includes(name)) {\n invalid(\"unknown-adjustment\", `\"${name}\" isn't a develop adjustment`);\n }\n if (typeof level !== \"number\") invalid(\"malformed-command\", `${name} is a number`);\n if (!isWhole(level, -100, 100)) {\n invalid(\"invalid-level\", `${name} is a whole number from -100 to 100`);\n }\n values[name as keyof ImageDevelop] = level;\n }\n if (all) allFields(value, ADJUSTMENTS, \"develop\");\n // In the adjustments' order, whatever the input's.\n return Object.fromEntries(\n DEVELOP_ADJUSTMENTS.filter((name) => name in values).map((name) => [name, values[name]]),\n ) as Partial<ImageDevelop>;\n}\n\n/** @internal */\nexport function checkFilter(value: unknown): ImageFilter | null {\n if (value === null) return null;\n if (!isRecord<ImageFilter>(value)) invalid(\"malformed-command\", \"a filter is an object or null\");\n allFields(value, [\"preset\", \"strength\"], \"a filter\");\n if (typeof value.preset !== \"string\") invalid(\"malformed-command\", \"a filter's preset is text\");\n if (!PRESETS.includes(value.preset)) {\n invalid(\"unknown-preset\", `a filter's preset is one of ${FILTER_PRESETS.join(\", \")}`);\n }\n if (typeof value.strength !== \"number\") {\n invalid(\"malformed-command\", \"a filter's strength is a number\");\n }\n if (!isWhole(value.strength, 0, 100)) {\n invalid(\"invalid-strength\", \"a filter's strength is a whole number from 0 to 100\");\n }\n return { preset: value.preset, strength: value.strength };\n}\n\n/** Each command's fields, which are all required. */\nconst COMMAND_FIELDS: Readonly<Record<ImageCommand[\"type\"], readonly string[]>> = {\n \"image.setCrop\": [\"type\", \"crop\"],\n \"image.setOrientation\": [\"type\", \"orientation\"],\n \"image.setOutput\": [\"type\", \"output\"],\n \"image.setMetadata\": [\"type\", \"field\", \"value\"],\n \"image.setDevelop\": [\"type\", \"values\"],\n \"image.setFilter\": [\"type\", \"filter\"],\n};\n\nfunction apply(\n plan: ImagePlan,\n input: unknown,\n sourceSize: (id: string) => ImageSize | undefined,\n): { state: ImagePlan; inverse: ImageCommand } {\n if (!isRecord<{ type: unknown }>(input)) invalid(\"malformed-command\", \"a command is an object\");\n const { type } = input;\n if (typeof type !== \"string\") invalid(\"malformed-command\", \"a command's type is text\");\n if (!Object.hasOwn(COMMAND_FIELDS, type)) {\n invalid(\"unknown-command\", `\"${type}\" isn't a command`);\n }\n const command = input as ImageCommand;\n allFields(command, COMMAND_FIELDS[command.type], `${command.type}`);\n switch (command.type) {\n case \"image.setCrop\": {\n const crop = command.crop === null ? null : checkCrop(command.crop);\n if (crop !== null) {\n const size = sourceSize(plan.base.source);\n if (size === undefined) invalid(\"unknown-source\", `unknown source \"${plan.base.source}\"`);\n checkCropInSource(crop, size);\n }\n return {\n state: { ...plan, base: { ...plan.base, crop } },\n inverse: { type: \"image.setCrop\", crop: plan.base.crop },\n };\n }\n case \"image.setOrientation\": {\n const orientation = checkOrientation(command.orientation);\n return {\n state: { ...plan, base: { ...plan.base, orientation } },\n inverse: { type: \"image.setOrientation\", orientation: plan.base.orientation },\n };\n }\n case \"image.setOutput\": {\n const output = checkOutput(command.output);\n return {\n state: { ...plan, output },\n inverse: { type: \"image.setOutput\", output: plan.output },\n };\n }\n case \"image.setMetadata\": {\n const { field } = command;\n if (typeof field !== \"string\") invalid(\"malformed-command\", \"a metadata field is text\");\n if (!(METADATA_FIELDS as readonly string[]).includes(field)) {\n invalid(\"unknown-metadata-field\", \"only title, description, artist and copyright are kept\");\n }\n const value = checkMetadataValue(field, command.value);\n return {\n state: { ...plan, metadata: { ...plan.metadata, [field]: value } },\n inverse: { type: \"image.setMetadata\", field, value: plan.metadata[field] },\n };\n }\n case \"image.setDevelop\": {\n const values = checkDevelop(command.values);\n const previous: Partial<Record<keyof ImageDevelop, number>> = {};\n for (const name of Object.keys(values) as (keyof ImageDevelop)[]) {\n previous[name] = plan.base.develop[name];\n }\n return {\n state: { ...plan, base: { ...plan.base, develop: { ...plan.base.develop, ...values } } },\n inverse: { type: \"image.setDevelop\", values: previous },\n };\n }\n case \"image.setFilter\": {\n const filter = checkFilter(command.filter);\n return {\n state: { ...plan, base: { ...plan.base, filter } },\n inverse: { type: \"image.setFilter\", filter: plan.base.filter },\n };\n }\n }\n}\n\n/**\n * Creates the reducer for {@link ImageCommand}s: a pure function that\n * applies one command and returns the command that undoes it (ADR 0003,\n * ADR 0029). It needs the oriented size of each source, to check crops.\n *\n * Commands are strict, as the `hm-image-command` schema is (sdk-core ADR\n * 0045): an invalid command, including one with a field its type doesn't\n * have, throws `ImageError` with `INVALID_COMMAND` and an\n * {@link ImageCommandRejection} as `details.reason`. The reducer never\n * silently corrects one.\n *\n * @public\n */\nexport function createImageReducer(\n sourceSize: (id: string) => ImageSize | undefined,\n): Reducer<ImagePlan, ImageCommand> {\n return (plan, command) => {\n try {\n return apply(plan, command, sourceSize);\n } catch (error) {\n if (!(error instanceof Invalid)) throw error;\n throw new ImageError(\"INVALID_COMMAND\", `Invalid command: ${error.message}.`, {\n details: { reason: error.reason },\n });\n }\n };\n}\n","import type { ImageCrop, ImageOrientation, ImageOutput, ImagePlan } from \"./plan.js\";\nimport type { ExifOrientation, ImageSize } from \"./source.js\";\n\n/**\n * A point in pixels, which may be fractional.\n *\n * @public\n */\nexport interface ImagePoint {\n readonly x: number;\n readonly y: number;\n}\n\n/**\n * The upright size of stored pixels with an EXIF orientation: orientations 5\n * to 8 swap width and height (ADR 0005).\n *\n * @public\n */\nexport function orientedSize(stored: ImageSize, orientation: ExifOrientation): ImageSize {\n return orientation >= 5 ? { width: stored.height, height: stored.width } : stored;\n}\n\n/**\n * The cropped area of a source, or the whole source when there's no crop.\n *\n * @public\n */\nexport function cropRect(crop: ImageCrop | null, source: ImageSize): ImageCrop {\n return crop ?? { x: 0, y: 0, width: source.width, height: source.height };\n}\n\n/**\n * The size of the composition: the cropped source, turned by the plan's own\n * rotation (ADR 0003).\n *\n * @public\n */\nexport function compositionSize(plan: ImagePlan, source: ImageSize): ImageSize {\n const { width, height } = cropRect(plan.base.crop, source);\n const turned = plan.base.orientation.rotate % 180 !== 0;\n return turned ? { width: height, height: width } : { width, height };\n}\n\n/**\n * The size an export produces: the composition scaled down or fitted inside\n * a box, never enlarged, rounded to whole pixels and at least 1 × 1.\n *\n * @public\n */\nexport function outputSize(output: ImageOutput, composition: ImageSize): ImageSize {\n const factor =\n output.kind === \"scale\"\n ? output.scale\n : Math.min(1, output.width / composition.width, output.height / composition.height);\n return {\n width: Math.max(1, Math.round(composition.width * factor)),\n height: Math.max(1, Math.round(composition.height * factor)),\n };\n}\n\n/**\n * Maps a point in the cropped source to the composition, through the plan's\n * rotation and then its flips. Points are continuous coordinates, so the\n * cropped rectangle's corners map to the composition's corners.\n *\n * @public\n */\nexport function sourceToComposition(\n point: ImagePoint,\n crop: ImageCrop,\n orientation: ImageOrientation,\n): ImagePoint {\n const x = point.x - crop.x;\n const y = point.y - crop.y;\n const { width, height } = crop;\n let turned: ImagePoint;\n switch (orientation.rotate) {\n case 90:\n turned = { x: height - y, y: x };\n break;\n case 180:\n turned = { x: width - x, y: height - y };\n break;\n case 270:\n turned = { x: y, y: width - x };\n break;\n default:\n turned = { x, y };\n }\n const size =\n orientation.rotate % 180 === 0 ? { width, height } : { width: height, height: width };\n return {\n x: orientation.flipX ? size.width - turned.x : turned.x,\n y: orientation.flipY ? size.height - turned.y : turned.y,\n };\n}\n\n/**\n * The inverse of {@link sourceToComposition}: maps a point in the\n * composition, such as the pointer, back to the source.\n *\n * @public\n */\nexport function compositionToSource(\n point: ImagePoint,\n crop: ImageCrop,\n orientation: ImageOrientation,\n): ImagePoint {\n const { width, height } = crop;\n const size =\n orientation.rotate % 180 === 0 ? { width, height } : { width: height, height: width };\n const x = orientation.flipX ? size.width - point.x : point.x;\n const y = orientation.flipY ? size.height - point.y : point.y;\n let source: ImagePoint;\n switch (orientation.rotate) {\n case 90:\n source = { x: y, y: height - x };\n break;\n case 180:\n source = { x: width - x, y: height - y };\n break;\n case 270:\n source = { x: width - y, y: x };\n break;\n default:\n source = { x, y };\n }\n return { x: source.x + crop.x, y: source.y + crop.y };\n}\n","import { compositionToSource, sourceToComposition } from \"./geometry.js\";\nimport type { ImageCrop, ImageOrientation } from \"./plan.js\";\nimport type { ImageSize } from \"./source.js\";\n\n/**\n * The crop frame's geometry (docs/adr/0007): pure functions over crops in\n * whole pixels of the oriented source, which the editor's frame, keys and\n * fields share, so every way of cropping gives the same result.\n */\n\n/**\n * An aspect ratio the crop panel offers: free, the source's own, or width\n * over height.\n *\n * @public\n */\nexport type ImageAspect = \"free\" | \"original\" | readonly [number, number];\n\n/**\n * The crop panel's presets, landscape then portrait (docs/adr/0007).\n *\n * @public\n */\nexport const ASPECT_PRESETS: readonly ImageAspect[] = [\n \"free\",\n \"original\",\n [1, 1],\n [4, 3],\n [3, 2],\n [16, 9],\n [3, 4],\n [2, 3],\n [9, 16],\n];\n\n/**\n * The ratio of an aspect, width over height, or `undefined` for free.\n *\n * @public\n */\nexport function aspectRatio(aspect: ImageAspect, source: ImageSize): number | undefined {\n if (aspect === \"free\") return undefined;\n if (aspect === \"original\") return source.width / source.height;\n return aspect[0] / aspect[1];\n}\n\n/** The whole source as a crop. */\nexport const wholeCrop = (source: ImageSize): ImageCrop => ({\n x: 0,\n y: 0,\n width: source.width,\n height: source.height,\n});\n\n/**\n * The largest crop of a ratio inside `within`, centred in it, in whole\n * pixels and at least 1 × 1. With no ratio, `within` as it is.\n *\n * @public\n */\nexport function fitAspect(within: ImageCrop, ratio: number | undefined): ImageCrop {\n if (ratio === undefined) return within;\n let width = within.width;\n let height = Math.round(width / ratio);\n if (height > within.height) {\n height = within.height;\n width = Math.round(height * ratio);\n }\n width = Math.max(1, Math.min(within.width, width));\n height = Math.max(1, Math.min(within.height, height));\n return {\n x: within.x + Math.floor((within.width - width) / 2),\n y: within.y + Math.floor((within.height - height) / 2),\n width,\n height,\n };\n}\n\n/**\n * A crop moved by whole pixels, kept inside the source.\n *\n * @public\n */\nexport function moveCrop(crop: ImageCrop, dx: number, dy: number, source: ImageSize): ImageCrop {\n return {\n ...crop,\n x: Math.min(source.width - crop.width, Math.max(0, crop.x + Math.round(dx))),\n y: Math.min(source.height - crop.height, Math.max(0, crop.y + Math.round(dy))),\n };\n}\n\n/**\n * The edges a handle moves: `n`, `s`, `e` and `w`, and the corners that\n * combine two.\n *\n * @public\n */\nexport type CropHandle = \"n\" | \"s\" | \"e\" | \"w\" | \"ne\" | \"nw\" | \"se\" | \"sw\";\n\n/**\n * A crop with a handle dragged by a distance in source pixels, kept inside\n * the source and at least 1 × 1, in whole pixels. With a ratio, the opposite\n * edge or corner stays put and the other side follows the ratio.\n *\n * @public\n */\nexport function dragHandle(\n crop: ImageCrop,\n handle: CropHandle,\n dx: number,\n dy: number,\n source: ImageSize,\n ratio?: number,\n): ImageCrop {\n let left = crop.x;\n let top = crop.y;\n let right = crop.x + crop.width;\n let bottom = crop.y + crop.height;\n if (handle.includes(\"w\")) left = Math.min(right - 1, Math.max(0, left + dx));\n if (handle.includes(\"e\")) right = Math.max(left + 1, Math.min(source.width, right + dx));\n if (handle.includes(\"n\")) top = Math.min(bottom - 1, Math.max(0, top + dy));\n if (handle.includes(\"s\")) bottom = Math.max(top + 1, Math.min(source.height, bottom + dy));\n left = Math.round(left);\n right = Math.round(right);\n top = Math.round(top);\n bottom = Math.round(bottom);\n if (ratio === undefined) {\n return { x: left, y: top, width: right - left, height: bottom - top };\n }\n // Keep the ratio from the moved size, anchored at the opposite side, and\n // within the room the source leaves there.\n const horizontal = handle.includes(\"e\") || handle.includes(\"w\");\n const vertical = handle.includes(\"n\") || handle.includes(\"s\");\n let width = right - left;\n let height = bottom - top;\n if (horizontal && !vertical) height = width / ratio;\n else if (vertical && !horizontal) width = height * ratio;\n else if (width / height > ratio) width = height * ratio;\n else height = width / ratio;\n const roomRight = handle.includes(\"w\") ? right : source.width - left;\n const roomDown = handle.includes(\"n\") ? bottom : source.height - top;\n const scale = Math.min(1, roomRight / width, roomDown / height);\n width = Math.max(1, Math.round(width * scale));\n height = Math.max(1, Math.round(height * scale));\n const x = handle.includes(\"w\") ? right - width : left;\n let y = handle.includes(\"n\") ? bottom - height : top;\n // A side handle keeps the crop centred across it.\n let cx = x;\n if (vertical && !horizontal) cx = Math.round(crop.x + (crop.width - width) / 2);\n if (horizontal && !vertical) y = Math.round(crop.y + (crop.height - height) / 2);\n return {\n x: Math.min(source.width - width, Math.max(0, cx)),\n y: Math.min(source.height - height, Math.max(0, y)),\n width,\n height,\n };\n}\n\n/**\n * Where a crop of the oriented source appears in the composition of the\n * whole source under an orientation: an axis-aligned rectangle, since the\n * plan turns in quarter turns.\n *\n * @public\n */\nexport function cropInComposition(\n crop: ImageCrop,\n orientation: ImageOrientation,\n source: ImageSize,\n): ImageCrop {\n const whole = wholeCrop(source);\n const a = sourceToComposition({ x: crop.x, y: crop.y }, whole, orientation);\n const b = sourceToComposition(\n { x: crop.x + crop.width, y: crop.y + crop.height },\n whole,\n orientation,\n );\n return {\n x: Math.min(a.x, b.x),\n y: Math.min(a.y, b.y),\n width: Math.abs(b.x - a.x),\n height: Math.abs(b.y - a.y),\n };\n}\n\n/**\n * A distance in the composition of the whole source, as a distance in the\n * oriented source: what a pointer drag on the stage moves the crop by.\n *\n * @public\n */\nexport function compositionDeltaToSource(\n dx: number,\n dy: number,\n orientation: ImageOrientation,\n source: ImageSize,\n): { readonly dx: number; readonly dy: number } {\n const whole = wholeCrop(source);\n const origin = compositionToSource({ x: 0, y: 0 }, whole, orientation);\n const moved = compositionToSource({ x: dx, y: dy }, whole, orientation);\n return { dx: moved.x - origin.x, dy: moved.y - origin.y };\n}\n\n/**\n * Which source edges a handle on screen moves, under an orientation: the\n * handle's compass point in the composition, mapped back to the source.\n *\n * @public\n */\nexport function handleInSource(handle: CropHandle, orientation: ImageOrientation): CropHandle {\n const vector = { x: 0, y: 0 };\n if (handle.includes(\"e\")) vector.x = 1;\n if (handle.includes(\"w\")) vector.x = -1;\n if (handle.includes(\"s\")) vector.y = 1;\n if (handle.includes(\"n\")) vector.y = -1;\n const unit = compositionDeltaToSource(vector.x, vector.y, orientation, { width: 2, height: 2 });\n const ns = unit.dy > 0 ? \"s\" : unit.dy < 0 ? \"n\" : \"\";\n const ew = unit.dx > 0 ? \"e\" : unit.dx < 0 ? \"w\" : \"\";\n return `${ns}${ew}` as CropHandle;\n}\n\n/**\n * Moves or resizes a crop from the keyboard as it's seen on screen\n * (docs/adr/0007): an arrow moves it that way on screen, by `step` pixels of\n * the source; with `resize`, Left and Right move its right edge on screen,\n * and Up and Down its bottom edge, keeping a ratio if one is set.\n *\n * @public\n */\nexport function nudgeCropOnScreen(\n crop: ImageCrop,\n key: \"ArrowLeft\" | \"ArrowRight\" | \"ArrowUp\" | \"ArrowDown\",\n step: number,\n resize: boolean,\n orientation: ImageOrientation,\n source: ImageSize,\n ratio?: number,\n): ImageCrop {\n const dx = key === \"ArrowLeft\" ? -step : key === \"ArrowRight\" ? step : 0;\n const dy = key === \"ArrowUp\" ? -step : key === \"ArrowDown\" ? step : 0;\n const moved = compositionDeltaToSource(dx, dy, orientation, source);\n if (!resize) return moveCrop(crop, moved.dx, moved.dy, source);\n const handle = handleInSource(dx === 0 ? \"s\" : \"e\", orientation);\n return dragHandle(crop, handle, moved.dx, moved.dy, source, ratio);\n}\n","import {\n applyCommands,\n createHistory,\n createStore,\n type HistoryStep,\n} from \"@hussmartinez/sdk-core\";\nimport { asImageError, throwIfAborted } from \"../errors/error-helpers.js\";\nimport { ImageError, isImageError } from \"../errors/image-error.js\";\nimport {\n checkFileLimits,\n checkOutputLimits,\n type ImageFilePolicy,\n type ImageFilePolicyOverrides,\n type ImageLimitName,\n imageLimits,\n} from \"../errors/image-limits.js\";\nimport { compositionSize, outputSize } from \"../model/geometry.js\";\nimport { createPlan, type ImagePlan } from \"../model/plan.js\";\nimport type {\n ImageKeepableMetadata,\n ImageMetadataPresence,\n ImageProbe,\n ImageSourceInfo,\n} from \"../model/source.js\";\nimport { createImageReducer, type ImageCommand } from \"../operations/commands.js\";\nimport type { ImageEngine } from \"../ports/image-engine.js\";\nimport type { ImageExportFormat, ImageProcessor } from \"../ports/image-processor.js\";\n\n/**\n * The document's source, as the editor shows it: its size and format, and\n * what metadata the file carried, which the export summary reports as\n * removed unless the user kept it (ADR 0005).\n *\n * @public\n */\nexport interface ImageSessionSource extends ImageSourceInfo {\n /** Which kinds of metadata the file carried, never their values. */\n readonly metadata: ImageMetadataPresence;\n /** The fields the user may choose to keep, as the file had them. */\n readonly keepable: ImageKeepableMetadata;\n}\n\n/**\n * The session's state, for `useSyncExternalStore`: a new object on every\n * change (ADR 0003).\n *\n * @public\n */\nexport interface ImageSessionSnapshot {\n /** `empty` until a file opens; `opening` while the first one is; then `ready`. */\n readonly status: \"empty\" | \"opening\" | \"ready\";\n /** The document, or `null` before a file is open. */\n readonly plan: ImagePlan | null;\n /** The document's source, or `null` before a file is open. */\n readonly source: ImageSessionSource | null;\n readonly canUndo: boolean;\n readonly canRedo: boolean;\n /** Whether a file is being opened. The current document stays until it's ready. */\n readonly opening: boolean;\n /** Whether an export is in progress. */\n readonly exporting: boolean;\n /** The limits the last open, edit or export came near: at or above their warnings. */\n readonly warnings: readonly ImageLimitName[];\n /** The last failure, until the next successful open, edit or export. */\n readonly error: ImageError | null;\n}\n\n/**\n * An anonymous usage event for the host's `onEvent` (ADR 0003). It never\n * carries file names, pixels, text the user typed or metadata values.\n *\n * @public\n */\nexport interface ImageSessionEvent {\n readonly type: \"open\" | \"execute\" | \"undo\" | \"redo\" | \"export\";\n readonly outcome: \"done\" | \"failed\" | \"cancelled\";\n /** The types of the commands applied or undone. */\n readonly commands: readonly ImageCommand[\"type\"][];\n}\n\n/**\n * Options for {@link createImageSession}.\n *\n * @public\n */\nexport interface ImageSessionOptions {\n /** Probes, decodes and holds sources. The session releases the sources it registered, never the engine. */\n readonly engine: ImageEngine;\n /** Renders and encodes exports, over the same engine's sources. */\n readonly processor: ImageProcessor;\n /** The host's limits, over `imageLimits`' defaults (ADR 0004). */\n readonly filePolicy?: ImageFilePolicyOverrides;\n readonly onEvent?: (event: ImageSessionEvent) => void;\n}\n\n/**\n * What an export produced, and what the summary before a download shows\n * (ADR 0003, ADR 0005).\n *\n * @public\n */\nexport interface ImageSessionExport {\n readonly blob: Blob;\n readonly width: number;\n readonly height: number;\n /**\n * The kinds of metadata the source carried that the file doesn't: every\n * kind, since exports keep only the fields the user chose, which are\n * never these. Empty when the source carried none.\n */\n readonly removed: readonly (keyof ImageMetadataPresence)[];\n /** The fields the user kept, which the file carries. */\n readonly kept: readonly (keyof ImageKeepableMetadata)[];\n}\n\n/**\n * An image editing session (ADR 0003, ADR 0008): one document, its plan\n * over the source it opened, edited by commands with undo and redo, and\n * exported through its processor.\n *\n * @public\n */\nexport interface ImageSession {\n getSnapshot(): ImageSessionSnapshot;\n /** Calls the listener after every change. Returns a function that unsubscribes. */\n subscribe(listener: () => void): () => void;\n /**\n * Probes, checks and decodes a file, and makes it the document, with a new\n * plan and an empty history; the previous source is released (ADR 0003,\n * ADR 0004). The newest open wins: an open that finishes after a later one\n * started applies nothing, releases its source and rejects with\n * `ABORTED`. A failed or cancelled open leaves the current document as it\n * was.\n */\n open(file: Blob, options?: { readonly signal?: AbortSignal }): Promise<ImageSessionSource>;\n /**\n * Applies commands as one undoable step. They're checked by the reducer,\n * then the output against `maxImageDimension` and `maxImagePixels`; a\n * failure throws `ImageError` and changes nothing.\n */\n execute(commands: ImageCommand | readonly ImageCommand[]): void;\n /**\n * Makes the document's plan equal to `plan`, as one undoable step of the\n * commands that reach it, checked as `execute` checks them (ADR 0003). A\n * plan equal to the current one changes nothing. A plan over another\n * source is `INVALID_COMMAND`. For editors whose host holds the plan.\n */\n applyPlan(plan: ImagePlan): void;\n /**\n * Runs `fn`, and records every step it executes as one undoable step, for\n * a gesture such as dragging a crop handle (ADR 0003). `fn` must be\n * synchronous.\n */\n group<T>(fn: () => T): T;\n /** Undoes the last step. Returns whether there was one. */\n undo(): boolean;\n /** Redoes the last undone step. Returns whether there was one. */\n redo(): boolean;\n /**\n * Renders and encodes the document (ADR 0003). An export that finishes\n * after another file was opened rejects with `ABORTED`.\n */\n export(\n format: ImageExportFormat,\n options?: { readonly signal?: AbortSignal; readonly onProgress?: (fraction: number) => void },\n ): Promise<ImageSessionExport>;\n /** Releases the source the session holds. Later calls throw. */\n destroy(): Promise<void>;\n}\n\nconst same = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b);\n\n/** The commands that turn `from` into `to`, field by field. */\nexport function commandsBetween(from: ImagePlan, to: ImagePlan): ImageCommand[] {\n const commands: ImageCommand[] = [];\n if (!same(from.base.crop, to.base.crop)) {\n commands.push({ type: \"image.setCrop\", crop: to.base.crop });\n }\n if (!same(from.base.orientation, to.base.orientation)) {\n commands.push({ type: \"image.setOrientation\", orientation: to.base.orientation });\n }\n const develop = Object.fromEntries(\n Object.entries(to.base.develop).filter(\n ([name, value]) => from.base.develop[name as keyof typeof from.base.develop] !== value,\n ),\n );\n if (Object.keys(develop).length > 0) {\n commands.push({ type: \"image.setDevelop\", values: develop });\n }\n if (!same(from.base.filter, to.base.filter)) {\n commands.push({ type: \"image.setFilter\", filter: to.base.filter });\n }\n if (!same(from.output, to.output)) {\n commands.push({ type: \"image.setOutput\", output: to.output });\n }\n for (const field of Object.keys(to.metadata) as (keyof ImageKeepableMetadata)[]) {\n if (from.metadata[field] !== to.metadata[field]) {\n commands.push({ type: \"image.setMetadata\", field, value: to.metadata[field] });\n }\n }\n return commands;\n}\n\nconst PRESENCE: readonly (keyof ImageMetadataPresence)[] = [\n \"location\",\n \"camera\",\n \"timestamps\",\n \"thumbnail\",\n \"colourProfile\",\n \"other\",\n];\n\n/** The source's own limits, and what holding it costs against `maxSessionSize`. */\nfunction checkSource(\n policy: ImageFilePolicy,\n file: Blob,\n probe: ImageProbe,\n): readonly ImageLimitName[] {\n const near = checkFileLimits(policy, file.size, probe);\n // One document at a time: the session holds this one source.\n const bytes = probe.oriented.width * probe.oriented.height * 4;\n if (policy.check(\"maxSessionSize\", bytes) === \"warning\") near.push(\"maxSessionSize\");\n return near;\n}\n\n/**\n * Creates an {@link ImageSession} (ADR 0003): its store and history are\n * sdk-core's (ADR 0029), its reducer is {@link createImageReducer}, and it\n * reaches files only through its engine and processor.\n *\n * @example\n * ```ts\n * const engine = createImageEngine();\n * const session = createImageSession({ engine, processor: createImageProcessor(engine) });\n * await session.open(file);\n * session.execute({ type: \"image.setDevelop\", values: { exposure: 20 } });\n * const { blob, removed } = await session.export({ type: \"jpeg\", quality: 0.9 });\n * ```\n *\n * @public\n */\nexport function createImageSession(options: ImageSessionOptions): ImageSession {\n const { engine, processor } = options;\n const policy: ImageFilePolicy = imageLimits.resolve(options.filePolicy);\n const history = createHistory<ImageCommand>();\n let source: ImageSessionSource | null = null;\n const reducer = createImageReducer((id) =>\n source !== null && source.id === id ? source : undefined,\n );\n let plan: ImagePlan | null = null;\n /** Each open's number: only the latest may become the document. */\n let opens = 0;\n let opening = 0;\n let exporting = 0;\n /** Which document an async result belongs to. */\n let generation = 0;\n let warnings: readonly ImageLimitName[] = [];\n let error: ImageError | null = null;\n let nextId = 0;\n let destroyed = false;\n\n const snapshot = (): ImageSessionSnapshot => ({\n status: plan !== null ? \"ready\" : opening > 0 ? \"opening\" : \"empty\",\n plan,\n source,\n canUndo: history.canUndo,\n canRedo: history.canRedo,\n opening: opening > 0,\n exporting: exporting > 0,\n warnings,\n error,\n });\n const store = createStore<ImageSessionSnapshot>(snapshot());\n const publish = () => store.set(snapshot());\n const emit = (event: ImageSessionEvent) => {\n try {\n options.onEvent?.(event);\n } catch {\n // A host's handler can't break the session.\n }\n };\n const assertAlive = () => {\n if (destroyed) throw new Error(\"The image session has been destroyed.\");\n };\n const fail = (reason: unknown): ImageError => {\n error = isImageError(reason) ? reason : asImageError(reason);\n return error;\n };\n const superseded = () =>\n new ImageError(\"ABORTED\", \"A later open replaced this one.\", {\n details: { reason: \"superseded\" },\n });\n\n /** The plan after `commands`, with its output checked, and the step. */\n const attempt = (from: ImagePlan, commands: readonly ImageCommand[]) => {\n const { state, inverses } = applyCommands(reducer, from, commands);\n if (source) {\n checkOutputLimits(policy, outputSize(state.output, compositionSize(state, source)));\n }\n const step: HistoryStep<ImageCommand> = { commands: [...commands], inverses: [...inverses] };\n return { state, step };\n };\n\n const replay = (direction: \"undo\" | \"redo\"): boolean => {\n assertAlive();\n const step = direction === \"undo\" ? history.undo() : history.redo();\n if (!step || plan === null) return false;\n const commands = direction === \"undo\" ? step.inverses : step.commands;\n try {\n plan = applyCommands(reducer, plan, commands).state;\n } catch (reason) {\n history.restore(direction);\n publish();\n emit({ type: direction, outcome: \"failed\", commands: commands.map((c) => c.type) });\n throw fail(reason);\n }\n error = null;\n publish();\n emit({ type: direction, outcome: \"done\", commands: commands.map((c) => c.type) });\n return true;\n };\n\n /** Applies commands as one undoable step: `execute`, which `applyPlan` shares. */\n const executeCommands = (input: ImageCommand | readonly ImageCommand[]) => {\n assertAlive();\n const commands = Array.isArray(input)\n ? (input as readonly ImageCommand[])\n : [input as ImageCommand];\n try {\n if (plan === null) {\n throw new ImageError(\"INVALID_COMMAND\", \"There's nothing to edit before a file is open.\");\n }\n const result = attempt(plan, commands);\n plan = result.state;\n history.push(result.step);\n error = null;\n emit({ type: \"execute\", outcome: \"done\", commands: commands.map((c) => c.type) });\n } catch (reason) {\n emit({ type: \"execute\", outcome: \"failed\", commands: commands.map((c) => c.type) });\n throw fail(reason);\n } finally {\n publish();\n }\n };\n\n return {\n getSnapshot: () => store.getSnapshot(),\n subscribe: (listener) => store.subscribe(listener),\n\n async open(file, openOptions = {}) {\n assertAlive();\n const { signal } = openOptions;\n opens += 1;\n const ticket = opens;\n nextId += 1;\n const id = `source-${nextId}`;\n let registered = false;\n opening += 1;\n publish();\n try {\n throwIfAborted(signal);\n // Before reading anything, then the rest against the probe (ADR 0004).\n policy.check(\"maxFileSize\", file.size);\n const probe = await engine.probe(file, signal ? { signal } : {});\n const near = checkSource(policy, file, probe);\n if (ticket !== opens) throw superseded();\n const info = await engine.register(id, file, probe, {\n filePolicy: policy,\n ...(signal ? { signal } : {}),\n });\n registered = true;\n throwIfAborted(signal);\n assertAlive();\n if (ticket !== opens) throw superseded();\n\n // From here to the end nothing awaits, so nothing can change under us.\n const previous = source;\n source = { ...info, metadata: probe.metadata, keepable: probe.keepable };\n plan = createPlan(id);\n history.clear();\n generation += 1;\n warnings = near;\n error = null;\n if (previous) void engine.release(previous.id).catch(() => {});\n emit({ type: \"open\", outcome: \"done\", commands: [] });\n return source;\n } catch (reason) {\n if (registered && source?.id !== id) await engine.release(id).catch(() => {});\n const failure = isImageError(reason) ? reason : asImageError(reason);\n const cancelled = failure.code === \"ABORTED\";\n // A superseded or cancelled open isn't the document's failure.\n if (!cancelled) fail(failure);\n emit({ type: \"open\", outcome: cancelled ? \"cancelled\" : \"failed\", commands: [] });\n throw failure;\n } finally {\n opening -= 1;\n publish();\n }\n },\n\n execute: (input) => executeCommands(input),\n\n applyPlan(next) {\n assertAlive();\n if (plan === null || next.base.source !== plan.base.source) {\n const failure = new ImageError(\"INVALID_COMMAND\", \"The plan isn't for the open image.\");\n error = failure;\n publish();\n throw failure;\n }\n const commands = commandsBetween(plan, next);\n if (commands.length > 0) executeCommands(commands);\n },\n\n group(fn) {\n assertAlive();\n return history.group(fn);\n },\n\n undo: () => replay(\"undo\"),\n redo: () => replay(\"redo\"),\n\n async export(format, exportOptions = {}) {\n assertAlive();\n const { signal, onProgress } = exportOptions;\n if (plan === null || source === null) {\n throw new ImageError(\"INVALID_COMMAND\", \"There's nothing to export before a file is open.\");\n }\n const started = generation;\n const exported = plan;\n const from = source;\n exporting += 1;\n publish();\n try {\n const size = outputSize(exported.output, compositionSize(exported, from));\n const blob = await processor.export(\n { plan: exported, format },\n {\n filePolicy: policy,\n ...(signal ? { signal } : {}),\n ...(onProgress ? { onProgress } : {}),\n },\n );\n // The document was replaced while this export ran: it applies nothing.\n if (started !== generation || destroyed) {\n throw new ImageError(\"ABORTED\", \"Another file was opened during the export.\", {\n details: { reason: \"superseded\" },\n });\n }\n error = null;\n emit({ type: \"export\", outcome: \"done\", commands: [] });\n return {\n blob,\n width: size.width,\n height: size.height,\n removed: PRESENCE.filter((kind) => from.metadata[kind]),\n kept: (Object.keys(exported.metadata) as (keyof ImageKeepableMetadata)[]).filter(\n (field) => exported.metadata[field] !== \"\",\n ),\n };\n } catch (reason) {\n const failure = isImageError(reason) ? reason : asImageError(reason);\n const cancelled = failure.code === \"ABORTED\";\n if (!cancelled) fail(failure);\n emit({ type: \"export\", outcome: cancelled ? \"cancelled\" : \"failed\", commands: [] });\n throw failure;\n } finally {\n exporting -= 1;\n if (!destroyed) publish();\n }\n },\n\n async destroy() {\n if (destroyed) return;\n destroyed = true;\n const held = source;\n source = null;\n plan = null;\n history.clear();\n publish();\n if (held) await engine.release(held.id).catch(() => {});\n },\n };\n}\n","import { defineMessages, type MessageValue, plural, sdkCoreMessages } from \"@hussmartinez/sdk-core\";\nimport { uiMessages } from \"@hussmartinez/ui\";\nimport type { ImageErrorCode } from \"../core/errors/image-error.js\";\nimport type { ImageLimitName } from \"../core/errors/image-limits.js\";\n\n/**\n * The image SDK's English message catalogue: sdk-core's and ui's messages, and text\n * for every {@link ImageErrorCode} and every limit's warning. Pass it to\n * `createMessages` from `@hussmartinez/sdk-core`, with the host's locale and\n * overrides. It also has the editor's text: its labels, states,\n * announcements and tool names.\n *\n * Error text is looked up by code, with the error's `details` as\n * parameters, and never taken from `error.message` (ADR 0019).\n *\n * @example\n * ```ts\n * const messages = createMessages(imageMessages, { locale: \"en\", overrides: props.messages });\n * messages.error(error); // \"This animation has 400 frames, which is over the 300-frame limit.\"\n * messages.t(\"warnings.maxSessionSize\", { actual: 600e6 });\n * ```\n *\n * @public\n */\nexport const imageMessages = /* @__PURE__ */ defineMessages({\n ...sdkCoreMessages,\n // ui's components' text, so hosts translate the drop zone and dialogs\n // through the editor's `messages` too (sdk-core ADR 0046).\n ...uiMessages,\n \"errors.INVALID_IMAGE\": \"This file isn't a valid image, or it's too damaged to open.\",\n \"errors.UNSUPPORTED_FORMAT\":\n \"This image format isn't supported. Try converting the file to PNG or JPEG, then open it again.\",\n \"errors.DECODE_FAILED\":\n \"This browser can't open this kind of image. Try another browser, or convert the file to PNG or JPEG.\",\n \"errors.INVALID_COMMAND\": \"This edit couldn't be made. Please try again.\",\n \"errors.INVALID_DOCUMENT\": \"This project is damaged, or it isn't an image project.\",\n \"errors.IMAGE_TOO_LARGE\":\n \"This image has more pixels than the editor can handle. Try a smaller version of it.\",\n \"errors.IMAGE_DIMENSION_TOO_LARGE\":\n \"This image is {actual, number} pixels across, which is over the {maximum, number}-pixel limit.\",\n \"errors.TOO_MANY_FRAMES\": /* @__PURE__ */ plural(\"maximum\", {\n one: \"This animation has {actual, number} frames, which is over the {maximum}-frame limit.\",\n other:\n \"This animation has {actual, number} frames, which is over the {maximum, number}-frame limit.\",\n }),\n \"errors.SESSION_TOO_LARGE\":\n \"The open images would use {actual, fileSize} of memory, which is over the {maximum, fileSize} limit. Close an image, or clear the undo history, and try again.\",\n \"errors.TOO_MANY_LAYERS\": /* @__PURE__ */ plural(\"maximum\", {\n one: \"An image can have {maximum} layer. Merge or delete layers, and try again.\",\n other:\n \"An image can have up to {maximum, number} layers. Merge or delete layers, and try again.\",\n }),\n \"warnings.maxImagePixels\": \"This image is large, and may be slow to edit on some devices.\",\n \"warnings.maxImageDimension\": \"This image is very wide or tall, and may be slow to edit.\",\n \"warnings.maxFrames\": /* @__PURE__ */ plural(\"actual\", {\n one: \"This animation has {actual} frame.\",\n other: \"This animation has {actual, number} frames, and may be slow to edit and export.\",\n }),\n \"warnings.maxSessionSize\":\n \"The open images use {actual, fileSize} of memory. Clearing the undo history frees memory.\",\n \"warnings.maxLayers\": /* @__PURE__ */ plural(\"actual\", {\n one: \"This image has {actual} layer.\",\n other: \"This image has {actual, number} layers, and may be slow to edit and export.\",\n }),\n \"editor.label\": \"Image editor\",\n \"editor.preview\": \"Edited image preview, {width, number} × {height, number}\",\n \"editor.empty\": \"Open an image to start editing. It stays on this device.\",\n \"editor.choose\": \"Choose an image\",\n \"editor.dropHint\": \"or drop it here\",\n \"editor.opening\": \"Opening the image…\",\n \"editor.cancel\": \"Cancel\",\n \"editor.opened\": \"Image opened, {width, number} × {height, number}.\",\n \"editor.undid\": \"Undid {action}.\",\n \"editor.redid\": \"Redid {action}.\",\n \"actions.image.setCrop\": \"crop\",\n \"actions.image.setOrientation\": \"rotate or flip\",\n \"actions.image.setOutput\": \"size\",\n \"actions.image.setMetadata\": \"metadata\",\n \"actions.image.setDevelop\": \"adjustment\",\n \"actions.image.setFilter\": \"filter\",\n \"toolbar.label\": \"Image tools\",\n \"toolbar.groups.file\": \"File\",\n \"toolbar.groups.history\": \"History\",\n \"toolbar.groups.orientation\": \"Rotate\",\n \"toolbar.groups.zoom\": \"Zoom\",\n \"toolbar.groups.other\": \"More tools\",\n \"tools.open\": \"Open image\",\n \"tools.undo\": \"Undo\",\n \"tools.redo\": \"Redo\",\n \"tools.rotate-left\": \"Rotate left\",\n \"tools.rotate-right\": \"Rotate right\",\n \"tools.zoom-in\": \"Zoom in\",\n \"tools.zoom-out\": \"Zoom out\",\n \"tools.zoom-fit\": \"Fit to the stage\",\n \"tools.crop\": \"Crop\",\n \"tools.flip-horizontal\": \"Flip horizontally\",\n \"tools.flip-vertical\": \"Flip vertically\",\n \"toolbar.groups.crop\": \"Crop\",\n \"crop.frame\": \"Crop area\",\n \"crop.frameDescription\":\n \"{width, number} × {height, number} pixels, from {x, number}, {y, number}. Arrow keys move it; with Alt, they resize it; Enter applies and Escape cancels.\",\n \"crop.size\": \"{width, number} × {height, number}, from {x, number}, {y, number}\",\n \"crop.panel\": \"Crop\",\n \"crop.x\": \"Left\",\n \"crop.y\": \"Top\",\n \"crop.width\": \"Width\",\n \"crop.height\": \"Height\",\n \"crop.aspect\": \"Aspect ratio\",\n \"crop.aspects.free\": \"Free\",\n \"crop.aspects.original\": \"Original\",\n \"crop.aspects.ratio\": \"{width}:{height}\",\n \"crop.apply\": \"Apply crop\",\n \"crop.cancel\": \"Cancel\",\n \"crop.reset\": \"Whole image\",\n \"crop.applied\": \"Cropped to {width, number} × {height, number}.\",\n \"inspector.label\": \"Panels\",\n \"inspector.adjust\": \"Adjust\",\n \"inspector.filters\": \"Filters\",\n \"develop.panel\": \"Adjust\",\n \"develop.temperature\": \"Temperature\",\n \"develop.tint\": \"Tint\",\n \"develop.exposure\": \"Exposure\",\n \"develop.highlights\": \"Highlights\",\n \"develop.shadows\": \"Shadows\",\n \"develop.contrast\": \"Contrast\",\n \"develop.saturation\": \"Saturation\",\n \"develop.vibrance\": \"Vibrance\",\n \"develop.reset\": \"Reset {name}\",\n \"develop.resetAll\": \"Reset all\",\n \"develop.wasReset\": \"All adjustments reset.\",\n \"filters.panel\": \"Filters\",\n \"filters.label\": \"Filter\",\n \"filters.none\": \"None\",\n \"filters.vivid\": \"Vivid\",\n \"filters.warm\": \"Warm\",\n \"filters.cool\": \"Cool\",\n \"filters.fade\": \"Fade\",\n \"filters.mono\": \"Mono\",\n \"filters.noir\": \"Noir\",\n \"filters.sepia\": \"Sepia\",\n \"filters.strength\": \"Strength\",\n \"toolbar.groups.export\": \"Export\",\n \"tools.export\": \"Export\",\n \"export.title\": \"Export image\",\n \"export.description\": \"The file is made on this device, and nothing is uploaded.\",\n \"export.format\": \"Format\",\n \"export.formats.png\": \"PNG\",\n \"export.formats.jpeg\": \"JPEG\",\n \"export.formats.webp\": \"WebP\",\n \"export.quality\": \"Quality\",\n \"export.size\": \"Size\",\n \"export.sizes.scale\": \"Scale\",\n \"export.sizes.fit\": \"Fit in a box\",\n \"export.scale\": \"Scale, in percent\",\n \"export.fitWidth\": \"Largest width\",\n \"export.fitHeight\": \"Largest height\",\n \"export.fields\": \"Details to include\",\n \"export.fieldsHint\": \"Only what you fill in is written to the file.\",\n \"export.field.title\": \"Title\",\n \"export.field.description\": \"Description\",\n \"export.field.artist\": \"Artist\",\n \"export.field.copyright\": \"Copyright\",\n \"export.summary\": \"Summary\",\n \"export.output\": \"{width, number} × {height, number} pixels, {format}\",\n \"export.removed\": \"Removed from the file\",\n \"export.removedNone\": \"The image had no other details to remove.\",\n \"export.kind.location\": \"Location\",\n \"export.kind.camera\": \"Camera details\",\n \"export.kind.timestamps\": \"Dates and times\",\n \"export.kind.thumbnail\": \"Embedded thumbnail\",\n \"export.kind.colourProfile\": \"Colour profile: colours outside sRGB are clipped\",\n \"export.kind.other\": \"Other metadata\",\n \"export.kept\": \"Kept in the file\",\n \"export.confirm\": \"Export\",\n \"export.cancel\": \"Cancel\",\n \"export.progress\": \"Exporting the image\",\n \"export.stop\": \"Stop exporting\",\n \"export.cancelled\": \"Export stopped.\",\n \"export.done\": \"Exported a {format} of {size, fileSize}.\",\n \"export.ready\": \"{width, number} × {height, number} pixels, {format}, {size, fileSize}\",\n \"export.download\": \"Download\",\n \"export.close\": \"Done\",\n}) satisfies Record<`errors.${ImageErrorCode}`, MessageValue> &\n Record<`warnings.${ImageLimitName}`, MessageValue>;\n\n/**\n * The type of {@link imageMessages}, for typing a host's overrides with\n * `MessageOverrides<ImageMessageCatalogue>`.\n *\n * @public\n */\nexport type ImageMessageCatalogue = typeof imageMessages;\n"],"mappings":";;;AAuEA,IAAa,aAAb,cAAgC,SAAyB;CAEvD,OAAyB;AAC3B;AAcA,SAAgB,aACd,OACA,MAC+C;CAC/C,OAAO,WAAW,OAAO,IAAI,KAAK,MAAM,SAAS;AACnD;;AC5EA,IAAa,EACX,OAAO,cACP,YACA,mBACE,mBAAmB,YAAY;CACjC,cAAc;CACd,iBAAiB;AACnB,CAAC;;ACQD,IAAa,wBAAwB;CACnC,GAAG;CACH,gBAAgB;EAAE,GAAG,WAAW;EAAgB,SAAS;EAAe,SAAS;CAAY;CAC7F,gBAAgB;EACd,MAAM;EACN,MAAM;EACN,SAAS;EACT,SAAS;CACX;CACA,mBAAmB;EAAE,MAAM;EAA6B,MAAM;EAAU,SAAS;CAAO;CACxF,WAAW;EAAE,MAAM;EAAmB,MAAM;EAAS,SAAS;EAAK,SAAS;CAAI;CAChF,gBAAgB;EACd,MAAM;EACN,MAAM;EACN,SAAS;EACT,SAAS;CACX;CACA,WAAW;EAAE,MAAM;EAAmB,MAAM;EAAS,SAAS;CAAI;AACpE;AAuDA,IAAa,cAA6D,6BACxE,uBACA,EAAE,YAAY,WAAW,CAC3B;AAQA,IAAa,kBAAkB;CAC7B;CACA;CACA;CACA;CACA;AACF;AAUA,SAAgB,gBACd,QACA,UACA,OACkB;CAClB,MAAM,EAAE,OAAO,WAAW,MAAM;CAChC,MAAM,SAA2D;EAC/D,aAAa;EACb,mBAAmB,KAAK,IAAI,OAAO,MAAM;EACzC,gBAAgB,QAAQ;EACxB,WAAW,MAAM;EACjB,gBAAgB,MAAM,oBAAoB;CAC5C;CACA,OAAO,gBAAgB,QAAQ,UAAU,OAAO,MAAM,OAAO,OAAO,MAAM,MAAM,SAAS;AAC3F;AAQA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