@capacms/sdk 1.0.0-next.14 → 1.0.0-next.15
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 +33 -0
- package/README.md +71 -1
- package/bin/capa-codegen.js +90 -8
- package/bin/capa.js +1 -1
- package/dist/codegen.d.ts +62 -4
- package/dist/codegen.js +216 -7
- package/dist/index.d.ts +1 -1
- package/dist/next/entry-fields.d.ts +6 -7
- package/dist/next/index.d.ts +1 -1
- package/dist/next/select-types.d.ts +43 -4
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,39 @@
|
|
|
2
2
|
|
|
3
3
|
## Unreleased
|
|
4
4
|
|
|
5
|
+
## 1.0.0-next.15
|
|
6
|
+
|
|
7
|
+
Published 2026-11-17. New since 1.0.0-next.14: `capa-codegen --shape api` (or `{ shape: "api" }` in code), an opt-in mode that writes types as `/api/` returns them: fields that can be null say so, required fields are no longer optional, enums are their options with a pk_ key, and media carry their real fields. Without the flag the output is byte for byte what it was.
|
|
8
|
+
|
|
9
|
+
- `capa-codegen --shape api`, new and opt-in, writes each model's interface
|
|
10
|
+
as the `fields` an `/api/entries` read with no select returns. Every field
|
|
11
|
+
is there and `null` when empty (`title: string | null`, not
|
|
12
|
+
`title?: string`), a required field included, since an entry saved before
|
|
13
|
+
the field was made required reads `null` there. A list is `T[] | null`.
|
|
14
|
+
With a `pk_` key, an enum is the union of its options plus `""`, which a
|
|
15
|
+
cleared select saves. With a `cap_` key it stays a `string`, since GraphQL
|
|
16
|
+
names the options only in prose that cannot be read back exactly. Media is
|
|
17
|
+
`CapaMedia`, which `CapaImage`, `CapaVideo` and `CapaFile` name: `id`,
|
|
18
|
+
`url`, `alt`, `type`, `width`, `height`, and the placeholders and focal
|
|
19
|
+
point where the project has them, without the `filename`, `filesize`,
|
|
20
|
+
`thumbnail` and `duration` the API never sends. A relation is the `{ id, model }` reference, a
|
|
21
|
+
relation list `{ items, pageInfo }` and never `null`, and a typed select
|
|
22
|
+
still expands both. In code, `generate(config, existing, { shape: "api" })`
|
|
23
|
+
and `restTypesFromIntrospection(introspection, { shape: "api" })`. The
|
|
24
|
+
default, `--shape legacy`, is unchanged byte for byte, so regenerating
|
|
25
|
+
without the flag changes nothing. The new file imports two type-only
|
|
26
|
+
brands from `@capacms/sdk/next`, `CapaRelationBrand` and
|
|
27
|
+
`CapaReferenceListBrand`, keyed by symbols the SDK declares. To read them,
|
|
28
|
+
the conditional types behind `Select<T>`, `EntryFields<T, S>`,
|
|
29
|
+
`FlatFields` and `IncludedFields` are rewritten, so their published `.d.ts`
|
|
30
|
+
changes. A type without the brands reads exactly as before, whatever its
|
|
31
|
+
keys are called: a hand-written `{ items, pageInfo }`, a field named
|
|
32
|
+
`__capaReferenceList` or `__capaRelation`, and media included. The file
|
|
33
|
+
must resolve the same `@capacms/sdk` as the app: with two installed
|
|
34
|
+
versions, a select that expands a relation fails to typecheck, so dedupe
|
|
35
|
+
the SDK (`pnpm dedupe`, `npm dedupe`) or pin one version. `--shape api`
|
|
36
|
+
warns when it finds more than one version near the file.
|
|
37
|
+
|
|
5
38
|
## 1.0.0-next.14
|
|
6
39
|
|
|
7
40
|
Published 2026-11-17. New since 1.0.0-next.13: `@capacms/sdk/sanitize`, an opt-in helper that makes an html field safe to render (it needs the new optional peer `sanitize-html`); the overlay scrolls at once for a viewer who asked for less motion; a release preview link to a release that is already done opens on the live site with a banner sentence; `createPreviewRoute` ends the release cookie when its link expires; and `releasePreviewBar` names the releases a page shows.
|
package/README.md
CHANGED
|
@@ -1501,6 +1501,75 @@ system key even on a model with a field of the same plain name
|
|
|
1501
1501
|
A `$` name that is no system key fails to compile. A field whose namespace
|
|
1502
1502
|
starts with `$` cannot be named, so `select: "*"` is how to read it.
|
|
1503
1503
|
|
|
1504
|
+
### The fields as `/api/` returns them: `--shape api`
|
|
1505
|
+
|
|
1506
|
+
By default, `capa-codegen` writes the `/v2` schema's interfaces, byte for
|
|
1507
|
+
byte what earlier versions wrote, so regenerating the file breaks no build.
|
|
1508
|
+
`--shape api` is the opt-in alternative. It writes each model's interface as
|
|
1509
|
+
the `fields` an `/api/entries` read with no select returns, so the type
|
|
1510
|
+
matches the JSON your code receives. It works with a `pk_` key, a `cap_` key
|
|
1511
|
+
and `--schema`.
|
|
1512
|
+
|
|
1513
|
+
```sh
|
|
1514
|
+
capa-codegen --out src/capa-types.ts --shape api
|
|
1515
|
+
capa-codegen --out src/capa-types.ts --shape api --check
|
|
1516
|
+
```
|
|
1517
|
+
|
|
1518
|
+
In code, pass `{ shape: "api" }` as the last argument of `generate` or
|
|
1519
|
+
`restTypesFromIntrospection`. `--shape legacy`, or `shape: "legacy"`, is the
|
|
1520
|
+
default. Here is what changes:
|
|
1521
|
+
|
|
1522
|
+
- Every field is there, and `null` when it is empty: `title: string | null`
|
|
1523
|
+
instead of `title?: string`. A required field is typed the same way. Capa
|
|
1524
|
+
checks `required` when an entry is saved, so an entry saved before a field
|
|
1525
|
+
was made required reads `null` there.
|
|
1526
|
+
- A list is `string[] | null`. The API sends `[]` or `null`, depending on
|
|
1527
|
+
how the list was saved.
|
|
1528
|
+
- With a `pk_` key, an enum is the union of its options, plus `""`, which a
|
|
1529
|
+
cleared select saves: `size: "small" | "medium" | "large" | "" | null`. An
|
|
1530
|
+
item of an enum list is only one of the options. An enum with no options
|
|
1531
|
+
is a `string`.
|
|
1532
|
+
- Media is `CapaMedia`, and `CapaImage`, `CapaVideo` and `CapaFile` name it:
|
|
1533
|
+
`id`, `url`, `alt`, `type`, `width` and `height`, each but `id` possibly
|
|
1534
|
+
`null`. The image placeholders and the focal point and crop are optional
|
|
1535
|
+
keys, there when the project has them. `filename`, `filesize`, `thumbnail`
|
|
1536
|
+
and `duration` are gone, since the API never sends them.
|
|
1537
|
+
- A relation is `CapaRelation<Author> | null`, the reference `{ id, model }`.
|
|
1538
|
+
A relation list is `CapaRelationList<Author>`, the `{ items, pageInfo }` of
|
|
1539
|
+
references, and never `null`. A relation into a model the file does not
|
|
1540
|
+
have is a `CapaReference` or a `CapaReferenceList`. The helpers still name
|
|
1541
|
+
the related model, so a typed select can expand a relation and the read
|
|
1542
|
+
types the expanded entry, as under Typed reads.
|
|
1543
|
+
- There is no `CapaInstance`. Type a whole entry as `Entry<Article>` from
|
|
1544
|
+
`@capacms/sdk/next`.
|
|
1545
|
+
|
|
1546
|
+
With a `cap_` key, an enum is a `string`, or `string[]` for a list. The key
|
|
1547
|
+
reads its models from the GraphQL schema, which types an enum as text and
|
|
1548
|
+
names its options only in a description written for people. That text cannot
|
|
1549
|
+
be read back exactly: an option can hold `, ` or a line break. A wrong union
|
|
1550
|
+
would refuse values the API sends, so the type stays wide. Use a `pk_` key to
|
|
1551
|
+
get the options as unions.
|
|
1552
|
+
|
|
1553
|
+
The file names its shape in its header, so a run that asks for the other
|
|
1554
|
+
shape writes the file again, even when the schema has not changed. Pass the
|
|
1555
|
+
same `--shape` to `--check` as to the run that wrote the file.
|
|
1556
|
+
|
|
1557
|
+
The file has one import, type-only: `CapaRelationBrand` and
|
|
1558
|
+
`CapaReferenceListBrand` from `@capacms/sdk/next`. They mark the relation
|
|
1559
|
+
helpers for the SDK's typed reads, keyed by symbols only the SDK declares,
|
|
1560
|
+
so no type of yours carries them by accident. Nothing of them is sent or
|
|
1561
|
+
received.
|
|
1562
|
+
|
|
1563
|
+
So the generated file must resolve the same copy of `@capacms/sdk` as your
|
|
1564
|
+
app. Two installed versions declare two sets of symbols, and the app's copy
|
|
1565
|
+
cannot see the file's brands. Plain reads still compile, but a select that
|
|
1566
|
+
expands a relation, such as `[{ author: ["name"] }]`, fails to typecheck, the
|
|
1567
|
+
expanded entry is not typed, and a `CapaReferenceList` reads as nullable.
|
|
1568
|
+
`npm ls @capacms/sdk` or `pnpm why @capacms/sdk` shows the copies. Dedupe them
|
|
1569
|
+
with `pnpm dedupe` or `npm dedupe`, or pin one version.
|
|
1570
|
+
`capa-codegen --shape api` warns when it finds more than one version near the
|
|
1571
|
+
file it writes.
|
|
1572
|
+
|
|
1504
1573
|
## Pages and preview
|
|
1505
1574
|
|
|
1506
1575
|
Capa can tell you which of **your** pages read which entries, and it can open a
|
|
@@ -2542,7 +2611,8 @@ writes the same interfaces from the key's GraphQL schema, with no tenant id,
|
|
|
2542
2611
|
and so does `--schema <file>`, a schema `capa-codegen --graphql --save-schema`
|
|
2543
2612
|
wrote. GraphQL does not say three things, so those types say less: every
|
|
2544
2613
|
field is optional, an enum is a `string`, and a field GraphQL leaves out is
|
|
2545
|
-
`unknown`.
|
|
2614
|
+
`unknown`. `--shape api` writes the fields as `/api/` returns them instead
|
|
2615
|
+
(see Typed select and codegen). There is no `CAPA_SCHEMA_CHECKSUM`, since that is the `/v2`
|
|
2546
2616
|
schema's checksum. Where the API does not serve GraphQL, use a `pk_` key. It
|
|
2547
2617
|
reads `.env.local` and `.env` too, as `next dev` does.
|
|
2548
2618
|
|
package/bin/capa-codegen.js
CHANGED
|
@@ -25,13 +25,19 @@
|
|
|
25
25
|
* minute). `--save-schema <file>` writes the schema it read, for a later
|
|
26
26
|
* `--schema <file>` run with no key, as in CI.
|
|
27
27
|
*
|
|
28
|
+
* `--shape api` writes each model's fields as /api/entries returns them with
|
|
29
|
+
* no select (every field there and null when empty, media and relations in
|
|
30
|
+
* the read's shape, an enum as its options with a pk_ key and a string with
|
|
31
|
+
* a cap_ key or `--schema`), for any of the three. Without it, or with `--shape legacy`, the file is the /v2
|
|
32
|
+
* schema's interfaces, exactly as before.
|
|
33
|
+
*
|
|
28
34
|
* Exit codes: 0 wrote or already current, 1 failed, 2 --check found a diff.
|
|
29
35
|
* `--check` is the CI mode: it fails when the committed file is out of date
|
|
30
36
|
* with the tenant's schema, which is the whole point of committing it.
|
|
31
37
|
*/
|
|
32
38
|
const fs = require("node:fs");
|
|
33
39
|
const path = require("node:path");
|
|
34
|
-
const { generate } = require("../dist/codegen.js");
|
|
40
|
+
const { codegenShape, generate } = require("../dist/codegen.js");
|
|
35
41
|
const { loadProjectEnv } = require("./project-env.js");
|
|
36
42
|
|
|
37
43
|
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
@@ -41,6 +47,77 @@ function arg(name, fallback) {
|
|
|
41
47
|
return i === -1 ? fallback : process.argv[i + 1];
|
|
42
48
|
}
|
|
43
49
|
|
|
50
|
+
/** `--shape`: "legacy" when left out. A flag with no value, or any other value, is refused. */
|
|
51
|
+
function shapeArg() {
|
|
52
|
+
const i = process.argv.indexOf("--shape");
|
|
53
|
+
if (i === -1) return "legacy";
|
|
54
|
+
return codegenShape(process.argv[i + 1] ?? "");
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A package's version, or "unknown" when its manifest cannot be read. */
|
|
58
|
+
function versionOf(manifest) {
|
|
59
|
+
try {
|
|
60
|
+
return String(JSON.parse(fs.readFileSync(manifest, "utf8")).version ?? "unknown");
|
|
61
|
+
} catch {
|
|
62
|
+
return "unknown";
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The versions of @capacms/sdk a module in `dir` can resolve, each with one
|
|
68
|
+
* place it was found: the copy in every node_modules above `dir`, and every
|
|
69
|
+
* version in a pnpm store there. Best effort: a copy nested inside another
|
|
70
|
+
* package's node_modules is not looked for.
|
|
71
|
+
*/
|
|
72
|
+
function sdkVersions(dir) {
|
|
73
|
+
const versions = new Map();
|
|
74
|
+
const add = (pkgDir) => {
|
|
75
|
+
const manifest = path.join(pkgDir, "package.json");
|
|
76
|
+
if (!fs.existsSync(manifest)) return;
|
|
77
|
+
const version = versionOf(manifest);
|
|
78
|
+
if (!versions.has(version)) versions.set(version, fs.realpathSync(pkgDir));
|
|
79
|
+
};
|
|
80
|
+
for (let at = path.resolve(dir); ; at = path.dirname(at)) {
|
|
81
|
+
const modules = path.join(at, "node_modules");
|
|
82
|
+
add(path.join(modules, "@capacms", "sdk"));
|
|
83
|
+
const store = path.join(modules, ".pnpm");
|
|
84
|
+
if (fs.existsSync(store)) {
|
|
85
|
+
for (const entry of fs.readdirSync(store).sort()) {
|
|
86
|
+
if (entry.startsWith("@capacms+sdk@")) add(path.join(store, entry, "node_modules", "@capacms", "sdk"));
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (path.dirname(at) === at) break;
|
|
90
|
+
}
|
|
91
|
+
return versions;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* An --shape api file's brands are symbols its own @capacms/sdk declares, so
|
|
96
|
+
* it must resolve the copy the app does. Two versions near it say it may not.
|
|
97
|
+
* TypeScript reads one name@version once, so two places of one version are one.
|
|
98
|
+
*/
|
|
99
|
+
function warnSdkCopies(out) {
|
|
100
|
+
let versions;
|
|
101
|
+
try {
|
|
102
|
+
versions = sdkVersions(path.dirname(path.resolve(process.cwd(), out)));
|
|
103
|
+
} catch {
|
|
104
|
+
// Best effort: an unreadable folder or a broken link never stops codegen.
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
if (versions.size < 2) return;
|
|
108
|
+
const list = [...versions].map(([version, at]) => `${version} (${path.relative(process.cwd(), at) || "."})`).join(", ");
|
|
109
|
+
console.error(
|
|
110
|
+
`capa-codegen: warning: more than one @capacms/sdk can be resolved near ${out}: ${list}. ` +
|
|
111
|
+
"An --shape api file must resolve the same copy as your app, or relation selects fail to typecheck. " +
|
|
112
|
+
"Dedupe @capacms/sdk (pnpm dedupe, npm dedupe) or pin one version.",
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The command that writes `out` again, as the user ran it. */
|
|
117
|
+
function rerun(out, shape) {
|
|
118
|
+
return `capa-codegen --out ${out}${shape === "api" ? " --shape api" : ""}`;
|
|
119
|
+
}
|
|
120
|
+
|
|
44
121
|
/** How often --watch looks at the documents, and reads the key's schema again. */
|
|
45
122
|
const WATCH_FILES_MS = 500;
|
|
46
123
|
const WATCH_SCHEMA_MS = 60_000;
|
|
@@ -162,7 +239,7 @@ async function graphqlMain(check) {
|
|
|
162
239
|
* the interfaces the /v2 schema gives a legacy key, for a cap_ key, which /v2
|
|
163
240
|
* refuses. Needs GraphQL on the API, and says so when it is off.
|
|
164
241
|
*/
|
|
165
|
-
async function restFromGraphQLMain(out, check) {
|
|
242
|
+
async function restFromGraphQLMain(out, check, shape) {
|
|
166
243
|
const { restTypesFromIntrospection } = require("../dist/codegen.js");
|
|
167
244
|
const { loadIntrospection } = require("./graphql-project.js");
|
|
168
245
|
let introspection;
|
|
@@ -176,7 +253,7 @@ async function restFromGraphQLMain(out, check) {
|
|
|
176
253
|
"set CAPA_KEY to a pk_ key and CAPA_TENANT_ID to read the /v2 schema instead.",
|
|
177
254
|
);
|
|
178
255
|
}
|
|
179
|
-
const result = restTypesFromIntrospection(introspection);
|
|
256
|
+
const result = restTypesFromIntrospection(introspection, { shape });
|
|
180
257
|
const omitted = result.restOnly;
|
|
181
258
|
if (omitted.length) {
|
|
182
259
|
const names = omitted.length === 1 ? omitted[0] : `${omitted.slice(0, -1).join(", ")} and ${omitted[omitted.length - 1]}`;
|
|
@@ -192,7 +269,7 @@ async function restFromGraphQLMain(out, check) {
|
|
|
192
269
|
return 0;
|
|
193
270
|
}
|
|
194
271
|
if (check) {
|
|
195
|
-
console.error(`capa-codegen: ${out} is OUT OF DATE with the key's GraphQL schema.\n Run:
|
|
272
|
+
console.error(`capa-codegen: ${out} is OUT OF DATE with the key's GraphQL schema.\n Run: ${rerun(out, shape)}`);
|
|
196
273
|
return 2;
|
|
197
274
|
}
|
|
198
275
|
fs.writeFileSync(target, result.source, "utf8");
|
|
@@ -203,20 +280,25 @@ async function restFromGraphQLMain(out, check) {
|
|
|
203
280
|
async function main() {
|
|
204
281
|
loadProjectEnv();
|
|
205
282
|
const check = process.argv.includes("--check");
|
|
206
|
-
if (process.argv.includes("--graphql"))
|
|
283
|
+
if (process.argv.includes("--graphql")) {
|
|
284
|
+
if (process.argv.includes("--shape")) throw new Error("--shape is for the REST types; --graphql writes the GraphQL schema's own.");
|
|
285
|
+
return graphqlMain(check);
|
|
286
|
+
}
|
|
287
|
+
const shape = shapeArg();
|
|
207
288
|
|
|
208
289
|
const out = arg("--out", "capa-types.ts");
|
|
290
|
+
if (shape === "api") warnSdkCopies(out);
|
|
209
291
|
const config = {
|
|
210
292
|
baseUrl: process.env.CAPA_API_URL || process.env.CAPA_BASE_URL || "",
|
|
211
293
|
apiKey: process.env.CAPA_KEY || process.env.CAPA_API_KEY || "",
|
|
212
294
|
tenantId: process.env.CAPA_TENANT_ID || "",
|
|
213
295
|
};
|
|
214
296
|
// /v2 reads legacy keys only: a cap_ key reads the same models over GraphQL.
|
|
215
|
-
if (config.apiKey.startsWith("cap_") || arg("--schema")) return restFromGraphQLMain(out, check);
|
|
297
|
+
if (config.apiKey.startsWith("cap_") || arg("--schema")) return restFromGraphQLMain(out, check, shape);
|
|
216
298
|
const target = path.resolve(process.cwd(), out);
|
|
217
299
|
const existing = fs.existsSync(target) ? fs.readFileSync(target, "utf8") : null;
|
|
218
300
|
|
|
219
|
-
const result = await generate(config, existing);
|
|
301
|
+
const result = await generate(config, existing, { shape });
|
|
220
302
|
|
|
221
303
|
if (!result.changed) {
|
|
222
304
|
console.log(`capa-codegen: ${out} is up to date (schema ${result.checksum ?? "unknown"}).`);
|
|
@@ -225,7 +307,7 @@ async function main() {
|
|
|
225
307
|
if (check) {
|
|
226
308
|
console.error(
|
|
227
309
|
`capa-codegen: ${out} is OUT OF DATE with the tenant schema (${result.checksum}).\n` +
|
|
228
|
-
` Run:
|
|
310
|
+
` Run: ${rerun(out, shape)}\n` +
|
|
229
311
|
` Types now present: ${result.types.join(", ")}`
|
|
230
312
|
);
|
|
231
313
|
return 2;
|
package/bin/capa.js
CHANGED
|
@@ -219,7 +219,7 @@ async function main() {
|
|
|
219
219
|
return result.status === null ? 1 : result.status;
|
|
220
220
|
}
|
|
221
221
|
console.error(
|
|
222
|
-
"usage: capa codegen [--
|
|
222
|
+
"usage: capa codegen [--out file] [--shape legacy|api] | capa codegen --graphql [--out file] | CAPA_API_URL=... CAPA_DRAFT_KEY=... capa persist [--documents src] [--manifest file] [--release id --env production]",
|
|
223
223
|
);
|
|
224
224
|
return 1;
|
|
225
225
|
}
|
package/dist/codegen.d.ts
CHANGED
|
@@ -37,6 +37,25 @@
|
|
|
37
37
|
*/
|
|
38
38
|
import { type CapaConfig } from "./config";
|
|
39
39
|
import type { CapaIntrospection } from "./next/graphql/introspection";
|
|
40
|
+
/**
|
|
41
|
+
* What a generated module types (ENG-5667).
|
|
42
|
+
*
|
|
43
|
+
* legacy the default: `/v2/schema/types`'s interfaces, byte for byte what
|
|
44
|
+
* every earlier version wrote, so a regenerated file breaks no build.
|
|
45
|
+
* api each model's `fields` as `/api/entries` returns them with no
|
|
46
|
+
* select (`apiTypes`): every field present and `null` when empty,
|
|
47
|
+
* media and relations in the read's shape, and an enum as its
|
|
48
|
+
* options where the schema says them exactly (a pk_ key's).
|
|
49
|
+
*/
|
|
50
|
+
export type CodegenShape = "legacy" | "api";
|
|
51
|
+
export interface CodegenOptions {
|
|
52
|
+
/** `"legacy"` when left out. */
|
|
53
|
+
shape?: CodegenShape;
|
|
54
|
+
}
|
|
55
|
+
/** The shape `options` asks for, `"legacy"` when it names none. */
|
|
56
|
+
export declare function codegenShape(shape: unknown): CodegenShape;
|
|
57
|
+
/** The shape a generated file was written in: `"api"` when it says so, `"legacy"` otherwise. */
|
|
58
|
+
export declare function readStampedShape(existing: string | null | undefined): CodegenShape;
|
|
40
59
|
export interface CodegenResult {
|
|
41
60
|
/** False when the schema checksum was unchanged and nothing was fetched. */
|
|
42
61
|
changed: boolean;
|
|
@@ -79,14 +98,14 @@ export declare function interfaceName(written: string): string;
|
|
|
79
98
|
* cannot declare an alias twice. Every model caught in such a collision is
|
|
80
99
|
* named by `namespaceInterface` instead, whatever order the models come in.
|
|
81
100
|
*/
|
|
82
|
-
export declare function modelInterfaceNames(models: readonly SchemaModel[]): Map<string, string>;
|
|
101
|
+
export declare function modelInterfaceNames(models: readonly SchemaModel[], shared?: readonly string[]): Map<string, string>;
|
|
83
102
|
export declare function normalizeTypes(source: string, checksum: string | null, schema?: SchemaForTypes | null): string;
|
|
84
103
|
export declare function typeNames(source: string): string[];
|
|
85
104
|
/**
|
|
86
105
|
* Fetch types if — and only if — the tenant's schema has changed since the
|
|
87
|
-
* checksum stamped in `existing
|
|
106
|
+
* checksum stamped in `existing`, or `existing` is in the other shape.
|
|
88
107
|
*/
|
|
89
|
-
export declare function generate(config: CapaConfig, existing?: string | null): Promise<CodegenResult>;
|
|
108
|
+
export declare function generate(config: CapaConfig, existing?: string | null, options?: CodegenOptions): Promise<CodegenResult>;
|
|
90
109
|
/**
|
|
91
110
|
* `/v2/schema/types`'s type map and preamble, so a `cap_` key, which `/v2`
|
|
92
111
|
* does not take, gets the interfaces a legacy key gets. Copied from
|
|
@@ -120,5 +139,44 @@ export interface RestTypesResult {
|
|
|
120
139
|
* no values; and a field GraphQL leaves out (its description's `Not exposed:`
|
|
121
140
|
* line) is `unknown`. No checksum is stamped: `CAPA_SCHEMA_CHECKSUM` is the
|
|
122
141
|
* `/v2/schema` checksum, which a `cap_` key cannot read.
|
|
142
|
+
*
|
|
143
|
+
* `shape: "api"` writes `apiTypes` from the same models instead, each enum
|
|
144
|
+
* a `string` (`apiModelsFromSummary`).
|
|
145
|
+
*/
|
|
146
|
+
export declare function restTypesFromIntrospection(introspection: CapaIntrospection, options?: CodegenOptions): RestTypesResult;
|
|
147
|
+
/**
|
|
148
|
+
* The declarations every `api` module holds beside its models, written as
|
|
149
|
+
* `/api/entries` returns each value (apps/api/src/api-next/entries/shape.ts):
|
|
150
|
+
*
|
|
151
|
+
* media `renderMedia`: the six keys every image, video and file has,
|
|
152
|
+
* then the placeholders and the focal point and crop, which are
|
|
153
|
+
* on every media value of a project that has them and absent from
|
|
154
|
+
* one that does not. `EntryMedia` in `@capacms/sdk/next`.
|
|
155
|
+
* relations a read with no select, or `*`, does not expand them: a
|
|
156
|
+
* relation is `{ id, model }` (`renderSingleRelation`), a relation
|
|
157
|
+
* list `{ items, pageInfo }`, never null (`renderArrayRelation`).
|
|
158
|
+
* The brand is optional, so the reference the API sends is the
|
|
159
|
+
* type, and it still names the related model for `Select<T>` and
|
|
160
|
+
* `EntryFields<T, S>`, which type an expanded read. A list into a
|
|
161
|
+
* model the module lacks carries `CapaReferenceListBrand`
|
|
162
|
+
* instead, which is how `EntryFields` knows it is never null.
|
|
163
|
+
* Both brands are keyed by symbols `@capacms/sdk/next` declares
|
|
164
|
+
* (next/select-types.ts), imported type-only (`API_IMPORT`).
|
|
165
|
+
*/
|
|
166
|
+
export declare const API_PREAMBLE = "/**\n * An image, video or file, as /api/ returns it. The keys after `height` are\n * there when the project has image placeholders or focal points and crops,\n * and null for a file without one.\n */\nexport interface CapaMedia {\n id: string;\n url: string | null;\n alt: string | null;\n type: string | null;\n width: number | null;\n height: number | null;\n blurDataURL?: string | null;\n averageColor?: string | null;\n dominantColor?: string | null;\n palette?: string[] | null;\n blurhash?: string | null;\n focalPoint?: { x: number; y: number } | null;\n crop?: { x: number; y: number; width: number; height: number } | null;\n}\n\nexport type CapaImage = CapaMedia;\nexport type CapaVideo = CapaMedia;\nexport type CapaFile = CapaMedia;\n\n/** A relation a read did not expand: the entry's id, and its model's namespace, null when the key cannot read that model. */\nexport interface CapaReference {\n id: string;\n model: string | null;\n}\n\n/**\n * A relation list a read did not expand. `limit` is there when a read\n * expands it. Never null, which its type-only brand tells the SDK's typed reads.\n */\nexport interface CapaReferenceList extends CapaReferenceListBrand {\n items: CapaReference[];\n pageInfo: { limit?: number; hasNext: boolean; next: string | null };\n}\n\n/** A relation to a model of this file: a reference, branded with the model a select can expand it into. */\nexport type CapaRelation<T> = CapaReference & CapaRelationBrand<\"one\", T>;\nexport type CapaRelationList<T> = CapaReferenceList & CapaRelationBrand<\"many\", T>;\n";
|
|
167
|
+
/**
|
|
168
|
+
* An `api` module: each model's interface is its entries' `fields` as
|
|
169
|
+
* `/api/entries` returns them to a read with no select, or `select=*`.
|
|
170
|
+
*
|
|
171
|
+
* Every field is there, since that read prints every field of the model, and
|
|
172
|
+
* every field but a relation list may be `null`: a field never saved, or
|
|
173
|
+
* emptied, reads null (`storedValue`), and so does a required one, since
|
|
174
|
+
* `required` is checked when an entry is saved, not when it is read, and an
|
|
175
|
+
* entry saved before the field was made required keeps no value for it. A
|
|
176
|
+
* list may read `[]` or `null`, as stored.
|
|
177
|
+
*
|
|
178
|
+
* Models and their `Select` and `Attrs` aliases are named and ordered as the
|
|
179
|
+
* legacy shape names and orders them (`modelInterfaceNames`). No `CapaInstance`:
|
|
180
|
+
* `Entry<T>` from `@capacms/sdk/next` is an `/api/` entry.
|
|
123
181
|
*/
|
|
124
|
-
export declare function
|
|
182
|
+
export declare function apiTypes(models: readonly SchemaModel[], checksum: string | null): string;
|
package/dist/codegen.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.LEGACY_PREAMBLE = exports.LEGACY_TYPE_MAP = void 0;
|
|
3
|
+
exports.API_PREAMBLE = exports.LEGACY_PREAMBLE = exports.LEGACY_TYPE_MAP = void 0;
|
|
4
|
+
exports.codegenShape = codegenShape;
|
|
5
|
+
exports.readStampedShape = readStampedShape;
|
|
4
6
|
exports.readStampedChecksum = readStampedChecksum;
|
|
5
7
|
exports.interfaceName = interfaceName;
|
|
6
8
|
exports.modelInterfaceNames = modelInterfaceNames;
|
|
@@ -8,6 +10,7 @@ exports.normalizeTypes = normalizeTypes;
|
|
|
8
10
|
exports.typeNames = typeNames;
|
|
9
11
|
exports.generate = generate;
|
|
10
12
|
exports.restTypesFromIntrospection = restTypesFromIntrospection;
|
|
13
|
+
exports.apiTypes = apiTypes;
|
|
11
14
|
/**
|
|
12
15
|
* codegen.ts — pull a tenant's generated types and write them to disk.
|
|
13
16
|
*
|
|
@@ -64,6 +67,24 @@ const GENERATED_HEADER = new Set([
|
|
|
64
67
|
"// Generated by @capacms/sdk. Do not edit by hand.",
|
|
65
68
|
"// Re-run `capa-codegen` after changing a model in Capa.",
|
|
66
69
|
]);
|
|
70
|
+
/** The line an `api` module carries, so a run asked for the other shape does not take the file as current. */
|
|
71
|
+
const SHAPE_MARKER = "// @capa-codegen-shape ";
|
|
72
|
+
/** The shape `options` asks for, `"legacy"` when it names none. */
|
|
73
|
+
function codegenShape(shape) {
|
|
74
|
+
if (shape === undefined || shape === null || shape === "legacy")
|
|
75
|
+
return "legacy";
|
|
76
|
+
if (shape === "api")
|
|
77
|
+
return "api";
|
|
78
|
+
throw new Error(`shape must be "legacy" or "api", not ${JSON.stringify(shape)}.`);
|
|
79
|
+
}
|
|
80
|
+
/** The shape a generated file was written in: `"api"` when it says so, `"legacy"` otherwise. */
|
|
81
|
+
function readStampedShape(existing) {
|
|
82
|
+
for (const line of (existing ?? "").split("\n", 20)) {
|
|
83
|
+
if (line.startsWith(SHAPE_MARKER))
|
|
84
|
+
return line.slice(SHAPE_MARKER.length).trim() === "api" ? "api" : "legacy";
|
|
85
|
+
}
|
|
86
|
+
return "legacy";
|
|
87
|
+
}
|
|
67
88
|
/** Read the checksum a previous run stamped into the generated file. */
|
|
68
89
|
function readStampedChecksum(existing) {
|
|
69
90
|
if (!existing)
|
|
@@ -122,8 +143,8 @@ function namespaceInterface(namespace) {
|
|
|
122
143
|
* cannot declare an alias twice. Every model caught in such a collision is
|
|
123
144
|
* named by `namespaceInterface` instead, whatever order the models come in.
|
|
124
145
|
*/
|
|
125
|
-
function modelInterfaceNames(models) {
|
|
126
|
-
const claims = new Map(
|
|
146
|
+
function modelInterfaceNames(models, shared = SHARED_NAMES) {
|
|
147
|
+
const claims = new Map(shared.map((name) => [name, new Set([""])]));
|
|
127
148
|
for (const { namespace } of models) {
|
|
128
149
|
const base = modelInterface(namespace);
|
|
129
150
|
for (const name of [base, `${base}Select`, `${base}Attrs`]) {
|
|
@@ -341,18 +362,26 @@ function typeNames(source) {
|
|
|
341
362
|
}
|
|
342
363
|
/**
|
|
343
364
|
* Fetch types if — and only if — the tenant's schema has changed since the
|
|
344
|
-
* checksum stamped in `existing
|
|
365
|
+
* checksum stamped in `existing`, or `existing` is in the other shape.
|
|
345
366
|
*/
|
|
346
|
-
async function generate(config, existing) {
|
|
367
|
+
async function generate(config, existing, options = {}) {
|
|
368
|
+
const shape = codegenShape(options.shape);
|
|
347
369
|
const resolved = (0, config_1.resolveConfig)(config);
|
|
348
370
|
const stamped = readStampedChecksum(existing);
|
|
349
|
-
|
|
371
|
+
// The checksum says the models did not move, not that the file is in the
|
|
372
|
+
// shape asked for: a file in the other shape is read again.
|
|
373
|
+
const etag = stamped && readStampedShape(existing) === shape ? `"${stamped}"` : null;
|
|
350
374
|
const schema = await (0, http_1.getJsonConditional)(resolved, "/v2/schema", etag);
|
|
351
375
|
if (schema === null) {
|
|
352
376
|
// 304 — the model set is byte-identical to what produced the file on disk.
|
|
353
377
|
return { changed: false, checksum: stamped, source: null, types: [] };
|
|
354
378
|
}
|
|
355
379
|
const checksum = schema.body?.checksum ?? (schema.etag ? schema.etag.replace(/"/g, "") : null);
|
|
380
|
+
if (shape === "api") {
|
|
381
|
+
// `/v2/schema` holds everything the shape needs, so `/v2/schema/types` is not read.
|
|
382
|
+
const source = apiTypes(schema.body?.models ?? [], checksum);
|
|
383
|
+
return { changed: source !== (existing ?? null), checksum, source, types: typeNames(source) };
|
|
384
|
+
}
|
|
356
385
|
const raw = await (0, http_1.getText)(resolved, "/v2/schema/types");
|
|
357
386
|
const source = normalizeTypes(raw, checksum, schema.body);
|
|
358
387
|
return { changed: source !== (existing ?? null), checksum, source, types: typeNames(source) };
|
|
@@ -442,9 +471,16 @@ function legacyFieldType(field) {
|
|
|
442
471
|
* no values; and a field GraphQL leaves out (its description's `Not exposed:`
|
|
443
472
|
* line) is `unknown`. No checksum is stamped: `CAPA_SCHEMA_CHECKSUM` is the
|
|
444
473
|
* `/v2/schema` checksum, which a `cap_` key cannot read.
|
|
474
|
+
*
|
|
475
|
+
* `shape: "api"` writes `apiTypes` from the same models instead, each enum
|
|
476
|
+
* a `string` (`apiModelsFromSummary`).
|
|
445
477
|
*/
|
|
446
|
-
function restTypesFromIntrospection(introspection) {
|
|
478
|
+
function restTypesFromIntrospection(introspection, options = {}) {
|
|
447
479
|
const summary = (0, summary_1.summarizeIntrospection)(introspection);
|
|
480
|
+
if (codegenShape(options.shape) === "api") {
|
|
481
|
+
const source = apiTypes(apiModelsFromSummary(summary.models), null);
|
|
482
|
+
return { source, types: typeNames(source), restOnly: summary.restOnly };
|
|
483
|
+
}
|
|
448
484
|
let text = `// Auto-generated Capa CMS types\n\n${exports.LEGACY_PREAMBLE}`;
|
|
449
485
|
const models = [];
|
|
450
486
|
for (const model of summary.models) {
|
|
@@ -467,3 +503,176 @@ function restTypesFromIntrospection(introspection) {
|
|
|
467
503
|
const source = normalizeTypes(text, null, { models });
|
|
468
504
|
return { source, types: typeNames(source), restOnly: summary.restOnly };
|
|
469
505
|
}
|
|
506
|
+
// -------------------------------------------------- shape: "api" (ENG-5667) ---
|
|
507
|
+
/**
|
|
508
|
+
* The declarations every `api` module holds beside its models, written as
|
|
509
|
+
* `/api/entries` returns each value (apps/api/src/api-next/entries/shape.ts):
|
|
510
|
+
*
|
|
511
|
+
* media `renderMedia`: the six keys every image, video and file has,
|
|
512
|
+
* then the placeholders and the focal point and crop, which are
|
|
513
|
+
* on every media value of a project that has them and absent from
|
|
514
|
+
* one that does not. `EntryMedia` in `@capacms/sdk/next`.
|
|
515
|
+
* relations a read with no select, or `*`, does not expand them: a
|
|
516
|
+
* relation is `{ id, model }` (`renderSingleRelation`), a relation
|
|
517
|
+
* list `{ items, pageInfo }`, never null (`renderArrayRelation`).
|
|
518
|
+
* The brand is optional, so the reference the API sends is the
|
|
519
|
+
* type, and it still names the related model for `Select<T>` and
|
|
520
|
+
* `EntryFields<T, S>`, which type an expanded read. A list into a
|
|
521
|
+
* model the module lacks carries `CapaReferenceListBrand`
|
|
522
|
+
* instead, which is how `EntryFields` knows it is never null.
|
|
523
|
+
* Both brands are keyed by symbols `@capacms/sdk/next` declares
|
|
524
|
+
* (next/select-types.ts), imported type-only (`API_IMPORT`).
|
|
525
|
+
*/
|
|
526
|
+
exports.API_PREAMBLE = `/**
|
|
527
|
+
* An image, video or file, as /api/ returns it. The keys after \`height\` are
|
|
528
|
+
* there when the project has image placeholders or focal points and crops,
|
|
529
|
+
* and null for a file without one.
|
|
530
|
+
*/
|
|
531
|
+
export interface CapaMedia {
|
|
532
|
+
id: string;
|
|
533
|
+
url: string | null;
|
|
534
|
+
alt: string | null;
|
|
535
|
+
type: string | null;
|
|
536
|
+
width: number | null;
|
|
537
|
+
height: number | null;
|
|
538
|
+
blurDataURL?: string | null;
|
|
539
|
+
averageColor?: string | null;
|
|
540
|
+
dominantColor?: string | null;
|
|
541
|
+
palette?: string[] | null;
|
|
542
|
+
blurhash?: string | null;
|
|
543
|
+
focalPoint?: { x: number; y: number } | null;
|
|
544
|
+
crop?: { x: number; y: number; width: number; height: number } | null;
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
export type CapaImage = CapaMedia;
|
|
548
|
+
export type CapaVideo = CapaMedia;
|
|
549
|
+
export type CapaFile = CapaMedia;
|
|
550
|
+
|
|
551
|
+
/** A relation a read did not expand: the entry's id, and its model's namespace, null when the key cannot read that model. */
|
|
552
|
+
export interface CapaReference {
|
|
553
|
+
id: string;
|
|
554
|
+
model: string | null;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/**
|
|
558
|
+
* A relation list a read did not expand. \`limit\` is there when a read
|
|
559
|
+
* expands it. Never null, which its type-only brand tells the SDK's typed reads.
|
|
560
|
+
*/
|
|
561
|
+
export interface CapaReferenceList extends CapaReferenceListBrand {
|
|
562
|
+
items: CapaReference[];
|
|
563
|
+
pageInfo: { limit?: number; hasNext: boolean; next: string | null };
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/** A relation to a model of this file: a reference, branded with the model a select can expand it into. */
|
|
567
|
+
export type CapaRelation<T> = CapaReference & CapaRelationBrand<"one", T>;
|
|
568
|
+
export type CapaRelationList<T> = CapaReferenceList & CapaRelationBrand<"many", T>;
|
|
569
|
+
`;
|
|
570
|
+
/**
|
|
571
|
+
* The api module's one import: the brands, type-only, from the SDK that
|
|
572
|
+
* declares their symbols, so no type of the customer's can carry them. The
|
|
573
|
+
* same specifier the \`Select\` aliases name.
|
|
574
|
+
*/
|
|
575
|
+
const API_IMPORT = 'import type { CapaReferenceListBrand, CapaRelationBrand } from "@capacms/sdk/next";';
|
|
576
|
+
/**
|
|
577
|
+
* The names an api module declares or imports, which a model's interface
|
|
578
|
+
* must not take. Both shapes' names, so a model keeps its name across shapes
|
|
579
|
+
* where it can.
|
|
580
|
+
*/
|
|
581
|
+
const API_SHARED_NAMES = [...new Set([...SHARED_NAMES, ...typeNames(exports.API_PREAMBLE), "CapaReferenceListBrand", "CapaRelationBrand"])];
|
|
582
|
+
/** A field's type in an `api` module: what `renderField` returns for it. */
|
|
583
|
+
function apiFieldType(field, models, names) {
|
|
584
|
+
const target = field.relationRef ? models.find((model) => model.id === field.relationRef || model.namespace === field.relationRef) : undefined;
|
|
585
|
+
const targetName = target ? names.get(target.namespace) : null;
|
|
586
|
+
if (field.type === "relation")
|
|
587
|
+
return targetName ? `CapaRelation<${targetName}> | null` : "CapaReference | null";
|
|
588
|
+
if (field.type === "array" && field.arrayType === "relation")
|
|
589
|
+
return targetName ? `CapaRelationList<${targetName}>` : "CapaReferenceList";
|
|
590
|
+
// An enum is checked against its options on every write (validateFieldType
|
|
591
|
+
// in apps/api/src/helpers/utils.ts), and narrowing them is a field
|
|
592
|
+
// conversion that moves the stored values (sameSig in
|
|
593
|
+
// packages/shared/src/field-conversion/types.ts). A single enum also takes
|
|
594
|
+
// "", which a cleared select saves; an item of a list does not. One with no
|
|
595
|
+
// options, or whose options are not known (a cap_ key), takes any text.
|
|
596
|
+
// Each option is written by JSON.stringify, which escapes every character a
|
|
597
|
+
// string literal cannot hold; the legacy shape's `enumLiteral` keeps its bytes.
|
|
598
|
+
const scalar = (type, single) => {
|
|
599
|
+
if (type !== "enum")
|
|
600
|
+
return exports.LEGACY_TYPE_MAP[type ?? ""] ?? "unknown";
|
|
601
|
+
const options = field.enumValues ?? [];
|
|
602
|
+
if (options.length === 0)
|
|
603
|
+
return "string";
|
|
604
|
+
return (single && !options.includes("") ? [...options, ""] : options).map((option) => JSON.stringify(option)).join(" | ");
|
|
605
|
+
};
|
|
606
|
+
if (field.type === "array") {
|
|
607
|
+
const item = scalar(field.arrayType && field.arrayType !== "array" ? field.arrayType : null, false);
|
|
608
|
+
return `${item.includes(" | ") ? `(${item})` : item}[] | null`;
|
|
609
|
+
}
|
|
610
|
+
const type = scalar(field.type, true);
|
|
611
|
+
return type === "unknown" ? type : `${type} | null`;
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* An `api` module: each model's interface is its entries' `fields` as
|
|
615
|
+
* `/api/entries` returns them to a read with no select, or `select=*`.
|
|
616
|
+
*
|
|
617
|
+
* Every field is there, since that read prints every field of the model, and
|
|
618
|
+
* every field but a relation list may be `null`: a field never saved, or
|
|
619
|
+
* emptied, reads null (`storedValue`), and so does a required one, since
|
|
620
|
+
* `required` is checked when an entry is saved, not when it is read, and an
|
|
621
|
+
* entry saved before the field was made required keeps no value for it. A
|
|
622
|
+
* list may read `[]` or `null`, as stored.
|
|
623
|
+
*
|
|
624
|
+
* Models and their `Select` and `Attrs` aliases are named and ordered as the
|
|
625
|
+
* legacy shape names and orders them (`modelInterfaceNames`). No `CapaInstance`:
|
|
626
|
+
* `Entry<T>` from `@capacms/sdk/next` is an `/api/` entry.
|
|
627
|
+
*/
|
|
628
|
+
function apiTypes(models, checksum) {
|
|
629
|
+
const names = modelInterfaceNames(models, API_SHARED_NAMES);
|
|
630
|
+
const blocks = models
|
|
631
|
+
.map((model) => {
|
|
632
|
+
const lines = [`export interface ${names.get(model.namespace)} {`];
|
|
633
|
+
for (const field of model.fields ?? [])
|
|
634
|
+
lines.push(` ${propertyKey(field.namespace)}: ${apiFieldType(field, models, names)};`);
|
|
635
|
+
lines.push("}");
|
|
636
|
+
return lines.join("\n");
|
|
637
|
+
})
|
|
638
|
+
.sort((a, b) => typeNames(a)[0].localeCompare(typeNames(b)[0]));
|
|
639
|
+
const aliases = [...names.values()].sort().flatMap((name) => [
|
|
640
|
+
`export type ${name}Select = import("@capacms/sdk/next").Select<${name}>;`,
|
|
641
|
+
`export type ${name}Attrs = import("@capacms/sdk/next").FieldAttrs<${name}>;`,
|
|
642
|
+
]);
|
|
643
|
+
const head = [
|
|
644
|
+
"// Generated by @capacms/sdk. Do not edit by hand.",
|
|
645
|
+
"// Re-run `capa-codegen --shape api` after changing a model in Capa.",
|
|
646
|
+
`${SHAPE_MARKER}api`,
|
|
647
|
+
checksum ? MARKER + checksum : null,
|
|
648
|
+
]
|
|
649
|
+
.filter(Boolean)
|
|
650
|
+
.join("\n");
|
|
651
|
+
const constant = checksum ? `${CHECKSUM_CONST}${JSON.stringify(checksum)};\n\n` : "";
|
|
652
|
+
const intro = "// Each model's fields as /api/entries returns them with no select: every field there, null when empty.";
|
|
653
|
+
return `${head}\n\n${API_IMPORT}\n\n${constant}${intro}\n\n${[exports.API_PREAMBLE.trimEnd(), ...blocks, ...aliases].join("\n\n")}\n`;
|
|
654
|
+
}
|
|
655
|
+
/**
|
|
656
|
+
* A cap_ key's models for `apiTypes`, from what its GraphQL schema says of
|
|
657
|
+
* them. No enum's options: GraphQL types an enum field as `String`, and the
|
|
658
|
+
* options its description lists for people are cut at 25, joined with `, `
|
|
659
|
+
* and with their whitespace folded (fieldDescription in the API's
|
|
660
|
+
* api-next/graphql/schema.ts), so `red, blue` cannot be told from two
|
|
661
|
+
* options. A wrong union refuses a value the API sends, so the enum is a
|
|
662
|
+
* `string`. A `pk_` key reads the options as saved.
|
|
663
|
+
*/
|
|
664
|
+
function apiModelsFromSummary(summary) {
|
|
665
|
+
return summary.map((model) => ({
|
|
666
|
+
namespace: model.namespace,
|
|
667
|
+
fields: [
|
|
668
|
+
...model.fields.map((field) => ({
|
|
669
|
+
namespace: field.namespace,
|
|
670
|
+
type: field.capaType,
|
|
671
|
+
arrayType: field.arrayType,
|
|
672
|
+
relationRef: field.target,
|
|
673
|
+
})),
|
|
674
|
+
// A field GraphQL leaves out (N5) is still on the entry, of a type it does not say.
|
|
675
|
+
...model.notExposed.map((namespace) => ({ namespace, type: "" })),
|
|
676
|
+
],
|
|
677
|
+
}));
|
|
678
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -7,4 +7,4 @@ export type { CreateWebhookEndpointInput, ListWebhookDeliveriesOptions, ResumeWe
|
|
|
7
7
|
export { DEFAULT_WEBHOOK_TOLERANCE_SECONDS, parseWebhookSignatureHeader, signWebhookPayload, verifyWebhookSignature, WEBHOOK_SIGNATURE_HEADER, } from "./webhook-signature";
|
|
8
8
|
export type { ParsedWebhookSignature, VerifyWebhookSignatureInput, } from "./webhook-signature";
|
|
9
9
|
export { generate, normalizeTypes, readStampedChecksum, restTypesFromIntrospection, typeNames } from "./codegen";
|
|
10
|
-
export type { CodegenResult, RestTypesResult } from "./codegen";
|
|
10
|
+
export type { CodegenOptions, CodegenResult, CodegenShape, RestTypesResult } from "./codegen";
|
|
@@ -28,7 +28,7 @@
|
|
|
28
28
|
* untyped.
|
|
29
29
|
*/
|
|
30
30
|
import type { Entry } from "./client";
|
|
31
|
-
import type { Select } from "./select-types";
|
|
31
|
+
import type { BrandTarget, IsMarkedReferenceList, Select, SymbolBrandKind } from "./select-types";
|
|
32
32
|
/** A relation a read did not expand: the entry's id, and its model's namespace, null when the key cannot read that model. */
|
|
33
33
|
export interface EntryReference {
|
|
34
34
|
id: string;
|
|
@@ -115,13 +115,12 @@ type RelationBrand = {
|
|
|
115
115
|
readonly __capaRelation: "one" | "many";
|
|
116
116
|
readonly __capaRelationTarget: unknown;
|
|
117
117
|
};
|
|
118
|
-
|
|
118
|
+
/** A relation codegen wrote: the legacy shape's required brand, as before, or `--shape api`'s `CapaRelationBrand`. */
|
|
119
|
+
type IsRelation<V> = Untyped<V> extends true ? false : NonNullable<V> extends RelationBrand ? true : [SymbolBrandKind<V>] extends [never] ? false : true;
|
|
119
120
|
type IsList<V> = NonNullable<V> extends {
|
|
120
121
|
readonly __capaRelation: "many";
|
|
121
|
-
} ? true : false;
|
|
122
|
-
type TargetOf<V> =
|
|
123
|
-
readonly __capaRelationTarget: infer R;
|
|
124
|
-
} ? R : never;
|
|
122
|
+
} ? true : "many" extends SymbolBrandKind<V> ? true : false;
|
|
123
|
+
type TargetOf<V> = BrandTarget<V>;
|
|
125
124
|
/** Media as codegen types it: `CapaImage`, `CapaVideo` and `CapaFile` each have a `url`. */
|
|
126
125
|
type StoredMedia = {
|
|
127
126
|
url: string;
|
|
@@ -130,7 +129,7 @@ type StoredMedia = {
|
|
|
130
129
|
* A field that is no relation: as stored, or `null` when it was never filled,
|
|
131
130
|
* but media, which the read returns in its public shape.
|
|
132
131
|
*/
|
|
133
|
-
type ValueTree<V> = Untyped<V> extends true ? V : NonNullable<V> extends ReadonlyArray<infer M> ? [M] extends [StoredMedia] ? EntryMedia[] | null : NonNullable<V> | null : NonNullable<V> extends StoredMedia ? EntryMedia | null : NonNullable<V> | null;
|
|
132
|
+
type ValueTree<V> = Untyped<V> extends true ? V : IsMarkedReferenceList<V> extends true ? V : NonNullable<V> extends ReadonlyArray<infer M> ? [M] extends [StoredMedia] ? EntryMedia[] | null : NonNullable<V> | null : NonNullable<V> extends StoredMedia ? EntryMedia | null : NonNullable<V> | null;
|
|
134
133
|
/** A relation the read did not expand. */
|
|
135
134
|
type ReferenceTree<V> = IsList<V> extends true ? RelationItems<EntryReference> : EntryReference | null;
|
|
136
135
|
/** A field the read names without expanding it. */
|
package/dist/next/index.d.ts
CHANGED
|
@@ -27,4 +27,4 @@ export type { FlatResponse, Inflated } from "./inflate";
|
|
|
27
27
|
export type { EntryFields, EntryMedia, EntryReference, FlatFields, IncludedFields, MediaCrop, MediaFocalPoint, MissingEntry, RelationItems, } from "./entry-fields";
|
|
28
28
|
export type { CapaAttrs, CapaAttrsOptions, CapaItem, FieldAttrs, TaggableField } from "./attrs";
|
|
29
29
|
export type { BuilderCallOptions, CallOptions, CapaNextClient, CapaNextConfig, EntriesResource, Entry, GraphQLClient, Filter, FilterOperator, FlatGetOptions, FlatListOptions, FlatPage, FlatSingle, Included, FilterScalar, FilterValue, GetOptions, ListOptions, Page, PageDetail, PageInfo, PageSummary, PagesListOptions, PagesResource, PreviewClaim, PreviewOptions, ReleasePreviewBar, ReleasePreviewState, ResponseMeta, ResponseShape, Single, } from "./client";
|
|
30
|
-
export type { ExpandedTargets, CapaRelation, CapaRelationList, RelationSelectOptions, Select, SelectItem, SelectSort, SortableSystemKey, SystemKey, } from "./select-types";
|
|
30
|
+
export type { ExpandedTargets, CapaReferenceListBrand, CapaRelation, CapaRelationBrand, CapaRelationList, RelationSelectOptions, Select, SelectItem, SelectSort, SortableSystemKey, SystemKey, } from "./select-types";
|
|
@@ -14,6 +14,47 @@ type RelationValue = {
|
|
|
14
14
|
readonly __capaRelation: "one" | "many";
|
|
15
15
|
readonly __capaRelationTarget: unknown;
|
|
16
16
|
};
|
|
17
|
+
/**
|
|
18
|
+
* The brands `capa-codegen --shape api` writes, keyed by symbols only this
|
|
19
|
+
* module declares. Each property is optional and type-only, so the JSON the
|
|
20
|
+
* API sends is the type, and no other type can carry the key, by accident or
|
|
21
|
+
* by a field of the same name: a type without them reads exactly as it did
|
|
22
|
+
* before the api shape existed. The legacy shape's brand is the required
|
|
23
|
+
* `__capaRelation` and `__capaRelationTarget` pair, read as it always was.
|
|
24
|
+
*/
|
|
25
|
+
declare const capaRelationBrand: unique symbol;
|
|
26
|
+
declare const capaReferenceListBrand: unique symbol;
|
|
27
|
+
/** A relation of `--shape api`: `"one"` or `"many"`, and the model a select can expand it into. */
|
|
28
|
+
export interface CapaRelationBrand<K extends "one" | "many", T> {
|
|
29
|
+
readonly [capaRelationBrand]?: {
|
|
30
|
+
readonly kind: K;
|
|
31
|
+
readonly target: T;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** A relation list of `--shape api` into a model its module lacks: never null. */
|
|
35
|
+
export interface CapaReferenceListBrand {
|
|
36
|
+
readonly [capaReferenceListBrand]?: true;
|
|
37
|
+
}
|
|
38
|
+
/** `V` without null, unless that leaves nothing or an index signature that would hold any key. */
|
|
39
|
+
type Keyed<V> = [NonNullable<V>] extends [never] ? never : symbol extends keyof NonNullable<V> ? never : NonNullable<V>;
|
|
40
|
+
/** Whether `V` declares key `K` itself. Never for `never`, whose `keyof` is every key. */
|
|
41
|
+
type HasKey<V, K> = [Keyed<V>] extends [never] ? false : K extends keyof Keyed<V> ? true : false;
|
|
42
|
+
/** `"one"` or `"many"` for a type that carries `CapaRelationBrand`; never for any other. */
|
|
43
|
+
export type SymbolBrandKind<V> = HasKey<V, typeof capaRelationBrand> extends true ? Keyed<V> extends {
|
|
44
|
+
readonly [capaRelationBrand]?: {
|
|
45
|
+
readonly kind: infer K;
|
|
46
|
+
};
|
|
47
|
+
} ? [K] extends ["one" | "many"] ? K : never : never : never;
|
|
48
|
+
/** True for a type that carries `CapaReferenceListBrand`, and nothing else. */
|
|
49
|
+
export type IsMarkedReferenceList<V> = HasKey<V, typeof capaReferenceListBrand> extends true ? [V] extends [NonNullable<V>] ? true : false : false;
|
|
50
|
+
/** The model a relation's brand names: the legacy shape's required one, as before, or `CapaRelationBrand`'s. */
|
|
51
|
+
export type BrandTarget<V> = NonNullable<V> extends {
|
|
52
|
+
readonly __capaRelationTarget: infer R;
|
|
53
|
+
} ? R : [SymbolBrandKind<V>] extends [never] ? never : Keyed<V> extends {
|
|
54
|
+
readonly [capaRelationBrand]?: {
|
|
55
|
+
readonly target: infer R;
|
|
56
|
+
};
|
|
57
|
+
} ? R : never;
|
|
17
58
|
/**
|
|
18
59
|
* A field type that says nothing about the field: `unknown`, as every field
|
|
19
60
|
* of an untyped client's `Record<string, unknown>` is, or `any`, as a type
|
|
@@ -24,12 +65,10 @@ type UntypedKeys<T> = {
|
|
|
24
65
|
[K in StringKey<T>]-?: Untyped<T[K]> extends true ? K : never;
|
|
25
66
|
}[StringKey<T>];
|
|
26
67
|
type RelationKeys<T> = {
|
|
27
|
-
[K in StringKey<T>]-?: Untyped<T[K]> extends true ? never : NonNullable<T[K]> extends RelationValue ? K : never;
|
|
68
|
+
[K in StringKey<T>]-?: Untyped<T[K]> extends true ? never : NonNullable<T[K]> extends RelationValue ? K : [SymbolBrandKind<T[K]>] extends [never] ? never : K;
|
|
28
69
|
}[StringKey<T>];
|
|
29
70
|
type ScalarKeys<T> = Exclude<StringKey<T>, RelationKeys<T>>;
|
|
30
|
-
type RelationTarget<T> =
|
|
31
|
-
readonly __capaRelationTarget: infer R;
|
|
32
|
-
} ? R : never;
|
|
71
|
+
type RelationTarget<T> = BrandTarget<T>;
|
|
33
72
|
/**
|
|
34
73
|
* A system key by its `$` name. The API reads a plain name as the model's
|
|
35
74
|
* field first, so `$tags` is how a select or sort asks for the entry's own
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@capacms/sdk",
|
|
3
|
-
"version": "1.0.0-next.
|
|
3
|
+
"version": "1.0.0-next.15",
|
|
4
4
|
"description": "The TypeScript SDK for Capa's content API: REST and GraphQL reads typed from your models, Next.js caching and live preview, and codegen.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"homepage": "https://docs.capacms.com/api",
|
|
@@ -147,6 +147,6 @@
|
|
|
147
147
|
"scripts": {
|
|
148
148
|
"build": "node scripts/shared-image.js && tsc -p tsconfig.json && tsc -p tsconfig.esm.json && node scripts/esm-scope.js",
|
|
149
149
|
"typecheck": "node scripts/shared-image.js && tsc -p tsconfig.json --noEmit && tsc -p tsconfig.esm.json --noEmit",
|
|
150
|
-
"test": "pnpm run build && node --test test/comments.test.js test/codegen.test.js test/client.test.js test/next-client.test.js test/nextjs.test.js test/webhooks.test.js test/relations.test.js test/attrs.test.js test/overlay.test.js test/overlay-dom.test.js test/overlay-items.test.js test/live-fields.test.js test/markdown.test.js test/overlay-fields.test.js test/nextjs-overlay-refresh.test.js test/nextjs-overlay-bundle.test.js test/inflate.test.js test/field-names.test.js test/next-graphql.test.js test/graphql-codegen.test.js test/graphql-contract.test.js test/readme-snippets.test.js test/nextjs-app.test.js test/nextjs-preview-app.test.js test/package-json.test.js test/changelog.test.js test/published-docs.test.js test/builder-messages.test.js test/image.test.js test/sanitize.test.js test/sanitize-browser.test.js test/sanitize-dom.test.js test/nextjs-image-loader.test.js test/capa-cli-handoff.test.js test/server.test.js test/nextjs-write-key-guard.test.js && tsc -p test/types/tsconfig.consumer.json --noEmit && tsc -p test/types/tsconfig.nonstrict.json --noEmit && tsc -p test/types/tsconfig.next.json --noEmit"
|
|
150
|
+
"test": "pnpm run build && node --test test/comments.test.js test/codegen.test.js test/codegen-shapes.test.js test/client.test.js test/next-client.test.js test/nextjs.test.js test/webhooks.test.js test/relations.test.js test/attrs.test.js test/overlay.test.js test/overlay-dom.test.js test/overlay-items.test.js test/live-fields.test.js test/markdown.test.js test/overlay-fields.test.js test/nextjs-overlay-refresh.test.js test/nextjs-overlay-bundle.test.js test/inflate.test.js test/field-names.test.js test/next-graphql.test.js test/graphql-codegen.test.js test/graphql-contract.test.js test/readme-snippets.test.js test/nextjs-app.test.js test/nextjs-preview-app.test.js test/package-json.test.js test/changelog.test.js test/published-docs.test.js test/builder-messages.test.js test/image.test.js test/sanitize.test.js test/sanitize-browser.test.js test/sanitize-dom.test.js test/nextjs-image-loader.test.js test/capa-cli-handoff.test.js test/server.test.js test/nextjs-write-key-guard.test.js && tsc -p test/types/tsconfig.consumer.json --noEmit && tsc -p test/types/tsconfig.nonstrict.json --noEmit && tsc -p test/types/tsconfig.next.json --noEmit"
|
|
151
151
|
}
|
|
152
152
|
}
|