@prismicio/client 7.2.0 → 7.3.0

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 (119) hide show
  1. package/dist/createClient.cjs +9 -1
  2. package/dist/createClient.cjs.map +1 -1
  3. package/dist/createClient.js +9 -1
  4. package/dist/createClient.js.map +1 -1
  5. package/dist/errors/ForbiddenError.cjs.map +1 -1
  6. package/dist/errors/ForbiddenError.d.ts +1 -1
  7. package/dist/errors/ForbiddenError.js.map +1 -1
  8. package/dist/errors/NotFoundError.cjs.map +1 -1
  9. package/dist/errors/NotFoundError.d.ts +1 -1
  10. package/dist/errors/NotFoundError.js.map +1 -1
  11. package/dist/errors/ParsingError.cjs.map +1 -1
  12. package/dist/errors/ParsingError.d.ts +1 -1
  13. package/dist/errors/ParsingError.js.map +1 -1
  14. package/dist/errors/RefExpiredError.cjs +7 -0
  15. package/dist/errors/RefExpiredError.cjs.map +1 -0
  16. package/dist/errors/RefExpiredError.d.ts +8 -0
  17. package/dist/errors/RefExpiredError.js +7 -0
  18. package/dist/errors/RefExpiredError.js.map +1 -0
  19. package/dist/errors/RefNotFoundError.cjs +7 -0
  20. package/dist/errors/RefNotFoundError.cjs.map +1 -0
  21. package/dist/errors/RefNotFoundError.d.ts +8 -0
  22. package/dist/errors/RefNotFoundError.js +7 -0
  23. package/dist/errors/RefNotFoundError.js.map +1 -0
  24. package/dist/helpers/asHTML.cjs +43 -50
  25. package/dist/helpers/asHTML.cjs.map +1 -1
  26. package/dist/helpers/asHTML.d.ts +31 -6
  27. package/dist/helpers/asHTML.js +42 -49
  28. package/dist/helpers/asHTML.js.map +1 -1
  29. package/dist/helpers/asImagePixelDensitySrcSet.d.ts +1 -1
  30. package/dist/helpers/asImageSrc.d.ts +1 -1
  31. package/dist/helpers/asImageWidthSrcSet.cjs +1 -1
  32. package/dist/helpers/asImageWidthSrcSet.cjs.map +1 -1
  33. package/dist/helpers/asImageWidthSrcSet.d.ts +1 -1
  34. package/dist/helpers/asImageWidthSrcSet.js +1 -1
  35. package/dist/helpers/asImageWidthSrcSet.js.map +1 -1
  36. package/dist/helpers/asLinkAttrs.d.ts +1 -1
  37. package/dist/helpers/asText.cjs +2 -2
  38. package/dist/helpers/asText.cjs.map +1 -1
  39. package/dist/helpers/asText.js +1 -1
  40. package/dist/helpers/asText.js.map +1 -1
  41. package/dist/helpers/isFilled.d.ts +10 -13
  42. package/dist/index.cjs +8 -7
  43. package/dist/index.cjs.map +1 -1
  44. package/dist/index.d.ts +28 -2
  45. package/dist/index.js +6 -2
  46. package/dist/index.js.map +1 -1
  47. package/dist/lib/serializerHelpers.cjs +91 -35
  48. package/dist/lib/serializerHelpers.cjs.map +1 -1
  49. package/dist/lib/serializerHelpers.d.ts +8 -8
  50. package/dist/lib/serializerHelpers.js +91 -35
  51. package/dist/lib/serializerHelpers.js.map +1 -1
  52. package/dist/package.json.cjs +1 -1
  53. package/dist/package.json.js +1 -1
  54. package/dist/richtext/asText.cjs +13 -0
  55. package/dist/richtext/asText.cjs.map +1 -0
  56. package/dist/richtext/asText.d.ts +12 -0
  57. package/dist/richtext/asText.js +13 -0
  58. package/dist/richtext/asText.js.map +1 -0
  59. package/dist/richtext/asTree.cjs +123 -0
  60. package/dist/richtext/asTree.cjs.map +1 -0
  61. package/dist/richtext/asTree.d.ts +14 -0
  62. package/dist/richtext/asTree.js +123 -0
  63. package/dist/richtext/asTree.js.map +1 -0
  64. package/dist/richtext/composeSerializers.cjs +17 -0
  65. package/dist/richtext/composeSerializers.cjs.map +1 -0
  66. package/dist/richtext/composeSerializers.d.ts +16 -0
  67. package/dist/richtext/composeSerializers.js +17 -0
  68. package/dist/richtext/composeSerializers.js.map +1 -0
  69. package/dist/richtext/index.d.ts +7 -0
  70. package/dist/richtext/serialize.cjs +19 -0
  71. package/dist/richtext/serialize.cjs.map +1 -0
  72. package/dist/richtext/serialize.d.ts +19 -0
  73. package/dist/richtext/serialize.js +19 -0
  74. package/dist/richtext/serialize.js.map +1 -0
  75. package/dist/richtext/types.cjs +11 -0
  76. package/dist/richtext/types.cjs.map +1 -0
  77. package/dist/richtext/types.d.ts +71 -0
  78. package/dist/richtext/types.js +11 -0
  79. package/dist/richtext/types.js.map +1 -0
  80. package/dist/richtext/wrapMapSerializer.cjs +24 -0
  81. package/dist/richtext/wrapMapSerializer.cjs.map +1 -0
  82. package/dist/richtext/wrapMapSerializer.d.ts +15 -0
  83. package/dist/richtext/wrapMapSerializer.js +24 -0
  84. package/dist/richtext/wrapMapSerializer.js.map +1 -0
  85. package/dist/richtext.cjs +15 -0
  86. package/dist/richtext.cjs.map +1 -0
  87. package/dist/richtext.js +15 -0
  88. package/dist/richtext.js.map +1 -0
  89. package/dist/types/value/image.d.ts +9 -0
  90. package/dist/types/value/linkToMedia.d.ts +1 -0
  91. package/dist/types/value/richText.cjs.map +1 -1
  92. package/dist/types/value/richText.d.ts +7 -0
  93. package/dist/types/value/richText.js.map +1 -1
  94. package/dist/types/value/sharedSlice.d.ts +1 -1
  95. package/dist/types/value/slice.d.ts +1 -1
  96. package/package.json +34 -15
  97. package/src/createClient.ts +17 -4
  98. package/src/errors/ForbiddenError.ts +5 -3
  99. package/src/errors/NotFoundError.ts +3 -1
  100. package/src/errors/ParsingError.ts +3 -1
  101. package/src/errors/RefExpiredError.ts +14 -0
  102. package/src/errors/RefNotFoundError.ts +14 -0
  103. package/src/helpers/asHTML.ts +166 -76
  104. package/src/helpers/asImageWidthSrcSet.ts +2 -0
  105. package/src/helpers/asText.ts +2 -2
  106. package/src/index.ts +9 -4
  107. package/src/lib/serializerHelpers.ts +140 -67
  108. package/src/richtext/asText.ts +27 -0
  109. package/src/richtext/asTree.ts +211 -0
  110. package/src/richtext/composeSerializers.ts +36 -0
  111. package/src/richtext/index.ts +14 -0
  112. package/src/richtext/serialize.ts +54 -0
  113. package/src/richtext/types.ts +153 -0
  114. package/src/richtext/wrapMapSerializer.ts +46 -0
  115. package/src/types/value/image.ts +9 -0
  116. package/src/types/value/linkToMedia.ts +1 -0
  117. package/src/types/value/richText.ts +7 -0
  118. package/src/types/value/sharedSlice.ts +1 -1
  119. package/src/types/value/slice.ts +1 -1
@@ -1,3 +1,5 @@
1
1
  import { PrismicError } from "./PrismicError";
2
2
 
3
- export class NotFoundError extends PrismicError<undefined> {}
3
+ export class NotFoundError<
4
+ TResponse = undefined,
5
+ > extends PrismicError<TResponse> {}
@@ -9,4 +9,6 @@ type ParsingErrorAPIResponse = {
9
9
  location: string;
10
10
  };
11
11
 
12
- export class ParsingError extends PrismicError<ParsingErrorAPIResponse> {}
12
+ export class ParsingError<
13
+ TResponse = ParsingErrorAPIResponse,
14
+ > extends PrismicError<TResponse> {}
@@ -0,0 +1,14 @@
1
+ import { ForbiddenError } from "./ForbiddenError";
2
+
3
+ type RefExpiredErrorAPIResponse = {
4
+ type: "api_validation_error";
5
+ message: string;
6
+ };
7
+
8
+ // This error extends `ForbiddenError` for backwards compatibility. Before the
9
+ // API started returning 410 for expired refs, it returnd 403, which threw a
10
+ // `ForbiddenError`.
11
+ // TODO: Extend this error from `PrismicError` in v8.
12
+ export class RefExpiredError<
13
+ TResponse = RefExpiredErrorAPIResponse,
14
+ > extends ForbiddenError<TResponse> {}
@@ -0,0 +1,14 @@
1
+ import { ForbiddenError } from "./ForbiddenError";
2
+
3
+ type RefNotFoundErrorAPIResponse = {
4
+ type: "api_notfound_error";
5
+ message: string;
6
+ };
7
+
8
+ // This error extends `ForbiddenError` for backwards compatibility. Before the
9
+ // API started returning 404 for not found refs, it returnd 403, which threw a
10
+ // `ForbiddenError`.
11
+ // TODO: Extend this error from `PrismicError` in v8.
12
+ export class RefNotFoundError<
13
+ TResponse = RefNotFoundErrorAPIResponse,
14
+ > extends ForbiddenError<TResponse> {}
@@ -1,13 +1,3 @@
1
- import {
2
- Element,
3
- RichTextFunctionSerializer,
4
- RichTextMapSerializer,
5
- RichTextMapSerializerFunction,
6
- composeSerializers,
7
- serialize,
8
- wrapMapSerializer,
9
- } from "@prismicio/richtext";
10
-
11
1
  import {
12
2
  serializeEmbed,
13
3
  serializeHyperlink,
@@ -19,14 +9,23 @@ import {
19
9
 
20
10
  import type { RichTextField } from "../types/value/richText";
21
11
 
12
+ import {
13
+ RichTextFunctionSerializer,
14
+ RichTextMapSerializer,
15
+ RichTextMapSerializerFunction,
16
+ composeSerializers,
17
+ serialize,
18
+ wrapMapSerializer,
19
+ } from "../richtext";
20
+
22
21
  import { LinkResolverFunction } from "./asLink";
23
22
 
24
23
  /**
25
24
  * Serializes a node from a rich text or title field with a function to HTML.
26
25
  *
27
- * Unlike a typical `@prismicio/richtext` function serializer, this serializer
28
- * converts the `children` argument to a single string rather than an array of
29
- * strings.
26
+ * Unlike a typical `@prismicio/client/richtext` function serializer, this
27
+ * serializer converts the `children` argument to a single string rather than an
28
+ * array of strings.
30
29
  *
31
30
  * @see Templating rich text and title fields from Prismic {@link https://prismic.io/docs/template-content-vanilla-javascript#rich-text-and-title}
32
31
  */
@@ -41,13 +40,28 @@ export type HTMLRichTextFunctionSerializer = (
41
40
  /**
42
41
  * Serializes a node from a rich text or title field with a map to HTML
43
42
  *
44
- * Unlike a typical `@prismicio/richtext` map serializer, this serializer
43
+ * Unlike a typical `@prismicio/client/richtext` map serializer, this serializer
45
44
  * converts the `children` property to a single string rather than an array of
46
- * strings.
45
+ * strings and accepts shorthand declarations.
47
46
  *
48
47
  * @see Templating rich text and title fields from Prismic {@link https://prismic.io/docs/template-content-vanilla-javascript#rich-text-and-title}
49
48
  */
50
49
  export type HTMLRichTextMapSerializer = {
50
+ [P in keyof RichTextMapSerializer<string>]: P extends RichTextMapSerializer<string>["span"]
51
+ ? HTMLStrictRichTextMapSerializer[P]
52
+ : HTMLStrictRichTextMapSerializer[P] | HTMLRichTextMapSerializerShorthand;
53
+ };
54
+
55
+ /**
56
+ * Serializes a node from a rich text or title field with a map to HTML
57
+ *
58
+ * Unlike a typical `@prismicio/client/richtext` map serializer, this serializer
59
+ * converts the `children` property to a single string rather than an array of
60
+ * strings but doesn't accept shorthand declarations.
61
+ *
62
+ * @see Templating rich text and title fields from Prismic {@link https://prismic.io/docs/template-content-vanilla-javascript#rich-text-and-title}
63
+ */
64
+ export type HTMLStrictRichTextMapSerializer = {
51
65
  [P in keyof RichTextMapSerializer<string>]: (payload: {
52
66
  type: Parameters<HTMLRichTextMapSerializerFunction<P>>[0]["type"];
53
67
  node: Parameters<HTMLRichTextMapSerializerFunction<P>>[0]["node"];
@@ -105,6 +119,21 @@ type ExtractTextTypeGeneric<T> = T extends RichTextMapSerializerFunction<
105
119
  ? U
106
120
  : never;
107
121
 
122
+ /**
123
+ * A shorthand definition for {@link HTMLRichTextMapSerializer} element types.
124
+ */
125
+ export type HTMLRichTextMapSerializerShorthand = {
126
+ /**
127
+ * Classes to apply to the element type.
128
+ */
129
+ class?: string;
130
+
131
+ /**
132
+ * Other attributes to apply to the element type.
133
+ */
134
+ [Attribute: string]: string | boolean | null | undefined;
135
+ };
136
+
108
137
  /**
109
138
  * Serializes a node from a rich text or title field with a map or a function to
110
139
  * HTML
@@ -117,70 +146,126 @@ export type HTMLRichTextSerializer =
117
146
  | HTMLRichTextFunctionSerializer;
118
147
 
119
148
  /**
120
- * Creates a default HTML rich text serializer with a given link resolver
121
- * providing sensible and safe defaults for every node type
149
+ * Creates a HTML rich text serializer with a given link resolver and provide
150
+ * sensible and safe defaults for every node type
122
151
  *
123
152
  * @internal
124
153
  */
125
- const createDefaultHTMLRichTextSerializer = (
154
+ const createHTMLRichTextSerializer = (
126
155
  linkResolver: LinkResolverFunction | undefined | null,
156
+ serializer?: HTMLRichTextMapSerializer | null,
127
157
  ): RichTextFunctionSerializer<string> => {
128
- return (_type, node, text, children, _key) => {
129
- switch (node.type) {
130
- case Element.heading1:
131
- return serializeStandardTag("h1", node, children);
132
- case Element.heading2:
133
- return serializeStandardTag("h2", node, children);
134
- case Element.heading3:
135
- return serializeStandardTag("h3", node, children);
136
- case Element.heading4:
137
- return serializeStandardTag("h4", node, children);
138
- case Element.heading5:
139
- return serializeStandardTag("h5", node, children);
140
- case Element.heading6:
141
- return serializeStandardTag("h6", node, children);
142
- case Element.paragraph:
143
- return serializeStandardTag("p", node, children);
144
- case Element.preformatted:
145
- return serializePreFormatted(node);
146
- case Element.strong:
147
- return serializeStandardTag("strong", node, children);
148
- case Element.em:
149
- return serializeStandardTag("em", node, children);
150
- case Element.listItem:
151
- return serializeStandardTag("li", node, children);
152
- case Element.oListItem:
153
- return serializeStandardTag("li", node, children);
154
- case Element.list:
155
- return serializeStandardTag("ul", node, children);
156
- case Element.oList:
157
- return serializeStandardTag("ol", node, children);
158
- case Element.image:
159
- return serializeImage(linkResolver, node);
160
- case Element.embed:
161
- return serializeEmbed(node);
162
- case Element.hyperlink:
163
- return serializeHyperlink(linkResolver, node, children);
164
- case Element.label:
165
- return serializeStandardTag("span", node, children);
166
- case Element.span:
167
- default:
168
- return serializeSpan(text);
158
+ const useSerializerOrDefault = <
159
+ BlockType extends keyof RichTextMapSerializer<string>,
160
+ >(
161
+ nodeSerializerOrShorthand: HTMLRichTextMapSerializer[BlockType],
162
+ defaultWithShorthand: NonNullable<
163
+ HTMLStrictRichTextMapSerializer[BlockType]
164
+ >,
165
+ ): NonNullable<HTMLStrictRichTextMapSerializer[BlockType]> => {
166
+ if (typeof nodeSerializerOrShorthand === "function") {
167
+ return ((payload) => {
168
+ return (
169
+ (
170
+ nodeSerializerOrShorthand as HTMLStrictRichTextMapSerializer[BlockType]
171
+ )(payload) || defaultWithShorthand(payload)
172
+ );
173
+ }) as NonNullable<HTMLStrictRichTextMapSerializer[BlockType]>;
169
174
  }
175
+
176
+ return defaultWithShorthand;
177
+ };
178
+
179
+ const mapSerializer: Required<HTMLStrictRichTextMapSerializer> = {
180
+ heading1: useSerializerOrDefault<"heading1">(
181
+ serializer?.heading1,
182
+ serializeStandardTag<"heading1">("h1", serializer?.heading1),
183
+ ),
184
+ heading2: useSerializerOrDefault<"heading2">(
185
+ serializer?.heading2,
186
+ serializeStandardTag<"heading2">("h2", serializer?.heading2),
187
+ ),
188
+ heading3: useSerializerOrDefault<"heading3">(
189
+ serializer?.heading3,
190
+ serializeStandardTag<"heading3">("h3", serializer?.heading3),
191
+ ),
192
+ heading4: useSerializerOrDefault<"heading4">(
193
+ serializer?.heading4,
194
+ serializeStandardTag<"heading4">("h4", serializer?.heading4),
195
+ ),
196
+ heading5: useSerializerOrDefault<"heading5">(
197
+ serializer?.heading5,
198
+ serializeStandardTag<"heading5">("h5", serializer?.heading5),
199
+ ),
200
+ heading6: useSerializerOrDefault<"heading6">(
201
+ serializer?.heading6,
202
+ serializeStandardTag<"heading6">("h6", serializer?.heading6),
203
+ ),
204
+ paragraph: useSerializerOrDefault<"paragraph">(
205
+ serializer?.paragraph,
206
+ serializeStandardTag<"paragraph">("p", serializer?.paragraph),
207
+ ),
208
+ preformatted: useSerializerOrDefault<"preformatted">(
209
+ serializer?.preformatted,
210
+ serializePreFormatted(serializer?.preformatted),
211
+ ),
212
+ strong: useSerializerOrDefault<"strong">(
213
+ serializer?.strong,
214
+ serializeStandardTag<"strong">("strong", serializer?.strong),
215
+ ),
216
+ em: useSerializerOrDefault<"em">(
217
+ serializer?.em,
218
+ serializeStandardTag<"em">("em", serializer?.em),
219
+ ),
220
+ listItem: useSerializerOrDefault<"listItem">(
221
+ serializer?.listItem,
222
+ serializeStandardTag<"listItem">("li", serializer?.listItem),
223
+ ),
224
+ oListItem: useSerializerOrDefault<"oListItem">(
225
+ serializer?.oListItem,
226
+ serializeStandardTag<"oListItem">("li", serializer?.oListItem),
227
+ ),
228
+ list: useSerializerOrDefault<"list">(
229
+ serializer?.list,
230
+ serializeStandardTag<"list">("ul", serializer?.list),
231
+ ),
232
+ oList: useSerializerOrDefault<"oList">(
233
+ serializer?.oList,
234
+ serializeStandardTag<"oList">("ol", serializer?.oList),
235
+ ),
236
+ image: useSerializerOrDefault<"image">(
237
+ serializer?.image,
238
+ serializeImage(linkResolver, serializer?.image),
239
+ ),
240
+ embed: useSerializerOrDefault<"embed">(
241
+ serializer?.embed,
242
+ serializeEmbed(serializer?.embed),
243
+ ),
244
+ hyperlink: useSerializerOrDefault<"hyperlink">(
245
+ serializer?.hyperlink,
246
+ serializeHyperlink(linkResolver, serializer?.hyperlink),
247
+ ),
248
+ label: useSerializerOrDefault<"label">(
249
+ serializer?.label,
250
+ serializeStandardTag<"label">("span", serializer?.label),
251
+ ),
252
+ span: useSerializerOrDefault<"span">(serializer?.span, serializeSpan()),
170
253
  };
254
+
255
+ return wrapMapSerializerWithStringChildren(mapSerializer);
171
256
  };
172
257
 
173
258
  /**
174
259
  * Wraps a map serializer into a regular function serializer. The given map
175
260
  * serializer should accept children as a string, not as an array of strings
176
- * like `@prismicio/richtext`'s `wrapMapSerializer`.
261
+ * like `@prismicio/client/richtext`'s `wrapMapSerializer`.
177
262
  *
178
263
  * @param mapSerializer - Map serializer to wrap
179
264
  *
180
265
  * @returns A regular function serializer
181
266
  */
182
267
  const wrapMapSerializerWithStringChildren = (
183
- mapSerializer: HTMLRichTextMapSerializer,
268
+ mapSerializer: HTMLStrictRichTextMapSerializer,
184
269
  ): RichTextFunctionSerializer<string> => {
185
270
  const modifiedMapSerializer = {} as RichTextMapSerializer<string>;
186
271
 
@@ -292,22 +377,27 @@ export const asHTML: {
292
377
 
293
378
  let serializer: RichTextFunctionSerializer<string>;
294
379
  if (config.serializer) {
295
- serializer = composeSerializers(
296
- typeof config.serializer === "object"
297
- ? wrapMapSerializerWithStringChildren(config.serializer)
298
- : (type, node, text, children, key) =>
299
- // TypeScript doesn't narrow the type correctly here since it is now in a callback function, so we have to cast it here.
300
- (config.serializer as HTMLRichTextFunctionSerializer)(
301
- type,
302
- node,
303
- text,
304
- children.join(""),
305
- key,
306
- ),
307
- createDefaultHTMLRichTextSerializer(config.linkResolver),
308
- );
380
+ if (typeof config.serializer === "function") {
381
+ serializer = composeSerializers(
382
+ (type, node, text, children, key) =>
383
+ // TypeScript doesn't narrow the type correctly here since it is now in a callback function, so we have to cast it here.
384
+ (config.serializer as HTMLRichTextFunctionSerializer)(
385
+ type,
386
+ node,
387
+ text,
388
+ children.join(""),
389
+ key,
390
+ ),
391
+ createHTMLRichTextSerializer(config.linkResolver),
392
+ );
393
+ } else {
394
+ serializer = createHTMLRichTextSerializer(
395
+ config.linkResolver,
396
+ config.serializer,
397
+ );
398
+ }
309
399
  } else {
310
- serializer = createDefaultHTMLRichTextSerializer(config.linkResolver);
400
+ serializer = createHTMLRichTextSerializer(config.linkResolver);
311
401
  }
312
402
 
313
403
  return serialize(richTextField, serializer).join(
@@ -94,8 +94,10 @@ export const asImageWidthSrcSet = <
94
94
  const {
95
95
  url,
96
96
  dimensions,
97
+ id: _id,
97
98
  alt: _alt,
98
99
  copyright: _copyright,
100
+ edit: _edit,
99
101
  ...responsiveViews
100
102
  } = field;
101
103
 
@@ -1,7 +1,7 @@
1
- import { asText as baseAsText } from "@prismicio/richtext";
2
-
3
1
  import { RichTextField } from "../types/value/richText";
4
2
 
3
+ import { asText as baseAsText } from "../richtext/asText";
4
+
5
5
  /**
6
6
  * Configuration that determines the output of `asText()`.
7
7
  */
package/src/index.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  // Imports are used for deprecations.
2
2
  import type { CustomTypeModelIntegrationField } from "./types/model/integration";
3
3
  import type { IntegrationField } from "./types/value/integration";
4
+ import { RichTextNodeType } from "./types/value/richText";
4
5
 
5
6
  import type {
6
7
  HTMLRichTextFunctionSerializer,
@@ -74,9 +75,6 @@ export * as isFilled from "./helpers/isFilled";
74
75
  // Conversion helper.
75
76
  export { documentToLinkField } from "./helpers/documentToLinkField";
76
77
 
77
- // RichText element types.
78
- export { Element } from "@prismicio/richtext";
79
-
80
78
  export type { LinkResolverFunction } from "./helpers/asLink";
81
79
  export type { AsLinkAttrsConfig } from "./helpers/asLinkAttrs";
82
80
 
@@ -103,6 +101,8 @@ export type { HTMLRichTextSerializer } from "./helpers/asHTML";
103
101
  export { PrismicError } from "./errors/PrismicError";
104
102
  export { ForbiddenError } from "./errors/ForbiddenError";
105
103
  export { NotFoundError } from "./errors/NotFoundError";
104
+ export { RefNotFoundError } from "./errors/RefNotFoundError";
105
+ export { RefExpiredError } from "./errors/RefExpiredError";
106
106
  export { ParsingError } from "./errors/ParsingError";
107
107
 
108
108
  //=============================================================================
@@ -110,7 +110,12 @@ export { ParsingError } from "./errors/ParsingError";
110
110
  //=============================================================================
111
111
 
112
112
  // Values - Types representing Prismic content.
113
- export { RichTextNodeType } from "./types/value/richText";
113
+ /**
114
+ * @deprecated Use {@link RichTextNodeType} instead.
115
+ */
116
+ // TODO: Remove in v8.
117
+ const Element = RichTextNodeType;
118
+ export { RichTextNodeType, Element };
114
119
  export { LinkType } from "./types/value/link";
115
120
  export { OEmbedType } from "./types/value/embed";
116
121
 
@@ -1,34 +1,82 @@
1
+ import type { RichTextMapSerializer } from "../richtext/types";
1
2
  import { LinkType } from "../types/value/link";
2
- import {
3
- RTBlockNode,
4
- RTEmbedNode,
5
- RTImageNode,
6
- RTInlineNode,
7
- RTLinkNode,
8
- RTPreformattedNode,
9
- RichTextNodeType,
10
- } from "../types/value/richText";
3
+ import { RTAnyNode } from "../types/value/richText";
11
4
 
5
+ import {
6
+ HTMLRichTextMapSerializer,
7
+ HTMLStrictRichTextMapSerializer,
8
+ } from "../helpers/asHTML";
12
9
  import { LinkResolverFunction, asLink } from "../helpers/asLink";
13
10
 
14
11
  import { escapeHTML } from "./escapeHTML";
15
12
 
16
- export const getLabel = (node: RTBlockNode | RTInlineNode): string => {
17
- return "data" in node && "label" in node.data
18
- ? ` class="${node.data.label}"`
19
- : "";
13
+ type Attributes = Record<string, string | boolean | null | undefined>;
14
+ const formatAttributes = (node: RTAnyNode, attributes: Attributes): string => {
15
+ const _attributes = { ...attributes };
16
+
17
+ // Add label to attributes
18
+ if ("data" in node && "label" in node.data && node.data.label) {
19
+ _attributes.class = _attributes.class
20
+ ? `${_attributes.class} ${node.data.label}`
21
+ : node.data.label;
22
+ }
23
+
24
+ const result = [];
25
+
26
+ for (const key in _attributes) {
27
+ const value = _attributes[key];
28
+
29
+ if (value) {
30
+ if (typeof value === "boolean") {
31
+ result.push(key);
32
+ } else {
33
+ result.push(`${key}="${escapeHTML(value)}"`);
34
+ }
35
+ }
36
+ }
37
+
38
+ // Add a space at the beginning if there's any result
39
+ if (result.length) {
40
+ result.unshift("");
41
+ }
42
+
43
+ return result.join(" ");
44
+ };
45
+
46
+ const getGeneralAttributes = (
47
+ serializerOrShorthand?: HTMLRichTextMapSerializer[keyof HTMLRichTextMapSerializer],
48
+ ): Attributes => {
49
+ return serializerOrShorthand && typeof serializerOrShorthand !== "function"
50
+ ? serializerOrShorthand
51
+ : {};
20
52
  };
21
53
 
22
- export const serializeStandardTag = (
54
+ export const serializeStandardTag = <
55
+ BlockType extends keyof RichTextMapSerializer<string>,
56
+ >(
23
57
  tag: string,
24
- node: RTBlockNode | RTInlineNode,
25
- children: string[],
26
- ): string => {
27
- return `<${tag}${getLabel(node)}>${children.join("")}</${tag}>`;
58
+ serializerOrShorthand?: HTMLRichTextMapSerializer[BlockType],
59
+ ): NonNullable<HTMLStrictRichTextMapSerializer[BlockType]> => {
60
+ const generalAttributes = getGeneralAttributes(serializerOrShorthand);
61
+
62
+ return (({ node, children }) => {
63
+ return `<${tag}${formatAttributes(
64
+ node,
65
+ generalAttributes,
66
+ )}>${children}</${tag}>`;
67
+ }) as NonNullable<HTMLStrictRichTextMapSerializer[BlockType]>;
28
68
  };
29
69
 
30
- export const serializePreFormatted = (node: RTPreformattedNode): string => {
31
- return `<pre${getLabel(node)}>${escapeHTML(node.text)}</pre>`;
70
+ export const serializePreFormatted = (
71
+ serializerOrShorthand?: HTMLRichTextMapSerializer["preformatted"],
72
+ ): NonNullable<HTMLStrictRichTextMapSerializer["preformatted"]> => {
73
+ const generalAttributes = getGeneralAttributes(serializerOrShorthand);
74
+
75
+ return ({ node }) => {
76
+ return `<pre${formatAttributes(node, generalAttributes)}>${escapeHTML(
77
+ node.text,
78
+ )}</pre>`;
79
+ };
32
80
  };
33
81
 
34
82
  export const serializeImage = (
@@ -36,35 +84,57 @@ export const serializeImage = (
36
84
  | LinkResolverFunction<string | null | undefined>
37
85
  | undefined
38
86
  | null,
39
- node: RTImageNode,
40
- ): string => {
41
- let imageTag = `<img src="${node.url}" alt="${escapeHTML(node.alt)}"${
42
- node.copyright ? ` copyright="${escapeHTML(node.copyright)}"` : ""
43
- } />`;
44
-
45
- // If the image has a link, we wrap it with an anchor tag
46
- if (node.linkTo) {
47
- imageTag = serializeHyperlink(
48
- linkResolver,
49
- {
50
- type: RichTextNodeType.hyperlink,
51
- data: node.linkTo,
52
- start: 0,
53
- end: 0,
54
- },
55
- [imageTag],
56
- );
57
- }
87
+ serializerOrShorthand?: HTMLRichTextMapSerializer["image"],
88
+ ): NonNullable<HTMLStrictRichTextMapSerializer["image"]> => {
89
+ const generalAttributes = getGeneralAttributes(serializerOrShorthand);
90
+
91
+ return ({ node }) => {
92
+ const attributes = {
93
+ ...generalAttributes,
94
+ src: node.url,
95
+ alt: node.alt,
96
+ copyright: node.copyright,
97
+ };
98
+
99
+ let imageTag = `<img${formatAttributes(node, attributes)} />`;
100
+
101
+ // If the image has a link, we wrap it with an anchor tag
102
+ if (node.linkTo) {
103
+ imageTag = serializeHyperlink(linkResolver)({
104
+ type: "hyperlink",
105
+ node: {
106
+ type: "hyperlink",
107
+ data: node.linkTo,
108
+ start: 0,
109
+ end: 0,
110
+ },
111
+ text: "",
112
+ children: imageTag,
113
+ key: "",
114
+ })!;
115
+ }
58
116
 
59
- return `<p class="block-img">${imageTag}</p>`;
117
+ return `<p class="block-img">${imageTag}</p>`;
118
+ };
60
119
  };
61
120
 
62
- export const serializeEmbed = (node: RTEmbedNode): string => {
63
- return `<div data-oembed="${node.oembed.embed_url}" data-oembed-type="${
64
- node.oembed.type
65
- }" data-oembed-provider="${node.oembed.provider_name}"${getLabel(node)}>${
66
- node.oembed.html
67
- }</div>`;
121
+ export const serializeEmbed = (
122
+ serializerOrShorthand?: HTMLRichTextMapSerializer["embed"],
123
+ ): NonNullable<HTMLStrictRichTextMapSerializer["embed"]> => {
124
+ const generalAttributes = getGeneralAttributes(serializerOrShorthand);
125
+
126
+ return ({ node }) => {
127
+ const attributes = {
128
+ ...generalAttributes,
129
+ ["data-oembed"]: node.oembed.embed_url,
130
+ ["data-oembed-type"]: node.oembed.type,
131
+ ["data-oembed-provider"]: node.oembed.provider_name,
132
+ };
133
+
134
+ return `<div${formatAttributes(node, attributes)}>${
135
+ node.oembed.html
136
+ }</div>`;
137
+ };
68
138
  };
69
139
 
70
140
  export const serializeHyperlink = (
@@ -72,30 +142,33 @@ export const serializeHyperlink = (
72
142
  | LinkResolverFunction<string | null | undefined>
73
143
  | undefined
74
144
  | null,
75
- node: RTLinkNode,
76
- children: string[],
77
- ): string => {
78
- switch (node.data.link_type) {
79
- case LinkType.Web: {
80
- return `<a href="${escapeHTML(node.data.url)}" ${
81
- node.data.target ? `target="${node.data.target}" ` : ""
82
- }rel="noopener noreferrer"${getLabel(node)}>${children.join("")}</a>`;
83
- }
145
+ serializerOrShorthand?: HTMLRichTextMapSerializer["hyperlink"],
146
+ ): NonNullable<HTMLStrictRichTextMapSerializer["hyperlink"]> => {
147
+ const generalAttributes = getGeneralAttributes(serializerOrShorthand);
84
148
 
85
- case LinkType.Document: {
86
- return `<a href="${asLink(node.data, linkResolver)}"${getLabel(
87
- node,
88
- )}>${children.join("")}</a>`;
89
- }
149
+ return ({ node, children }): string => {
150
+ const attributes = {
151
+ ...generalAttributes,
152
+ };
90
153
 
91
- case LinkType.Media: {
92
- return `<a href="${node.data.url}"${getLabel(node)}>${children.join(
93
- "",
94
- )}</a>`;
154
+ if (node.data.link_type === LinkType.Web) {
155
+ attributes.href = node.data.url;
156
+ attributes.target = node.data.target;
157
+ attributes.rel = "noopener noreferrer";
158
+ } else if (node.data.link_type === LinkType.Document) {
159
+ attributes.href = asLink(node.data, { linkResolver });
160
+ } else if (node.data.link_type === LinkType.Media) {
161
+ attributes.href = node.data.url;
95
162
  }
96
- }
163
+
164
+ return `<a${formatAttributes(node, attributes)}>${children}</a>`;
165
+ };
97
166
  };
98
167
 
99
- export const serializeSpan = (content?: string): string => {
100
- return content ? escapeHTML(content).replace(/\n/g, "<br />") : "";
168
+ export const serializeSpan = (): NonNullable<
169
+ HTMLStrictRichTextMapSerializer["span"]
170
+ > => {
171
+ return ({ text }): string => {
172
+ return text ? escapeHTML(text).replace(/\n/g, "<br />") : "";
173
+ };
101
174
  };