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

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.
Files changed (60) hide show
  1. package/CHANGELOG.md +170 -0
  2. package/README.md +368 -5
  3. package/bin/capa-check-bundle.js +80 -0
  4. package/bin/capa.js +3 -3
  5. package/bin/graphql-project.js +1 -1
  6. package/dist/client.d.ts +84 -4
  7. package/dist/client.js +23 -5
  8. package/dist/esm/image/index.d.ts +69 -2
  9. package/dist/esm/image/index.js +108 -5
  10. package/dist/esm/image/shared-params.generated.d.ts +126 -2
  11. package/dist/esm/image/shared-params.generated.js +224 -5
  12. package/dist/esm/overlay/index.d.ts +4 -1
  13. package/dist/esm/overlay/index.js +382 -30
  14. package/dist/esm/overlay/live-fields.d.ts +133 -0
  15. package/dist/esm/overlay/live-fields.js +478 -0
  16. package/dist/esm/overlay/markdown.d.ts +38 -0
  17. package/dist/esm/overlay/markdown.js +536 -0
  18. package/dist/esm/overlay/protocol.d.ts +51 -5
  19. package/dist/esm/overlay/protocol.js +79 -9
  20. package/dist/image/index.d.ts +69 -2
  21. package/dist/image/index.js +109 -4
  22. package/dist/image/shared-params.generated.d.ts +126 -2
  23. package/dist/image/shared-params.generated.js +235 -6
  24. package/dist/index.d.ts +1 -1
  25. package/dist/next/attrs.d.ts +42 -1
  26. package/dist/next/attrs.js +42 -3
  27. package/dist/next/client.d.ts +48 -1
  28. package/dist/next/client.js +33 -2
  29. package/dist/next/entry-fields.d.ts +43 -2
  30. package/dist/next/graphql/request.d.ts +4 -0
  31. package/dist/next/graphql/request.js +4 -0
  32. package/dist/next/graphql/tree.js +9 -0
  33. package/dist/next/index.d.ts +4 -4
  34. package/dist/next/index.js +3 -1
  35. package/dist/nextjs/index.d.ts +91 -7
  36. package/dist/nextjs/index.js +230 -17
  37. package/dist/nextjs/write-key-guard.d.ts +117 -0
  38. package/dist/nextjs/write-key-guard.js +285 -0
  39. package/dist/overlay/index.d.ts +4 -1
  40. package/dist/overlay/index.js +399 -29
  41. package/dist/overlay/live-fields.d.ts +133 -0
  42. package/dist/overlay/live-fields.js +493 -0
  43. package/dist/overlay/markdown.d.ts +38 -0
  44. package/dist/overlay/markdown.js +539 -0
  45. package/dist/overlay/protocol.d.ts +51 -5
  46. package/dist/overlay/protocol.js +82 -9
  47. package/dist/server/browser.d.ts +1 -0
  48. package/dist/server/browser.js +20 -0
  49. package/dist/server/client.d.ts +268 -0
  50. package/dist/server/client.js +335 -0
  51. package/dist/server/errors.d.ts +60 -0
  52. package/dist/server/errors.js +120 -0
  53. package/dist/server/index.d.ts +14 -0
  54. package/dist/server/index.js +32 -0
  55. package/dist/server/key-format.d.ts +41 -0
  56. package/dist/server/key-format.js +91 -0
  57. package/dist/server/transport.d.ts +47 -0
  58. package/dist/server/transport.js +114 -0
  59. package/dist/webhooks.d.ts +8 -0
  60. package/package.json +18 -4
@@ -1,23 +1,33 @@
1
1
  /**
2
2
  * The live preview protocol, site side. Pure: no DOM, no globals, so it can be
3
- * tested under plain `node --test`.
3
+ * tested under plain `node --test`. Its one import, `./live-fields.js`, is
4
+ * pure too.
4
5
  *
5
6
  * The Capa admin frames the site and the two talk over `postMessage`. Every
6
7
  * message is a plain object `{ source, v: 1, type, ...fields }`:
7
8
  *
8
9
  * admin -> site (source "capa-admin")
9
10
  * hello {} sent on the frame's load
10
- * highlight { entryId, field: string | null } entryId "" clears
11
+ * highlight { entryId, field: string | null, item? }
12
+ * entryId "" clears. `item`: one item
13
+ * of a list field (`data-capa-item`)
11
14
  * outline { on: boolean } outline every tagged element
12
15
  * refresh {} re-render the draft
13
16
  * patch { entryId, fields: [{ field, value, saved }] }
14
17
  * unsaved text, as the editor types it
18
+ * fields { entryId, fields: [{ field, kind, value, saved }] }
19
+ * unsaved HTML and Rich Text, images,
20
+ * toggles and dates (`./live-fields.ts`).
21
+ * Sent only to an overlay whose ready
22
+ * lists "fields". A kind it does not
23
+ * know is skipped, the rest kept
15
24
  *
16
25
  * site -> admin (source "capa")
17
26
  * ready { path, entries, features } after hello, and after every navigation.
18
27
  * `features`: what this overlay can do
19
28
  * beyond v1 (`SITE_FEATURES`)
20
- * select { entryId, field } a tagged element was clicked
29
+ * select { entryId, field, item? } a tagged element was clicked. `item`:
30
+ * its `data-capa-item`, when it has one
21
31
  * hover { entryId, field } | { entryId: "", field: null }
22
32
  * visible { entryId, field } the tagged element at the centre of the
23
33
  * viewport changed (throttled, on scroll)
@@ -29,6 +39,15 @@
29
39
  * same kind of addition: an admin sends `patch` only to an overlay whose
30
40
  * `ready` lists "patch", and an older admin never reads `features`.
31
41
  *
42
+ * `item` is the same kind of addition, on two messages v1 already has. The
43
+ * site tags one item of a list (`capaAttrs(entry, "faqs", { item: 2 })`), a
44
+ * click reports it, and the editor opens that item rather than the top of
45
+ * the list. The editor sends it with a highlight only where the project has
46
+ * it on (`CAPA_PREVIEW_TARGETS`), and an overlay that does not read it
47
+ * outlines the whole field, as before. An item that is not a well-formed
48
+ * path (`isItemPath`) is dropped and the message kept: the field is still
49
+ * right.
50
+ *
32
51
  * A PATCH IS TEXT ONLY, and only where the page shows the field verbatim. The
33
52
  * overlay changes a tagged element's text while it reads exactly `saved` (the
34
53
  * value the page was rendered from) or what this page last patched it to, so
@@ -38,14 +57,29 @@
38
57
  * The admin keeps its own copy of these shapes (`apps/admin`, no dependency on
39
58
  * this package). If you change one side, change the other.
40
59
  */
60
+ import { acceptLiveFields } from "./live-fields.js";
41
61
  export const PROTOCOL_VERSION = 1;
42
62
  export const ADMIN_SOURCE = "capa-admin";
43
63
  export const SITE_SOURCE = "capa";
44
- /** What this overlay can do beyond v1, listed in its `ready`. */
45
- export const SITE_FEATURES = ["patch"];
64
+ /**
65
+ * What this overlay can do beyond v1, listed in its `ready`. `release`: this
66
+ * SDK sends a release preview's token on its reads (`Capa-Release`), so the
67
+ * admin can tell a site that shows a release from one that shows every draft.
68
+ */
69
+ export const SITE_FEATURES = ["patch", "fields", "release"];
46
70
  /** A `patch` past these is refused whole: no form has that many text fields, or that much text in one. */
47
71
  export const PATCH_MAX_FIELDS = 500;
48
72
  export const PATCH_MAX_LENGTH = 100_000;
73
+ /**
74
+ * One item of a list field, as `data-capa-item` spells it: up to 16 segments
75
+ * joined with dots, each a whole number or a key of letters, digits, `_` and
76
+ * `-` (`2`, `2.question`). `itemPath` in `@capacms/sdk/next` writes it.
77
+ */
78
+ const ITEM_PATH = /^[A-Za-z0-9_-]{1,64}(\.[A-Za-z0-9_-]{1,64}){0,15}$/;
79
+ /** Whether a value is an item path an overlay sends and an editor reads. */
80
+ export function isItemPath(value) {
81
+ return typeof value === "string" && value.length <= 1040 && ITEM_PATH.test(value);
82
+ }
49
83
  /**
50
84
  * `https://admin.example.com/` and `https://admin.example.com` are one origin,
51
85
  * and a configured value that is not a URL at all is dropped rather than
@@ -99,12 +133,17 @@ export function acceptMessage(event, allowedOrigins, parent) {
99
133
  if (typeof m.on !== "boolean")
100
134
  return null;
101
135
  return { source: ADMIN_SOURCE, v: 1, type: "outline", on: m.on };
102
- case "highlight":
136
+ case "highlight": {
103
137
  if (typeof m.entryId !== "string")
104
138
  return null;
105
139
  if (m.field !== null && typeof m.field !== "string")
106
140
  return null;
107
- return { source: ADMIN_SOURCE, v: 1, type: "highlight", entryId: m.entryId, field: m.field };
141
+ const highlight = { source: ADMIN_SOURCE, v: 1, type: "highlight", entryId: m.entryId, field: m.field };
142
+ // Optional: an item of the field, kept only when it is one (a clear has none).
143
+ if (m.entryId !== "" && m.field !== null && isItemPath(m.item))
144
+ highlight.item = m.item;
145
+ return highlight;
146
+ }
108
147
  case "patch": {
109
148
  if (typeof m.entryId !== "string" || m.entryId === "")
110
149
  return null;
@@ -125,6 +164,14 @@ export function acceptMessage(event, allowedOrigins, parent) {
125
164
  }
126
165
  return { source: ADMIN_SOURCE, v: 1, type: "patch", entryId: m.entryId, fields };
127
166
  }
167
+ case "fields": {
168
+ if (typeof m.entryId !== "string" || m.entryId === "")
169
+ return null;
170
+ const fields = acceptLiveFields(m.fields);
171
+ if (fields === null)
172
+ return null;
173
+ return { source: ADMIN_SOURCE, v: 1, type: "fields", entryId: m.entryId, fields };
174
+ }
128
175
  default:
129
176
  return null;
130
177
  }
@@ -162,8 +209,31 @@ export function readyMessage(path, entries, features) {
162
209
  ? { source: SITE_SOURCE, v: 1, type: "ready", path, entries, features: [...features] }
163
210
  : { source: SITE_SOURCE, v: 1, type: "ready", path, entries };
164
211
  }
165
- export function selectMessage(entryId, field) {
166
- return { source: SITE_SOURCE, v: 1, type: "select", entryId, field };
212
+ /** A click on a tagged element, with its list item when it names a well-formed one. */
213
+ export function selectMessage(entryId, field, item) {
214
+ return isItemPath(item)
215
+ ? { source: SITE_SOURCE, v: 1, type: "select", entryId, field, item }
216
+ : { source: SITE_SOURCE, v: 1, type: "select", entryId, field };
217
+ }
218
+ /**
219
+ * Whether an element's `data-capa-item` is the item asked for, or inside it:
220
+ * `2.question` is in item `2`. Pure, so the overlay's matching is tested
221
+ * without a DOM.
222
+ */
223
+ export function itemMatches(tagged, wanted) {
224
+ if (typeof tagged !== "string")
225
+ return false;
226
+ return tagged === wanted || tagged.startsWith(`${wanted}.`);
227
+ }
228
+ /**
229
+ * The label the overlay draws for an item: "faqs › item 3" for an index,
230
+ * which counts from one as an editor does, "faqs › question" for a key.
231
+ */
232
+ export function itemLabel(field, item) {
233
+ if (!isItemPath(item))
234
+ return field;
235
+ const parts = item.split(".").map((part) => (/^\d+$/.test(part) ? `item ${Number(part) + 1}` : part));
236
+ return `${field} › ${parts.join(" › ")}`;
167
237
  }
168
238
  export function hoverMessage(entryId, field) {
169
239
  return entryId === ""
@@ -9,21 +9,33 @@
9
9
  * from the rules the API serves by (`canonicalQuery` and `parseImageParams`,
10
10
  * compiled in from @capa/shared at build time), so the two cannot drift.
11
11
  *
12
- * Three rules beside the API's:
12
+ * Four rules beside the API's:
13
13
  * - Nothing is enlarged. When the image's own width is known (the `/api/`
14
14
  * media shape carries it), a request for more pixels than it has is brought
15
15
  * down to its size, keeping the requested shape.
16
16
  * - `format=auto` is only sent when asked for.
17
17
  * - A URL that is not a Capa image comes back unchanged.
18
+ * - A crop to a shape (`fit: "cover"` with a width and a height) of a media
19
+ * value that carries an editor's focal point or crop names them in the URL
20
+ * (`fp`, `rect`), so moving the focal point gives a new URL rather than a
21
+ * copy cached under the old one. A media value without them, and a URL or
22
+ * a key without `fp` or `rect`, builds exactly the URL it always did.
18
23
  *
19
24
  * A stored URL on `api.capacms.com/files/` (older uploads) names the same file
20
25
  * as the CDN: the CDN fetches from that host. Built URLs go to the CDN host,
21
26
  * where a resized copy is cached at the edge rather than made again by the
22
27
  * origin on every request.
23
28
  */
24
- import { MAX_OUTPUT_EDGE, type ImageFit, type ImageFormat } from "./shared-params.generated.js";
29
+ import { MAX_OUTPUT_EDGE, type CropRect, type FocalPoint, type ImageFit, type ImageFormat } from "./shared-params.generated.js";
25
30
  export type { ImageFit, ImageFormat };
26
31
  export { MAX_OUTPUT_EDGE };
32
+ /**
33
+ * The spot in an image an editor marked as the one that matters most, as
34
+ * fractions of the image from 0 to 1: `x` from the left, `y` from the top.
35
+ */
36
+ export type ImageFocalPoint = FocalPoint;
37
+ /** The part of an image an editor chose to show, as fractions of the image from 0 to 1. */
38
+ export type ImageCrop = CropRect;
27
39
  /** Where Capa serves files. A media `url` from the API starts with this and `/files/`. */
28
40
  export declare const CAPA_CDN_ORIGIN = "https://cdn.capacms.com";
29
41
  /**
@@ -43,6 +55,14 @@ export interface ImageLike {
43
55
  height?: number | null;
44
56
  /** The file's kind. Anything but `image` (or a missing kind) is returned unchanged. */
45
57
  type?: string | null;
58
+ /**
59
+ * The editor's focal point, where `/api/` sends one. A crop to a shape
60
+ * (`fit: "cover"` with a width and a height) centres on it, and its URL
61
+ * names it as `fp`.
62
+ */
63
+ focalPoint?: ImageFocalPoint | null;
64
+ /** The editor's crop, where `/api/` sends one. A crop to a shape stays inside it, and its URL names it as `rect`. */
65
+ crop?: ImageCrop | null;
46
66
  }
47
67
  /** A media value, a full CDN URL, or a file key (`sunns_1790971326210_d54fed020806.jpg`). */
48
68
  export type ImageSource = string | ImageLike;
@@ -66,6 +86,14 @@ export interface ImageOptions {
66
86
  * currently returns JPEG, so use `webp` until that is fixed.
67
87
  */
68
88
  format?: ImageFormat;
89
+ /**
90
+ * The focal point for a crop to a shape (`fit: "cover"` with a width and a
91
+ * height), in place of the media value's. Other requests have nothing to
92
+ * centre, so it is left out of their URL.
93
+ */
94
+ focalPoint?: ImageFocalPoint | null;
95
+ /** A crop, in place of the media value's. It applies to any resize, and on its own crops the image. */
96
+ crop?: ImageCrop | null;
69
97
  }
70
98
  /** The options `srcSet` takes: each candidate's width comes from its list, and its height from `aspectRatio`. */
71
99
  export interface SrcSetOptions {
@@ -74,6 +102,10 @@ export interface SrcSetOptions {
74
102
  fit?: ImageFit;
75
103
  quality?: number;
76
104
  format?: ImageFormat;
105
+ /** As `imageUrl`'s: applies to each candidate cropped to a shape (`aspectRatio` with `fit: "cover"`). */
106
+ focalPoint?: ImageFocalPoint | null;
107
+ /** As `imageUrl`'s: applies to every candidate. */
108
+ crop?: ImageCrop | null;
77
109
  }
78
110
  /**
79
111
  * The URL of a Capa image, resized as `options` say, spelled exactly as Capa's
@@ -118,3 +150,38 @@ export declare function srcSet(image: ImageSource | null | undefined, widths: re
118
150
  * ```
119
151
  */
120
152
  export declare function sizes(breakpoints: Readonly<Record<number, string>>, fallback?: string): string;
153
+ /**
154
+ * What `/api/` sends of an image's placeholders, where Capa makes them: a
155
+ * tiny blurred copy as a data URL, and its colours.
156
+ */
157
+ export interface PlaceholderLike {
158
+ blurDataURL?: string | null;
159
+ averageColor?: string | null;
160
+ dominantColor?: string | null;
161
+ }
162
+ /** next/image's `placeholder` and `blurDataURL` props, to spread onto an `<Image>`. */
163
+ export type ImagePlaceholder = {
164
+ placeholder: "blur";
165
+ blurDataURL: string;
166
+ } | {
167
+ placeholder: "empty";
168
+ };
169
+ /**
170
+ * next/image's placeholder props for a media value: `placeholder="blur"` with
171
+ * its `blurDataURL` when it has one, and `placeholder="empty"` otherwise, so
172
+ * the result can always be spread:
173
+ *
174
+ * ```tsx
175
+ * <Image src={imageUrl(hero)} alt={hero.alt ?? ""} width={1200} height={800} {...imagePlaceholder(hero)} />
176
+ * ```
177
+ */
178
+ export declare function imagePlaceholder(image: PlaceholderLike | null | undefined): ImagePlaceholder;
179
+ /**
180
+ * A colour to paint an image's space with while it loads, as `#rrggbb`: its
181
+ * average colour, else its dominant one, else undefined.
182
+ *
183
+ * ```tsx
184
+ * <div style={{ backgroundColor: placeholderColor(hero) }}>...</div>
185
+ * ```
186
+ */
187
+ export declare function placeholderColor(image: PlaceholderLike | null | undefined): string | undefined;
@@ -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;