@open33/harness-attachment 0.0.0-stage → 0.1.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.
@@ -0,0 +1,74 @@
1
+ /** Wire-form admission of base64-encoded image uploads. @module @open33/harness-attachment/admission */
2
+
3
+ import { Buffer } from 'node:buffer'
4
+ import { AttachmentError } from './error.ts'
5
+ import type { AttachmentStore } from './index.ts'
6
+ import type {
7
+ EncodedFileAttachment,
8
+ EncodedImageAttachment,
9
+ FileAttachmentRef,
10
+ ImageAttachmentRef,
11
+ SaveImageAttachment,
12
+ } from './types.ts'
13
+
14
+ /** Decode one upload payload while rejecting non-canonical base64 forms. */
15
+ function decodeCanonicalBase64(data: string, empty: 'reject' | 'accept', code: 'INVALID_IMAGE_BASE64' | 'INVALID_FILE_BASE64'): Uint8Array {
16
+ const decoded = Buffer.from(data, 'base64')
17
+ if ((data.length === 0 && empty === 'reject') || decoded.toString('base64') !== data) {
18
+ throw new AttachmentError(
19
+ code === 'INVALID_IMAGE_BASE64' ? 'Image upload is not canonical base64.' : 'File upload is not canonical base64.',
20
+ code,
21
+ )
22
+ }
23
+ return new Uint8Array(decoded)
24
+ }
25
+
26
+ function decodeBase64(data: string): Uint8Array {
27
+ return decodeCanonicalBase64(data, 'reject', 'INVALID_IMAGE_BASE64')
28
+ }
29
+
30
+ /** Store input for one decoded upload. */
31
+ function saveInput(image: EncodedImageAttachment): SaveImageAttachment {
32
+ return {
33
+ data: decodeBase64(image.data),
34
+ mediaType: image.mediaType,
35
+ ...image.name === undefined ? {} : { name: image.name },
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Admit one wire image batch: enforce canonical base64 on every member, then
41
+ * delegate batch admission — count and aggregate-byte limits, media-type and
42
+ * per-image validation, ordered commit — to {@link AttachmentStore.saveImages}.
43
+ * The shared entry for every RPC endpoint accepting browser uploads.
44
+ * @param attachments - the deployment attachment store owning batch policy.
45
+ * @param images - base64-encoded uploads in caller order.
46
+ * @returns durable references in the same order as `images`.
47
+ * @throws AttachmentError on a non-canonical payload or a refused batch.
48
+ */
49
+ export async function admitEncodedImages(
50
+ attachments: AttachmentStore,
51
+ images: readonly EncodedImageAttachment[],
52
+ ): Promise<readonly ImageAttachmentRef[]> {
53
+ return attachments.saveImages(images.map(saveInput))
54
+ }
55
+
56
+ /**
57
+ * Admit one wire file upload: enforce canonical base64 (an empty file is a
58
+ * valid zero-byte payload), then delegate verbatim commit to
59
+ * {@link AttachmentStore.saveFile}. The shared entry for every RPC endpoint
60
+ * accepting browser file uploads.
61
+ * @param attachments - the deployment attachment store.
62
+ * @param file - base64-encoded upload and optional display name.
63
+ * @returns the durable content-addressed file reference.
64
+ * @throws AttachmentError on a non-canonical payload or a storage failure.
65
+ */
66
+ export async function admitEncodedFile(
67
+ attachments: AttachmentStore,
68
+ file: EncodedFileAttachment,
69
+ ): Promise<FileAttachmentRef> {
70
+ return attachments.saveFile({
71
+ data: decodeCanonicalBase64(file.data, 'accept', 'INVALID_FILE_BASE64'),
72
+ ...file.name === undefined ? {} : { name: file.name },
73
+ })
74
+ }
package/src/brand.ts ADDED
@@ -0,0 +1,27 @@
1
+ /** Attachment identifier brand. @module @open33/harness-attachment/brand */
2
+
3
+ import type { Branded } from '@open33/harness-brand'
4
+
5
+ /** Opaque content-addressed identifier for one immutable attachment object. */
6
+ export type AttachmentId = Branded<'AttachmentId'>
7
+
8
+ /**
9
+ * Brand a validated storage identifier.
10
+ * @param value - backend-produced opaque identifier.
11
+ * @returns the branded identifier.
12
+ */
13
+ export function AttachmentId(value: string): AttachmentId {
14
+ return value as AttachmentId
15
+ }
16
+
17
+ /** Opaque deterministic identity for one request-image transformation. */
18
+ export type ImageVariantId = Branded<'ImageVariantId'>
19
+
20
+ /**
21
+ * Brand a validated request-image transformation identifier.
22
+ * @param value - attachment-provider-produced opaque identifier.
23
+ * @returns the branded identifier.
24
+ */
25
+ export function ImageVariantId(value: string): ImageVariantId {
26
+ return value as ImageVariantId
27
+ }
package/src/error.ts ADDED
@@ -0,0 +1,85 @@
1
+ /** Attachment failure class. @module @open33/harness-attachment/error */
2
+
3
+ import { HarnessError } from '@open33/harness-error'
4
+
5
+ const IMAGE_ADMISSION_ERROR_CODES = [
6
+ 'TOO_MANY_IMAGES',
7
+ 'IMAGES_TOO_LARGE',
8
+ 'UNSUPPORTED_IMAGE_TYPE',
9
+ 'INVALID_IMAGE_BASE64',
10
+ 'INVALID_IMAGE',
11
+ 'IMAGE_TYPE_MISMATCH',
12
+ 'IMAGE_TOO_LARGE',
13
+ 'IMAGE_TOO_MANY_PIXELS',
14
+ 'IMAGE_DIMENSION_TOO_LARGE',
15
+ ] as const
16
+
17
+ /** Caller-correctable attachment failure codes raised while admitting image input. */
18
+ export type ImageAdmissionErrorCode = typeof IMAGE_ADMISSION_ERROR_CODES[number]
19
+
20
+ const ATTACHMENT_ERROR_CODES = [
21
+ ...IMAGE_ADMISSION_ERROR_CODES,
22
+ 'INVALID_FILE_BASE64',
23
+ 'INVALID_ATTACHMENT_REF',
24
+ 'ATTACHMENT_CORRUPT',
25
+ 'ATTACHMENT_WRITE_FAILED',
26
+ 'ATTACHMENT_NOT_FOUND',
27
+ 'ATTACHMENT_READ_FAILED',
28
+ 'ATTACHMENT_PROJECTION_UNSUPPORTED',
29
+ 'ATTACHMENT_FILES_UNSUPPORTED',
30
+ ] as const
31
+
32
+ /** Stable attachment failure codes used for protocol error routing. */
33
+ export type AttachmentErrorCode = typeof ATTACHMENT_ERROR_CODES[number]
34
+
35
+ /** Runtime membership for structurally compatible errors crossing package boundaries. */
36
+ const IMAGE_ADMISSION_ERROR_CODE_SET: ReadonlySet<string> = new Set(IMAGE_ADMISSION_ERROR_CODES)
37
+ const ATTACHMENT_ERROR_CODE_SET: ReadonlySet<string> = new Set(ATTACHMENT_ERROR_CODES)
38
+
39
+ /**
40
+ * Stable failures suitable for host RPC error mapping. Extends {@link HarnessError}, so a tool
41
+ * result that fails with it records `name` `AttachmentError` and its `code`. Consumers that may
42
+ * receive an error from a duplicate package installation identify it with {@link isAttachmentError},
43
+ * which matches the code instead of the prototype chain.
44
+ */
45
+ export class AttachmentError extends HarnessError {
46
+ /** Stable machine-routing failure code. */
47
+ override readonly code: AttachmentErrorCode
48
+
49
+ /**
50
+ * @param message - human-readable failure description without raw bytes or host paths.
51
+ * @param code - stable machine-routing code.
52
+ * @param options - optional chained cause.
53
+ */
54
+ constructor(message: string, code: AttachmentErrorCode, options?: ErrorOptions) {
55
+ super(message, code, options)
56
+ this.name = 'AttachmentError'
57
+ this.code = code
58
+ }
59
+ }
60
+
61
+ /**
62
+ * Identify attachment failures by their stable code across duplicate package installations.
63
+ * @param error - failure raised while validating, persisting, or reading an attachment.
64
+ * @returns whether the failure carries a recognized attachment error code.
65
+ */
66
+ export function isAttachmentError(error: unknown): error is AttachmentError {
67
+ return error instanceof Error
68
+ && 'code' in error
69
+ && typeof error.code === 'string'
70
+ && ATTACHMENT_ERROR_CODE_SET.has(error.code)
71
+ }
72
+
73
+ /**
74
+ * Distinguish caller-correctable image admission failures from storage faults.
75
+ * @param error - failure raised while validating or persisting an image batch.
76
+ * @returns whether the caller can correct the proposed image content or batch.
77
+ */
78
+ export function isImageAdmissionError(
79
+ error: unknown,
80
+ ): error is AttachmentError & { readonly code: ImageAdmissionErrorCode } {
81
+ return error instanceof Error
82
+ && 'code' in error
83
+ && typeof error.code === 'string'
84
+ && IMAGE_ADMISSION_ERROR_CODE_SET.has(error.code)
85
+ }
package/src/index.ts ADDED
@@ -0,0 +1,293 @@
1
+ /** Durable attachment storage seam (`ctx.attachments`). @module @open33/harness-attachment */
2
+
3
+ import { Buffer } from 'node:buffer'
4
+ import { Context, Service } from '@open33/cordis'
5
+ import { admitEncodedFile as admitFileInput, admitEncodedImages } from './admission.ts'
6
+ import { AttachmentError, isAttachmentError as matchesAttachmentError } from './error.ts'
7
+ import type {
8
+ AdmittedPromptContentPart,
9
+ AttachmentAdmissionPart,
10
+ EncodedFileAttachment,
11
+ FileAttachmentRef,
12
+ ImageAttachmentLimits,
13
+ ImageAttachmentRef,
14
+ ImageRequestTarget,
15
+ PromptContentPart,
16
+ RequestImageAttachment,
17
+ SaveFileAttachment,
18
+ SaveFileStreamAttachment,
19
+ SaveImageAttachment,
20
+ StoredImageAttachment,
21
+ } from './types.ts'
22
+
23
+ export { AttachmentId, ImageVariantId } from './brand.ts'
24
+ export { AttachmentError, isAttachmentError, isImageAdmissionError } from './error.ts'
25
+ export type { AttachmentErrorCode, ImageAdmissionErrorCode } from './error.ts'
26
+ export { admitEncodedFile, admitEncodedImages } from './admission.ts'
27
+ export { longEdgeDimensions, requestImageDimensions } from './request-projection.ts'
28
+ export type { ProjectedDimensions } from './request-projection.ts'
29
+ export type {
30
+ AttachmentId as AttachmentIdType,
31
+ AdmittedPromptContentPart,
32
+ AttachmentAdmissionPart,
33
+ EncodedFileAttachment,
34
+ EncodedImageAttachment,
35
+ FileAttachmentRef,
36
+ ImageAttachmentLimits,
37
+ ImageAttachmentRef,
38
+ ImageRequestTarget,
39
+ ImageMediaType,
40
+ PromptContentPart,
41
+ RequestImageAttachment,
42
+ SaveFileAttachment,
43
+ SaveFileStreamAttachment,
44
+ SaveImageAttachment,
45
+ StoredImageAttachment,
46
+ } from './types.ts'
47
+
48
+ declare module '@open33/cordis' {
49
+ interface Context {
50
+ attachments: AttachmentStore
51
+ }
52
+ }
53
+
54
+ /** Whether one admission part still carries encoded image bytes. */
55
+ function isEncodedImage(part: AttachmentAdmissionPart): part is Extract<PromptContentPart, { readonly type: 'image' }> {
56
+ return part.type === 'image' && !('attachment' in part)
57
+ }
58
+
59
+ /** Whether one admission part references an image an earlier upload stored. */
60
+ function isStoredImage(
61
+ part: AttachmentAdmissionPart,
62
+ ): part is Extract<AttachmentAdmissionPart, { readonly type: 'image'; readonly encodedBytes: number }> {
63
+ return part.type === 'image' && 'attachment' in part
64
+ }
65
+
66
+ /** Refuse one message whose images exceed the configured count or aggregate byte limit. */
67
+ function assertMessageImages(limits: ImageAttachmentLimits, count: number, bytes: number): void {
68
+ if (count > limits.maxImagesPerMessage) {
69
+ throw new AttachmentError('Image batch exceeds the configured image-count limit.', 'TOO_MANY_IMAGES')
70
+ }
71
+ if (bytes > limits.maxMessageImageBytes) {
72
+ throw new AttachmentError('Image batch exceeds the configured aggregate image-byte limit.', 'IMAGES_TOO_LARGE')
73
+ }
74
+ }
75
+
76
+ /** Immutable binary attachment service. Implementations validate bytes before publishing a reference. */
77
+ export abstract class AttachmentStore extends Service {
78
+ constructor(ctx: Context) {
79
+ super(ctx, 'attachments')
80
+ }
81
+
82
+ /** Deployment-resolved image policy used by authoritative and fast-path validation. */
83
+ abstract readonly imageLimits: ImageAttachmentLimits
84
+
85
+ /**
86
+ * Validate one image without persisting it.
87
+ * Batch callers validate every member before saving any member.
88
+ * @param input - encoded bytes, declared media type, and optional display name.
89
+ * @returns completion after the encoded raster has been fully decoded.
90
+ */
91
+ abstract validateImage(input: SaveImageAttachment): Promise<void>
92
+
93
+ /**
94
+ * Validate one ordered image batch before committing any member.
95
+ * Validation failures start no writes; storage failures return no partial
96
+ * references, although already published content-addressed objects may stay
97
+ * unreachable until a future retention policy collects them.
98
+ * @param inputs - encoded images in their owning message order.
99
+ * @returns durable references in the exact input order.
100
+ */
101
+ protected validateImageBatch(inputs: readonly SaveImageAttachment[]): void {
102
+ const limits = this.imageLimits
103
+ assertMessageImages(limits, inputs.length, inputs.reduce((sum, input) => sum + input.data.byteLength, 0))
104
+ for (const input of inputs) {
105
+ if (!limits.mediaTypes.includes(input.mediaType)) {
106
+ throw new AttachmentError(`Image type ${input.mediaType} is not accepted by this deployment.`, 'UNSUPPORTED_IMAGE_TYPE')
107
+ }
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Validate and durably commit one ordered image batch.
113
+ * @param inputs - encoded images in owning-message order.
114
+ * @returns durable normalized attachment references in the same order after every member succeeds.
115
+ */
116
+ async saveImages(inputs: readonly SaveImageAttachment[]): Promise<readonly ImageAttachmentRef[]> {
117
+ this.validateImageBatch(inputs)
118
+ for (const input of inputs) await this.validateImage(input)
119
+
120
+ const refs: ImageAttachmentRef[] = []
121
+ for (const input of inputs) refs.push(await this.saveImage(input))
122
+ return refs
123
+ }
124
+
125
+ /**
126
+ * Admit one Host prompt and replace each encoded image with its durable reference.
127
+ * Text, durable file references, and already stored images pass through unchanged.
128
+ * Every image part counts toward `maxImagesPerMessage` and `maxMessageImageBytes`;
129
+ * a stored image counts the bytes of the upload that stored it. Refused content
130
+ * starts no writes. A prompt without encoded images performs no storage operation.
131
+ * @param content - prompt parts in message order after upload receipt resolution.
132
+ * @returns admitted prompt parts in the same order as `content`.
133
+ * @throws AttachmentError when the image batch is refused.
134
+ */
135
+ async admitPromptContent(
136
+ content: readonly AttachmentAdmissionPart[],
137
+ ): Promise<AdmittedPromptContentPart[]> {
138
+ const encoded = content.filter(isEncodedImage)
139
+ const stored = content.filter(isStoredImage)
140
+ // Each upload passed the limits alone; the encoded batch below checks only itself.
141
+ if (stored.length > 0) {
142
+ assertMessageImages(
143
+ this.imageLimits,
144
+ encoded.length + stored.length,
145
+ encoded.reduce((sum, part) => sum + Buffer.byteLength(part.data, 'base64'), 0)
146
+ + stored.reduce((sum, part) => sum + part.encodedBytes, 0),
147
+ )
148
+ }
149
+ const refs = encoded.length === 0 ? [] : await admitEncodedImages(this, encoded)
150
+ let next = 0
151
+ return content.map((part) => {
152
+ if (part.type === 'text') return { type: 'text', text: part.text }
153
+ if (part.type === 'file') return { type: 'file', attachment: part.attachment }
154
+ if ('attachment' in part) return { type: 'image', attachment: part.attachment }
155
+ return { type: 'image', attachment: refs[next++] as ImageAttachmentRef }
156
+ })
157
+ }
158
+
159
+ /**
160
+ * Decode and durably commit one canonical base64 file upload.
161
+ * @param input - canonical base64 bytes and optional display name.
162
+ * @returns the durable content-addressed file reference.
163
+ * @throws AttachmentError when the encoding or storage operation is refused.
164
+ */
165
+ admitEncodedFile(input: EncodedFileAttachment): Promise<FileAttachmentRef> {
166
+ return admitFileInput(this, input)
167
+ }
168
+
169
+ /**
170
+ * Identify a failure emitted by this attachment capability by its stable code.
171
+ * @param error - value caught from an attachment operation.
172
+ * @returns whether the value is an attachment failure.
173
+ */
174
+ isAttachmentError(error: unknown): error is AttachmentError {
175
+ return matchesAttachmentError(error)
176
+ }
177
+
178
+ /**
179
+ * Validate and durably commit one image before its owning session event is appended.
180
+ * The returned reference describes the persisted normalized image. When
181
+ * normalization reduces the raster, its `originalDimensions` records the
182
+ * orientation-applied input dimensions.
183
+ * @param input - encoded bytes, declared media type, and optional display name.
184
+ * @returns the durable content-addressed normalized image reference.
185
+ */
186
+ abstract saveImage(input: SaveImageAttachment): Promise<ImageAttachmentRef>
187
+
188
+ /**
189
+ * Read one image and verify its ID, format, byte length, and dimensions against the supplied reference.
190
+ * @param ref - supplied image reference; name and originalDimensions are preserved without file verification.
191
+ * @param signal - optional cancellation for backend read and verification work.
192
+ * @returns the verified bytes and normalized attachment reference.
193
+ * @throws the signal reason when aborted, or a storage error when verification fails.
194
+ */
195
+ abstract readImage(ref: ImageAttachmentRef, signal?: AbortSignal): Promise<StoredImageAttachment>
196
+
197
+ /**
198
+ * Locate the provider-owned normalized object in the harness host filesystem.
199
+ * @param ref - durable normalized attachment reference.
200
+ * @returns an absolute host path, or undefined when this backend is not host-file-backed.
201
+ * @throws an AttachmentError when the durable reference is invalid.
202
+ */
203
+ imageHostPath(ref: ImageAttachmentRef): string | undefined {
204
+ void ref
205
+ return undefined
206
+ }
207
+
208
+ /**
209
+ * Durably commit one file byte-for-byte before its owning session event is
210
+ * appended. Files carry no admission limits: any byte content and length is
211
+ * accepted, and the stored object is the exact submitted bytes. Backends
212
+ * without verbatim file storage keep this default rejection.
213
+ * @param input - exact bytes and optional display name.
214
+ * @returns the durable content-addressed file reference.
215
+ */
216
+ saveFile(input: SaveFileAttachment): Promise<FileAttachmentRef> {
217
+ void input
218
+ return Promise.reject(new AttachmentError(
219
+ 'The mounted attachment provider cannot store verbatim files.',
220
+ 'ATTACHMENT_FILES_UNSUPPORTED',
221
+ ))
222
+ }
223
+
224
+ /**
225
+ * Durably commit one file byte-for-byte from bounded chunks. Providers must
226
+ * apply backpressure and must not collect the complete file in memory.
227
+ * Backends without streamed verbatim storage keep this default rejection.
228
+ * @param input - ordered exact bytes, optional cancellation, and display name.
229
+ * @returns the durable content-addressed file reference.
230
+ */
231
+ saveFileStream(input: SaveFileStreamAttachment): Promise<FileAttachmentRef> {
232
+ void input
233
+ return Promise.reject(new AttachmentError(
234
+ 'The mounted attachment provider cannot stream verbatim files.',
235
+ 'ATTACHMENT_FILES_UNSUPPORTED',
236
+ ))
237
+ }
238
+
239
+ /**
240
+ * Read and verify one verbatim stored file as bounded chunks. Providers must
241
+ * not collect the complete file in memory. Backends without verbatim file
242
+ * reads keep this default rejection.
243
+ * @param ref - durable file reference from the session log.
244
+ * @param signal - optional cancellation for backend reads and verification work.
245
+ * @returns exact file bytes in order; integrity failures reject the iteration.
246
+ */
247
+ async *readFileStream(
248
+ ref: FileAttachmentRef,
249
+ signal?: AbortSignal,
250
+ ): AsyncIterable<Uint8Array> {
251
+ signal?.throwIfAborted()
252
+ void ref
253
+ await Promise.reject(new AttachmentError(
254
+ 'The mounted attachment provider cannot read verbatim files.',
255
+ 'ATTACHMENT_FILES_UNSUPPORTED',
256
+ ))
257
+ }
258
+
259
+ /**
260
+ * Locate the verbatim stored file object in the harness host filesystem.
261
+ * @param ref - durable file reference.
262
+ * @returns an absolute host path, or undefined when this backend is not host-file-backed.
263
+ * @throws an AttachmentError when the durable reference is invalid.
264
+ */
265
+ fileHostPath(ref: FileAttachmentRef): string | undefined {
266
+ void ref
267
+ return undefined
268
+ }
269
+
270
+ /**
271
+ * Generate or read one deterministic model-request version from the stored normalized image.
272
+ * @param ref - durable provider-independent normalized attachment reference.
273
+ * @param target - route-chosen dimensions and byte target; an unmet byte target yields the smallest ladder output.
274
+ * @param signal - optional cancellation.
275
+ * @returns request bytes and the cache/upload identity covering every transform input.
276
+ */
277
+ readImageRequest(
278
+ ref: ImageAttachmentRef,
279
+ target: ImageRequestTarget,
280
+ signal?: AbortSignal,
281
+ ): Promise<RequestImageAttachment> {
282
+ signal?.throwIfAborted()
283
+ void ref
284
+ void target
285
+ return Promise.reject(new AttachmentError(
286
+ 'The mounted attachment provider cannot derive model-request images.',
287
+ 'ATTACHMENT_PROJECTION_UNSUPPORTED',
288
+ ))
289
+ }
290
+
291
+ }
292
+
293
+ export default AttachmentStore
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Pure request-projection geometry shared by model routes and provider-side
3
+ * request pricing. @module @open33/harness-attachment/request-projection
4
+ */
5
+
6
+ /** Integer width and height of one projected image. */
7
+ export interface ProjectedDimensions {
8
+ width: number
9
+ height: number
10
+ }
11
+
12
+ /**
13
+ * Compute aspect-preserving integer dimensions within a hard total-pixel budget.
14
+ * @param width - positive source width.
15
+ * @param height - positive source height.
16
+ * @param maxPixels - positive width-times-height cap.
17
+ * @returns inward-rounded dimensions; small images are not enlarged.
18
+ */
19
+ export function requestImageDimensions(
20
+ width: number,
21
+ height: number,
22
+ maxPixels: number,
23
+ ): ProjectedDimensions {
24
+ const scale = Math.min(1, Math.sqrt(maxPixels / (width * height)))
25
+ if (scale === 1) return { width, height }
26
+ if (width >= height) {
27
+ let projectedWidth = Math.max(1, Math.floor(width * scale))
28
+ let projectedHeight = Math.max(1, Math.round(projectedWidth * height / width))
29
+ while (projectedWidth * projectedHeight > maxPixels && projectedWidth > 1) {
30
+ projectedWidth -= 1
31
+ projectedHeight = Math.max(1, Math.round(projectedWidth * height / width))
32
+ }
33
+ return { width: projectedWidth, height: projectedHeight }
34
+ }
35
+ let projectedHeight = Math.max(1, Math.floor(height * scale))
36
+ let projectedWidth = Math.max(1, Math.round(projectedHeight * width / height))
37
+ while (projectedWidth * projectedHeight > maxPixels && projectedHeight > 1) {
38
+ projectedHeight -= 1
39
+ projectedWidth = Math.max(1, Math.round(projectedHeight * width / height))
40
+ }
41
+ return { width: projectedWidth, height: projectedHeight }
42
+ }
43
+
44
+ /**
45
+ * Compute aspect-preserving integer dimensions with an exact long edge; the
46
+ * short edge rounds to the nearest pixel, as an encoder resize by the
47
+ * long edge alone.
48
+ * @param width - positive source width.
49
+ * @param height - positive source height.
50
+ * @param longEdge - positive target for the longer source edge.
51
+ * @returns the target dimensions; a long edge at or above the source returns the source unchanged.
52
+ */
53
+ export function longEdgeDimensions(
54
+ width: number,
55
+ height: number,
56
+ longEdge: number,
57
+ ): ProjectedDimensions {
58
+ if (longEdge >= Math.max(width, height)) return { width, height }
59
+ return width >= height
60
+ ? { width: longEdge, height: Math.max(1, Math.round(longEdge * height / width)) }
61
+ : { width: Math.max(1, Math.round(longEdge * width / height)), height: longEdge }
62
+ }