@prismicio/next 0.2.0-alpha.0 → 0.2.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 (82) hide show
  1. package/README.md +3 -1
  2. package/dist/PrismicNextImage.cjs +86 -0
  3. package/dist/PrismicNextImage.cjs.map +1 -0
  4. package/dist/PrismicNextImage.d.ts +52 -0
  5. package/dist/PrismicNextImage.js +69 -0
  6. package/dist/PrismicNextImage.js.map +1 -0
  7. package/dist/PrismicPreview.cjs +83 -0
  8. package/dist/PrismicPreview.cjs.map +1 -0
  9. package/dist/PrismicPreview.d.ts +42 -0
  10. package/dist/PrismicPreview.js +66 -0
  11. package/dist/PrismicPreview.js.map +1 -0
  12. package/dist/enableAutoPreviews.cjs +17 -0
  13. package/dist/enableAutoPreviews.cjs.map +1 -0
  14. package/dist/enableAutoPreviews.d.ts +38 -0
  15. package/dist/enableAutoPreviews.js +17 -0
  16. package/dist/enableAutoPreviews.js.map +1 -0
  17. package/dist/exitPreview.cjs +8 -0
  18. package/dist/exitPreview.cjs.map +1 -0
  19. package/dist/exitPreview.d.ts +30 -0
  20. package/dist/exitPreview.js +8 -0
  21. package/dist/exitPreview.js.map +1 -0
  22. package/dist/imgixLoader.cjs +17 -0
  23. package/dist/imgixLoader.cjs.map +1 -0
  24. package/dist/imgixLoader.d.ts +9 -0
  25. package/dist/imgixLoader.js +17 -0
  26. package/dist/imgixLoader.js.map +1 -0
  27. package/dist/index.cjs +17 -182
  28. package/dist/index.cjs.map +1 -0
  29. package/dist/index.d.ts +8 -204
  30. package/dist/index.js +17 -153
  31. package/dist/index.js.map +1 -0
  32. package/dist/lib/__PRODUCTION__.cjs +5 -0
  33. package/dist/lib/__PRODUCTION__.cjs.map +1 -0
  34. package/dist/lib/__PRODUCTION__.d.ts +7 -0
  35. package/dist/lib/__PRODUCTION__.js +5 -0
  36. package/dist/lib/__PRODUCTION__.js.map +1 -0
  37. package/dist/lib/devMsg.cjs +8 -0
  38. package/dist/lib/devMsg.cjs.map +1 -0
  39. package/dist/lib/devMsg.d.ts +16 -0
  40. package/dist/lib/devMsg.js +8 -0
  41. package/dist/lib/devMsg.js.map +1 -0
  42. package/dist/lib/getPreviewCookieRepositoryName.cjs +7 -0
  43. package/dist/lib/getPreviewCookieRepositoryName.cjs.map +1 -0
  44. package/dist/lib/getPreviewCookieRepositoryName.d.ts +9 -0
  45. package/dist/lib/getPreviewCookieRepositoryName.js +7 -0
  46. package/dist/lib/getPreviewCookieRepositoryName.js.map +1 -0
  47. package/dist/lib/getPrismicPreviewCookie.cjs +38 -0
  48. package/dist/lib/getPrismicPreviewCookie.cjs.map +1 -0
  49. package/dist/lib/getPrismicPreviewCookie.d.ts +9 -0
  50. package/dist/lib/getPrismicPreviewCookie.js +21 -0
  51. package/dist/lib/getPrismicPreviewCookie.js.map +1 -0
  52. package/dist/package.json.cjs +5 -0
  53. package/dist/package.json.cjs.map +1 -0
  54. package/dist/package.json.js +5 -0
  55. package/dist/package.json.js.map +1 -0
  56. package/dist/redirectToPreviewURL.cjs +22 -0
  57. package/dist/redirectToPreviewURL.cjs.map +1 -0
  58. package/dist/redirectToPreviewURL.d.ts +59 -0
  59. package/dist/redirectToPreviewURL.js +22 -0
  60. package/dist/redirectToPreviewURL.js.map +1 -0
  61. package/dist/setPreviewData.cjs +28 -0
  62. package/dist/setPreviewData.cjs.map +1 -0
  63. package/dist/setPreviewData.d.ts +29 -0
  64. package/dist/setPreviewData.js +11 -0
  65. package/dist/setPreviewData.js.map +1 -0
  66. package/dist/types.d.ts +21 -0
  67. package/package.json +40 -35
  68. package/src/PrismicNextImage.tsx +141 -0
  69. package/src/PrismicPreview.tsx +80 -93
  70. package/src/enableAutoPreviews.ts +4 -2
  71. package/src/exitPreview.ts +15 -7
  72. package/src/imgixLoader.ts +25 -0
  73. package/src/index.ts +16 -11
  74. package/src/lib/__PRODUCTION__.ts +7 -0
  75. package/src/lib/devMsg.ts +20 -0
  76. package/src/lib/getPreviewCookieRepositoryName.ts +14 -0
  77. package/src/lib/getPrismicPreviewCookie.ts +33 -0
  78. package/src/redirectToPreviewURL.ts +11 -6
  79. package/src/setPreviewData.ts +7 -2
  80. package/src/types.ts +3 -2
  81. package/src/lib/extractPreviewRefRepositoryName.ts +0 -60
  82. package/src/lib/getCookie.ts +0 -51
@@ -0,0 +1,141 @@
1
+ import Image, { ImageProps } from "next/image";
2
+ import { buildURL, ImgixURLParams } from "imgix-url-builder";
3
+ import * as prismicH from "@prismicio/helpers";
4
+ import * as prismicT from "@prismicio/types";
5
+
6
+ import { __PRODUCTION__ } from "./lib/__PRODUCTION__";
7
+ import { devMsg } from "./lib/devMsg";
8
+
9
+ import { imgixLoader } from "./imgixLoader";
10
+
11
+ const castInt = (input: string | number | undefined): number | undefined => {
12
+ if (typeof input === "number" || typeof input === "undefined") {
13
+ return input;
14
+ } else {
15
+ const parsed = Number.parseInt(input);
16
+
17
+ if (Number.isNaN(parsed)) {
18
+ return undefined;
19
+ } else {
20
+ return parsed;
21
+ }
22
+ }
23
+ };
24
+
25
+ export type PrismicNextImageProps = Omit<ImageProps, "src" | "alt"> & {
26
+ /**
27
+ * The Prismic Image field or thumbnail to render.
28
+ */
29
+ field: prismicT.ImageFieldImage | null | undefined;
30
+
31
+ /**
32
+ * An object of Imgix URL API parameters to transform the image.
33
+ *
34
+ * @see https://docs.imgix.com/apis/rendering
35
+ */
36
+ imgixParams?: ImgixURLParams;
37
+
38
+ /**
39
+ * Declare an image as decorative by providing `alt=""`.
40
+ *
41
+ * See:
42
+ * https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/alt#decorative_images
43
+ */
44
+ alt?: "";
45
+
46
+ /**
47
+ * Declare an image as decorative only if the Image field does not have
48
+ * alternative text by providing `fallbackAlt=""`.
49
+ *
50
+ * See:
51
+ * https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/alt#decorative_images
52
+ */
53
+ fallbackAlt?: "";
54
+
55
+ /**
56
+ * Rendered when the field is empty. If a fallback is not given, `null` will
57
+ * be rendered.
58
+ */
59
+ fallback?: React.ReactNode;
60
+ };
61
+
62
+ /**
63
+ * React component that renders an image from a Prismic Image field or one of
64
+ * its thumbnails using `next/image`. It will automatically set the `alt`
65
+ * attribute using the Image field's `alt` property.
66
+ *
67
+ * It uses an Imgix URL-based loader by default. A custom loader can be provided
68
+ * with the `loader` prop. If you would like to use the Next.js Image
69
+ * Optimization API instead, set `loader={undefined}`.
70
+ *
71
+ * @param props - Props for the component.
72
+ *
73
+ * @returns A responsive image component using `next/image` for the given Image
74
+ * field.
75
+ * @see To learn more about `next/image`, see: https://nextjs.org/docs/api-reference/next/image
76
+ */
77
+ export const PrismicNextImage = ({
78
+ field,
79
+ imgixParams = {},
80
+ alt,
81
+ fallbackAlt,
82
+ fill,
83
+ width,
84
+ height,
85
+ fallback = null,
86
+ ...restProps
87
+ }: PrismicNextImageProps): JSX.Element => {
88
+ if (!__PRODUCTION__) {
89
+ if (typeof alt === "string" && alt !== "") {
90
+ console.warn(
91
+ `[PrismicNextImage] The "alt" prop can only be used to declare an image as decorative by passing an empty string (alt="") but was provided a non-empty string. You can resolve this warning by removing the "alt" prop or changing it to alt="". For more details, see ${devMsg(
92
+ "alt-must-be-an-empty-string",
93
+ )}`,
94
+ );
95
+ }
96
+
97
+ if (typeof fallbackAlt === "string" && fallbackAlt !== "") {
98
+ console.warn(
99
+ `[PrismicNextImage] The "fallbackAlt" prop can only be used to declare an image as decorative by passing an empty string (fallbackAlt="") but was provided a non-empty string. You can resolve this warning by removing the "fallbackAlt" prop or changing it to fallbackAlt="". For more details, see ${devMsg(
100
+ "alt-must-be-an-empty-string",
101
+ )}`,
102
+ );
103
+ }
104
+ }
105
+
106
+ if (prismicH.isFilled.imageThumbnail(field)) {
107
+ const src = buildURL(field.url, imgixParams);
108
+
109
+ const ar = field.dimensions.width / field.dimensions.height;
110
+
111
+ const castedWidth = castInt(width);
112
+ const castedHeight = castInt(height);
113
+
114
+ let resolvedWidth = castedWidth ?? field.dimensions.width;
115
+ let resolvedHeight = castedHeight ?? field.dimensions.width;
116
+
117
+ if (castedWidth != null && castedHeight == null) {
118
+ resolvedHeight = castedWidth / ar;
119
+ } else if (castedWidth == null && castedHeight != null) {
120
+ resolvedWidth = castedHeight * ar;
121
+ }
122
+
123
+ return (
124
+ <Image
125
+ src={src}
126
+ width={fill ? undefined : resolvedWidth}
127
+ height={fill ? undefined : resolvedHeight}
128
+ // A non-null assertion is required since we
129
+ // can't statically know if an alt attribute is
130
+ // available.
131
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
132
+ alt={(alt ?? (field.alt || fallbackAlt))!}
133
+ fill={fill}
134
+ loader={imgixLoader}
135
+ {...restProps}
136
+ />
137
+ );
138
+ } else {
139
+ return <>{fallback}</>;
140
+ }
141
+ };
@@ -1,10 +1,9 @@
1
1
  import * as React from "react";
2
- import * as prismic from "@prismicio/client";
3
- import { PrismicToolbar } from "@prismicio/react";
4
2
  import { useRouter } from "next/router";
3
+ import Script from "next/script";
5
4
 
6
- import { getCookie } from "./lib/getCookie";
7
- import { extractPreviewRefRepositoryName } from "./lib/extractPreviewRefRepositoryName";
5
+ import { getPrismicPreviewCookie } from "./lib/getPrismicPreviewCookie";
6
+ import { getPreviewCookieRepositoryName } from "./lib/getPreviewCookieRepositoryName";
8
7
 
9
8
  /**
10
9
  * Props for `<PrismicPreview>`.
@@ -41,45 +40,6 @@ export type PrismicPreviewProps = {
41
40
  children?: React.ReactNode;
42
41
  };
43
42
 
44
- /**
45
- * Updates (or starts) Next.js Preview Mode using a given API endpoint and
46
- * reloads the page.
47
- *
48
- * @param updatePreviewURL - The API endpoint that sets Preview Mode data.
49
- */
50
- const updatePreviewMode = async (updatePreviewURL: string): Promise<void> => {
51
- // Start Next.js Preview Mode via the given preview API endpoint.
52
- const res = await globalThis.fetch(updatePreviewURL);
53
-
54
- if (res.ok) {
55
- // Reload the page with an active Preview Mode.
56
- window.location.reload();
57
- } else {
58
- console.error(
59
- `[<PrismicPreview>] Failed to start or update Preview Mode using the "${updatePreviewURL}" API endpoint. Does it exist?`,
60
- );
61
- }
62
- };
63
-
64
- /**
65
- * Exits Next.js Preview Mode using a given API endpoint and reloads the page.
66
- *
67
- * @param exitPreviewURL - The API endpoint that exits Preview Mode.
68
- */
69
- const exitPreviewMode = async (exitPreviewURL: string): Promise<void> => {
70
- // Exit Next.js Preview Mode via the given exit preview API endpoint.
71
- const res = await globalThis.fetch(exitPreviewURL);
72
-
73
- if (res.ok) {
74
- // Reload the page with an inactive Preview Mode.
75
- window.location.reload();
76
- } else {
77
- console.error(
78
- `[<PrismicPreview>] Failed to exit Preview Mode using the "${exitPreviewURL}" API endpoint. Does it exist?`,
79
- );
80
- }
81
- };
82
-
83
43
  /**
84
44
  * React component that sets up Prismic Previews using the Prismic Toolbar. When
85
45
  * the Prismic Toolbar send events to the browser, such as on preview updates
@@ -91,10 +51,10 @@ const exitPreviewMode = async (exitPreviewURL: string): Promise<void> => {
91
51
  */
92
52
  export function PrismicPreview({
93
53
  repositoryName,
54
+ children,
94
55
  updatePreviewURL = "/api/preview",
95
56
  exitPreviewURL = "/api/exit-preview",
96
- children,
97
- }: PrismicPreviewProps): JSX.Element {
57
+ }: PrismicPreviewProps): React.ReactNode {
98
58
  const router = useRouter();
99
59
 
100
60
  const resolvedUpdatePreviewURL = router.basePath + updatePreviewURL;
@@ -102,64 +62,88 @@ export function PrismicPreview({
102
62
 
103
63
  React.useEffect(() => {
104
64
  /**
105
- * The Prismic preview cookie.
106
- */
107
- const previewCookie = getCookie(prismic.cookie.preview);
108
-
109
- /**
110
- * Determines if the current Prismic preview session is for the repository
111
- * configured for this instance of `<PrismicPreview>`.
112
- */
113
- const prismicPreviewSessionIsForThisRepo = Boolean(
114
- previewCookie &&
115
- extractPreviewRefRepositoryName(previewCookie) === repositoryName,
116
- );
117
-
118
- /**
119
- * Determines if the current location is a descendant of the app's base path.
120
- *
121
- * This is used to prevent infinite refrehes; when `isDescendantOfBasePath`
122
- * is `false`, `router.isPreview` is also `false`.
123
- *
124
- * If the app does not have a base path, this should always be `true`.
65
+ * Starts Preview Mode and refreshes the page's props.
125
66
  */
126
- const locationIsDescendantOfBasePath = window.location.href.startsWith(
127
- window.location.origin + router.basePath,
128
- );
129
-
130
- /**
131
- * Determines if the current user loaded the page from a share link.
132
- *
133
- * Currently, we can only deduce this by checking if router.isPreview is
134
- * false (i.e. Preview Mode is inactive) and a Prismic preview cookie is present.
135
- */
136
- const loadedFromShareLink = !router.isPreview && previewCookie;
137
-
138
- if (
139
- prismicPreviewSessionIsForThisRepo &&
140
- locationIsDescendantOfBasePath &&
141
- loadedFromShareLink
142
- ) {
143
- updatePreviewMode(resolvedUpdatePreviewURL);
144
-
145
- return;
146
- }
67
+ const startPreviewMode = async () => {
68
+ // Start Next.js Preview Mode via the given preview API endpoint.
69
+ const res = await globalThis.fetch(resolvedUpdatePreviewURL);
70
+
71
+ if (res.ok) {
72
+ globalThis.location.reload();
73
+ } else {
74
+ console.error(
75
+ `[<PrismicPreview>] Failed to start or update Preview Mode using the "${resolvedUpdatePreviewURL}" API endpoint. Does it exist?`,
76
+ );
77
+ }
78
+ };
147
79
 
148
80
  const handlePrismicPreviewUpdate = async (event: Event) => {
149
81
  // Prevent the toolbar from reloading the page.
150
82
  event.preventDefault();
151
- await updatePreviewMode(resolvedUpdatePreviewURL);
83
+
84
+ await startPreviewMode();
152
85
  };
153
86
 
154
87
  const handlePrismicPreviewEnd = async (event: Event) => {
155
88
  // Prevent the toolbar from reloading the page.
156
89
  event.preventDefault();
157
- await exitPreviewMode(resolvedExitPreviewURL);
90
+
91
+ // Exit Next.js Preview Mode via the given preview API endpoint.
92
+ const res = await globalThis.fetch(resolvedExitPreviewURL);
93
+
94
+ if (res.ok) {
95
+ globalThis.location.reload();
96
+ } else {
97
+ console.error(
98
+ `[<PrismicPreview>] Failed to exit Preview Mode using the "${resolvedExitPreviewURL}" API endpoint. Does it exist?`,
99
+ );
100
+ }
158
101
  };
159
102
 
160
- // Register Prismic Toolbar event handlers.
161
- window.addEventListener("prismicPreviewUpdate", handlePrismicPreviewUpdate);
162
- window.addEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
103
+ if (router.isPreview) {
104
+ // Register Prismic Toolbar event handlers.
105
+ window.addEventListener(
106
+ "prismicPreviewUpdate",
107
+ handlePrismicPreviewUpdate,
108
+ );
109
+ window.addEventListener("prismicPreviewEnd", handlePrismicPreviewEnd);
110
+ } else {
111
+ const prismicPreviewCookie = getPrismicPreviewCookie(
112
+ globalThis.document.cookie,
113
+ );
114
+
115
+ if (prismicPreviewCookie) {
116
+ // If a Prismic preview cookie is present, but Next.js Preview
117
+ // Mode is not active, we must activate Preview Mode manually.
118
+ //
119
+ // This will happen when a visitor accesses the page using a
120
+ // Prismic preview share link.
121
+
122
+ /**
123
+ * Determines if the current location is a descendant of the app's base
124
+ * path.
125
+ *
126
+ * This is used to prevent infinite refrehes; when
127
+ * `isDescendantOfBasePath` is `false`, `router.isPreview` is also
128
+ * `false`.
129
+ *
130
+ * If the app does not have a base path, this should always be `true`.
131
+ */
132
+ const locationIsDescendantOfBasePath = window.location.href.startsWith(
133
+ window.location.origin + router.basePath,
134
+ );
135
+
136
+ const prismicPreviewCookieRepositoryName =
137
+ getPreviewCookieRepositoryName(prismicPreviewCookie);
138
+
139
+ if (
140
+ locationIsDescendantOfBasePath &&
141
+ prismicPreviewCookieRepositoryName === repositoryName
142
+ ) {
143
+ startPreviewMode();
144
+ }
145
+ }
146
+ }
163
147
 
164
148
  // On cleanup, unregister Prismic Toolbar event handlers.
165
149
  return () => {
@@ -171,8 +155,8 @@ export function PrismicPreview({
171
155
  };
172
156
  }, [
173
157
  repositoryName,
174
- resolvedUpdatePreviewURL,
175
158
  resolvedExitPreviewURL,
159
+ resolvedUpdatePreviewURL,
176
160
  router.isPreview,
177
161
  router.basePath,
178
162
  ]);
@@ -180,7 +164,10 @@ export function PrismicPreview({
180
164
  return (
181
165
  <>
182
166
  {children}
183
- <PrismicToolbar repositoryName={repositoryName} />
167
+ <Script
168
+ src={`https://static.cdn.prismic.io/prismic.js?repo=${repositoryName}&new=true`}
169
+ strategy="lazyOnload"
170
+ />
184
171
  </>
185
172
  );
186
173
  }
@@ -10,7 +10,8 @@ interface PrismicNextPreviewData {
10
10
  *
11
11
  * @param previewData - The Next.js preview data object to check.
12
12
  *
13
- * @returns `true` if `previewData` contains Prismic preview data, `false` otherwise.
13
+ * @returns `true` if `previewData` contains Prismic preview data, `false`
14
+ * otherwise.
14
15
  */
15
16
  const isPrismicNextPreviewData = (
16
17
  previewData: PreviewData,
@@ -45,7 +46,8 @@ export type EnableAutoPreviewsConfig<
45
46
  /**
46
47
  * A Next.js API endpoint request object.
47
48
  *
48
- * Pass a `req` object when using `enableAutoPreviews` in a Next.js API endpoint.
49
+ * Pass a `req` object when using `enableAutoPreviews` in a Next.js API
50
+ * endpoint.
49
51
  */
50
52
  req?: HttpRequestLike;
51
53
  }
@@ -1,4 +1,4 @@
1
- import type { NextApiRequest, NextApiResponse } from "next";
1
+ import type { NextApiResponse, NextApiRequest } from "next";
2
2
 
3
3
  /**
4
4
  * Configuration for `exitPreview`.
@@ -14,13 +14,15 @@ export type ExitPreviewConfig = {
14
14
  // redirect the user to the referring URL, but it no longer has that
15
15
  // behavior.
16
16
  //
17
- // `req` is retained as a parameter to make setting up an
18
- // exit preview API route easier (this eliminates the awkward need to
19
- // handle an unused `req` param).
17
+ // `req` is retained as a parameter to make setting up an exit preview
18
+ // API route easier (this eliminates the awkward need to handle an
19
+ // unused `req` param).
20
20
  //
21
21
  // It is also retained in case it is needed in the future, such as
22
22
  // reading headers or metadata about the request.
23
- req: Pick<NextApiRequest, "headers">;
23
+ req: {
24
+ headers: NextApiRequest["headers"];
25
+ };
24
26
 
25
27
  /**
26
28
  * The `res` object from a Next.js API route. This is given as a parameter to
@@ -28,7 +30,11 @@ export type ExitPreviewConfig = {
28
30
  *
29
31
  * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
30
32
  */
31
- res: Pick<NextApiResponse, "clearPreviewData" | "json">;
33
+ res: {
34
+ clearPreviewData: NextApiResponse["clearPreviewData"];
35
+ status: NextApiResponse["status"];
36
+ json: NextApiResponse["json"];
37
+ };
32
38
  };
33
39
 
34
40
  /**
@@ -38,5 +44,7 @@ export function exitPreview(config: ExitPreviewConfig): void {
38
44
  // Exit the current user from Preview Mode.
39
45
  config.res.clearPreviewData();
40
46
 
41
- config.res.json({ success: true });
47
+ // 205 status is used to prevent CDN-level caching. The default 200
48
+ // status code is typically treated as non-changing and cacheable.
49
+ config.res.status(205).json({ success: true });
42
50
  }
@@ -0,0 +1,25 @@
1
+ import { ImageLoaderProps } from "next/image";
2
+ import { buildURL, ImgixURLParams } from "imgix-url-builder";
3
+
4
+ /**
5
+ * A `next/image` loader for Imgix, which Prismic uses, with an optional
6
+ * collection of default Imgix parameters.
7
+ *
8
+ * @see To learn about `next/image` loaders: https://nextjs.org/docs/api-reference/next/image#loader
9
+ * @see To learn about Imgix's URL API: https://docs.imgix.com/apis/rendering
10
+ */
11
+ export const imgixLoader = (args: ImageLoaderProps): string => {
12
+ const url = new URL(args.src);
13
+
14
+ const params: ImgixURLParams = {
15
+ fit: (url.searchParams.get("fit") as ImgixURLParams["fit"]) || "max",
16
+ w: args.width,
17
+ h: undefined,
18
+ };
19
+
20
+ if (args.quality) {
21
+ params.q = args.quality;
22
+ }
23
+
24
+ return buildURL(args.src, params);
25
+ };
package/src/index.ts CHANGED
@@ -1,16 +1,21 @@
1
- export { setPreviewData } from "./setPreviewData";
2
- export type { SetPreviewDataConfig } from "./setPreviewData";
1
+ export { setPreviewData, SetPreviewDataConfig } from "./setPreviewData";
3
2
 
4
- export { exitPreview } from "./exitPreview";
5
- export type { ExitPreviewConfig } from "./exitPreview";
3
+ export { exitPreview, ExitPreviewConfig } from "./exitPreview";
6
4
 
7
- export { PrismicPreview } from "./PrismicPreview";
8
- export type { PrismicPreviewProps } from "./PrismicPreview";
5
+ export { PrismicPreview, PrismicPreviewProps } from "./PrismicPreview";
9
6
 
10
- export { enableAutoPreviews } from "./enableAutoPreviews";
11
- export type { EnableAutoPreviewsConfig } from "./enableAutoPreviews";
7
+ export {
8
+ EnableAutoPreviewsConfig,
9
+ enableAutoPreviews,
10
+ } from "./enableAutoPreviews";
12
11
 
13
- export { redirectToPreviewURL } from "./redirectToPreviewURL";
14
- export type { RedirectToPreviewURLConfig } from "./redirectToPreviewURL";
12
+ export {
13
+ RedirectToPreviewURLConfig,
14
+ redirectToPreviewURL,
15
+ } from "./redirectToPreviewURL";
15
16
 
16
- export type { CreateClientConfig } from "./types";
17
+ export { PrismicNextImage, PrismicNextImageProps } from "./PrismicNextImage";
18
+
19
+ export { imgixLoader } from "./imgixLoader";
20
+
21
+ export { CreateClientConfig } from "./types";
@@ -0,0 +1,7 @@
1
+ /**
2
+ * `true` if in the production environment, `false` otherwise.
3
+ *
4
+ * This boolean can be used to perform actions only in development environments,
5
+ * such as logging.
6
+ */
7
+ export const __PRODUCTION__ = process.env.NODE_ENV === "production";
@@ -0,0 +1,20 @@
1
+ import { version } from "../../package.json";
2
+
3
+ /**
4
+ * Returns a `prismic.dev/msg` URL for a given message slug.
5
+ *
6
+ * @example
7
+ *
8
+ * ```ts
9
+ * devMsg("missing-param");
10
+ * // => "https://prismic.dev/msg/next/v1.2.3/missing-param.md"
11
+ * ```
12
+ *
13
+ * @param slug - Slug for the message. This corresponds to a Markdown file in
14
+ * the Git repository's `/messages` directory.
15
+ *
16
+ * @returns The `prismic.dev/msg` URL for the given slug.
17
+ */
18
+ export const devMsg = (slug: string) => {
19
+ return `https://prismic.dev/msg/next/v${version}/${slug}`;
20
+ };
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Extracts preview reference repo name from stringified Prismic preview cookie
3
+ *
4
+ * @param previewCookie - The Prismic preview cookie.
5
+ *
6
+ * @returns The repository name for the Prismic preview cookie. If the cookie
7
+ * represents an inactive preview session, `undefined` will be returned.
8
+ */
9
+ export const getPreviewCookieRepositoryName = (
10
+ previewCookie: string,
11
+ ): string | undefined => {
12
+ return (decodeURIComponent(previewCookie).match(/"(.+).prismic.io"/) ||
13
+ [])[1];
14
+ };
@@ -0,0 +1,33 @@
1
+ import * as prismic from "@prismicio/client";
2
+
3
+ const readValue = (value: string): string => {
4
+ return value.replace(/%3B/g, ";");
5
+ };
6
+
7
+ /**
8
+ * Returns the value of a cookie from a given cookie store.
9
+ *
10
+ * @param cookieJar - The stringified cookie store from which to read the
11
+ * cookie.
12
+ *
13
+ * @returns The value of the cookie, if it exists.
14
+ */
15
+ export const getPrismicPreviewCookie = (
16
+ cookieJar: string,
17
+ ): string | undefined => {
18
+ const cookies = cookieJar.split("; ");
19
+
20
+ let value: string | undefined;
21
+
22
+ for (const cookie of cookies) {
23
+ const parts = cookie.split("=");
24
+ const name = readValue(parts[0]).replace(/%3D/g, "=");
25
+
26
+ if (name === prismic.cookie.preview) {
27
+ value = readValue(parts.slice(1).join("="));
28
+ continue;
29
+ }
30
+ }
31
+
32
+ return value;
33
+ };
@@ -36,7 +36,9 @@ export type RedirectToPreviewURLConfig<
36
36
  *
37
37
  * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
38
38
  */
39
- req: Pick<NextApiRequest, "query">;
39
+ req: {
40
+ query: NextApiRequest["query"];
41
+ };
40
42
 
41
43
  /**
42
44
  * The `res` object from a Next.js API route. This is given as a parameter to
@@ -44,7 +46,9 @@ export type RedirectToPreviewURLConfig<
44
46
  *
45
47
  * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
46
48
  */
47
- res: Pick<NextApiResponse, "redirect">;
49
+ res: {
50
+ redirect: NextApiResponse["redirect"];
51
+ };
48
52
 
49
53
  /**
50
54
  * The Prismic client configured for the preview session's repository.
@@ -59,11 +63,12 @@ export type RedirectToPreviewURLConfig<
59
63
  linkResolver?: TLinkResolverFunction;
60
64
 
61
65
  /**
62
- * The default redirect URL if a URL cannot be determined for the previewed document.
66
+ * The default redirect URL if a URL cannot be determined for the previewed
67
+ * document.
63
68
  *
64
- * **Note**: If your `next.config.js` file contains a `basePath`, you must
65
- * include the `basePath` as part of this option. `redirectToPreviewURL()`
66
- * cannot read your global `basePath`.
69
+ * **Note**: If you `next.config.js` file contains a `basePath`, the
70
+ * `defaultURL` option must _not_ include it. Instead, provide the `basePath`
71
+ * property using the `basePath` option.
67
72
  */
68
73
  defaultURL?: string;
69
74
 
@@ -11,7 +11,10 @@ export type SetPreviewDataConfig = {
11
11
  *
12
12
  * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
13
13
  */
14
- req: Pick<NextApiRequest, "query" | "cookies">;
14
+ req: {
15
+ query: NextApiRequest["query"];
16
+ cookies: NextApiRequest["cookies"];
17
+ };
15
18
 
16
19
  /**
17
20
  * The `res` object from a Next.js API route. This is given as a parameter to
@@ -19,7 +22,9 @@ export type SetPreviewDataConfig = {
19
22
  *
20
23
  * @see Next.js API route docs: {@link https://nextjs.org/docs/api-routes/introduction}
21
24
  */
22
- res: Pick<NextApiResponse, "setPreviewData">;
25
+ res: {
26
+ setPreviewData: NextApiResponse["setPreviewData"];
27
+ };
23
28
  };
24
29
 
25
30
  /**
package/src/types.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { PreviewData, NextApiRequest } from "next";
1
+ import type { PreviewData, NextApiRequest } from "next";
2
+ import type { ClientConfig } from "@prismicio/client";
2
3
 
3
4
  /**
4
5
  * Configuration for creating a Prismic client with automatic preview support in
@@ -19,4 +20,4 @@ export type CreateClientConfig = {
19
20
  * Pass a `req` object when using in a Next.js API endpoint.
20
21
  */
21
22
  req?: NextApiRequest;
22
- };
23
+ } & ClientConfig;