@capacms/sdk 1.0.0-next.10 → 1.0.0-next.11

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.
@@ -5,6 +5,8 @@ exports.isCapaImageUrl = isCapaImageUrl;
5
5
  exports.imageUrl = imageUrl;
6
6
  exports.srcSet = srcSet;
7
7
  exports.sizes = sizes;
8
+ exports.imagePlaceholder = imagePlaceholder;
9
+ exports.placeholderColor = placeholderColor;
8
10
  /**
9
11
  * `@capacms/sdk/image`: URLs for Capa's image CDN, for any framework.
10
12
  *
@@ -16,12 +18,17 @@ exports.sizes = sizes;
16
18
  * from the rules the API serves by (`canonicalQuery` and `parseImageParams`,
17
19
  * compiled in from @capa/shared at build time), so the two cannot drift.
18
20
  *
19
- * Three rules beside the API's:
21
+ * Four rules beside the API's:
20
22
  * - Nothing is enlarged. When the image's own width is known (the `/api/`
21
23
  * media shape carries it), a request for more pixels than it has is brought
22
24
  * down to its size, keeping the requested shape.
23
25
  * - `format=auto` is only sent when asked for.
24
26
  * - A URL that is not a Capa image comes back unchanged.
27
+ * - A crop to a shape (`fit: "cover"` with a width and a height) of a media
28
+ * value that carries an editor's focal point or crop names them in the URL
29
+ * (`fp`, `rect`), so moving the focal point gives a new URL rather than a
30
+ * copy cached under the old one. A media value without them, and a URL or
31
+ * a key without `fp` or `rect`, builds exactly the URL it always did.
25
32
  *
26
33
  * A stored URL on `api.capacms.com/files/` (older uploads) names the same file
27
34
  * as the CDN: the CDN fetches from that host. Built URLs go to the CDN host,
@@ -70,20 +77,31 @@ function positive(value) {
70
77
  function hasScheme(text) {
71
78
  return /^[a-z][a-z0-9+.-]*:/i.test(text);
72
79
  }
80
+ /** What a media value says about itself: its size, and an editor's focal point and crop when they are well formed. */
81
+ function known(image) {
82
+ const out = { intrinsicWidth: positive(image?.width), intrinsicHeight: positive(image?.height) };
83
+ const focalPoint = image ? (0, shared_params_generated_js_1.readFocalPoint)(image.focalPoint) : null;
84
+ const crop = image ? (0, shared_params_generated_js_1.readCrop)(image.crop) : null;
85
+ if (focalPoint)
86
+ out.focalPoint = focalPoint;
87
+ if (crop)
88
+ out.crop = crop;
89
+ return out;
90
+ }
73
91
  /** A string or `url` as a Capa image, or why not. */
74
92
  function resolveUrl(text, image) {
75
93
  if (hasScheme(text)) {
76
94
  const url = capaFileUrl(text);
77
95
  if (url === null)
78
96
  return { unchanged: text };
79
- return { target: { url, intrinsicWidth: positive(image?.width), intrinsicHeight: positive(image?.height) } };
97
+ return { target: { url, ...known(image) } };
80
98
  }
81
99
  // A path (`/logo.png`, `//host/x`) is the site's own or another host's.
82
100
  if (text === "" || text.startsWith("/"))
83
101
  return { unchanged: text };
84
102
  // A file key, which may hold folders: each segment is encoded on its own.
85
103
  const path = text.split("/").map(encodeURIComponent).join("/");
86
- return { target: { url: new URL(`${exports.CAPA_CDN_ORIGIN}${FILES_PATH}${path}`), intrinsicWidth: positive(image?.width), intrinsicHeight: positive(image?.height) } };
104
+ return { target: { url: new URL(`${exports.CAPA_CDN_ORIGIN}${FILES_PATH}${path}`), ...known(image) } };
87
105
  }
88
106
  function resolve(image) {
89
107
  if (image === null || image === undefined)
@@ -169,10 +187,65 @@ function build(fn, target, options) {
169
187
  const parsed = (0, shared_params_generated_js_1.parseImageParams)(query);
170
188
  if (!parsed.ok)
171
189
  fail(fn, parsed.rejection.error);
172
- const canonical = (0, shared_params_generated_js_1.canonicalQuery)(search, parsed.params);
190
+ const focal = focalParams(fn, target, options, parsed.params, search);
191
+ // With no focal point or crop to name, the URL is spelled as it always was:
192
+ // an `fp` or `rect` already in it is an unknown key, kept as it is.
193
+ const canonical = focal === null ? (0, shared_params_generated_js_1.canonicalQuery)(search, parsed.params) : (0, shared_params_generated_js_1.canonicalQuery)(search, focal, { focal: true });
173
194
  const href = `${url.origin}${url.pathname}${canonical ? `?${canonical}` : ""}${url.hash}`;
174
195
  return { href, width: parsed.params.width };
175
196
  }
197
+ /**
198
+ * The parameters with the focal point and crop this URL names, or null when
199
+ * it names none of its own making.
200
+ *
201
+ * Capa's CDN crops a request to a shape (`fit=cover` with a width and a
202
+ * height) around the focal point and inside the crop an editor set on the
203
+ * file, whether the URL names them or not. Named in the URL, a moved focal
204
+ * point is a new URL, so no browser or edge keeps the old crop under it. A
205
+ * crop given as an option applies to any resize, as the CDN applies a `rect`
206
+ * it is sent. Options win over the media value, which wins over an `fp` or
207
+ * `rect` the URL already had. With none of them, null: the URL is spelled as
208
+ * it always was.
209
+ */
210
+ function focalParams(fn, target, options, params, search) {
211
+ let askedFocal;
212
+ if (options.focalPoint !== undefined && options.focalPoint !== null) {
213
+ const read = (0, shared_params_generated_js_1.readFocalPoint)(options.focalPoint);
214
+ if (read === null)
215
+ fail(fn, "`focalPoint` must be { x, y }, numbers from 0 to 1");
216
+ askedFocal = read;
217
+ }
218
+ let askedCrop;
219
+ if (options.crop !== undefined && options.crop !== null) {
220
+ const read = (0, shared_params_generated_js_1.readCrop)(options.crop);
221
+ if (read === null)
222
+ fail(fn, "`crop` must be { x, y, width, height }, numbers from 0 to 1 with a width and a height above 0, inside the image");
223
+ askedCrop = read;
224
+ }
225
+ const cover = params.fit === "cover" && params.width !== undefined && params.height !== undefined && params.blur === undefined;
226
+ const focalPoint = cover ? askedFocal ?? target.focalPoint : undefined;
227
+ const rect = askedCrop ?? (cover ? target.crop : undefined);
228
+ // What the URL already said (a URL this function built, handed back to it,
229
+ // as next/image hands its loader a `src`), kept where nothing here replaces
230
+ // it, and spelled as the CDN spells it. One the CDN would refuse stays an
231
+ // unknown key, as it is, unless something here replaces it.
232
+ const own = {};
233
+ for (const [key, value] of new URLSearchParams(search))
234
+ if (shared_params_generated_js_1.FOCAL_PARAMS.has(key) && !(key in own))
235
+ own[key] = value;
236
+ const ownFocal = (0, shared_params_generated_js_1.parseFocalParams)(own);
237
+ const kept = ownFocal.ok ? ownFocal : {};
238
+ const fp = focalPoint ?? kept.focalPoint;
239
+ const r = rect ?? kept.rect;
240
+ if (fp === undefined && r === undefined)
241
+ return null;
242
+ const out = { ...params };
243
+ if (fp !== undefined)
244
+ out.focalPoint = fp;
245
+ if (r !== undefined)
246
+ out.rect = r;
247
+ return out;
248
+ }
176
249
  function imageUrl(image, options = {}) {
177
250
  const resolved = resolve(image);
178
251
  if (resolved === null)
@@ -223,6 +296,8 @@ function srcSet(image, widths, options = {}) {
223
296
  fit: options.fit,
224
297
  quality: options.quality,
225
298
  format: options.format,
299
+ focalPoint: options.focalPoint,
300
+ crop: options.crop,
226
301
  });
227
302
  if (seen.has(href))
228
303
  continue;
@@ -255,3 +330,33 @@ function sizes(breakpoints, fallback = "100vw") {
255
330
  rules.sort(([a], [b]) => b - a);
256
331
  return [...rules.map(([px, size]) => `(min-width: ${px}px) ${size}`), fallback.trim()].join(", ");
257
332
  }
333
+ const BLUR_DATA_URL = /^data:image\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/]+={0,2}$/i;
334
+ const HEX_COLOUR = /^#[0-9a-f]{6}$/i;
335
+ /**
336
+ * next/image's placeholder props for a media value: `placeholder="blur"` with
337
+ * its `blurDataURL` when it has one, and `placeholder="empty"` otherwise, so
338
+ * the result can always be spread:
339
+ *
340
+ * ```tsx
341
+ * <Image src={imageUrl(hero)} alt={hero.alt ?? ""} width={1200} height={800} {...imagePlaceholder(hero)} />
342
+ * ```
343
+ */
344
+ function imagePlaceholder(image) {
345
+ const blur = image?.blurDataURL;
346
+ return typeof blur === "string" && BLUR_DATA_URL.test(blur) ? { placeholder: "blur", blurDataURL: blur } : { placeholder: "empty" };
347
+ }
348
+ /**
349
+ * A colour to paint an image's space with while it loads, as `#rrggbb`: its
350
+ * average colour, else its dominant one, else undefined.
351
+ *
352
+ * ```tsx
353
+ * <div style={{ backgroundColor: placeholderColor(hero) }}>...</div>
354
+ * ```
355
+ */
356
+ function placeholderColor(image) {
357
+ for (const colour of [image?.averageColor, image?.dominantColor]) {
358
+ if (typeof colour === "string" && HEX_COLOUR.test(colour))
359
+ return colour.toLowerCase();
360
+ }
361
+ return undefined;
362
+ }
@@ -113,6 +113,13 @@ export interface ImageParams {
113
113
  dpr: number;
114
114
  upscale: boolean;
115
115
  keepMetadata: boolean;
116
+ /**
117
+ * `fp` and `rect` (ENG-5959), read by `parseFocalParams` and only for a
118
+ * project with the focal point and crop on; absent otherwise, and then the
119
+ * two are unknown keys like any other.
120
+ */
121
+ focalPoint?: FocalPoint;
122
+ rect?: CropRect;
116
123
  /** True when any parameter that changes the bytes was supplied. */
117
124
  wantsTransform: boolean;
118
125
  }
@@ -154,7 +161,16 @@ export interface CanonicalResult {
154
161
  *
155
162
  * @param rawQuery the query string as received, without the leading `?`
156
163
  */
157
- export declare function canonicalise(rawQuery: string, params: ImageParams): CanonicalResult;
164
+ export declare function canonicalise(rawQuery: string, params: ImageParams, options?: CanonicalOptions): CanonicalResult;
165
+ export interface CanonicalOptions {
166
+ /**
167
+ * True when `fp` and `rect` are parameters here (the project has the focal
168
+ * point and crop on): they are then spelled from `params` like the others,
169
+ * and their presence enables canonicalisation. False or absent, they are
170
+ * unknown keys, kept verbatim, exactly as before ENG-5959.
171
+ */
172
+ focal?: boolean;
173
+ }
158
174
  /**
159
175
  * The canonical spelling itself, without `canonicalise`'s gate.
160
176
  *
@@ -168,7 +184,7 @@ export declare function canonicalise(rawQuery: string, params: ImageParams): Can
168
184
  * @param rawQuery the query string, without the leading `?`; read only for the
169
185
  * keys this module does not know, which are kept
170
186
  */
171
- export declare function canonicalQuery(rawQuery: string, params: ImageParams): string;
187
+ export declare function canonicalQuery(rawQuery: string, params: ImageParams, options?: CanonicalOptions): string;
172
188
  /**
173
189
  * A stable string identifying the transform, for the ETag.
174
190
  *
@@ -188,3 +204,111 @@ export declare function buildSignature(params: ImageParams, resolvedFormat?: Con
188
204
  * preference, so an entry carrying it is skipped rather than matched.
189
205
  */
190
206
  export declare function resolveAutoFormat(accept: string | undefined | null): "avif" | "webp" | null;
207
+ /** A focal point: fractions of the oriented image, from the left and the top. */
208
+ export interface FocalPoint {
209
+ x: number;
210
+ y: number;
211
+ }
212
+ /** A crop: fractions of the oriented image. */
213
+ export interface CropRect {
214
+ x: number;
215
+ y: number;
216
+ width: number;
217
+ height: number;
218
+ }
219
+ /** `fp` and `rect`: parameters only where the focal point and crop are on. */
220
+ export declare const FOCAL_PARAMS: Set<string>;
221
+ /** Decimal places a fraction keeps: a ten-thousandth, under a pixel up to 10,000 px. */
222
+ export declare const FRACTION_DECIMALS = 4;
223
+ /** A number rounded to FRACTION_DECIMALS. */
224
+ export declare function roundFraction(n: number): number;
225
+ /**
226
+ * A focal point from stored metadata or a request body, or null when it is
227
+ * not one: an object whose `x` and `y` are numbers from 0 to 1.
228
+ */
229
+ export declare function readFocalPoint(value: unknown): FocalPoint | null;
230
+ /**
231
+ * A crop from stored metadata or a request body, or null when it is not one:
232
+ * `x`, `y`, `width` and `height` from 0 to 1, a width and a height above 0,
233
+ * and inside the image.
234
+ */
235
+ export declare function readCrop(value: unknown): CropRect | null;
236
+ /**
237
+ * A focal point exactly as the api stores one (`normaliseFocalPatch` in
238
+ * apps/api routes/v2/file-uploads.ts): `{ x, y }` and no other key, numbers
239
+ * from 0 to 1. Stricter than `readFocalPoint`, which reads one out of any
240
+ * object that has them: this is the test for "ENG-5959 wrote this", which a
241
+ * replace carries over and the legacy routes hide. Anything else under the
242
+ * name is a project's own metadata and is left alone.
243
+ */
244
+ export declare function isStoredFocalPoint(value: unknown): value is FocalPoint;
245
+ /** A crop exactly as the api stores one: `{ x, y, width, height }` and no other key. See `isStoredFocalPoint`. */
246
+ export declare function isStoredCrop(value: unknown): value is CropRect;
247
+ export type FocalParseResult = {
248
+ ok: true;
249
+ focalPoint?: FocalPoint;
250
+ rect?: CropRect;
251
+ } | {
252
+ ok: false;
253
+ rejection: ParamRejection;
254
+ };
255
+ /**
256
+ * `fp` and `rect`, for a project with the focal point and crop on. The route
257
+ * calls it after it knows the file's project; anywhere else the two are
258
+ * unknown keys and this is never called.
259
+ */
260
+ export declare function parseFocalParams(query: Record<string, unknown>): FocalParseResult;
261
+ /** What the file says, from its `file_uploads.metadata`. */
262
+ export interface StoredFocal {
263
+ focalPoint: FocalPoint | null;
264
+ crop: CropRect | null;
265
+ }
266
+ /**
267
+ * The crop and focal point a request applies: the URL's, else the file's,
268
+ * and the file's only for a `fit=cover` crop to both a width and a height.
269
+ * A blur placeholder keeps its own square geometry and applies only a `rect`
270
+ * the URL names.
271
+ */
272
+ /**
273
+ * A crop to a shape: `fit=cover` with a width and a height, and no blur. The
274
+ * one request the file's stored focal point and crop apply to.
275
+ */
276
+ export declare function isCoverCrop(params: ImageParams): boolean;
277
+ /**
278
+ * True when this request's bytes depend on the file's STORED focal point or
279
+ * crop: a cover crop that does not name both `fp` and `rect` itself. Its
280
+ * bytes change under the same URL when an editor saves either, so a browser
281
+ * must not keep them as long as an immutable variant (`GET /files/*`).
282
+ */
283
+ export declare function followsStoredFocal(params: ImageParams): boolean;
284
+ export declare function appliedFocal(params: ImageParams, stored: StoredFocal | null): {
285
+ rect: CropRect | null;
286
+ focalPoint: FocalPoint | null;
287
+ };
288
+ /** A region of the oriented source, in whole pixels, for sharp's `extract`. */
289
+ export interface PixelRegion {
290
+ left: number;
291
+ top: number;
292
+ width: number;
293
+ height: number;
294
+ }
295
+ /**
296
+ * The part of the source to cut out before the resize, or null for none.
297
+ *
298
+ * `source` is the image as a person sees it. `target` is the `fit=cover` box
299
+ * (width and height after dpr), or null for any other request. The crop is cut
300
+ * first; with a target and a focal point, the window of the target's shape
301
+ * that a cover resize would keep is then moved, inside the crop, so its centre
302
+ * is as close to the focal point as the crop allows. Without a focal point the
303
+ * crop alone is returned and the resize centres in it as it always has.
304
+ *
305
+ * The window is the largest of the target's shape that fits the crop, so the
306
+ * resize that follows scales it to the target without cutting anything more.
307
+ */
308
+ export declare function focalRegion(source: {
309
+ width: number;
310
+ height: number;
311
+ }, target: {
312
+ width: number;
313
+ height: number;
314
+ } | null, rect: CropRect | null, focalPoint: FocalPoint | null): PixelRegion | null;
@@ -27,7 +27,7 @@
27
27
  * run what it builds back through `canonicalise`. The API imports it from here.
28
28
  */
29
29
  Object.defineProperty(exports, "__esModule", { value: true });
30
- exports.NEW_PARAMS = exports.LEGACY_PARAMS = exports.AVIF_DEFAULT_QUALITY = exports.DEFAULT_QUALITY = exports.MAX_BLUR = exports.MIN_BLUR = exports.MAX_OUTPUT_EDGE = exports.OUTPUT_MIME = void 0;
30
+ exports.FRACTION_DECIMALS = exports.FOCAL_PARAMS = exports.NEW_PARAMS = exports.LEGACY_PARAMS = exports.AVIF_DEFAULT_QUALITY = exports.DEFAULT_QUALITY = exports.MAX_BLUR = exports.MIN_BLUR = exports.MAX_OUTPUT_EDGE = exports.OUTPUT_MIME = void 0;
31
31
  exports.defaultQuality = defaultQuality;
32
32
  exports.droppableQuality = droppableQuality;
33
33
  exports.parseImageParams = parseImageParams;
@@ -35,6 +35,16 @@ exports.canonicalise = canonicalise;
35
35
  exports.canonicalQuery = canonicalQuery;
36
36
  exports.buildSignature = buildSignature;
37
37
  exports.resolveAutoFormat = resolveAutoFormat;
38
+ exports.roundFraction = roundFraction;
39
+ exports.readFocalPoint = readFocalPoint;
40
+ exports.readCrop = readCrop;
41
+ exports.isStoredFocalPoint = isStoredFocalPoint;
42
+ exports.isStoredCrop = isStoredCrop;
43
+ exports.parseFocalParams = parseFocalParams;
44
+ exports.isCoverCrop = isCoverCrop;
45
+ exports.followsStoredFocal = followsStoredFocal;
46
+ exports.appliedFocal = appliedFocal;
47
+ exports.focalRegion = focalRegion;
38
48
  /** Content type emitted for each explicitly requestable output format. */
39
49
  exports.OUTPUT_MIME = {
40
50
  webp: "image/webp",
@@ -322,6 +332,18 @@ function num(n) {
322
332
  function encodePart(text) {
323
333
  return encodeURIComponent(text).replace(/'/g, "%27");
324
334
  }
335
+ /**
336
+ * `fp` and `rect` are comma lists, spelled with bare commas: a browser sends a
337
+ * query's `,` as it is, so `fp=0.25,0.5` comes back byte for byte, and reads
338
+ * better than `fp=0.25%2C0.5`. Only where they are parameters; an unknown key
339
+ * keeps `encodePart`'s spelling, as before.
340
+ */
341
+ function listValue(key, options) {
342
+ return options.focal === true && exports.FOCAL_PARAMS.has(key);
343
+ }
344
+ function encodeList(value) {
345
+ return value.split(",").map(encodePart).join(",");
346
+ }
325
347
  /**
326
348
  * The canonical spelling of a query, so `?width=200&format=webp` and
327
349
  * `?format=webp&width=200` are one edge object rather than two.
@@ -334,12 +356,12 @@ function encodePart(text) {
334
356
  *
335
357
  * @param rawQuery the query string as received, without the leading `?`
336
358
  */
337
- function canonicalise(rawQuery, params) {
359
+ function canonicalise(rawQuery, params, options = {}) {
338
360
  const received = new URLSearchParams(rawQuery);
339
- const usesNewParam = [...received.keys()].some((k) => exports.NEW_PARAMS.has(k));
361
+ const usesNewParam = [...received.keys()].some((k) => exports.NEW_PARAMS.has(k) || (options.focal === true && exports.FOCAL_PARAMS.has(k)));
340
362
  if (!usesNewParam)
341
363
  return { query: rawQuery, isCanonical: true };
342
- const query = canonicalQuery(rawQuery, params);
364
+ const query = canonicalQuery(rawQuery, params, options);
343
365
  return { query, isCanonical: query === rawQuery };
344
366
  }
345
367
  /**
@@ -355,7 +377,7 @@ function canonicalise(rawQuery, params) {
355
377
  * @param rawQuery the query string, without the leading `?`; read only for the
356
378
  * keys this module does not know, which are kept
357
379
  */
358
- function canonicalQuery(rawQuery, params) {
380
+ function canonicalQuery(rawQuery, params, options = {}) {
359
381
  const received = new URLSearchParams(rawQuery);
360
382
  const keys = [...new Set([...received.keys()])];
361
383
  const out = new Map();
@@ -387,6 +409,12 @@ function canonicalQuery(rawQuery, params) {
387
409
  out.set("upscale", "1");
388
410
  if (params.keepMetadata)
389
411
  out.set("keepMetadata", "1");
412
+ if (options.focal === true) {
413
+ if (params.focalPoint !== undefined)
414
+ out.set("fp", fractions([params.focalPoint.x, params.focalPoint.y]));
415
+ if (params.rect !== undefined)
416
+ out.set("rect", fractions([params.rect.x, params.rect.y, params.rect.width, params.rect.height]));
417
+ }
390
418
  // Unknown keys are preserved verbatim (first value wins, repeats collapse),
391
419
  // so a cache-buster survives the redirect instead of being silently dropped.
392
420
  //
@@ -396,6 +424,8 @@ function canonicalQuery(rawQuery, params) {
396
424
  for (const key of keys) {
397
425
  if (exports.LEGACY_PARAMS.has(key) || exports.NEW_PARAMS.has(key))
398
426
  continue;
427
+ if (options.focal === true && exports.FOCAL_PARAMS.has(key))
428
+ continue;
399
429
  const value = received.get(key) ?? "";
400
430
  if (key === "" && value === "")
401
431
  continue;
@@ -403,7 +433,7 @@ function canonicalQuery(rawQuery, params) {
403
433
  }
404
434
  const sorted = [...out.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
405
435
  return sorted
406
- .map(([k, v]) => (v === "" ? encodePart(k) : `${encodePart(k)}=${encodePart(v)}`))
436
+ .map(([k, v]) => (v === "" ? encodePart(k) : `${encodePart(k)}=${listValue(k, options) ? encodeList(v) : encodePart(v)}`))
407
437
  .join("&");
408
438
  }
409
439
  /**
@@ -434,6 +464,16 @@ function buildSignature(params, resolvedFormat) {
434
464
  parts.push(`q${params.quality}`);
435
465
  if (params.keepMetadata)
436
466
  parts.push("meta");
467
+ // The crop and the focal point this transform applies (`appliedFocal`), from
468
+ // the URL or from the file, so a new focal point on the file is a new ETag
469
+ // under the same URL. Colons, not the URL's commas: If-None-Match is a
470
+ // comma-separated list, and an ETag with a comma in it never matches its
471
+ // own revalidation (files.ts ifNoneMatchSatisfied), so every one would be a
472
+ // full 200.
473
+ if (params.rect !== undefined)
474
+ parts.push(`r${fractions([params.rect.x, params.rect.y, params.rect.width, params.rect.height], ":")}`);
475
+ if (params.focalPoint !== undefined)
476
+ parts.push(`p${fractions([params.focalPoint.x, params.focalPoint.y], ":")}`);
437
477
  return parts.join("_") || "raw";
438
478
  }
439
479
  /**
@@ -469,3 +509,192 @@ function resolveAutoFormat(accept) {
469
509
  return "webp";
470
510
  return null;
471
511
  }
512
+ /** `fp` and `rect`: parameters only where the focal point and crop are on. */
513
+ exports.FOCAL_PARAMS = new Set(["fp", "rect"]);
514
+ /** Decimal places a fraction keeps: a ten-thousandth, under a pixel up to 10,000 px. */
515
+ exports.FRACTION_DECIMALS = 4;
516
+ /** Slack for `x + width <= 1` after rounding to FRACTION_DECIMALS. */
517
+ const FRACTION_EPSILON = 1e-9;
518
+ /** A number rounded to FRACTION_DECIMALS. */
519
+ function roundFraction(n) {
520
+ const scale = 10 ** exports.FRACTION_DECIMALS;
521
+ return Math.round(n * scale) / scale;
522
+ }
523
+ function fraction(value) {
524
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 1)
525
+ return null;
526
+ return roundFraction(value);
527
+ }
528
+ function plainObject(value) {
529
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
530
+ }
531
+ /**
532
+ * A focal point from stored metadata or a request body, or null when it is
533
+ * not one: an object whose `x` and `y` are numbers from 0 to 1.
534
+ */
535
+ function readFocalPoint(value) {
536
+ const v = plainObject(value);
537
+ if (!v)
538
+ return null;
539
+ const x = fraction(v.x);
540
+ const y = fraction(v.y);
541
+ return x === null || y === null ? null : { x, y };
542
+ }
543
+ /**
544
+ * A crop from stored metadata or a request body, or null when it is not one:
545
+ * `x`, `y`, `width` and `height` from 0 to 1, a width and a height above 0,
546
+ * and inside the image.
547
+ */
548
+ function readCrop(value) {
549
+ const v = plainObject(value);
550
+ if (!v)
551
+ return null;
552
+ const x = fraction(v.x);
553
+ const y = fraction(v.y);
554
+ const width = fraction(v.width);
555
+ const height = fraction(v.height);
556
+ if (x === null || y === null || width === null || height === null)
557
+ return null;
558
+ if (width <= 0 || height <= 0)
559
+ return null;
560
+ if (x + width > 1 + FRACTION_EPSILON || y + height > 1 + FRACTION_EPSILON)
561
+ return null;
562
+ return { x, y, width, height };
563
+ }
564
+ /** True when `value` has exactly these own keys, in any order. */
565
+ function hasExactly(value, keys) {
566
+ const own = Object.keys(value);
567
+ return own.length === keys.length && keys.every((key) => own.includes(key));
568
+ }
569
+ /**
570
+ * A focal point exactly as the api stores one (`normaliseFocalPatch` in
571
+ * apps/api routes/v2/file-uploads.ts): `{ x, y }` and no other key, numbers
572
+ * from 0 to 1. Stricter than `readFocalPoint`, which reads one out of any
573
+ * object that has them: this is the test for "ENG-5959 wrote this", which a
574
+ * replace carries over and the legacy routes hide. Anything else under the
575
+ * name is a project's own metadata and is left alone.
576
+ */
577
+ function isStoredFocalPoint(value) {
578
+ const v = plainObject(value);
579
+ return v !== null && hasExactly(v, ["x", "y"]) && readFocalPoint(v) !== null;
580
+ }
581
+ /** A crop exactly as the api stores one: `{ x, y, width, height }` and no other key. See `isStoredFocalPoint`. */
582
+ function isStoredCrop(value) {
583
+ const v = plainObject(value);
584
+ return v !== null && hasExactly(v, ["x", "y", "width", "height"]) && readCrop(v) !== null;
585
+ }
586
+ /** Numbers as the canonical URL spells them: comma separated, no trailing zeros. */
587
+ function fractions(values, separator = ",") {
588
+ return values.map((n) => String(roundFraction(n))).join(separator);
589
+ }
590
+ /** `0.25,0.5` into numbers, or null when any part is not a plain decimal. */
591
+ function decimalList(text, count) {
592
+ const parts = text.split(",");
593
+ if (parts.length !== count)
594
+ return null;
595
+ const out = [];
596
+ for (const part of parts) {
597
+ const n = strictNumber(part);
598
+ if (n === null)
599
+ return null;
600
+ out.push(n);
601
+ }
602
+ return out;
603
+ }
604
+ /**
605
+ * `fp` and `rect`, for a project with the focal point and crop on. The route
606
+ * calls it after it knows the file's project; anywhere else the two are
607
+ * unknown keys and this is never called.
608
+ */
609
+ function parseFocalParams(query) {
610
+ const reject = (error, param) => ({ ok: false, rejection: { error, param } });
611
+ const fpRaw = single(query.fp, "fp");
612
+ if (!fpRaw.ok)
613
+ return { ok: false, rejection: fpRaw.rejection };
614
+ let focalPoint;
615
+ if (fpRaw.value !== undefined) {
616
+ const list = decimalList(fpRaw.value, 2);
617
+ const read = list ? readFocalPoint({ x: list[0], y: list[1] }) : null;
618
+ if (!read)
619
+ return reject("`fp` must be two numbers from 0 to 1, x,y", "fp");
620
+ focalPoint = read;
621
+ }
622
+ const rectRaw = single(query.rect, "rect");
623
+ if (!rectRaw.ok)
624
+ return { ok: false, rejection: rectRaw.rejection };
625
+ let rect;
626
+ if (rectRaw.value !== undefined) {
627
+ const list = decimalList(rectRaw.value, 4);
628
+ const read = list ? readCrop({ x: list[0], y: list[1], width: list[2], height: list[3] }) : null;
629
+ if (!read) {
630
+ return reject("`rect` must be four numbers from 0 to 1, x,y,width,height, with a width and a height above 0, inside the image", "rect");
631
+ }
632
+ rect = read;
633
+ }
634
+ return { ok: true, focalPoint, rect };
635
+ }
636
+ /**
637
+ * The crop and focal point a request applies: the URL's, else the file's,
638
+ * and the file's only for a `fit=cover` crop to both a width and a height.
639
+ * A blur placeholder keeps its own square geometry and applies only a `rect`
640
+ * the URL names.
641
+ */
642
+ /**
643
+ * A crop to a shape: `fit=cover` with a width and a height, and no blur. The
644
+ * one request the file's stored focal point and crop apply to.
645
+ */
646
+ function isCoverCrop(params) {
647
+ return params.fit === "cover" && params.width !== undefined && params.height !== undefined && params.blur === undefined;
648
+ }
649
+ /**
650
+ * True when this request's bytes depend on the file's STORED focal point or
651
+ * crop: a cover crop that does not name both `fp` and `rect` itself. Its
652
+ * bytes change under the same URL when an editor saves either, so a browser
653
+ * must not keep them as long as an immutable variant (`GET /files/*`).
654
+ */
655
+ function followsStoredFocal(params) {
656
+ return isCoverCrop(params) && (params.focalPoint === undefined || params.rect === undefined);
657
+ }
658
+ function appliedFocal(params, stored) {
659
+ const cover = isCoverCrop(params);
660
+ const rect = params.rect ?? (cover ? stored?.crop ?? null : null);
661
+ const focalPoint = cover ? params.focalPoint ?? stored?.focalPoint ?? null : null;
662
+ return { rect, focalPoint };
663
+ }
664
+ /**
665
+ * The part of the source to cut out before the resize, or null for none.
666
+ *
667
+ * `source` is the image as a person sees it. `target` is the `fit=cover` box
668
+ * (width and height after dpr), or null for any other request. The crop is cut
669
+ * first; with a target and a focal point, the window of the target's shape
670
+ * that a cover resize would keep is then moved, inside the crop, so its centre
671
+ * is as close to the focal point as the crop allows. Without a focal point the
672
+ * crop alone is returned and the resize centres in it as it always has.
673
+ *
674
+ * The window is the largest of the target's shape that fits the crop, so the
675
+ * resize that follows scales it to the target without cutting anything more.
676
+ */
677
+ function focalRegion(source, target, rect, focalPoint) {
678
+ const W = Math.max(1, Math.round(source.width));
679
+ const H = Math.max(1, Math.round(source.height));
680
+ let region = { left: 0, top: 0, width: W, height: H };
681
+ if (rect) {
682
+ const left = Math.min(W - 1, Math.round(rect.x * W));
683
+ const top = Math.min(H - 1, Math.round(rect.y * H));
684
+ region = {
685
+ left,
686
+ top,
687
+ width: Math.max(1, Math.min(W - left, Math.round(rect.width * W))),
688
+ height: Math.max(1, Math.min(H - top, Math.round(rect.height * H))),
689
+ };
690
+ }
691
+ if (!target || !focalPoint)
692
+ return rect ? region : null;
693
+ const scale = Math.max(target.width / region.width, target.height / region.height);
694
+ const width = Math.max(1, Math.min(region.width, Math.round(target.width / scale)));
695
+ const height = Math.max(1, Math.min(region.height, Math.round(target.height / scale)));
696
+ const clamp = (value, lo, hi) => Math.min(hi, Math.max(lo, value));
697
+ const left = clamp(Math.round(focalPoint.x * W - width / 2), region.left, region.left + region.width - width);
698
+ const top = clamp(Math.round(focalPoint.y * H - height / 2), region.top, region.top + region.height - height);
699
+ return { left, top, width, height };
700
+ }
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  export { createClient, instanceIdOf } from "./client";
2
- export type { CapaClient, CreateScheduledActionsInput, CreateScheduledActionsResult, LayoutCard, LayoutDisplay, LayoutField, LayoutInline, LayoutWidth, ListOptions, ListScheduledActionsOptions, ModelLayout, ModelLayoutInfo, ModelsResource, Page, ResolvedScheduleTime, ScheduledAction, ScheduledActionsPage, ScheduledActionsResource, ScheduledActionStatus, ScheduledActionTarget, SearchHit, WorkspaceApplyResult, WorkspaceChanges, WorkspaceDocNode, WorkspaceDocument, WorkspaceSummary, WorkspaceTemplate, WorkspaceTreeDocument, WorkspacesResource, } from "./client";
2
+ export type { CapaClient, CreateScheduledActionsInput, CreateScheduledActionsResult, FieldValue, LayoutCard, LayoutDisplay, LayoutField, LayoutInline, LayoutWidth, ListOptions, ListScheduledActionsOptions, ModelLayout, ModelLayoutInfo, ModelsResource, OneWithRelations, Page, ReadOneOptions, RelatedEntry, Relations, ResolvedScheduleTime, ScheduledAction, ScheduledActionsPage, ScheduledActionsResource, ScheduledActionStatus, ScheduledActionTarget, SearchHit, WorkspaceApplyResult, WorkspaceChanges, WorkspaceDocNode, WorkspaceDocument, WorkspaceSummary, WorkspaceTemplate, WorkspaceTreeDocument, WorkspacesResource, } from "./client";
3
3
  export type { CapaConfig } from "./config";
4
4
  export { CapaError } from "./http";
5
5
  export { WEBHOOKS_NEED_ACCESS_TOKEN } from "./webhooks";