@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.
- package/CHANGELOG.md +170 -0
- package/README.md +368 -5
- package/bin/capa-check-bundle.js +80 -0
- package/bin/capa.js +3 -3
- package/bin/graphql-project.js +1 -1
- package/dist/client.d.ts +84 -4
- package/dist/client.js +23 -5
- package/dist/esm/image/index.d.ts +69 -2
- package/dist/esm/image/index.js +108 -5
- package/dist/esm/image/shared-params.generated.d.ts +126 -2
- package/dist/esm/image/shared-params.generated.js +224 -5
- package/dist/esm/overlay/index.d.ts +4 -1
- package/dist/esm/overlay/index.js +382 -30
- package/dist/esm/overlay/live-fields.d.ts +133 -0
- package/dist/esm/overlay/live-fields.js +478 -0
- package/dist/esm/overlay/markdown.d.ts +38 -0
- package/dist/esm/overlay/markdown.js +536 -0
- package/dist/esm/overlay/protocol.d.ts +51 -5
- package/dist/esm/overlay/protocol.js +79 -9
- package/dist/image/index.d.ts +69 -2
- package/dist/image/index.js +109 -4
- package/dist/image/shared-params.generated.d.ts +126 -2
- package/dist/image/shared-params.generated.js +235 -6
- package/dist/index.d.ts +1 -1
- package/dist/next/attrs.d.ts +42 -1
- package/dist/next/attrs.js +42 -3
- package/dist/next/client.d.ts +48 -1
- package/dist/next/client.js +33 -2
- package/dist/next/entry-fields.d.ts +43 -2
- package/dist/next/graphql/request.d.ts +4 -0
- package/dist/next/graphql/request.js +4 -0
- package/dist/next/graphql/tree.js +9 -0
- package/dist/next/index.d.ts +4 -4
- package/dist/next/index.js +3 -1
- package/dist/nextjs/index.d.ts +91 -7
- package/dist/nextjs/index.js +230 -17
- package/dist/nextjs/write-key-guard.d.ts +117 -0
- package/dist/nextjs/write-key-guard.js +285 -0
- package/dist/overlay/index.d.ts +4 -1
- package/dist/overlay/index.js +399 -29
- package/dist/overlay/live-fields.d.ts +133 -0
- package/dist/overlay/live-fields.js +493 -0
- package/dist/overlay/markdown.d.ts +38 -0
- package/dist/overlay/markdown.js +539 -0
- package/dist/overlay/protocol.d.ts +51 -5
- package/dist/overlay/protocol.js +82 -9
- package/dist/server/browser.d.ts +1 -0
- package/dist/server/browser.js +20 -0
- package/dist/server/client.d.ts +268 -0
- package/dist/server/client.js +335 -0
- package/dist/server/errors.d.ts +60 -0
- package/dist/server/errors.js +120 -0
- package/dist/server/index.d.ts +14 -0
- package/dist/server/index.js +32 -0
- package/dist/server/key-format.d.ts +41 -0
- package/dist/server/key-format.js +91 -0
- package/dist/server/transport.d.ts +47 -0
- package/dist/server/transport.js +114 -0
- package/dist/webhooks.d.ts +8 -0
- package/package.json +18 -4
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* capa-check-bundle — fail when a Capa server write key (capw_) is in the
|
|
4
|
+
* files a browser downloads.
|
|
5
|
+
*
|
|
6
|
+
* capa-check-bundle scans .next (and out, if there is one) in the current directory
|
|
7
|
+
* capa-check-bundle <dir>... scans each directory given (.next, build, dist, out)
|
|
8
|
+
*
|
|
9
|
+
* THE REQUIRED STEP for a Next.js site that holds a write key. Run it after the
|
|
10
|
+
* build, in the same script, so a key that would reach a browser fails the
|
|
11
|
+
* deploy:
|
|
12
|
+
*
|
|
13
|
+
* "build": "next build && capa-check-bundle"
|
|
14
|
+
*
|
|
15
|
+
* For a Next build directory (`.next`, or whatever `distDir` names) it scans
|
|
16
|
+
* what a browser downloads: every file under `static/`, and the pages
|
|
17
|
+
* prerendering wrote under `server/` (HTML, RSC payloads, static route
|
|
18
|
+
* bodies, `getStaticProps` data). A key passed from a server component to a
|
|
19
|
+
* client component's props lands there, on a static page, and nowhere in
|
|
20
|
+
* `static/`. `withCapaWriteKeyGuard` runs inside `next build` before
|
|
21
|
+
* prerendering, so it cannot see those files; this bin can. Any other
|
|
22
|
+
* directory (`out`, a Vite `dist`) is scanned whole.
|
|
23
|
+
*
|
|
24
|
+
* Exit 0 when no key is found, 1 with each file and line when one is, 2 when a
|
|
25
|
+
* directory given does not exist. Only a match whose checksum is right counts
|
|
26
|
+
* as a key; a value merely shaped like one is printed as a warning and exits
|
|
27
|
+
* 0. A key is printed as its first 12 characters only.
|
|
28
|
+
*/
|
|
29
|
+
const fs = require("node:fs");
|
|
30
|
+
const path = require("node:path");
|
|
31
|
+
const {
|
|
32
|
+
isNextBuildDir,
|
|
33
|
+
scanForWriteKeys,
|
|
34
|
+
scanNextBuildForWriteKeys,
|
|
35
|
+
splitFindings,
|
|
36
|
+
writeKeyReport,
|
|
37
|
+
writeKeyShapeWarning,
|
|
38
|
+
} = require("../dist/nextjs/write-key-guard.js");
|
|
39
|
+
|
|
40
|
+
const USAGE = "usage: capa-check-bundle [dir ...] (default: .next, and out when it exists)";
|
|
41
|
+
|
|
42
|
+
function main(argv) {
|
|
43
|
+
if (argv.includes("--help") || argv.includes("-h")) {
|
|
44
|
+
console.log(USAGE);
|
|
45
|
+
return 0;
|
|
46
|
+
}
|
|
47
|
+
const unknown = argv.find((arg) => arg.startsWith("-"));
|
|
48
|
+
if (unknown) {
|
|
49
|
+
console.error(`capa-check-bundle: unknown option ${unknown}\n${USAGE}`);
|
|
50
|
+
return 2;
|
|
51
|
+
}
|
|
52
|
+
const explicit = argv.length > 0;
|
|
53
|
+
const dirs = explicit ? argv : [".next", ...(fs.existsSync("out") ? ["out"] : [])];
|
|
54
|
+
let found = 0;
|
|
55
|
+
const scanned = [];
|
|
56
|
+
for (const dir of dirs) {
|
|
57
|
+
if (!fs.existsSync(dir)) {
|
|
58
|
+
console.error(
|
|
59
|
+
explicit
|
|
60
|
+
? `capa-check-bundle: ${dir} does not exist.`
|
|
61
|
+
: "capa-check-bundle: .next does not exist. Run it after next build, from the app's directory, or name the directory to scan.",
|
|
62
|
+
);
|
|
63
|
+
return 2;
|
|
64
|
+
}
|
|
65
|
+
const label = dir.replace(/[\\/]+$/, "");
|
|
66
|
+
const build = isNextBuildDir(dir);
|
|
67
|
+
const { keys, shaped } = splitFindings(build ? scanNextBuildForWriteKeys(dir) : scanForWriteKeys(dir));
|
|
68
|
+
scanned.push(build ? `${label} (static files and prerendered pages)` : label);
|
|
69
|
+
if (shaped.length > 0) console.error(writeKeyShapeWarning(shaped, label));
|
|
70
|
+
if (keys.length > 0) {
|
|
71
|
+
found += keys.length;
|
|
72
|
+
console.error(writeKeyReport(keys, label));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
if (found > 0) return 1;
|
|
76
|
+
console.log(`capa-check-bundle: no Capa write key in ${scanned.join(", ")}.`);
|
|
77
|
+
return 0;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
process.exitCode = main(process.argv.slice(2));
|
package/bin/capa.js
CHANGED
|
@@ -15,10 +15,10 @@
|
|
|
15
15
|
* literal is sent as written, so its own text is stored too, as
|
|
16
16
|
* `<Name> (literal)`.
|
|
17
17
|
*
|
|
18
|
-
* CAPA_API_URL=https://
|
|
18
|
+
* CAPA_API_URL=https://cdn.capacms.com CAPA_DRAFT_KEY=cap_test_... capa persist [--documents src] [--manifest persisted.json]
|
|
19
19
|
*
|
|
20
20
|
* Two things must hold for a document to be stored (spec 17, amendment 28).
|
|
21
|
-
* The POST reaches the host that stores documents:
|
|
21
|
+
* The POST reaches the host that stores documents: cdn.capacms.com sends
|
|
22
22
|
* every POST there, and a self-hosted stack whose read host stores nothing
|
|
23
23
|
* names the other host in CAPA_ADMIN_URL, which wins over CAPA_API_URL. And
|
|
24
24
|
* the key is a development key, since a production key ships in site
|
|
@@ -177,7 +177,7 @@ async function persist() {
|
|
|
177
177
|
if (declined === rows.length && rows.length) {
|
|
178
178
|
console.error(
|
|
179
179
|
`capa persist: ${api.baseUrl} stored nothing. A host that serves reads only runs documents but never stores one: ` +
|
|
180
|
-
"set CAPA_ADMIN_URL to the API host your Capa admin uses (https://
|
|
180
|
+
"set CAPA_ADMIN_URL to the API host your Capa admin uses (https://cdn.capacms.com sends every POST there), " +
|
|
181
181
|
`and make ${api.keyName} a development key.`,
|
|
182
182
|
);
|
|
183
183
|
}
|
package/bin/graphql-project.js
CHANGED
|
@@ -56,7 +56,7 @@ function firstSet(env, names) {
|
|
|
56
56
|
* Capa tool reads, with `CAPA_BASE_URL` and `CAPA_API_KEY` as aliases.
|
|
57
57
|
*
|
|
58
58
|
* With `admin` (for `capa persist`): the host is `CAPA_ADMIN_URL` when it is
|
|
59
|
-
* set, else `CAPA_API_URL`. `https://
|
|
59
|
+
* set, else `CAPA_API_URL`. `https://cdn.capacms.com` sends every POST to the
|
|
60
60
|
* host that stores persisted documents, so a site's own URL registers them; a
|
|
61
61
|
* self-hosted stack whose read host stores nothing names its admin host in
|
|
62
62
|
* `CAPA_ADMIN_URL`. The key is the development key, `CAPA_DRAFT_KEY` as
|
package/dist/client.d.ts
CHANGED
|
@@ -28,7 +28,68 @@ export interface ListOptions {
|
|
|
28
28
|
*/
|
|
29
29
|
where?: Record<string, string | number | boolean>;
|
|
30
30
|
}
|
|
31
|
-
|
|
31
|
+
/**
|
|
32
|
+
* One field of a `/v2/api` entry as Capa stores it: `{ type, value, sortOrder }`.
|
|
33
|
+
* A relation field's `value` is the related entry's id, or a list of ids.
|
|
34
|
+
*/
|
|
35
|
+
export interface FieldValue<V = unknown> {
|
|
36
|
+
type?: string;
|
|
37
|
+
value: V;
|
|
38
|
+
sortOrder?: number;
|
|
39
|
+
[key: string]: unknown;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* One entry of `relations`: a related entry as `/v2/api` sends it.
|
|
43
|
+
*
|
|
44
|
+
* Unlike a row of `data`, it keeps its fields under `data` only, so `id` is
|
|
45
|
+
* always the entry's UUID and `title` the served version's title, whatever the
|
|
46
|
+
* model's fields are called. `modelType` is its model's namespace. The API
|
|
47
|
+
* sends more columns than these (`tenantId`, `tags`, `dataModel`, its
|
|
48
|
+
* versions), and they come through as sent.
|
|
49
|
+
*/
|
|
50
|
+
export interface RelatedEntry<D = Record<string, FieldValue>> {
|
|
51
|
+
id: string;
|
|
52
|
+
modelId: string;
|
|
53
|
+
/** The related entry's model namespace. */
|
|
54
|
+
modelType: string;
|
|
55
|
+
title: string | null;
|
|
56
|
+
data: D;
|
|
57
|
+
createdAt: string;
|
|
58
|
+
updatedAt: string;
|
|
59
|
+
[key: string]: unknown;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* A read's related entries by entry id, at every level down to `depth`, each
|
|
63
|
+
* once however many rows name it. `{}` at depth 0, the default. An id a row
|
|
64
|
+
* holds with no entry here is one the key cannot read: unpublished for a
|
|
65
|
+
* production key, or deleted.
|
|
66
|
+
*/
|
|
67
|
+
export type Relations<R = RelatedEntry> = Record<string, R>;
|
|
68
|
+
/**
|
|
69
|
+
* `getContentById` and `findOne` with `withRelations: true`: the row they
|
|
70
|
+
* return without it, and what the same answer carried beside it.
|
|
71
|
+
*/
|
|
72
|
+
export interface OneWithRelations<T, R = RelatedEntry> {
|
|
73
|
+
data: T;
|
|
74
|
+
/** The row's instance id, read as `Page.ids` reads it (`instanceIdOf`). */
|
|
75
|
+
id: string | null;
|
|
76
|
+
relations: Relations<R>;
|
|
77
|
+
meta: Page<T>["meta"];
|
|
78
|
+
cacheTags: string[];
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* What `getContentById` and `findOne` take. A literal `withRelations: true`
|
|
82
|
+
* types the result as `OneWithRelations`, a literal `false` or none as the row,
|
|
83
|
+
* and a `boolean` (or a value of this type) as either.
|
|
84
|
+
*/
|
|
85
|
+
export interface ReadOneOptions extends Pick<ListOptions, "depth"> {
|
|
86
|
+
/**
|
|
87
|
+
* Return `{ data, id, relations, meta, cacheTags }` in place of the row, so
|
|
88
|
+
* its related entries can be read. Sent nowhere: the request is the same.
|
|
89
|
+
*/
|
|
90
|
+
withRelations?: boolean;
|
|
91
|
+
}
|
|
92
|
+
export interface Page<T, R = RelatedEntry> {
|
|
32
93
|
data: T[];
|
|
33
94
|
/**
|
|
34
95
|
* Instance ids positionally matching `data`, `null` only when the API sent
|
|
@@ -36,6 +97,11 @@ export interface Page<T> {
|
|
|
36
97
|
* which is the model's own field whenever one is named `id`.
|
|
37
98
|
*/
|
|
38
99
|
ids: (string | null)[];
|
|
100
|
+
/**
|
|
101
|
+
* The related entries of `data`, by id: `page.relations[row.data.author.value]`.
|
|
102
|
+
* Read with `depth` of 1 or more; see `Relations`.
|
|
103
|
+
*/
|
|
104
|
+
relations: Relations<R>;
|
|
39
105
|
meta: {
|
|
40
106
|
total?: number;
|
|
41
107
|
totalPages?: number;
|
|
@@ -48,9 +114,23 @@ export interface Page<T> {
|
|
|
48
114
|
cacheTags: string[];
|
|
49
115
|
}
|
|
50
116
|
export interface CapaClient {
|
|
51
|
-
listContent<T = Record<string, unknown
|
|
52
|
-
getContentById<T = Record<string, unknown
|
|
53
|
-
|
|
117
|
+
listContent<T = Record<string, unknown>, R = RelatedEntry>(namespace: string, options?: ListOptions): Promise<Page<T, R>>;
|
|
118
|
+
getContentById<T = Record<string, unknown>, R = RelatedEntry>(namespace: string, id: string, options: ReadOneOptions & {
|
|
119
|
+
withRelations: true;
|
|
120
|
+
}): Promise<OneWithRelations<T, R> | null>;
|
|
121
|
+
getContentById<T = Record<string, unknown>>(namespace: string, id: string, options?: ReadOneOptions & {
|
|
122
|
+
withRelations?: false;
|
|
123
|
+
}): Promise<T | null>;
|
|
124
|
+
/** A `ReadOneOptions` value, or a `withRelations` known only at run time: either shape. */
|
|
125
|
+
getContentById<T = Record<string, unknown>, R = RelatedEntry>(namespace: string, id: string, options?: ReadOneOptions): Promise<T | OneWithRelations<T, R> | null>;
|
|
126
|
+
findOne<T = Record<string, unknown>, R = RelatedEntry>(namespace: string, where: Record<string, string | number | boolean>, options: ReadOneOptions & {
|
|
127
|
+
withRelations: true;
|
|
128
|
+
}): Promise<OneWithRelations<T, R> | null>;
|
|
129
|
+
findOne<T = Record<string, unknown>>(namespace: string, where: Record<string, string | number | boolean>, options?: ReadOneOptions & {
|
|
130
|
+
withRelations?: false;
|
|
131
|
+
}): Promise<T | null>;
|
|
132
|
+
/** A `ReadOneOptions` value, or a `withRelations` known only at run time: either shape. */
|
|
133
|
+
findOne<T = Record<string, unknown>, R = RelatedEntry>(namespace: string, where: Record<string, string | number | boolean>, options?: ReadOneOptions): Promise<T | OneWithRelations<T, R> | null>;
|
|
54
134
|
search(q: string, options?: {
|
|
55
135
|
namespace?: string;
|
|
56
136
|
limit?: number;
|
package/dist/client.js
CHANGED
|
@@ -65,6 +65,14 @@ function contentQuery(options = {}) {
|
|
|
65
65
|
q[k] = v;
|
|
66
66
|
return q;
|
|
67
67
|
}
|
|
68
|
+
/**
|
|
69
|
+
* A content answer as a `Page`. A `structure=tree` answer (asked for through
|
|
70
|
+
* `where`) carries no relations map, and gets `{}`.
|
|
71
|
+
*/
|
|
72
|
+
function pageOf(body, cacheTags) {
|
|
73
|
+
const rows = body.data ?? [];
|
|
74
|
+
return { data: rows, ids: rows.map(instanceIdOf), relations: body.relations ?? {}, meta: body.meta ?? {}, cacheTags };
|
|
75
|
+
}
|
|
68
76
|
/**
|
|
69
77
|
* `/v2` answers every `cap_` key "Invalid API key", which reads as a bad key
|
|
70
78
|
* rather than the wrong client, so one is refused here before the tenant id is
|
|
@@ -85,11 +93,20 @@ function createClient(config) {
|
|
|
85
93
|
const resolved = (0, config_1.resolveConfig)(config);
|
|
86
94
|
async function listContent(namespace, options = {}) {
|
|
87
95
|
const { body, cacheTags } = await (0, http_1.getJson)(resolved, `/v2/api/${encodeURIComponent(namespace)}`, contentQuery(options));
|
|
88
|
-
|
|
89
|
-
|
|
96
|
+
return pageOf(body, cacheTags);
|
|
97
|
+
}
|
|
98
|
+
/** The first row of a page: alone, or with what the answer carried beside it. */
|
|
99
|
+
function one(page, options) {
|
|
100
|
+
const row = page.data[0];
|
|
101
|
+
if (row === undefined)
|
|
102
|
+
return null;
|
|
103
|
+
if (options.withRelations !== true)
|
|
104
|
+
return row;
|
|
105
|
+
return { data: row, id: page.ids[0] ?? null, relations: page.relations, meta: page.meta, cacheTags: page.cacheTags };
|
|
90
106
|
}
|
|
91
107
|
return {
|
|
92
108
|
listContent,
|
|
109
|
+
// `Promise<any>` here and on findOne: CapaClient's overloads type the result by `withRelations`.
|
|
93
110
|
async getContentById(namespace, id, options = {}) {
|
|
94
111
|
// Fail here rather than spending a request on a guaranteed 400. See
|
|
95
112
|
// instanceIdOf: for a shadowing model, the "id" on a listContent row is
|
|
@@ -100,8 +117,8 @@ function createClient(config) {
|
|
|
100
117
|
`of \`row.id\`: the model "${namespace}" has a field named "id" that overwrites the ` +
|
|
101
118
|
`instance id in that response. See #4628.`);
|
|
102
119
|
}
|
|
103
|
-
const { body } = await (0, http_1.getJson)(resolved, `/v2/api/${encodeURIComponent(namespace)}`, { ids: id, depth: options.depth, limit: 1 });
|
|
104
|
-
return (body
|
|
120
|
+
const { body, cacheTags } = await (0, http_1.getJson)(resolved, `/v2/api/${encodeURIComponent(namespace)}`, { ids: id, depth: options.depth, limit: 1 });
|
|
121
|
+
return one(pageOf(body, cacheTags), options);
|
|
105
122
|
},
|
|
106
123
|
/**
|
|
107
124
|
* One row matched by field values — `findOne("shopify_page", {handle})`.
|
|
@@ -114,8 +131,9 @@ function createClient(config) {
|
|
|
114
131
|
* the right fix, and belongs in Capa rather than here.
|
|
115
132
|
*/
|
|
116
133
|
async findOne(namespace, where, options = {}) {
|
|
134
|
+
// `withRelations` rides along in the spread; contentQuery sends only the keys it knows.
|
|
117
135
|
const page = await listContent(namespace, { ...options, where, limit: 1 });
|
|
118
|
-
return page
|
|
136
|
+
return one(page, options);
|
|
119
137
|
},
|
|
120
138
|
async search(q, options = {}) {
|
|
121
139
|
const text = String(q ?? "").trim();
|
|
@@ -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
|
-
*
|
|
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;
|
package/dist/esm/image/index.js
CHANGED
|
@@ -9,19 +9,24 @@
|
|
|
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
|
-
*
|
|
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 { canonicalQuery, LEGACY_PARAMS, MAX_OUTPUT_EDGE, NEW_PARAMS, parseImageParams, } from "./shared-params.generated.js";
|
|
29
|
+
import { canonicalQuery, FOCAL_PARAMS, LEGACY_PARAMS, MAX_OUTPUT_EDGE, NEW_PARAMS, parseFocalParams, parseImageParams, readCrop, readFocalPoint, } from "./shared-params.generated.js";
|
|
25
30
|
export { MAX_OUTPUT_EDGE };
|
|
26
31
|
/** Where Capa serves files. A media `url` from the API starts with this and `/files/`. */
|
|
27
32
|
export const CAPA_CDN_ORIGIN = "https://cdn.capacms.com";
|
|
@@ -63,20 +68,31 @@ function positive(value) {
|
|
|
63
68
|
function hasScheme(text) {
|
|
64
69
|
return /^[a-z][a-z0-9+.-]*:/i.test(text);
|
|
65
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
|
+
}
|
|
66
82
|
/** A string or `url` as a Capa image, or why not. */
|
|
67
83
|
function resolveUrl(text, image) {
|
|
68
84
|
if (hasScheme(text)) {
|
|
69
85
|
const url = capaFileUrl(text);
|
|
70
86
|
if (url === null)
|
|
71
87
|
return { unchanged: text };
|
|
72
|
-
return { target: { url,
|
|
88
|
+
return { target: { url, ...known(image) } };
|
|
73
89
|
}
|
|
74
90
|
// A path (`/logo.png`, `//host/x`) is the site's own or another host's.
|
|
75
91
|
if (text === "" || text.startsWith("/"))
|
|
76
92
|
return { unchanged: text };
|
|
77
93
|
// A file key, which may hold folders: each segment is encoded on its own.
|
|
78
94
|
const path = text.split("/").map(encodeURIComponent).join("/");
|
|
79
|
-
return { target: { url: new URL(`${CAPA_CDN_ORIGIN}${FILES_PATH}${path}`),
|
|
95
|
+
return { target: { url: new URL(`${CAPA_CDN_ORIGIN}${FILES_PATH}${path}`), ...known(image) } };
|
|
80
96
|
}
|
|
81
97
|
function resolve(image) {
|
|
82
98
|
if (image === null || image === undefined)
|
|
@@ -162,10 +178,65 @@ function build(fn, target, options) {
|
|
|
162
178
|
const parsed = parseImageParams(query);
|
|
163
179
|
if (!parsed.ok)
|
|
164
180
|
fail(fn, parsed.rejection.error);
|
|
165
|
-
const
|
|
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 });
|
|
166
185
|
const href = `${url.origin}${url.pathname}${canonical ? `?${canonical}` : ""}${url.hash}`;
|
|
167
186
|
return { href, width: parsed.params.width };
|
|
168
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
|
+
}
|
|
169
240
|
export function imageUrl(image, options = {}) {
|
|
170
241
|
const resolved = resolve(image);
|
|
171
242
|
if (resolved === null)
|
|
@@ -216,6 +287,8 @@ export function srcSet(image, widths, options = {}) {
|
|
|
216
287
|
fit: options.fit,
|
|
217
288
|
quality: options.quality,
|
|
218
289
|
format: options.format,
|
|
290
|
+
focalPoint: options.focalPoint,
|
|
291
|
+
crop: options.crop,
|
|
219
292
|
});
|
|
220
293
|
if (seen.has(href))
|
|
221
294
|
continue;
|
|
@@ -248,3 +321,33 @@ export function sizes(breakpoints, fallback = "100vw") {
|
|
|
248
321
|
rules.sort(([a], [b]) => b - a);
|
|
249
322
|
return [...rules.map(([px, size]) => `(min-width: ${px}px) ${size}`), fallback.trim()].join(", ");
|
|
250
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
|
+
}
|