@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,203 @@
1
+ /**
2
+ * entry-fields.ts — an entry's `fields` as `/api/entries` returns them, typed
3
+ * from the model and the select.
4
+ *
5
+ * A model type says what an editor stores: `capa-codegen` writes a relation as
6
+ * the related model (`CapaRelation<Authors>`), a relation list as a list of
7
+ * them, and media as the upload (`CapaImage`). A read answers in its own shape
8
+ * (docs/api/entries.md), and these types say which:
9
+ *
10
+ * - a field the select names is always there, and `null` when it was never
11
+ * filled, as the API writes it: optional in the model, never absent here;
12
+ * - a field the select does not name is not there;
13
+ * - a relation the select does not expand is a reference, `{ id, model }`,
14
+ * or null when it is empty;
15
+ * - an expanded relation is the related entry, with `fields` of its own, or
16
+ * `{ id, model, missing: true }` when that entry was deleted, is
17
+ * unpublished for a production key, or is in a model the key cannot read;
18
+ * - a relation list is `{ items, pageInfo }`, expanded or not;
19
+ * - media is `{ id, url, alt, type, width, height }`, never the upload's
20
+ * own keys, plus an image's placeholders and its focal point and crop
21
+ * where the project has them (optional, absent otherwise).
22
+ *
23
+ * A select the compiler can read exactly, a literal passed as its type
24
+ * (`list<Articles, typeof select>`), types what it names. One it cannot, a
25
+ * string or a value typed as `Select<T>` itself, types every field, and each
26
+ * relation as any of the three it may be, which the caller narrows
27
+ * (`"fields" in author`). An untyped model (`Record<string, unknown>`) stays
28
+ * untyped.
29
+ */
30
+ import type { Entry } from "./client";
31
+ import type { Select } from "./select-types";
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
+ export interface EntryReference {
34
+ id: string;
35
+ model: string | null;
36
+ }
37
+ /**
38
+ * An expanded relation the API looked for and did not find: the entry was
39
+ * deleted, is unpublished for a production key, or is in a model the key
40
+ * cannot read.
41
+ */
42
+ export interface MissingEntry extends EntryReference {
43
+ missing: true;
44
+ }
45
+ /** A relation list, expanded or not. `limit` is there when the read expanded it. */
46
+ export interface RelationItems<E> {
47
+ items: E[];
48
+ pageInfo: {
49
+ limit?: number;
50
+ hasNext: boolean;
51
+ next: string | null;
52
+ };
53
+ }
54
+ /** An editor's focal point: fractions of the image from 0 to 1, `x` from the left and `y` from the top. */
55
+ export interface MediaFocalPoint {
56
+ x: number;
57
+ y: number;
58
+ }
59
+ /** An editor's crop: fractions of the image from 0 to 1. */
60
+ export interface MediaCrop {
61
+ x: number;
62
+ y: number;
63
+ width: number;
64
+ height: number;
65
+ }
66
+ /**
67
+ * An image, video or file as `/api/` returns it.
68
+ *
69
+ * The keys after `height` are optional: they are on every media value of a
70
+ * project that has them, and absent from one that does not. Where they are
71
+ * there, each is null for a video or other file and for an image without one.
72
+ */
73
+ export interface EntryMedia {
74
+ id: string;
75
+ url: string | null;
76
+ alt: string | null;
77
+ type: string | null;
78
+ width: number | null;
79
+ height: number | null;
80
+ /**
81
+ * A tiny blurred copy of the image, 20 pixels on its long side, as a data
82
+ * URL, to show while it loads: next/image's `blurDataURL`
83
+ * (`imagePlaceholder` in `@capacms/sdk/image`). With image placeholders.
84
+ */
85
+ blurDataURL?: string | null;
86
+ /** The image's average colour, `#rrggbb`, to paint its space while it loads. With image placeholders. */
87
+ averageColor?: string | null;
88
+ /** The colour that covers the most of the image, `#rrggbb`: the first of `palette`. With image placeholders. */
89
+ dominantColor?: string | null;
90
+ /** Up to five `#rrggbb` colours, the image's main colour groups, largest first. With image placeholders. */
91
+ palette?: string[] | null;
92
+ /** A BlurHash of the image (https://blurha.sh), for a decoder on the page. With image placeholders. */
93
+ blurhash?: string | null;
94
+ /**
95
+ * The spot an editor marked as the one that matters most. Capa's CDN
96
+ * centres a crop to a shape on it, and `imageUrl` names it in that URL.
97
+ * With focal points and crops.
98
+ */
99
+ focalPoint?: MediaFocalPoint | null;
100
+ /** The part of the image an editor chose to show. A crop to a shape stays inside it. With focal points and crops. */
101
+ crop?: MediaCrop | null;
102
+ }
103
+ /**
104
+ * Levels of entries left to type: the root entry and 4 below it, the API's 5
105
+ * levels. A relation past the last level is typed as a reference, which is all
106
+ * the API returns there.
107
+ */
108
+ type Depth = [never, 0, 1, 2, 3, 4];
109
+ type Flatten<T> = {
110
+ [K in keyof T]: T[K];
111
+ };
112
+ /** A field type that says nothing: `unknown`, or `any`. */
113
+ type Untyped<V> = 0 extends 1 & V ? true : unknown extends V ? true : false;
114
+ type RelationBrand = {
115
+ readonly __capaRelation: "one" | "many";
116
+ readonly __capaRelationTarget: unknown;
117
+ };
118
+ type IsRelation<V> = Untyped<V> extends true ? false : NonNullable<V> extends RelationBrand ? true : false;
119
+ type IsList<V> = NonNullable<V> extends {
120
+ readonly __capaRelation: "many";
121
+ } ? true : false;
122
+ type TargetOf<V> = NonNullable<V> extends {
123
+ readonly __capaRelationTarget: infer R;
124
+ } ? R : never;
125
+ /** Media as codegen types it: `CapaImage`, `CapaVideo` and `CapaFile` each have a `url`. */
126
+ type StoredMedia = {
127
+ url: string;
128
+ };
129
+ /**
130
+ * A field that is no relation: as stored, or `null` when it was never filled,
131
+ * but media, which the read returns in its public shape.
132
+ */
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;
134
+ /** A relation the read did not expand. */
135
+ type ReferenceTree<V> = IsList<V> extends true ? RelationItems<EntryReference> : EntryReference | null;
136
+ /** A field the read names without expanding it. */
137
+ type FieldTree<V> = IsRelation<V> extends true ? ReferenceTree<V> : ValueTree<V>;
138
+ /** An expanded relation, its entries read with `S`, at level `D`. */
139
+ type ExpandedTree<V, S, D extends number> = IsList<V> extends true ? RelationItems<Entry<FieldsAt<TargetOf<V>, S, D>> | MissingEntry> : Entry<FieldsAt<TargetOf<V>, S, D>> | MissingEntry | null;
140
+ /** A relation the read may or may not have expanded, with any select, at level `D`. */
141
+ type EitherTree<V, D extends number> = IsList<V> extends true ? RelationItems<EntryReference | MissingEntry | Entry<FieldsAt<TargetOf<V>, string, D>>> : EntryReference | MissingEntry | Entry<FieldsAt<TargetOf<V>, string, D>> | null;
142
+ /** Every field, relations as references: a read with no select, or `*`. */
143
+ type ReferenceFields<T> = {
144
+ [K in keyof T]-?: FieldTree<T[K]>;
145
+ };
146
+ /** Every field, each relation as whatever it may be: a select the compiler cannot read. */
147
+ type LooseFields<T, D extends number> = {
148
+ [K in keyof T]-?: IsRelation<T[K]> extends true ? EitherTree<T[K], Depth[D]> : ValueTree<T[K]>;
149
+ };
150
+ /** The relations a select item expands, by name. */
151
+ type ExpandedIn<I> = I extends string ? never : Extract<keyof I, string>;
152
+ /** What the select writes for relation `K`: its list, `*`, or its options' `select`. */
153
+ type SubSelect<I, K extends string> = I extends {
154
+ readonly [P in K]: infer V;
155
+ } ? V extends {
156
+ readonly select: infer S;
157
+ } ? S : V : never;
158
+ /**
159
+ * The fields a literal select names, `I` being the union of its items: each
160
+ * named field, every field for `*`, and each expanded relation as the entries
161
+ * its own select reads. A system key (`$tags`) sits beside `fields`, on the entry.
162
+ */
163
+ type SelectedFields<T, I, D extends number> = Flatten<{
164
+ [K in keyof T as K extends ExpandedIn<I> ? IsRelation<T[K]> extends true ? never : K : "*" extends I ? K : K extends I ? K : never]-?: FieldTree<T[K]>;
165
+ } & {
166
+ [K in keyof T as K extends ExpandedIn<I> ? (IsRelation<T[K]> extends true ? K : never) : never]-?: ExpandedTree<T[K], SubSelect<I, K & string>, Depth[D]>;
167
+ }>;
168
+ type FieldsAt<T, S, D extends number> = string extends keyof T ? T : [D] extends [never] ? ReferenceFields<T> : [S] extends [undefined] ? ReferenceFields<T> : [S] extends ["*"] ? ReferenceFields<T> : S extends ReadonlyArray<infer I> ? Select<T> extends S ? LooseFields<T, D> : SelectedFields<T, I, D> : LooseFields<T, D>;
169
+ /**
170
+ * `fields` of an entry of model `T` read with select `S`, as `/api/entries`
171
+ * returns them. Pass the select's own type for exact fields
172
+ * (`list<Articles, typeof select>`); without it every field is typed, and
173
+ * each relation as whatever it may be.
174
+ */
175
+ export type EntryFields<T, S = Select<T> | string> = FieldsAt<T, S, 4>;
176
+ /** A field of a `shape=flat` read: each relation a reference, since the entry it names is in `included`. */
177
+ type FlatTree<V> = IsRelation<V> extends true ? IsList<V> extends true ? RelationItems<EntryReference | MissingEntry> : EntryReference | MissingEntry | null : ValueTree<V>;
178
+ /** The fields a select names at its root: every field for none, `*`, a string or `Select<T>`. */
179
+ type NamedKeys<T, S> = [S] extends [undefined] ? keyof T : S extends ReadonlyArray<infer I> ? Select<T> extends S ? keyof T : "*" extends I ? keyof T : Extract<keyof T, I | ExpandedIn<I>> : keyof T;
180
+ /** `fields` of an entry in a `shape=flat` read's `data`. */
181
+ export type FlatFields<T, S = Select<T>> = string extends keyof T ? T : {
182
+ [K in keyof T as K extends NamedKeys<T, S> ? K : never]-?: FlatTree<T[K]>;
183
+ };
184
+ /**
185
+ * `fields` of an entry in `included`: the union of what every path that
186
+ * reached it selected, so any field may be absent.
187
+ */
188
+ export type IncludedFields<I> = I extends unknown ? string extends keyof I ? I : {
189
+ [K in keyof I]?: FlatTree<I[K]>;
190
+ } : never;
191
+ /**
192
+ * Where a flat result keeps the model and select it was read with, for
193
+ * `inflate` to type the tree it returns. A symbol, never a field, and never a
194
+ * runtime value.
195
+ */
196
+ declare const flatRead: unique symbol;
197
+ export type { flatRead };
198
+ export interface FlatRead<T, S> {
199
+ readonly [flatRead]?: {
200
+ model: T;
201
+ select: S;
202
+ };
203
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,136 @@
1
+ /**
2
+ * errors.ts — what a failed `/api/` call throws.
3
+ *
4
+ * `CapaError` is one refusal of the whole request: the REST envelope's
5
+ * `{ error }`, or a GraphQL response with `errors` and no `data`, whatever
6
+ * its status. `CapaGraphQLError` is one entry of a GraphQL `errors` array. A
7
+ * GraphQL request the API ran resolves with those in `errors` rather than
8
+ * throwing, because its `data` carries the root fields that did succeed. They
9
+ * are returned, not thrown, so they are plain objects: a result goes through
10
+ * `Response.json` or into a client component's props with every field kept.
11
+ */
12
+ export interface ApiErrorEnvelope {
13
+ error?: {
14
+ type?: unknown;
15
+ code?: unknown;
16
+ message?: unknown;
17
+ param?: unknown;
18
+ hint?: unknown;
19
+ docs?: unknown;
20
+ };
21
+ meta?: {
22
+ requestId?: unknown;
23
+ };
24
+ }
25
+ export declare class CapaError extends Error {
26
+ readonly status: number;
27
+ readonly type: string;
28
+ readonly code: string;
29
+ readonly param?: string;
30
+ readonly hint?: string;
31
+ readonly requestId: string;
32
+ readonly docs: string;
33
+ /**
34
+ * Every error of a refused GraphQL request, in order. The fields above come
35
+ * from the first one. Empty for a REST call.
36
+ */
37
+ readonly graphqlErrors: readonly CapaGraphQLError[];
38
+ /**
39
+ * Seconds the API asked the caller to wait before trying again, from a 429's
40
+ * `Retry-After` (seconds or an HTTP date). Undefined when it sent none.
41
+ */
42
+ readonly retryAfter?: number;
43
+ constructor(input: {
44
+ status: number;
45
+ type: string;
46
+ code: string;
47
+ message: string;
48
+ param?: string;
49
+ hint?: string;
50
+ requestId: string;
51
+ docs: string;
52
+ graphqlErrors?: readonly CapaGraphQLError[];
53
+ retryAfter?: number;
54
+ });
55
+ }
56
+ /**
57
+ * A `Retry-After` header in seconds: delta-seconds as sent, an HTTP date as
58
+ * the whole seconds from `now` until it (0 once it has passed). Undefined when
59
+ * the header is absent or neither.
60
+ */
61
+ export declare function retryAfterOf(value: string | null | undefined, now?: number): number | undefined;
62
+ export declare function isCapaError(error: unknown): error is CapaError;
63
+ export declare function optionalString(value: unknown): string | undefined;
64
+ export declare function unparseable(status: number, requestId: string): CapaError;
65
+ export declare function errorFromEnvelope(status: number, body: ApiErrorEnvelope, fallbackRequestId: string, retryAfter?: number): CapaError;
66
+ /** One `errors[]` item as the API sends it. */
67
+ export interface GraphQLErrorItem {
68
+ message: string;
69
+ locations?: Array<{
70
+ line: number;
71
+ column: number;
72
+ }>;
73
+ path?: Array<string | number>;
74
+ extensions?: {
75
+ code?: string;
76
+ type?: string;
77
+ param?: string;
78
+ hint?: string;
79
+ docs?: string;
80
+ requestId?: string;
81
+ [key: string]: unknown;
82
+ };
83
+ }
84
+ /**
85
+ * One GraphQL error: the spec's `{ message, locations, path, extensions }`,
86
+ * with the fields a caller acts on lifted out of `extensions`: `code` to
87
+ * branch on, `hint` for the fix, `docs` for the page that explains it,
88
+ * `param` for the argument at fault. `path` names the root field it belongs
89
+ * to.
90
+ *
91
+ * A plain object, not an `Error`: an `Error`'s `message` is not enumerable,
92
+ * so `JSON.stringify` drops it, and React sends an `Error` to a client
93
+ * component as a generic message in production. Only what the API sent is
94
+ * set, so a JSON round trip gives back an equal object. Check one with
95
+ * `isCapaGraphQLError`.
96
+ */
97
+ export interface CapaGraphQLError {
98
+ readonly message: string;
99
+ readonly locations?: ReadonlyArray<{
100
+ line: number;
101
+ column: number;
102
+ }>;
103
+ readonly path?: ReadonlyArray<string | number>;
104
+ readonly extensions: Readonly<Record<string, unknown>>;
105
+ /** `extensions.code`, or `unknown` when the API sent none. */
106
+ readonly code: string;
107
+ readonly type?: string;
108
+ readonly param?: string;
109
+ readonly hint?: string;
110
+ readonly docs?: string;
111
+ }
112
+ /** Whether `value` is a `CapaGraphQLError`: by its shape, so one that went through JSON is one too. */
113
+ export declare function isCapaGraphQLError(value: unknown): value is CapaGraphQLError;
114
+ /** Turn a parsed `errors` value into typed errors, skipping anything that is not one. */
115
+ export declare function graphqlErrorsOf(value: unknown): CapaGraphQLError[];
116
+ /**
117
+ * A GraphQL request the API refused as a whole: a status other than 200, or
118
+ * a 200 with `errors` and no `data`, passed in as the refusal's `status`. The
119
+ * `CapaError` fields come from the first error, and `graphqlErrors` holds all
120
+ * of them. A body in the REST envelope shape, which a proxy or an older API
121
+ * can send, is read as one.
122
+ */
123
+ export declare function errorFromGraphQLBody(status: number, body: unknown, fallbackRequestId: string, retryAfter?: number): CapaError;
124
+ /** A `CapaError` for errors already read: the fields of the first, and all of them in `graphqlErrors`. */
125
+ export declare function errorFromGraphQLErrors(status: number, errors: readonly CapaGraphQLError[], fallbackRequestId: string, retryAfter?: number): CapaError;
126
+ /**
127
+ * `/api/graphql` answered as a path the API does not serve: a POST
128
+ * `405 mutations_not_enabled`, a GET `404 route_not_found`, in the REST
129
+ * envelope. `CAPA_API_GRAPHQL=off` does that, and so does the admin host for a
130
+ * GET, since it serves GraphQL by POST only. The GraphQL handler never answers
131
+ * in that envelope (a real mutation's refusal is `{ errors }`), so the
132
+ * envelope is what tells "GraphQL is not here" from "this document was
133
+ * refused", and a query is never told it tried to write. Null for any other
134
+ * answer.
135
+ */
136
+ export declare function graphqlNotServed(status: number, body: unknown, method: "GET" | "POST", fallbackRequestId: string): CapaError | null;
@@ -0,0 +1,214 @@
1
+ "use strict";
2
+ /**
3
+ * errors.ts — what a failed `/api/` call throws.
4
+ *
5
+ * `CapaError` is one refusal of the whole request: the REST envelope's
6
+ * `{ error }`, or a GraphQL response with `errors` and no `data`, whatever
7
+ * its status. `CapaGraphQLError` is one entry of a GraphQL `errors` array. A
8
+ * GraphQL request the API ran resolves with those in `errors` rather than
9
+ * throwing, because its `data` carries the root fields that did succeed. They
10
+ * are returned, not thrown, so they are plain objects: a result goes through
11
+ * `Response.json` or into a client component's props with every field kept.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.CapaError = void 0;
15
+ exports.retryAfterOf = retryAfterOf;
16
+ exports.isCapaError = isCapaError;
17
+ exports.optionalString = optionalString;
18
+ exports.unparseable = unparseable;
19
+ exports.errorFromEnvelope = errorFromEnvelope;
20
+ exports.isCapaGraphQLError = isCapaGraphQLError;
21
+ exports.graphqlErrorsOf = graphqlErrorsOf;
22
+ exports.errorFromGraphQLBody = errorFromGraphQLBody;
23
+ exports.errorFromGraphQLErrors = errorFromGraphQLErrors;
24
+ exports.graphqlNotServed = graphqlNotServed;
25
+ class CapaError extends Error {
26
+ status;
27
+ type;
28
+ code;
29
+ param;
30
+ hint;
31
+ requestId;
32
+ docs;
33
+ /**
34
+ * Every error of a refused GraphQL request, in order. The fields above come
35
+ * from the first one. Empty for a REST call.
36
+ */
37
+ graphqlErrors;
38
+ /**
39
+ * Seconds the API asked the caller to wait before trying again, from a 429's
40
+ * `Retry-After` (seconds or an HTTP date). Undefined when it sent none.
41
+ */
42
+ retryAfter;
43
+ constructor(input) {
44
+ super(input.message);
45
+ this.name = "CapaError";
46
+ this.status = input.status;
47
+ this.type = input.type;
48
+ this.code = input.code;
49
+ this.param = input.param;
50
+ this.hint = input.hint;
51
+ this.requestId = input.requestId;
52
+ this.docs = input.docs;
53
+ this.graphqlErrors = input.graphqlErrors ?? [];
54
+ if (input.retryAfter !== undefined)
55
+ this.retryAfter = input.retryAfter;
56
+ }
57
+ }
58
+ exports.CapaError = CapaError;
59
+ /**
60
+ * A `Retry-After` header in seconds: delta-seconds as sent, an HTTP date as
61
+ * the whole seconds from `now` until it (0 once it has passed). Undefined when
62
+ * the header is absent or neither.
63
+ */
64
+ function retryAfterOf(value, now = Date.now()) {
65
+ if (value === null || value === undefined)
66
+ return undefined;
67
+ const text = value.trim();
68
+ if (/^\d+$/.test(text))
69
+ return Number(text);
70
+ const at = Date.parse(text);
71
+ if (Number.isNaN(at))
72
+ return undefined;
73
+ return Math.max(0, Math.ceil((at - now) / 1000));
74
+ }
75
+ function isCapaError(error) {
76
+ return error instanceof CapaError;
77
+ }
78
+ function optionalString(value) {
79
+ return typeof value === "string" ? value : undefined;
80
+ }
81
+ function unparseable(status, requestId) {
82
+ return new CapaError({
83
+ status,
84
+ type: "api_error",
85
+ code: "unparseable_response",
86
+ message: "Capa returned a response that was not a valid /api/ JSON envelope.",
87
+ requestId,
88
+ docs: "",
89
+ });
90
+ }
91
+ function errorFromEnvelope(status, body, fallbackRequestId, retryAfter) {
92
+ const detail = body.error;
93
+ if (!detail ||
94
+ typeof detail.type !== "string" ||
95
+ typeof detail.code !== "string" ||
96
+ typeof detail.message !== "string" ||
97
+ typeof detail.docs !== "string") {
98
+ return unparseable(status, fallbackRequestId);
99
+ }
100
+ return new CapaError({
101
+ status,
102
+ type: detail.type,
103
+ code: detail.code,
104
+ message: detail.message,
105
+ param: optionalString(detail.param),
106
+ hint: optionalString(detail.hint),
107
+ requestId: optionalString(body.meta?.requestId) ?? fallbackRequestId,
108
+ docs: detail.docs,
109
+ retryAfter,
110
+ });
111
+ }
112
+ /** The string values of `keys` in `from`, leaving out each one that is absent or not a string. */
113
+ function stringsOf(from, keys) {
114
+ const out = {};
115
+ for (const key of keys) {
116
+ const value = optionalString(from[key]);
117
+ if (value !== undefined)
118
+ out[key] = value;
119
+ }
120
+ return out;
121
+ }
122
+ function capaGraphQLError(item) {
123
+ const extensions = item.extensions && typeof item.extensions === "object" ? item.extensions : {};
124
+ return {
125
+ message: item.message,
126
+ ...(Array.isArray(item.locations) ? { locations: item.locations } : {}),
127
+ ...(Array.isArray(item.path) ? { path: item.path } : {}),
128
+ extensions,
129
+ code: optionalString(extensions.code) ?? "unknown",
130
+ ...stringsOf(extensions, ["type", "param", "hint", "docs"]),
131
+ };
132
+ }
133
+ /** Whether `value` is a `CapaGraphQLError`: by its shape, so one that went through JSON is one too. */
134
+ function isCapaGraphQLError(value) {
135
+ if (!value || typeof value !== "object" || value instanceof Error)
136
+ return false;
137
+ const error = value;
138
+ return (typeof error.message === "string" &&
139
+ typeof error.code === "string" &&
140
+ !!error.extensions &&
141
+ typeof error.extensions === "object" &&
142
+ !Array.isArray(error.extensions));
143
+ }
144
+ /** Turn a parsed `errors` value into typed errors, skipping anything that is not one. */
145
+ function graphqlErrorsOf(value) {
146
+ if (!Array.isArray(value))
147
+ return [];
148
+ return value
149
+ .filter((item) => !!item && typeof item === "object" && typeof item.message === "string")
150
+ .map(capaGraphQLError);
151
+ }
152
+ /**
153
+ * A GraphQL request the API refused as a whole: a status other than 200, or
154
+ * a 200 with `errors` and no `data`, passed in as the refusal's `status`. The
155
+ * `CapaError` fields come from the first error, and `graphqlErrors` holds all
156
+ * of them. A body in the REST envelope shape, which a proxy or an older API
157
+ * can send, is read as one.
158
+ */
159
+ function errorFromGraphQLBody(status, body, fallbackRequestId, retryAfter) {
160
+ const object = body && typeof body === "object" ? body : {};
161
+ const errors = graphqlErrorsOf(object.errors);
162
+ if (errors.length === 0)
163
+ return errorFromEnvelope(status, object, fallbackRequestId, retryAfter);
164
+ return errorFromGraphQLErrors(status, errors, fallbackRequestId, retryAfter);
165
+ }
166
+ /** A `CapaError` for errors already read: the fields of the first, and all of them in `graphqlErrors`. */
167
+ function errorFromGraphQLErrors(status, errors, fallbackRequestId, retryAfter) {
168
+ const [first] = errors;
169
+ return new CapaError({
170
+ status,
171
+ type: first.type ?? "api_error",
172
+ code: first.code,
173
+ message: first.message,
174
+ param: first.param,
175
+ hint: first.hint,
176
+ requestId: optionalString(first.extensions.requestId) ?? fallbackRequestId,
177
+ docs: first.docs ?? "",
178
+ graphqlErrors: errors,
179
+ retryAfter,
180
+ });
181
+ }
182
+ /**
183
+ * `/api/graphql` answered as a path the API does not serve: a POST
184
+ * `405 mutations_not_enabled`, a GET `404 route_not_found`, in the REST
185
+ * envelope. `CAPA_API_GRAPHQL=off` does that, and so does the admin host for a
186
+ * GET, since it serves GraphQL by POST only. The GraphQL handler never answers
187
+ * in that envelope (a real mutation's refusal is `{ errors }`), so the
188
+ * envelope is what tells "GraphQL is not here" from "this document was
189
+ * refused", and a query is never told it tried to write. Null for any other
190
+ * answer.
191
+ */
192
+ function graphqlNotServed(status, body, method, fallbackRequestId) {
193
+ if (status !== 404 && status !== 405)
194
+ return null;
195
+ const object = body && typeof body === "object" ? body : {};
196
+ if (Array.isArray(object.errors))
197
+ return null;
198
+ const refusal = errorFromEnvelope(status, object, fallbackRequestId);
199
+ if (refusal.code !== "mutations_not_enabled" && refusal.code !== "route_not_found")
200
+ return null;
201
+ const byGet = method === "GET";
202
+ return new CapaError({
203
+ status,
204
+ type: refusal.type,
205
+ code: refusal.code,
206
+ message: byGet ? "This Capa host does not serve GraphQL by GET." : "This Capa deployment does not serve GraphQL.",
207
+ hint: byGet
208
+ ? "GraphQL is switched off here (CAPA_API_GRAPHQL=off), or this is the admin host, which serves GraphQL by POST only. " +
209
+ 'Send it by POST (method: "POST", without persisted); if that is refused too, read with client.entries.list or client.entries.get.'
210
+ : "GraphQL is switched off here (CAPA_API_GRAPHQL=off). Read the same content with client.entries.list or client.entries.get until it is back on.",
211
+ requestId: refusal.requestId,
212
+ docs: refusal.docs,
213
+ });
214
+ }
@@ -0,0 +1,37 @@
1
+ export declare const NAME_QUOTE = "\"";
2
+ /** Whether REST can name a field namespace at all: every one but an empty one or one starting with `$`. */
3
+ export declare function isNameable(namespace: string): boolean;
4
+ /** A namespace as every REST grammar writes it: bare where it can be, quoted otherwise. */
5
+ export declare function writeName(namespace: string): string;
6
+ /** One segment of a sort or filter path: a system key (`$id`) keeps its sigil, a namespace is written by `writeName`. */
7
+ export declare function writePathSegment(segment: string): string;
8
+ /** A path (`["at.place", "zip.code"]`) as sort and where write it: `"at.place"."zip.code"`. */
9
+ export declare function writePath(path: readonly string[]): string;
10
+ /** The quoted name opening at `text[pos]`, and the index just past its closing quote; null when it never closes. */
11
+ export declare function readQuoted(text: string, pos: number): {
12
+ name: string;
13
+ end: number;
14
+ } | null;
15
+ /** A name as written, read back: `"price.usd"` is `price.usd`, a bare name is itself. Null for a quote that does not close the name. */
16
+ export declare function readName(text: string): string | null;
17
+ /**
18
+ * `text` split on `separator` wherever it stands outside a quoted name and,
19
+ * unless `nested` is false, outside parentheses: a select level is split on
20
+ * its commas outside both, a list of names on its commas outside quotes.
21
+ * Null when a quote never closes.
22
+ */
23
+ export declare function splitOutside(text: string, separator: string, { nested }?: {
24
+ nested?: boolean | undefined;
25
+ }): string[] | null;
26
+ /** One segment of a sort or filter path, read back, and whether it was quoted: a quoted one is always a field. */
27
+ export interface NameSegment {
28
+ name: string;
29
+ quoted: boolean;
30
+ }
31
+ /**
32
+ * A sort or filter path's segments, split on the dots outside quotes, each
33
+ * read back (`"at.place"."zip.code"` is `at.place` then `zip.code`). A bare
34
+ * segment is everything up to the next dot, as the API reads it. Null when a
35
+ * quote never closes or runs into something other than a dot.
36
+ */
37
+ export declare function readPath(text: string): NameSegment[] | null;