@capacms/sdk 1.0.0-next.1 → 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.
Files changed (93) hide show
  1. package/CHANGELOG.md +487 -0
  2. package/README.md +1810 -183
  3. package/bin/capa-codegen.js +192 -5
  4. package/bin/capa.js +235 -0
  5. package/bin/graphql-project.js +142 -0
  6. package/bin/project-env.js +58 -0
  7. package/dist/client.d.ts +89 -4
  8. package/dist/client.js +40 -5
  9. package/dist/codegen.d.ts +55 -0
  10. package/dist/codegen.js +320 -39
  11. package/dist/config.d.ts +5 -36
  12. package/dist/config.js +47 -1
  13. package/dist/esm/image/index.d.ts +187 -0
  14. package/dist/esm/image/index.js +353 -0
  15. package/dist/esm/image/shared-params.generated.d.ts +314 -0
  16. package/dist/esm/image/shared-params.generated.js +680 -0
  17. package/dist/esm/nextjs/image-loader.d.ts +60 -0
  18. package/dist/esm/nextjs/image-loader.js +67 -0
  19. package/dist/esm/nextjs/overlay.d.ts +30 -0
  20. package/dist/esm/nextjs/overlay.js +75 -0
  21. package/dist/esm/overlay/index.d.ts +32 -0
  22. package/dist/esm/overlay/index.js +576 -0
  23. package/dist/esm/overlay/protocol.d.ts +187 -0
  24. package/dist/esm/overlay/protocol.js +240 -0
  25. package/dist/esm/package.json +4 -0
  26. package/dist/graphql-codegen.d.ts +117 -0
  27. package/dist/graphql-codegen.js +705 -0
  28. package/dist/http.js +1 -1
  29. package/dist/image/index.d.ts +187 -0
  30. package/dist/image/index.js +362 -0
  31. package/dist/image/shared-params.generated.d.ts +314 -0
  32. package/dist/image/shared-params.generated.js +700 -0
  33. package/dist/index.d.ts +3 -3
  34. package/dist/index.js +2 -1
  35. package/dist/next/attrs.d.ts +84 -10
  36. package/dist/next/attrs.js +119 -2
  37. package/dist/next/client.d.ts +176 -32
  38. package/dist/next/client.js +212 -90
  39. package/dist/next/entry-fields.d.ts +203 -0
  40. package/dist/next/entry-fields.js +2 -0
  41. package/dist/next/errors.d.ts +136 -0
  42. package/dist/next/errors.js +214 -0
  43. package/dist/next/field-names.d.ts +37 -0
  44. package/dist/next/field-names.js +145 -0
  45. package/dist/next/graphql/build.d.ts +27 -0
  46. package/dist/next/graphql/build.js +98 -0
  47. package/dist/next/graphql/documents.d.ts +67 -0
  48. package/dist/next/graphql/documents.js +35 -0
  49. package/dist/next/graphql/edit-mode.d.ts +16 -0
  50. package/dist/next/graphql/edit-mode.js +93 -0
  51. package/dist/next/graphql/filter-values.d.ts +34 -0
  52. package/dist/next/graphql/filter-values.js +96 -0
  53. package/dist/next/graphql/introspection.d.ts +89 -0
  54. package/dist/next/graphql/introspection.js +102 -0
  55. package/dist/next/graphql/plan.d.ts +115 -0
  56. package/dist/next/graphql/plan.js +531 -0
  57. package/dist/next/graphql/request.d.ts +228 -0
  58. package/dist/next/graphql/request.js +283 -0
  59. package/dist/next/graphql/rest.d.ts +66 -0
  60. package/dist/next/graphql/rest.js +502 -0
  61. package/dist/next/graphql/selection.d.ts +55 -0
  62. package/dist/next/graphql/selection.js +212 -0
  63. package/dist/next/graphql/sha256.d.ts +13 -0
  64. package/dist/next/graphql/sha256.js +86 -0
  65. package/dist/next/graphql/summary.d.ts +83 -0
  66. package/dist/next/graphql/summary.js +151 -0
  67. package/dist/next/graphql/tree-layout.d.ts +36 -0
  68. package/dist/next/graphql/tree-layout.js +20 -0
  69. package/dist/next/graphql/tree.d.ts +171 -0
  70. package/dist/next/graphql/tree.js +258 -0
  71. package/dist/next/graphql/typed.d.ts +261 -0
  72. package/dist/next/graphql/typed.js +146 -0
  73. package/dist/next/index.d.ts +30 -5
  74. package/dist/next/index.js +32 -1
  75. package/dist/next/inflate.d.ts +51 -0
  76. package/dist/next/inflate.js +243 -0
  77. package/dist/next/key-family.d.ts +31 -0
  78. package/dist/next/key-family.js +66 -0
  79. package/dist/next/select-types.d.ts +58 -5
  80. package/dist/next/system-keys.d.ts +27 -0
  81. package/dist/next/system-keys.js +42 -0
  82. package/dist/nextjs/image-loader.d.ts +60 -0
  83. package/dist/nextjs/image-loader.js +71 -0
  84. package/dist/nextjs/index.d.ts +484 -5
  85. package/dist/nextjs/index.js +688 -6
  86. package/dist/nextjs/overlay.d.ts +30 -0
  87. package/dist/nextjs/overlay.js +78 -0
  88. package/dist/overlay/index.d.ts +14 -2
  89. package/dist/overlay/index.js +282 -43
  90. package/dist/overlay/protocol.d.ts +98 -2
  91. package/dist/overlay/protocol.js +151 -4
  92. package/dist/webhooks.d.ts +8 -0
  93. package/package.json +63 -15
@@ -0,0 +1,187 @@
1
+ /**
2
+ * `@capacms/sdk/image`: URLs for Capa's image CDN, for any framework.
3
+ *
4
+ * Capa serves every upload at `https://cdn.capacms.com/files/<key>` and
5
+ * resizes it by query: `width`, `height`, `fit`, `quality`, `dpr`, `blur` and
6
+ * `format`. The API answers a URL whose query is spelled any other way than
7
+ * its canonical spelling with a 301 the edge keeps for a year, so every URL
8
+ * built here is already canonical. The spelling is not decided here: it comes
9
+ * from the rules the API serves by (`canonicalQuery` and `parseImageParams`,
10
+ * compiled in from @capa/shared at build time), so the two cannot drift.
11
+ *
12
+ * Four rules beside the API's:
13
+ * - Nothing is enlarged. When the image's own width is known (the `/api/`
14
+ * media shape carries it), a request for more pixels than it has is brought
15
+ * down to its size, keeping the requested shape.
16
+ * - `format=auto` is only sent when asked for.
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.
23
+ *
24
+ * A stored URL on `api.capacms.com/files/` (older uploads) names the same file
25
+ * as the CDN: the CDN fetches from that host. Built URLs go to the CDN host,
26
+ * where a resized copy is cached at the edge rather than made again by the
27
+ * origin on every request.
28
+ */
29
+ import { MAX_OUTPUT_EDGE, type CropRect, type FocalPoint, type ImageFit, type ImageFormat } from "./shared-params.generated.js";
30
+ export type { ImageFit, ImageFormat };
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;
39
+ /** Where Capa serves files. A media `url` from the API starts with this and `/files/`. */
40
+ export declare const CAPA_CDN_ORIGIN = "https://cdn.capacms.com";
41
+ /**
42
+ * True when `src` is a full URL of a file on Capa: `https://cdn.capacms.com/files/...`
43
+ * or `https://api.capacms.com/files/...`. A key, a path or another host is not.
44
+ * Use it to mark the other images `unoptimized` in next/image.
45
+ */
46
+ export declare function isCapaImageUrl(src: string): boolean;
47
+ /**
48
+ * A media value: the `/api/` shape `{ id, url, alt, type, width, height }`, the
49
+ * legacy client's `CapaImage`, or anything else with a `url`. `width` and
50
+ * `height` are the image's own pixel size, used so it is never enlarged.
51
+ */
52
+ export interface ImageLike {
53
+ url: string | null;
54
+ width?: number | null;
55
+ height?: number | null;
56
+ /** The file's kind. Anything but `image` (or a missing kind) is returned unchanged. */
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;
66
+ }
67
+ /** A media value, a full CDN URL, or a file key (`sunns_1790971326210_d54fed020806.jpg`). */
68
+ export type ImageSource = string | ImageLike;
69
+ /** What Capa's CDN can do to an image. Every one is optional, and a default is left out of the URL. */
70
+ export interface ImageOptions {
71
+ /** Width in CSS pixels; with `dpr`, the image is `width × dpr` pixels wide. */
72
+ width?: number | null;
73
+ /** Height in CSS pixels. */
74
+ height?: number | null;
75
+ /** How the image meets a box given by both `width` and `height`: `inside` (the default), `cover` (crop) or `contain` (pad). */
76
+ fit?: ImageFit;
77
+ /** 1 to 100; Capa's default is 80. Ignored for png. */
78
+ quality?: number;
79
+ /** Device pixel ratio, 1 to 3. */
80
+ dpr?: number;
81
+ /** A blurred placeholder `blur × blur` pixels square, 1 to 256. */
82
+ blur?: number;
83
+ /**
84
+ * The format to encode. Left out, the image keeps its own format. `auto`
85
+ * picks AVIF or WebP from the browser's `Accept` header; through the CDN it
86
+ * currently returns JPEG, so use `webp` until that is fixed.
87
+ */
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;
97
+ }
98
+ /** The options `srcSet` takes: each candidate's width comes from its list, and its height from `aspectRatio`. */
99
+ export interface SrcSetOptions {
100
+ /** Width over height. Given, each candidate is `width` by `width / aspectRatio`; use it with `fit: "cover"` to crop. */
101
+ aspectRatio?: number;
102
+ fit?: ImageFit;
103
+ quality?: number;
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;
109
+ }
110
+ /**
111
+ * The URL of a Capa image, resized as `options` say, spelled exactly as Capa's
112
+ * CDN serves it without a redirect.
113
+ *
114
+ * `image` is a media value (`entry.fields.hero`), a CDN URL, or a file key.
115
+ * Gives `undefined` when there is no image (`null`, or a media value whose
116
+ * `url` is null or empty, which is how the legacy API sends an unset image),
117
+ * so a media value always gives `string | undefined`; a string always gives a
118
+ * string. Gives back unchanged a URL that is not a Capa image (another host, a
119
+ * site path) or a media value that is not an image. Throws a `TypeError` for
120
+ * an option Capa would refuse with a 400.
121
+ *
122
+ * ```ts
123
+ * imageUrl(entry.fields.hero, { width: 1200, format: "webp" })
124
+ * // https://cdn.capacms.com/files/<key>?format=webp&width=1200
125
+ * ```
126
+ */
127
+ export declare function imageUrl(image: string, options?: ImageOptions): string;
128
+ export declare function imageUrl(image: ImageSource | null | undefined, options?: ImageOptions): string | undefined;
129
+ /**
130
+ * A `srcset` for a Capa image: one candidate per width, smallest first, each
131
+ * as `<url> <width>w`. Widths past the image's own width (when known) are
132
+ * dropped in favour of one candidate at its own width.
133
+ *
134
+ * Gives `undefined` when there is nothing to resize: no image, or one that is
135
+ * not Capa's. Throws a `TypeError` for a width list that is empty or not whole
136
+ * pixels, or an option Capa would refuse.
137
+ *
138
+ * ```ts
139
+ * srcSet(entry.fields.hero, [640, 960, 1280, 1920], { format: "webp" })
140
+ * ```
141
+ */
142
+ export declare function srcSet(image: ImageSource | null | undefined, widths: readonly number[], options?: SrcSetOptions): string | undefined;
143
+ /**
144
+ * A `sizes` attribute from min-width breakpoints, widest first so the first
145
+ * match is the right one, then the fallback.
146
+ *
147
+ * ```ts
148
+ * sizes({ 768: "50vw", 1280: "33vw" })
149
+ * // (min-width: 1280px) 33vw, (min-width: 768px) 50vw, 100vw
150
+ * ```
151
+ */
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;
@@ -0,0 +1,353 @@
1
+ /**
2
+ * `@capacms/sdk/image`: URLs for Capa's image CDN, for any framework.
3
+ *
4
+ * Capa serves every upload at `https://cdn.capacms.com/files/<key>` and
5
+ * resizes it by query: `width`, `height`, `fit`, `quality`, `dpr`, `blur` and
6
+ * `format`. The API answers a URL whose query is spelled any other way than
7
+ * its canonical spelling with a 301 the edge keeps for a year, so every URL
8
+ * built here is already canonical. The spelling is not decided here: it comes
9
+ * from the rules the API serves by (`canonicalQuery` and `parseImageParams`,
10
+ * compiled in from @capa/shared at build time), so the two cannot drift.
11
+ *
12
+ * Four rules beside the API's:
13
+ * - Nothing is enlarged. When the image's own width is known (the `/api/`
14
+ * media shape carries it), a request for more pixels than it has is brought
15
+ * down to its size, keeping the requested shape.
16
+ * - `format=auto` is only sent when asked for.
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.
23
+ *
24
+ * A stored URL on `api.capacms.com/files/` (older uploads) names the same file
25
+ * as the CDN: the CDN fetches from that host. Built URLs go to the CDN host,
26
+ * where a resized copy is cached at the edge rather than made again by the
27
+ * origin on every request.
28
+ */
29
+ import { canonicalQuery, FOCAL_PARAMS, LEGACY_PARAMS, MAX_OUTPUT_EDGE, NEW_PARAMS, parseFocalParams, parseImageParams, readCrop, readFocalPoint, } from "./shared-params.generated.js";
30
+ export { MAX_OUTPUT_EDGE };
31
+ /** Where Capa serves files. A media `url` from the API starts with this and `/files/`. */
32
+ export const CAPA_CDN_ORIGIN = "https://cdn.capacms.com";
33
+ /**
34
+ * The API's own host, which some stored URLs name (`https://api.capacms.com/files/<key>`).
35
+ * It is the CDN's origin, with nothing in front of it, so the same key is the
36
+ * same file on both; a URL built here always names the CDN.
37
+ */
38
+ const CAPA_API_ORIGIN = "https://api.capacms.com";
39
+ const CAPA_ORIGINS = new Set([CAPA_CDN_ORIGIN, CAPA_API_ORIGIN]);
40
+ const FILES_PATH = "/files/";
41
+ /** A full `https://` URL of a file on Capa's CDN or API host, as a URL, or null. */
42
+ function capaFileUrl(text) {
43
+ let url;
44
+ try {
45
+ url = new URL(text);
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ if (!CAPA_ORIGINS.has(url.origin) || !url.pathname.startsWith(FILES_PATH) || url.pathname.length === FILES_PATH.length)
51
+ return null;
52
+ // The same path, query and fragment on the CDN host.
53
+ return url.origin === CAPA_CDN_ORIGIN ? url : new URL(`${url.pathname}${url.search}${url.hash}`, CAPA_CDN_ORIGIN);
54
+ }
55
+ /**
56
+ * True when `src` is a full URL of a file on Capa: `https://cdn.capacms.com/files/...`
57
+ * or `https://api.capacms.com/files/...`. A key, a path or another host is not.
58
+ * Use it to mark the other images `unoptimized` in next/image.
59
+ */
60
+ export function isCapaImageUrl(src) {
61
+ return typeof src === "string" && /^https:\/\//i.test(src) && capaFileUrl(src) !== null;
62
+ }
63
+ const OPTION_KEYS = ["width", "height", "fit", "quality", "dpr", "blur", "format"];
64
+ function positive(value) {
65
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : undefined;
66
+ }
67
+ /** True when `text` names a scheme (`https:`, `data:`), so it is a URL rather than a file key. */
68
+ function hasScheme(text) {
69
+ return /^[a-z][a-z0-9+.-]*:/i.test(text);
70
+ }
71
+ /** What a media value says about itself: its size, and an editor's focal point and crop when they are well formed. */
72
+ function known(image) {
73
+ const out = { intrinsicWidth: positive(image?.width), intrinsicHeight: positive(image?.height) };
74
+ const focalPoint = image ? readFocalPoint(image.focalPoint) : null;
75
+ const crop = image ? readCrop(image.crop) : null;
76
+ if (focalPoint)
77
+ out.focalPoint = focalPoint;
78
+ if (crop)
79
+ out.crop = crop;
80
+ return out;
81
+ }
82
+ /** A string or `url` as a Capa image, or why not. */
83
+ function resolveUrl(text, image) {
84
+ if (hasScheme(text)) {
85
+ const url = capaFileUrl(text);
86
+ if (url === null)
87
+ return { unchanged: text };
88
+ return { target: { url, ...known(image) } };
89
+ }
90
+ // A path (`/logo.png`, `//host/x`) is the site's own or another host's.
91
+ if (text === "" || text.startsWith("/"))
92
+ return { unchanged: text };
93
+ // A file key, which may hold folders: each segment is encoded on its own.
94
+ const path = text.split("/").map(encodeURIComponent).join("/");
95
+ return { target: { url: new URL(`${CAPA_CDN_ORIGIN}${FILES_PATH}${path}`), ...known(image) } };
96
+ }
97
+ function resolve(image) {
98
+ if (image === null || image === undefined)
99
+ return null;
100
+ if (typeof image === "string")
101
+ return resolveUrl(image);
102
+ if (typeof image !== "object" || typeof image.url !== "string" || image.url === "")
103
+ return null;
104
+ if (typeof image.type === "string" && image.type !== "image" && !image.type.startsWith("image/"))
105
+ return { unchanged: image.url };
106
+ return resolveUrl(image.url, image);
107
+ }
108
+ /** A number from a query value, when it is one. */
109
+ function numeric(value) {
110
+ if (typeof value !== "string" || !/^\d+(\.\d+)?$/.test(value.trim()))
111
+ return undefined;
112
+ return positive(Number(value));
113
+ }
114
+ /**
115
+ * Brings a request that would enlarge the image down to the image's own size.
116
+ *
117
+ * The scale the request puts on the image's content is worked out for its
118
+ * fit. `inside` and `contain` fit the image within the box, so the smaller of
119
+ * the two ratios rules and both sizes must be known; `cover` fills the box, so
120
+ * the larger rules, and with only the width known the width's ratio is a floor
121
+ * on it. Above 1, the box is divided by that scale, which keeps its shape and
122
+ * makes the content its own size. Nothing changes when the scale cannot be
123
+ * worked out. Blur is left alone: its size comes from `blur`, not the box.
124
+ */
125
+ function capToImage(query, target) {
126
+ const W = target.intrinsicWidth;
127
+ const H = target.intrinsicHeight;
128
+ if ((W === undefined && H === undefined) || query.blur !== undefined)
129
+ return;
130
+ const width = numeric(query.width);
131
+ const height = numeric(query.height);
132
+ const dpr = numeric(query.dpr) ?? 1;
133
+ const fit = typeof query.fit === "string" ? query.fit.trim().toLowerCase() : "inside";
134
+ const sw = width !== undefined && W !== undefined ? (width * dpr) / W : undefined;
135
+ const sh = height !== undefined && H !== undefined ? (height * dpr) / H : undefined;
136
+ let scale;
137
+ if (width !== undefined && height === undefined)
138
+ scale = sw;
139
+ else if (height !== undefined && width === undefined)
140
+ scale = sh;
141
+ else if (width !== undefined && height !== undefined) {
142
+ if (fit === "cover")
143
+ scale = sh === undefined ? sw : sw === undefined ? sh : Math.max(sw, sh);
144
+ else
145
+ scale = sw === undefined || sh === undefined ? undefined : Math.min(sw, sh);
146
+ }
147
+ if (scale === undefined || scale <= 1)
148
+ return;
149
+ // The epsilon keeps a division that is exact on paper (1600 / (4/3)) from flooring to one less.
150
+ const down = (n) => String(Math.max(1, Math.floor(n / scale + 1e-9)));
151
+ if (width !== undefined)
152
+ query.width = down(width);
153
+ if (height !== undefined)
154
+ query.height = down(height);
155
+ }
156
+ function fail(fn, message) {
157
+ throw new TypeError(`@capacms/sdk: ${fn}: ${message}`);
158
+ }
159
+ /** The canonical URL for a Capa image, and the pixel width it asks for. */
160
+ function build(fn, target, options) {
161
+ const { url } = target;
162
+ const search = url.search.slice(1);
163
+ // The URL's own image parameters, as Fastify would hand them to the API.
164
+ const query = {};
165
+ for (const [key, value] of new URLSearchParams(search)) {
166
+ if (!LEGACY_PARAMS.has(key) && !NEW_PARAMS.has(key))
167
+ continue;
168
+ const prior = query[key];
169
+ query[key] = prior === undefined ? value : [].concat(prior, value);
170
+ }
171
+ // The options win over them.
172
+ for (const key of OPTION_KEYS) {
173
+ const value = options[key];
174
+ if (value !== undefined && value !== null)
175
+ query[key] = String(value);
176
+ }
177
+ capToImage(query, target);
178
+ const parsed = parseImageParams(query);
179
+ if (!parsed.ok)
180
+ fail(fn, parsed.rejection.error);
181
+ const focal = focalParams(fn, target, options, parsed.params, search);
182
+ // With no focal point or crop to name, the URL is spelled as it always was:
183
+ // an `fp` or `rect` already in it is an unknown key, kept as it is.
184
+ const canonical = focal === null ? canonicalQuery(search, parsed.params) : canonicalQuery(search, focal, { focal: true });
185
+ const href = `${url.origin}${url.pathname}${canonical ? `?${canonical}` : ""}${url.hash}`;
186
+ return { href, width: parsed.params.width };
187
+ }
188
+ /**
189
+ * The parameters with the focal point and crop this URL names, or null when
190
+ * it names none of its own making.
191
+ *
192
+ * Capa's CDN crops a request to a shape (`fit=cover` with a width and a
193
+ * height) around the focal point and inside the crop an editor set on the
194
+ * file, whether the URL names them or not. Named in the URL, a moved focal
195
+ * point is a new URL, so no browser or edge keeps the old crop under it. A
196
+ * crop given as an option applies to any resize, as the CDN applies a `rect`
197
+ * it is sent. Options win over the media value, which wins over an `fp` or
198
+ * `rect` the URL already had. With none of them, null: the URL is spelled as
199
+ * it always was.
200
+ */
201
+ function focalParams(fn, target, options, params, search) {
202
+ let askedFocal;
203
+ if (options.focalPoint !== undefined && options.focalPoint !== null) {
204
+ const read = readFocalPoint(options.focalPoint);
205
+ if (read === null)
206
+ fail(fn, "`focalPoint` must be { x, y }, numbers from 0 to 1");
207
+ askedFocal = read;
208
+ }
209
+ let askedCrop;
210
+ if (options.crop !== undefined && options.crop !== null) {
211
+ const read = readCrop(options.crop);
212
+ if (read === null)
213
+ 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");
214
+ askedCrop = read;
215
+ }
216
+ const cover = params.fit === "cover" && params.width !== undefined && params.height !== undefined && params.blur === undefined;
217
+ const focalPoint = cover ? askedFocal ?? target.focalPoint : undefined;
218
+ const rect = askedCrop ?? (cover ? target.crop : undefined);
219
+ // What the URL already said (a URL this function built, handed back to it,
220
+ // as next/image hands its loader a `src`), kept where nothing here replaces
221
+ // it, and spelled as the CDN spells it. One the CDN would refuse stays an
222
+ // unknown key, as it is, unless something here replaces it.
223
+ const own = {};
224
+ for (const [key, value] of new URLSearchParams(search))
225
+ if (FOCAL_PARAMS.has(key) && !(key in own))
226
+ own[key] = value;
227
+ const ownFocal = parseFocalParams(own);
228
+ const kept = ownFocal.ok ? ownFocal : {};
229
+ const fp = focalPoint ?? kept.focalPoint;
230
+ const r = rect ?? kept.rect;
231
+ if (fp === undefined && r === undefined)
232
+ return null;
233
+ const out = { ...params };
234
+ if (fp !== undefined)
235
+ out.focalPoint = fp;
236
+ if (r !== undefined)
237
+ out.rect = r;
238
+ return out;
239
+ }
240
+ export function imageUrl(image, options = {}) {
241
+ const resolved = resolve(image);
242
+ if (resolved === null)
243
+ return undefined;
244
+ if ("unchanged" in resolved)
245
+ return resolved.unchanged;
246
+ return build("imageUrl", resolved.target, options).href;
247
+ }
248
+ /**
249
+ * A `srcset` for a Capa image: one candidate per width, smallest first, each
250
+ * as `<url> <width>w`. Widths past the image's own width (when known) are
251
+ * dropped in favour of one candidate at its own width.
252
+ *
253
+ * Gives `undefined` when there is nothing to resize: no image, or one that is
254
+ * not Capa's. Throws a `TypeError` for a width list that is empty or not whole
255
+ * pixels, or an option Capa would refuse.
256
+ *
257
+ * ```ts
258
+ * srcSet(entry.fields.hero, [640, 960, 1280, 1920], { format: "webp" })
259
+ * ```
260
+ */
261
+ export function srcSet(image, widths, options = {}) {
262
+ if (!Array.isArray(widths) || widths.length === 0 || !widths.every((w) => Number.isSafeInteger(w) && w > 0)) {
263
+ fail("srcSet", `widths must be a list of whole pixel widths, such as [640, 1280]. Got ${JSON.stringify(widths)}.`);
264
+ }
265
+ const loose = options;
266
+ if (loose.width !== undefined)
267
+ fail("srcSet", "srcSet takes its widths as the second argument, not a `width` option.");
268
+ if (loose.height !== undefined)
269
+ fail("srcSet", "give `aspectRatio` (width / height) rather than `height`; each candidate's height follows its width.");
270
+ if (loose.dpr !== undefined || loose.blur !== undefined) {
271
+ fail("srcSet", "`dpr` and `blur` do not apply to a srcset: the browser picks a candidate by its w descriptor.");
272
+ }
273
+ const { aspectRatio } = options;
274
+ if (aspectRatio !== undefined && positive(aspectRatio) === undefined) {
275
+ fail("srcSet", `\`aspectRatio\` must be a positive number (width / height). Got ${JSON.stringify(aspectRatio)}.`);
276
+ }
277
+ const resolved = resolve(image);
278
+ if (resolved === null || "unchanged" in resolved)
279
+ return undefined;
280
+ const seen = new Set();
281
+ const candidates = [];
282
+ for (const width of [...new Set(widths)].sort((a, b) => a - b)) {
283
+ const height = aspectRatio === undefined ? undefined : Math.max(1, Math.round(width / aspectRatio));
284
+ const { href, width: built } = build("srcSet", resolved.target, {
285
+ width,
286
+ height,
287
+ fit: options.fit,
288
+ quality: options.quality,
289
+ format: options.format,
290
+ focalPoint: options.focalPoint,
291
+ crop: options.crop,
292
+ });
293
+ if (seen.has(href))
294
+ continue;
295
+ seen.add(href);
296
+ candidates.push(`${href} ${built ?? width}w`);
297
+ }
298
+ return candidates.join(", ");
299
+ }
300
+ /**
301
+ * A `sizes` attribute from min-width breakpoints, widest first so the first
302
+ * match is the right one, then the fallback.
303
+ *
304
+ * ```ts
305
+ * sizes({ 768: "50vw", 1280: "33vw" })
306
+ * // (min-width: 1280px) 33vw, (min-width: 768px) 50vw, 100vw
307
+ * ```
308
+ */
309
+ export function sizes(breakpoints, fallback = "100vw") {
310
+ const rules = [];
311
+ for (const [key, size] of Object.entries(breakpoints)) {
312
+ const px = Number(key);
313
+ if (!/^\d+$/.test(key) || px <= 0)
314
+ fail("sizes", `breakpoints are min-widths in pixels, such as { 768: "50vw" }. Got ${JSON.stringify(key)}.`);
315
+ if (typeof size !== "string" || size.trim() === "")
316
+ fail("sizes", `the size for ${key}px must be a length, such as "50vw". Got ${JSON.stringify(size)}.`);
317
+ rules.push([px, size.trim()]);
318
+ }
319
+ if (typeof fallback !== "string" || fallback.trim() === "")
320
+ fail("sizes", `the fallback must be a length, such as "100vw". Got ${JSON.stringify(fallback)}.`);
321
+ rules.sort(([a], [b]) => b - a);
322
+ return [...rules.map(([px, size]) => `(min-width: ${px}px) ${size}`), fallback.trim()].join(", ");
323
+ }
324
+ const BLUR_DATA_URL = /^data:image\/[a-z0-9.+-]+;base64,[A-Za-z0-9+/]+={0,2}$/i;
325
+ const HEX_COLOUR = /^#[0-9a-f]{6}$/i;
326
+ /**
327
+ * next/image's placeholder props for a media value: `placeholder="blur"` with
328
+ * its `blurDataURL` when it has one, and `placeholder="empty"` otherwise, so
329
+ * the result can always be spread:
330
+ *
331
+ * ```tsx
332
+ * <Image src={imageUrl(hero)} alt={hero.alt ?? ""} width={1200} height={800} {...imagePlaceholder(hero)} />
333
+ * ```
334
+ */
335
+ export function imagePlaceholder(image) {
336
+ const blur = image?.blurDataURL;
337
+ return typeof blur === "string" && BLUR_DATA_URL.test(blur) ? { placeholder: "blur", blurDataURL: blur } : { placeholder: "empty" };
338
+ }
339
+ /**
340
+ * A colour to paint an image's space with while it loads, as `#rrggbb`: its
341
+ * average colour, else its dominant one, else undefined.
342
+ *
343
+ * ```tsx
344
+ * <div style={{ backgroundColor: placeholderColor(hero) }}>...</div>
345
+ * ```
346
+ */
347
+ export function placeholderColor(image) {
348
+ for (const colour of [image?.averageColor, image?.dominantColor]) {
349
+ if (typeof colour === "string" && HEX_COLOUR.test(colour))
350
+ return colour.toLowerCase();
351
+ }
352
+ return undefined;
353
+ }