@prismicio/svelte 3.0.0-pr.71.9e4af9f → 3.0.0-pr.71.c286545

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.
@@ -1,5 +1,7 @@
1
1
  <script lang="ts">
2
2
  import { beforeNavigate, goto, refreshAll } from "$app/navigation"
3
+ import { resolve } from "$app/paths"
4
+ import { page } from "$app/state"
3
5
  import { getToolbarSrc } from "@prismicio/client"
4
6
  import { onMount } from "svelte"
5
7
 
@@ -19,13 +21,26 @@
19
21
  * Only set this value if the route parameter's name differs from the parameter's value.
20
22
  */
21
23
  routePrefixName?: string
24
+
25
+ /**
26
+ * The path of your preview route, without `paths.base`. The Prismic Toolbar uses it to create
27
+ * share links.
28
+ *
29
+ * @defaultValue `"/api/preview"`
30
+ */
31
+ previewURL?: string
22
32
  }
23
33
 
24
- const { repositoryName, routePrefix = "preview", routePrefixName = routePrefix }: Props = $props()
34
+ const {
35
+ repositoryName,
36
+ routePrefix = "preview",
37
+ routePrefixName = routePrefix,
38
+ previewURL = "/api/preview",
39
+ }: Props = $props()
25
40
 
26
- // `v=5` opts into the toolbar's modern flow, which follows the session set by
27
- // `redirectToPreviewURL()`.
28
- const toolbarSrc = $derived(`${getToolbarSrc(repositoryName)}&v=5`)
41
+ const toolbarSrc = $derived(getToolbarSrc(repositoryName, { version: 5 }))
42
+ // `resolve()` can return a path relative to the current page, which changes on navigation.
43
+ const previewPath = $derived(new URL(resolve(previewURL, {}), page.url).pathname)
29
44
 
30
45
  /** Set to `true` when the next `beforeNavigate()` call should not prefix the route. */
31
46
  let endingPreview = $state(false)
@@ -47,7 +62,6 @@
47
62
  (event) => {
48
63
  event.preventDefault()
49
64
 
50
- document.cookie = "io.prismic.previewSession=; Path=/; Max-Age=0"
51
65
  endingPreview = true
52
66
 
53
67
  goto(
@@ -92,5 +106,5 @@
92
106
  </script>
93
107
 
94
108
  <svelte:head>
95
- <script defer src={toolbarSrc}></script>
109
+ <script defer src={toolbarSrc} data-preview-url={previewPath}></script>
96
110
  </svelte:head>
@@ -12,6 +12,13 @@ type Props = {
12
12
  * Only set this value if the route parameter's name differs from the parameter's value.
13
13
  */
14
14
  routePrefixName?: string;
15
+ /**
16
+ * The path of your preview route, without `paths.base`. The Prismic Toolbar uses it to create
17
+ * share links.
18
+ *
19
+ * @defaultValue `"/api/preview"`
20
+ */
21
+ previewURL?: string;
15
22
  };
16
23
  declare const PrismicPreview: import("svelte").Component<Props, {}, "">;
17
24
  type PrismicPreview = ReturnType<typeof PrismicPreview>;
@@ -2,7 +2,7 @@ import * as prismic from "@prismicio/client";
2
2
  import type { Cookies } from "@sveltejs/kit";
3
3
  export type RedirectToPreviewURLConfig = {
4
4
  /** The Prismic client configured for the preview session's repository. */
5
- client: Pick<prismic.Client, "resolvePreviewURL" | "documentAPIEndpoint">;
5
+ client: Pick<prismic.Client, "resolvePreviewURL">;
6
6
  /**
7
7
  * The `request` object from a `+server` file.
8
8
  *
@@ -1,4 +1,6 @@
1
+ import { resolve } from "$app/paths";
1
2
  import * as prismic from "@prismicio/client";
3
+ import { getSafePath } from "../lib/getSafePath";
2
4
  /**
3
5
  * Redirects a visitor to the URL of a previewed Prismic document from within a SvelteKit `+server`
4
6
  * file.
@@ -18,15 +20,10 @@ import * as prismic from "@prismicio/client";
18
20
  * ```
19
21
  */
20
22
  export const redirectToPreviewURL = async (config) => {
21
- const { searchParams } = new URL(config.request.url);
22
- const session = searchParams.get("session");
23
- const documentID = searchParams.get("documentId") ?? undefined;
23
+ const previewToken = new URL(config.request.url).searchParams.get("token") ?? undefined;
24
+ const documentID = new URL(config.request.url).searchParams.get("documentId") ?? undefined;
24
25
  const routePrefix = config.routePrefix ?? "preview";
25
- // Share links from the toolbar's modern flow only carry the session.
26
- const previewToken = searchParams.get("token") ??
27
- (session ? await getSessionRef(config.client.documentAPIEndpoint, session) : undefined);
28
- const path = session ? getSafePath(searchParams.get("path")) : undefined;
29
- const location = path ??
26
+ const location = getSharedPath(config.request.url, routePrefix) ??
30
27
  "/" +
31
28
  routePrefix +
32
29
  (await config.client.resolvePreviewURL({
@@ -37,11 +34,18 @@ export const redirectToPreviewURL = async (config) => {
37
34
  // Prevent a flash of non-preview content by setting the preview token
38
35
  // on the initial page load.
39
36
  if (previewToken) {
40
- config.cookies.set(prismic.cookie.preview, previewToken, cookieOptions);
37
+ config.cookies.set(prismic.cookie.preview, previewToken, {
38
+ path: "/",
39
+ httpOnly: false,
40
+ });
41
41
  }
42
- // The toolbar follows the preview session with this cookie.
42
+ // The toolbar's `v=5` flow follows the preview session with this cookie.
43
+ const session = new URL(config.request.url).searchParams.get("session");
43
44
  if (session) {
44
- config.cookies.set("io.prismic.previewSession", session, cookieOptions);
45
+ config.cookies.set(prismic.cookie.previewSession, session, {
46
+ path: "/",
47
+ httpOnly: false,
48
+ });
45
49
  }
46
50
  return new Response(undefined, {
47
51
  status: 307,
@@ -50,27 +54,19 @@ export const redirectToPreviewURL = async (config) => {
50
54
  },
51
55
  });
52
56
  };
53
- const cookieOptions = { path: "/", httpOnly: false };
54
- /** Returns the session's current ref from the repository's public endpoint. */
55
- const getSessionRef = async (documentAPIEndpoint, session) => {
56
- const url = new URL(`/previews/token/${encodeURIComponent(session)}`, documentAPIEndpoint);
57
- url.hostname = url.hostname.replace(".cdn.", ".");
58
- const { ref } = await (await fetch(url)).json();
59
- if (!ref) {
60
- throw new prismic.PreviewTokenExpiredError("The preview session has ended.", url.href, undefined);
61
- }
62
- return ref;
63
- };
64
57
  /**
65
- * Returns `path` if it is a path on this website. The path already includes SvelteKit's
66
- * `paths.base`.
58
+ * Returns the `path` param of toolbar share links inside the preview route prefix, or `undefined`
59
+ * if it is missing or not a path on this website.
67
60
  */
68
- const getSafePath = (path) => {
69
- if (!path?.startsWith("/")) {
61
+ const getSharedPath = (requestURL, routePrefix) => {
62
+ const path = getSafePath(new URL(requestURL).searchParams.get("path"));
63
+ // `path` comes from the browser, so it already includes `paths.base`. `resolve()` returns `base`
64
+ // either absolute or relative to the request.
65
+ const base = new URL(resolve("/", {}), requestURL).pathname.slice(0, -1);
66
+ const rest = path?.startsWith(base) ? path.slice(base.length) : undefined;
67
+ // `/docs` and `/docs?q=1` are under the `/docs` base, but `/docs-old` isn't.
68
+ if (rest === undefined || !/^([/?#]|$)/.test(rest)) {
70
69
  return;
71
70
  }
72
- // Paths like `//evil.com` and `/\evil.com` resolve to another origin.
73
- const origin = "https://placeholder.invalid";
74
- const url = new URL(path, origin);
75
- return url.origin === origin ? url.pathname + url.search + url.hash : undefined;
71
+ return /^\/([^/?#]*)/.exec(rest)?.[1] === routePrefix ? path : `${base}/${routePrefix}${rest}`;
76
72
  };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Returns `path` if it stays on the current origin, like `/blog?page=2#top`. It comes from
3
+ * `location`, so it already includes `paths.base`.
4
+ */
5
+ export declare function getSafePath(path: string | null | undefined): string | undefined;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Returns `path` if it stays on the current origin, like `/blog?page=2#top`. It comes from
3
+ * `location`, so it already includes `paths.base`.
4
+ */
5
+ export function getSafePath(path) {
6
+ if (!path?.startsWith("/") || path.startsWith("//") || path.startsWith("/\\")) {
7
+ return;
8
+ }
9
+ const origin = "https://placeholder.invalid";
10
+ let url;
11
+ try {
12
+ url = new URL(path, origin);
13
+ }
14
+ catch {
15
+ return;
16
+ }
17
+ const safePath = url.href.slice(origin.length);
18
+ // Normalizing can create `//`, like with `/.//example.com`.
19
+ if (url.origin === origin && !safePath.startsWith("//")) {
20
+ return safePath;
21
+ }
22
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prismicio/svelte",
3
- "version": "3.0.0-pr.71.9e4af9f",
3
+ "version": "3.0.0-pr.71.c286545",
4
4
  "description": "Svelte components to present Prismic content.",
5
5
  "keywords": [
6
6
  "prismic",
@@ -62,7 +62,7 @@
62
62
  "esm-env": "^1.2.2"
63
63
  },
64
64
  "devDependencies": {
65
- "@prismicio/client": "^7.22.3",
65
+ "@prismicio/client": "^7.23.0",
66
66
  "@prismicio/mock": "^0.7.2",
67
67
  "@sveltejs/kit": "^3.0.1",
68
68
  "@sveltejs/package": "^3.0.1",
@@ -71,16 +71,16 @@
71
71
  "@types/node": "^26.6.5",
72
72
  "@vitest/coverage-v8": "^5.0.5",
73
73
  "globals": "^17.13.0",
74
- "happy-dom": "^21.0.3",
75
- "oxfmt": "^0.73.0",
76
- "oxlint": "^1.88.0",
74
+ "happy-dom": "^21.0.4",
75
+ "oxfmt": "^0.74.0",
76
+ "oxlint": "^1.89.0",
77
77
  "standard-version": "^9.5.0",
78
78
  "svelte": "^5.57.2",
79
79
  "typescript": "^6.0.3",
80
80
  "vitest": "^5.0.5"
81
81
  },
82
82
  "peerDependencies": {
83
- "@prismicio/client": ">=7",
83
+ "@prismicio/client": "^7.23.0",
84
84
  "@sveltejs/kit": "^3.0.0",
85
85
  "svelte": "^5.16.0"
86
86
  },
@@ -1,5 +1,7 @@
1
1
  <script lang="ts">
2
2
  import { beforeNavigate, goto, refreshAll } from "$app/navigation"
3
+ import { resolve } from "$app/paths"
4
+ import { page } from "$app/state"
3
5
  import { getToolbarSrc } from "@prismicio/client"
4
6
  import { onMount } from "svelte"
5
7
 
@@ -19,13 +21,26 @@
19
21
  * Only set this value if the route parameter's name differs from the parameter's value.
20
22
  */
21
23
  routePrefixName?: string
24
+
25
+ /**
26
+ * The path of your preview route, without `paths.base`. The Prismic Toolbar uses it to create
27
+ * share links.
28
+ *
29
+ * @defaultValue `"/api/preview"`
30
+ */
31
+ previewURL?: string
22
32
  }
23
33
 
24
- const { repositoryName, routePrefix = "preview", routePrefixName = routePrefix }: Props = $props()
34
+ const {
35
+ repositoryName,
36
+ routePrefix = "preview",
37
+ routePrefixName = routePrefix,
38
+ previewURL = "/api/preview",
39
+ }: Props = $props()
25
40
 
26
- // `v=5` opts into the toolbar's modern flow, which follows the session set by
27
- // `redirectToPreviewURL()`.
28
- const toolbarSrc = $derived(`${getToolbarSrc(repositoryName)}&v=5`)
41
+ const toolbarSrc = $derived(getToolbarSrc(repositoryName, { version: 5 }))
42
+ // `resolve()` can return a path relative to the current page, which changes on navigation.
43
+ const previewPath = $derived(new URL(resolve(previewURL, {}), page.url).pathname)
29
44
 
30
45
  /** Set to `true` when the next `beforeNavigate()` call should not prefix the route. */
31
46
  let endingPreview = $state(false)
@@ -47,7 +62,6 @@
47
62
  (event) => {
48
63
  event.preventDefault()
49
64
 
50
- document.cookie = "io.prismic.previewSession=; Path=/; Max-Age=0"
51
65
  endingPreview = true
52
66
 
53
67
  goto(
@@ -92,5 +106,5 @@
92
106
  </script>
93
107
 
94
108
  <svelte:head>
95
- <script defer src={toolbarSrc}></script>
109
+ <script defer src={toolbarSrc} data-preview-url={previewPath}></script>
96
110
  </svelte:head>
@@ -1,12 +1,15 @@
1
+ import { resolve } from "$app/paths"
1
2
  import * as prismic from "@prismicio/client"
2
3
  import type { Cookies } from "@sveltejs/kit"
3
4
 
5
+ import { getSafePath } from "../lib/getSafePath"
6
+
4
7
  export type RedirectToPreviewURLConfig = {
5
8
  /** The Prismic client configured for the preview session's repository. */
6
9
  // `Pick` is used to use the smallest possible subset of
7
10
  // `prismic.Client`. Doing this reduces the surface area for breaking
8
11
  // type changes.
9
- client: Pick<prismic.Client, "resolvePreviewURL" | "documentAPIEndpoint">
12
+ client: Pick<prismic.Client, "resolvePreviewURL">
10
13
 
11
14
  /**
12
15
  * The `request` object from a `+server` file.
@@ -50,19 +53,12 @@ export type RedirectToPreviewURLConfig = {
50
53
  export const redirectToPreviewURL = async (
51
54
  config: RedirectToPreviewURLConfig,
52
55
  ): Promise<Response> => {
53
- const { searchParams } = new URL(config.request.url)
54
- const session = searchParams.get("session")
55
- const documentID = searchParams.get("documentId") ?? undefined
56
+ const previewToken = new URL(config.request.url).searchParams.get("token") ?? undefined
57
+ const documentID = new URL(config.request.url).searchParams.get("documentId") ?? undefined
56
58
  const routePrefix = config.routePrefix ?? "preview"
57
59
 
58
- // Share links from the toolbar's modern flow only carry the session.
59
- const previewToken =
60
- searchParams.get("token") ??
61
- (session ? await getSessionRef(config.client.documentAPIEndpoint, session) : undefined)
62
-
63
- const path = session ? getSafePath(searchParams.get("path")) : undefined
64
60
  const location =
65
- path ??
61
+ getSharedPath(config.request.url, routePrefix) ??
66
62
  "/" +
67
63
  routePrefix +
68
64
  (await config.client.resolvePreviewURL({
@@ -74,12 +70,19 @@ export const redirectToPreviewURL = async (
74
70
  // Prevent a flash of non-preview content by setting the preview token
75
71
  // on the initial page load.
76
72
  if (previewToken) {
77
- config.cookies.set(prismic.cookie.preview, previewToken, cookieOptions)
73
+ config.cookies.set(prismic.cookie.preview, previewToken, {
74
+ path: "/",
75
+ httpOnly: false,
76
+ })
78
77
  }
79
78
 
80
- // The toolbar follows the preview session with this cookie.
79
+ // The toolbar's `v=5` flow follows the preview session with this cookie.
80
+ const session = new URL(config.request.url).searchParams.get("session")
81
81
  if (session) {
82
- config.cookies.set("io.prismic.previewSession", session, cookieOptions)
82
+ config.cookies.set(prismic.cookie.previewSession, session, {
83
+ path: "/",
84
+ httpOnly: false,
85
+ })
83
86
  }
84
87
 
85
88
  return new Response(undefined, {
@@ -90,37 +93,20 @@ export const redirectToPreviewURL = async (
90
93
  })
91
94
  }
92
95
 
93
- const cookieOptions = { path: "/", httpOnly: false }
94
-
95
- /** Returns the session's current ref from the repository's public endpoint. */
96
- const getSessionRef = async (documentAPIEndpoint: string, session: string): Promise<string> => {
97
- const url = new URL(`/previews/token/${encodeURIComponent(session)}`, documentAPIEndpoint)
98
- url.hostname = url.hostname.replace(".cdn.", ".")
99
-
100
- const { ref } = await (await fetch(url)).json()
101
- if (!ref) {
102
- throw new prismic.PreviewTokenExpiredError(
103
- "The preview session has ended.",
104
- url.href,
105
- undefined,
106
- )
107
- }
108
-
109
- return ref
110
- }
111
-
112
96
  /**
113
- * Returns `path` if it is a path on this website. The path already includes SvelteKit's
114
- * `paths.base`.
97
+ * Returns the `path` param of toolbar share links inside the preview route prefix, or `undefined`
98
+ * if it is missing or not a path on this website.
115
99
  */
116
- const getSafePath = (path: string | null): string | undefined => {
117
- if (!path?.startsWith("/")) {
100
+ const getSharedPath = (requestURL: string, routePrefix: string): string | undefined => {
101
+ const path = getSafePath(new URL(requestURL).searchParams.get("path"))
102
+ // `path` comes from the browser, so it already includes `paths.base`. `resolve()` returns `base`
103
+ // either absolute or relative to the request.
104
+ const base = new URL(resolve("/", {}), requestURL).pathname.slice(0, -1)
105
+ const rest = path?.startsWith(base) ? path.slice(base.length) : undefined
106
+ // `/docs` and `/docs?q=1` are under the `/docs` base, but `/docs-old` isn't.
107
+ if (rest === undefined || !/^([/?#]|$)/.test(rest)) {
118
108
  return
119
109
  }
120
110
 
121
- // Paths like `//evil.com` and `/\evil.com` resolve to another origin.
122
- const origin = "https://placeholder.invalid"
123
- const url = new URL(path, origin)
124
-
125
- return url.origin === origin ? url.pathname + url.search + url.hash : undefined
111
+ return /^\/([^/?#]*)/.exec(rest)?.[1] === routePrefix ? path : `${base}/${routePrefix}${rest}`
126
112
  }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Returns `path` if it stays on the current origin, like `/blog?page=2#top`. It comes from
3
+ * `location`, so it already includes `paths.base`.
4
+ */
5
+ export function getSafePath(path: string | null | undefined): string | undefined {
6
+ if (!path?.startsWith("/") || path.startsWith("//") || path.startsWith("/\\")) {
7
+ return
8
+ }
9
+
10
+ const origin = "https://placeholder.invalid"
11
+ let url: URL
12
+ try {
13
+ url = new URL(path, origin)
14
+ } catch {
15
+ return
16
+ }
17
+ const safePath = url.href.slice(origin.length)
18
+ // Normalizing can create `//`, like with `/.//example.com`.
19
+ if (url.origin === origin && !safePath.startsWith("//")) {
20
+ return safePath
21
+ }
22
+ }