sanity-plugin-visual-editor 1.0.0 → 1.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.
- package/LICENSE +1 -1
- package/README.md +263 -16
- package/TESTING.md +133 -0
- package/dist/PreviewBar-D_rw0bhP.js +3503 -0
- package/dist/PreviewBar-D_rw0bhP.js.map +1 -0
- package/dist/bar.d.ts +22 -0
- package/dist/bar.js +67 -0
- package/dist/bar.js.map +1 -0
- package/dist/cloudflare.d.ts +87 -0
- package/dist/cloudflare.js +1134 -0
- package/dist/cloudflare.js.map +1 -0
- package/dist/data-D0qotTtt.d.ts +177 -0
- package/dist/host-x2eXr-LJ.js +619 -0
- package/dist/host-x2eXr-LJ.js.map +1 -0
- package/dist/host.d.ts +162 -0
- package/dist/host.js +3 -0
- package/dist/index-hDzatlg7.d.ts +276 -0
- package/dist/index.d.ts +18 -18
- package/dist/index.js +7 -8
- package/dist/link-search-JtZkxz4k.js +14 -0
- package/dist/link-search-JtZkxz4k.js.map +1 -0
- package/dist/next-client.d.ts +22 -0
- package/dist/next-client.js +112 -0
- package/dist/next-client.js.map +1 -0
- package/dist/next.d.ts +135 -0
- package/dist/next.js +176 -0
- package/dist/next.js.map +1 -0
- package/dist/node-labels-CDiW5rMq.js +122 -0
- package/dist/node-labels-CDiW5rMq.js.map +1 -0
- package/dist/page-documents-BFFcH8lD.d.ts +54 -0
- package/dist/page-documents-mGfw_flR.js +67 -0
- package/dist/page-documents-mGfw_flR.js.map +1 -0
- package/dist/perspective-BmS9TVtr.js +106 -0
- package/dist/perspective-BmS9TVtr.js.map +1 -0
- package/dist/preview-links-BZDZyIey.js +119 -0
- package/dist/preview-links-BZDZyIey.js.map +1 -0
- package/dist/preview-links-DM6BCiLV.d.ts +87 -0
- package/dist/protocol-BNO38gYy.js +280 -0
- package/dist/protocol-BNO38gYy.js.map +1 -0
- package/dist/protocol-BnRCy2wJ.d.ts +386 -0
- package/dist/server-B8MqMyaN.js +748 -0
- package/dist/server-B8MqMyaN.js.map +1 -0
- package/dist/server.d.ts +4 -0
- package/dist/server.js +3 -0
- package/dist/shell-DZotxRXX.d.ts +37 -0
- package/dist/studio.d.ts +93 -0
- package/dist/studio.js +1263 -0
- package/dist/studio.js.map +1 -0
- package/dist/sveltekit.d.ts +281 -0
- package/dist/sveltekit.js +394 -0
- package/dist/sveltekit.js.map +1 -0
- package/package.json +120 -39
- package/dist/index.d.mts +0 -21
- package/dist/index.js.map +0 -1
- package/dist/index.mjs +0 -8
- package/dist/index.mjs.map +0 -1
- package/sanity.json +0 -8
- package/src/index.ts +0 -27
- package/v2-incompatible.js +0 -11
|
@@ -0,0 +1,748 @@
|
|
|
1
|
+
import { n as searchKinds } from "./link-search-JtZkxz4k.js";
|
|
2
|
+
import { c as parsePerspective, d as releaseIdOf, i as RELEASES_QUERY, l as perspectiveStack, m as serializePerspective, n as PERSPECTIVE_COOKIE, o as activeReleases, t as DRAFTS } from "./perspective-BmS9TVtr.js";
|
|
3
|
+
import { a as PREVIEW_LINK_TTL_SECONDS, c as generatePreviewLinkCode, f as normalizePreviewPathname, h as previewLinkKey, l as isPreviewLinkCode, m as previewLinkExpiry, o as assertLinkTtl, p as parsePreviewLinkValue, s as createPreviewLink } from "./preview-links-BZDZyIey.js";
|
|
4
|
+
import { t as findPageDocumentRule } from "./page-documents-mGfw_flR.js";
|
|
5
|
+
import "./protocol-BNO38gYy.js";
|
|
6
|
+
import { fetchSharedAccessQuery } from "@sanity/preview-url-secret/constants";
|
|
7
|
+
import { validatePreviewUrl } from "@sanity/preview-url-secret";
|
|
8
|
+
/**
|
|
9
|
+
* Signed, expiring link-session cookies: what a `/p/<code>` link leaves in the browser instead of
|
|
10
|
+
* the site's preview secret. The value is `<expires>.<signature>`, where `expires` is in seconds
|
|
11
|
+
* since the epoch and the signature is HMAC-SHA-256 over it, keyed with the preview secret. It
|
|
12
|
+
* proves "opened a live share link, valid until `expires`" and nothing else, so copying it gains
|
|
13
|
+
* no more than the link itself gave.
|
|
14
|
+
*/
|
|
15
|
+
/** The link-session cookie's default name. */
|
|
16
|
+
const LINK_SESSION_COOKIE = "__sanity_preview_link", encoder = new TextEncoder(), LABEL = "sanity-preview-bar/link-session/v1:";
|
|
17
|
+
function key(secret) {
|
|
18
|
+
if (!secret) throw Error("sanity-visual-editor: the preview secret is empty");
|
|
19
|
+
return crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
20
|
+
name: "HMAC",
|
|
21
|
+
hash: "SHA-256"
|
|
22
|
+
}, !1, ["sign", "verify"]);
|
|
23
|
+
}
|
|
24
|
+
function toBase64Url(bytes) {
|
|
25
|
+
let binary = "";
|
|
26
|
+
for (let byte of new Uint8Array(bytes)) binary += String.fromCharCode(byte);
|
|
27
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
28
|
+
}
|
|
29
|
+
function fromBase64Url(value) {
|
|
30
|
+
if (!/^[A-Za-z0-9_-]+$/.test(value)) return null;
|
|
31
|
+
try {
|
|
32
|
+
let binary = atob(value.replace(/-/g, "+").replace(/_/g, "/")), bytes = new Uint8Array(binary.length);
|
|
33
|
+
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
|
34
|
+
return bytes;
|
|
35
|
+
} catch {
|
|
36
|
+
return null;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
/** A link-session cookie value valid until `expiresAt` (ms since the epoch). */
|
|
40
|
+
async function signLinkSession(secret, expiresAt) {
|
|
41
|
+
let expires = String(Math.floor(expiresAt / 1e3));
|
|
42
|
+
return `${expires}.${toBase64Url(await crypto.subtle.sign("HMAC", await key(secret), encoder.encode(LABEL + expires)))}`;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* When a link-session cookie value expires (ms since the epoch), or `null` when it is malformed,
|
|
46
|
+
* forged or expired. The signature check is `crypto.subtle.verify`'s, which is constant-time.
|
|
47
|
+
*/
|
|
48
|
+
async function verifyLinkSession(secret, value, now = Date.now()) {
|
|
49
|
+
if (!value || value.length > 128) return null;
|
|
50
|
+
let match = /^(\d{1,12})\.([A-Za-z0-9_-]+)$/.exec(value);
|
|
51
|
+
if (!match) return null;
|
|
52
|
+
let expiresAt = Number(match[1]) * 1e3;
|
|
53
|
+
if (!(expiresAt > now)) return null;
|
|
54
|
+
let signature = fromBase64Url(match[2]);
|
|
55
|
+
return signature && await crypto.subtle.verify("HMAC", await key(secret), signature, encoder.encode(LABEL + match[1])) ? expiresAt : null;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Client for the Cloudflare realtime preview hub Worker/DO, plus signed HMAC session tokens for
|
|
59
|
+
* the Studio live-edit endpoints (`/api/preview/live-edit*`).
|
|
60
|
+
*/
|
|
61
|
+
const HUB_ORIGIN = "https://preview-hub.internal", PERSPECTIVE_HEADER = "x-preview-perspective";
|
|
62
|
+
/**
|
|
63
|
+
* Wraps a Cloudflare service binding (`env.PREVIEW_HUB`) into typed `previewHub(client)` and
|
|
64
|
+
* `hubFor(name)` helpers.
|
|
65
|
+
*/
|
|
66
|
+
function createPreviewHubClient(getService) {
|
|
67
|
+
function hubFor(name) {
|
|
68
|
+
let service = getService();
|
|
69
|
+
return !service || name === "raw" || name === "published" ? null : {
|
|
70
|
+
async query(query, params = {}, label) {
|
|
71
|
+
let response = await service.fetch(`${HUB_ORIGIN}/query`, {
|
|
72
|
+
method: "POST",
|
|
73
|
+
headers: {
|
|
74
|
+
"content-type": "application/json",
|
|
75
|
+
[PERSPECTIVE_HEADER]: name
|
|
76
|
+
},
|
|
77
|
+
body: JSON.stringify({
|
|
78
|
+
query,
|
|
79
|
+
params,
|
|
80
|
+
label
|
|
81
|
+
})
|
|
82
|
+
});
|
|
83
|
+
if (!response.ok) throw Error(`Preview hub: HTTP ${response.status} ${await response.text()}`);
|
|
84
|
+
let { result } = await response.json();
|
|
85
|
+
return result;
|
|
86
|
+
},
|
|
87
|
+
debug(pathAndSearch) {
|
|
88
|
+
return service.fetch(`${HUB_ORIGIN}${pathAndSearch}`, { headers: { [PERSPECTIVE_HEADER]: name } });
|
|
89
|
+
},
|
|
90
|
+
async overlay(document, seq) {
|
|
91
|
+
let response = await service.fetch(`${HUB_ORIGIN}/overlay`, {
|
|
92
|
+
method: "POST",
|
|
93
|
+
headers: {
|
|
94
|
+
"content-type": "application/json",
|
|
95
|
+
[PERSPECTIVE_HEADER]: name
|
|
96
|
+
},
|
|
97
|
+
body: JSON.stringify({
|
|
98
|
+
document,
|
|
99
|
+
seq
|
|
100
|
+
})
|
|
101
|
+
});
|
|
102
|
+
if (!response.ok) throw Error(`Preview hub: HTTP ${response.status}`);
|
|
103
|
+
return (await response.json()).applied;
|
|
104
|
+
},
|
|
105
|
+
events(search, signal) {
|
|
106
|
+
return service.fetch(`${HUB_ORIGIN}/events${search}`, {
|
|
107
|
+
headers: { [PERSPECTIVE_HEADER]: name },
|
|
108
|
+
signal
|
|
109
|
+
});
|
|
110
|
+
},
|
|
111
|
+
socket(search) {
|
|
112
|
+
return service.fetch(`${HUB_ORIGIN}/socket${search}`, { headers: {
|
|
113
|
+
upgrade: "websocket",
|
|
114
|
+
[PERSPECTIVE_HEADER]: name
|
|
115
|
+
} });
|
|
116
|
+
},
|
|
117
|
+
editSocket() {
|
|
118
|
+
return service.fetch(`${HUB_ORIGIN}/socket`, { headers: {
|
|
119
|
+
upgrade: "websocket",
|
|
120
|
+
[PERSPECTIVE_HEADER]: name,
|
|
121
|
+
"x-live-edit": "1"
|
|
122
|
+
} });
|
|
123
|
+
}
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
function previewHub(client) {
|
|
127
|
+
let name = previewHubName(client.config().perspective);
|
|
128
|
+
return name ? hubFor(name) : null;
|
|
129
|
+
}
|
|
130
|
+
return {
|
|
131
|
+
hubFor,
|
|
132
|
+
previewHub
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/** Default cookie that authorises `/api/preview/live-edit`. */
|
|
136
|
+
const LIVE_EDIT_COOKIE = "sanity-live-edit", LIVE_EDIT_PATH = "/api/preview/live-edit", LIVE_EDIT_TTL_S = 43200;
|
|
137
|
+
async function hmac(secret, message) {
|
|
138
|
+
let key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), {
|
|
139
|
+
name: "HMAC",
|
|
140
|
+
hash: "SHA-256"
|
|
141
|
+
}, !1, ["sign"]), signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(message));
|
|
142
|
+
return btoa(String.fromCharCode(...new Uint8Array(signature))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
143
|
+
}
|
|
144
|
+
function sign(secret, expires) {
|
|
145
|
+
return hmac(secret, `live-edit:${expires}`);
|
|
146
|
+
}
|
|
147
|
+
function sameString(a, b) {
|
|
148
|
+
if (a.length !== b.length) return !1;
|
|
149
|
+
let diff = 0;
|
|
150
|
+
for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
151
|
+
return diff === 0;
|
|
152
|
+
}
|
|
153
|
+
/** A signed `<expires>.<signature>` token for the live-edit cookie. */
|
|
154
|
+
async function createLiveEditToken(secret, now = Date.now()) {
|
|
155
|
+
let expires = Math.floor(now / 1e3) + LIVE_EDIT_TTL_S;
|
|
156
|
+
return `${expires}.${await sign(secret, expires)}`;
|
|
157
|
+
}
|
|
158
|
+
/** Whether a live-edit cookie value is a valid, unexpired token. */
|
|
159
|
+
async function verifyLiveEditToken(secret, token, now = Date.now()) {
|
|
160
|
+
if (!token) return !1;
|
|
161
|
+
let [raw, signature] = token.split("."), expires = Number(raw);
|
|
162
|
+
return !Number.isInteger(expires) || expires < now / 1e3 || !signature ? !1 : sameString(await sign(secret, expires), signature);
|
|
163
|
+
}
|
|
164
|
+
/** How long a live ticket opens sockets and polls. Pages hand out a fresh one on every render. */
|
|
165
|
+
const LIVE_TICKET_TTL_S = 43200, HUB_NAME = /^[\w.,-]{1,256}$/;
|
|
166
|
+
/**
|
|
167
|
+
* The hub name for a preview perspective: `drafts`, or a release stack such as `rABC,drafts`.
|
|
168
|
+
* `null` for perspectives that have no hub (`published`, `raw`).
|
|
169
|
+
*/
|
|
170
|
+
function previewHubName(perspective) {
|
|
171
|
+
let name = Array.isArray(perspective) ? perspective.join(",") : typeof perspective == "string" && perspective ? perspective : "drafts";
|
|
172
|
+
return name === "published" || name === "raw" || !HUB_NAME.test(name) ? null : name;
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* A live ticket: proof, signed by the site, that a page was rendered in preview mode for one hub
|
|
176
|
+
* (`<hub>.<expires>.<signature>`). The page hands it to its tab, which sends it with the socket
|
|
177
|
+
* and the long poll. A Worker entry can check it without the framework's preview cookie, which
|
|
178
|
+
* only the framework can read (Next.js's draft mode cookie is a per-build value).
|
|
179
|
+
*/
|
|
180
|
+
async function createLiveTicket(secret, hub, now = Date.now()) {
|
|
181
|
+
if (!HUB_NAME.test(hub)) throw Error(`Invalid preview hub name: ${hub}`);
|
|
182
|
+
let expires = Math.ceil(now / 1e3 / 3600) * 3600 + LIVE_TICKET_TTL_S;
|
|
183
|
+
return `${hub}.${expires}.${await hmac(secret, `live:${hub}:${expires}`)}`;
|
|
184
|
+
}
|
|
185
|
+
/** The hub a live ticket opens, or `null` when it is missing, forged or expired. */
|
|
186
|
+
async function verifyLiveTicket(secret, ticket, now = Date.now()) {
|
|
187
|
+
if (!ticket) return null;
|
|
188
|
+
let last = ticket.lastIndexOf("."), middle = ticket.lastIndexOf(".", last - 1);
|
|
189
|
+
if (middle <= 0) return null;
|
|
190
|
+
let hub = ticket.slice(0, middle), expires = Number(ticket.slice(middle + 1, last)), signature = ticket.slice(last + 1);
|
|
191
|
+
return !HUB_NAME.test(hub) || !Number.isInteger(expires) || expires < now / 1e3 || !signature ? null : sameString(await hmac(secret, `live:${hub}:${expires}`), signature) ? hub : null;
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* The realtime preview hub's site routes (`/api/preview/*`), framework-neutral: a web `Request`
|
|
195
|
+
* in, a web `Response` out, or `null` for a path that isn't one of them.
|
|
196
|
+
*
|
|
197
|
+
* - `GET socket` tab → hub invalidations over a WebSocket (`101`)
|
|
198
|
+
* - `GET events` the same as a long poll, where a socket can't open
|
|
199
|
+
* - `GET hub/stats|bench` debug output of the tab's hub
|
|
200
|
+
* - `POST live-edit/session` trades a Studio preview secret for the live-edit cookie
|
|
201
|
+
* - `POST live-edit` one unsaved Studio edit
|
|
202
|
+
* - `GET live-edit/socket` unsaved Studio edits over a WebSocket (`101`)
|
|
203
|
+
*
|
|
204
|
+
* Tabs prove they are in preview with a live ticket (`createLiveTicket`), which names their hub;
|
|
205
|
+
* the Studio proves an editor with the live-edit cookie. Neither needs the framework, so the
|
|
206
|
+
* WebSocket routes also run in a Worker entry ahead of the framework, which can't return a `101`.
|
|
207
|
+
*/
|
|
208
|
+
/** Default base path of the hub's site routes. */
|
|
209
|
+
const PREVIEW_ROUTES_PATH = "/api/preview", LIVE_TICKET_PARAM = "ticket", NO_STORE = {
|
|
210
|
+
"cache-control": "private, no-store",
|
|
211
|
+
"x-robots-tag": "noindex"
|
|
212
|
+
};
|
|
213
|
+
function text(body, status) {
|
|
214
|
+
return new Response(body, {
|
|
215
|
+
status,
|
|
216
|
+
headers: NO_STORE
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
function readCookie(request, name) {
|
|
220
|
+
for (let part of (request.headers.get("cookie") ?? "").split(";")) {
|
|
221
|
+
let index = part.indexOf("=");
|
|
222
|
+
if (!(index < 0 || part.slice(0, index).trim() !== name)) try {
|
|
223
|
+
return decodeURIComponent(part.slice(index + 1).trim());
|
|
224
|
+
} catch {
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
function isUpgrade(request) {
|
|
230
|
+
return request.headers.get("upgrade")?.toLowerCase() === "websocket";
|
|
231
|
+
}
|
|
232
|
+
/** `?after=<cursor>` alone: the ticket stays on this side of the hub. */
|
|
233
|
+
function cursorSearch(url) {
|
|
234
|
+
let after = url.searchParams.get("after");
|
|
235
|
+
return after ? `?${new URLSearchParams({ after })}` : "";
|
|
236
|
+
}
|
|
237
|
+
function createPreviewRoutes(options) {
|
|
238
|
+
let basePath = (options.basePath ?? "/api/preview").replace(/\/+$/, ""), maxBytes = options.maxBytes ?? 1e6, secret = () => typeof options.secret == "function" ? options.secret() : options.secret, { hubFor } = createPreviewHubClient(options.hub), liveEditPath = `${basePath}${LIVE_EDIT_PATH.slice(12)}`;
|
|
239
|
+
async function tabHub(request, url) {
|
|
240
|
+
let ticket = url.searchParams.get(LIVE_TICKET_PARAM);
|
|
241
|
+
return ticket ? secret() ? verifyLiveTicket(secret(), ticket) : null : await options.fallbackHub?.(request) ?? null;
|
|
242
|
+
}
|
|
243
|
+
async function editor(request) {
|
|
244
|
+
return secret() ? verifyLiveEditToken(secret(), readCookie(request, LIVE_EDIT_COOKIE)) : !1;
|
|
245
|
+
}
|
|
246
|
+
/** Answers a hub route, or returns `null` for any other path. */
|
|
247
|
+
async function handle(request) {
|
|
248
|
+
let url = new URL(request.url);
|
|
249
|
+
if (!url.pathname.startsWith(`${basePath}/`)) return null;
|
|
250
|
+
let route = url.pathname.slice(basePath.length + 1).replace(/\/+$/, ""), method = request.method;
|
|
251
|
+
if (route === "socket" || route === "live-edit/socket") {
|
|
252
|
+
if (method !== "GET") return null;
|
|
253
|
+
if (!isUpgrade(request)) return text("Expected a WebSocket", 426);
|
|
254
|
+
if (route === "live-edit/socket") {
|
|
255
|
+
if (!await editor(request)) return text("No live-edit session", 401);
|
|
256
|
+
let hub = hubFor("drafts");
|
|
257
|
+
return hub ? hub.editSocket() : text("No preview hub", 503);
|
|
258
|
+
}
|
|
259
|
+
let name = await tabHub(request, url);
|
|
260
|
+
if (!name) return text("Preview mode only", 403);
|
|
261
|
+
let hub = hubFor(name);
|
|
262
|
+
return hub ? hub.socket(cursorSearch(url)) : new Response(null, {
|
|
263
|
+
status: 204,
|
|
264
|
+
headers: NO_STORE
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
if (route === "events" && method === "GET") {
|
|
268
|
+
let name = await tabHub(request, url);
|
|
269
|
+
if (!name) return text("Preview mode only", 403);
|
|
270
|
+
let hub = hubFor(name);
|
|
271
|
+
if (!hub) return new Response(null, {
|
|
272
|
+
status: 204,
|
|
273
|
+
headers: NO_STORE
|
|
274
|
+
});
|
|
275
|
+
let upstream = await hub.events(cursorSearch(url), request.signal);
|
|
276
|
+
return new Response(await upstream.text(), {
|
|
277
|
+
status: upstream.status,
|
|
278
|
+
headers: {
|
|
279
|
+
"content-type": "application/json",
|
|
280
|
+
...NO_STORE
|
|
281
|
+
}
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
if ((route === "hub/stats" || route === "hub/bench") && method === "GET") {
|
|
285
|
+
let name = await tabHub(request, url);
|
|
286
|
+
if (!name) return text("Preview mode only", 403);
|
|
287
|
+
let hub = hubFor(name);
|
|
288
|
+
if (!hub) return Response.json({
|
|
289
|
+
hub: null,
|
|
290
|
+
perspective: name,
|
|
291
|
+
reason: "No preview hub binding."
|
|
292
|
+
}, { headers: NO_STORE });
|
|
293
|
+
let search = new URLSearchParams(url.search);
|
|
294
|
+
search.delete(LIVE_TICKET_PARAM);
|
|
295
|
+
let query = search.size ? `?${search}` : "", upstream = await hub.debug(`/${route.slice(4)}${query}`);
|
|
296
|
+
return new Response(await upstream.text(), {
|
|
297
|
+
status: upstream.status,
|
|
298
|
+
headers: {
|
|
299
|
+
"content-type": "application/json",
|
|
300
|
+
...NO_STORE
|
|
301
|
+
}
|
|
302
|
+
});
|
|
303
|
+
}
|
|
304
|
+
if (route === "live-edit/session" && method === "POST") {
|
|
305
|
+
if (!options.client) return null;
|
|
306
|
+
if (!secret()) return text("Live edits are off: no secret", 503);
|
|
307
|
+
let { isValid } = await validatePreviewUrl(options.client, request.url);
|
|
308
|
+
if (!isValid) return text("Invalid preview secret", 401);
|
|
309
|
+
let token = await createLiveEditToken(secret()), cookie = [
|
|
310
|
+
`${LIVE_EDIT_COOKIE}=${encodeURIComponent(token)}`,
|
|
311
|
+
`Path=${liveEditPath}`,
|
|
312
|
+
`Max-Age=${LIVE_EDIT_TTL_S}`,
|
|
313
|
+
"HttpOnly",
|
|
314
|
+
...url.protocol === "https:" ? ["Secure"] : [],
|
|
315
|
+
"SameSite=Strict"
|
|
316
|
+
].join("; ");
|
|
317
|
+
return new Response(null, {
|
|
318
|
+
status: 204,
|
|
319
|
+
headers: {
|
|
320
|
+
...NO_STORE,
|
|
321
|
+
"set-cookie": cookie
|
|
322
|
+
}
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
if (route === "live-edit" && method === "POST") {
|
|
326
|
+
if (!await editor(request)) return text("No live-edit session", 401);
|
|
327
|
+
let body = await request.text();
|
|
328
|
+
if (body.length > maxBytes) return text("Document too large", 413);
|
|
329
|
+
let parsed;
|
|
330
|
+
try {
|
|
331
|
+
parsed = JSON.parse(body);
|
|
332
|
+
} catch {
|
|
333
|
+
return text("Invalid JSON", 400);
|
|
334
|
+
}
|
|
335
|
+
let { document, seq } = parsed;
|
|
336
|
+
if (!document || typeof document._id != "string" || !document._id.startsWith("drafts.") || typeof seq != "number") return text("Expected { document: draft, seq }", 400);
|
|
337
|
+
let hub = hubFor("drafts");
|
|
338
|
+
if (!hub) return Response.json({ applied: !1 }, {
|
|
339
|
+
status: 503,
|
|
340
|
+
headers: NO_STORE
|
|
341
|
+
});
|
|
342
|
+
let applied = await hub.overlay(document, seq);
|
|
343
|
+
return Response.json({ applied }, {
|
|
344
|
+
status: 202,
|
|
345
|
+
headers: NO_STORE
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
return null;
|
|
349
|
+
}
|
|
350
|
+
return {
|
|
351
|
+
basePath,
|
|
352
|
+
handle,
|
|
353
|
+
/**
|
|
354
|
+
* For a Worker entry, ahead of the framework: answers the two WebSocket routes and returns
|
|
355
|
+
* `null` for everything else, which then goes to the framework.
|
|
356
|
+
*/
|
|
357
|
+
async upgrade(request) {
|
|
358
|
+
if (!isUpgrade(request)) return null;
|
|
359
|
+
let { pathname } = new URL(request.url);
|
|
360
|
+
return pathname !== `${basePath}/socket` && pathname !== `${liveEditPath}/socket` ? null : handle(request);
|
|
361
|
+
}
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
const TTL_DAYS = PREVIEW_LINK_TTL_SECONDS / 86400;
|
|
365
|
+
function escapeHtml(value) {
|
|
366
|
+
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
|
367
|
+
}
|
|
368
|
+
/**
|
|
369
|
+
* Default zero-JS HTML screen for expired or unavailable `/p/<code>` preview links.
|
|
370
|
+
* Matches Sanity Presentation's `ErrorCard` (`sanity@6.23` + `@sanity/ui@4` `buildTheme()`):
|
|
371
|
+
* flat full-height canvas, centered `Container width={0}` (320px), semibold `size={1}` title and
|
|
372
|
+
* muted message over a ghost "Open Studio" button. Override via `renderLinkError` to customize.
|
|
373
|
+
*/
|
|
374
|
+
function renderPreviewLinkErrorHtml({ expired, brand, studioPath = "/studio" }) {
|
|
375
|
+
let title = expired ? "This preview link has expired" : "This preview link couldn’t be opened", message = expired ? `Preview links open for ${TTL_DAYS} days. Ask the person who shared it for a new link.` : "Something went wrong on our side. Try the link again in a moment.";
|
|
376
|
+
return `<!doctype html>
|
|
377
|
+
<html lang="en">
|
|
378
|
+
<head>
|
|
379
|
+
<meta charset="utf-8" />
|
|
380
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
381
|
+
<meta name="robots" content="noindex" />
|
|
382
|
+
<title>${escapeHtml(expired ? "Preview link expired" : "Preview link error")} · ${escapeHtml(brand.title)}</title>
|
|
383
|
+
<style>
|
|
384
|
+
:root {
|
|
385
|
+
color-scheme: light dark;
|
|
386
|
+
--bg: #ffffff;
|
|
387
|
+
--fg: #252837;
|
|
388
|
+
--muted: #515870;
|
|
389
|
+
--btn-bg: #f6f6f8;
|
|
390
|
+
--btn-fg: #4e556d;
|
|
391
|
+
--btn-border: #e6e6ea;
|
|
392
|
+
--btn-hover-bg: #eeeef1;
|
|
393
|
+
--btn-hover-fg: #353a4d;
|
|
394
|
+
--btn-hover-border: #dedee4;
|
|
395
|
+
--btn-active-bg: #e3e4e8;
|
|
396
|
+
--btn-active-fg: #222533;
|
|
397
|
+
--btn-active-border: #d4d5db;
|
|
398
|
+
--focus-ring: #556bfc;
|
|
399
|
+
}
|
|
400
|
+
@media (prefers-color-scheme: dark) {
|
|
401
|
+
:root {
|
|
402
|
+
--bg: #13141b;
|
|
403
|
+
--fg: #e4e5e9;
|
|
404
|
+
--muted: #979cb0;
|
|
405
|
+
--btn-bg: #191a24;
|
|
406
|
+
--btn-fg: #999eb3;
|
|
407
|
+
--btn-border: #262837;
|
|
408
|
+
--btn-hover-bg: #21232f;
|
|
409
|
+
--btn-hover-fg: #c1c3d0;
|
|
410
|
+
--btn-hover-border: #2e3141;
|
|
411
|
+
--btn-active-bg: #2a2d3f;
|
|
412
|
+
--btn-active-fg: #e6e7ec;
|
|
413
|
+
--btn-active-border: #363a50;
|
|
414
|
+
--focus-ring: #596ffc;
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
* { box-sizing: border-box; }
|
|
418
|
+
html, body { height: 100%; margin: 0; }
|
|
419
|
+
body {
|
|
420
|
+
background: var(--bg);
|
|
421
|
+
color: var(--fg);
|
|
422
|
+
font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Liberation Sans", Helvetica, Arial, system-ui, sans-serif;
|
|
423
|
+
font-size: 13px;
|
|
424
|
+
line-height: 19px;
|
|
425
|
+
-webkit-font-smoothing: antialiased;
|
|
426
|
+
-moz-osx-font-smoothing: grayscale;
|
|
427
|
+
}
|
|
428
|
+
main {
|
|
429
|
+
min-height: 100dvh;
|
|
430
|
+
display: flex;
|
|
431
|
+
align-items: center;
|
|
432
|
+
justify-content: center;
|
|
433
|
+
}
|
|
434
|
+
.container {
|
|
435
|
+
width: 100%;
|
|
436
|
+
max-width: 320px;
|
|
437
|
+
padding: 20px;
|
|
438
|
+
display: flex;
|
|
439
|
+
flex-direction: column;
|
|
440
|
+
gap: 20px;
|
|
441
|
+
}
|
|
442
|
+
.copy {
|
|
443
|
+
display: flex;
|
|
444
|
+
flex-direction: column;
|
|
445
|
+
gap: 12px;
|
|
446
|
+
}
|
|
447
|
+
h1 {
|
|
448
|
+
margin: 0;
|
|
449
|
+
font-size: 13px;
|
|
450
|
+
line-height: 19px;
|
|
451
|
+
font-weight: 600;
|
|
452
|
+
color: var(--fg);
|
|
453
|
+
}
|
|
454
|
+
p {
|
|
455
|
+
margin: 0;
|
|
456
|
+
font-size: 13px;
|
|
457
|
+
line-height: 19px;
|
|
458
|
+
font-weight: 400;
|
|
459
|
+
color: var(--muted);
|
|
460
|
+
}
|
|
461
|
+
.actions { display: flex; }
|
|
462
|
+
a.button {
|
|
463
|
+
display: inline-flex;
|
|
464
|
+
align-items: center;
|
|
465
|
+
justify-content: center;
|
|
466
|
+
gap: 8px;
|
|
467
|
+
padding: 6px 10px;
|
|
468
|
+
border-radius: 3px;
|
|
469
|
+
font-size: 13px;
|
|
470
|
+
line-height: 19px;
|
|
471
|
+
font-weight: 500;
|
|
472
|
+
text-decoration: none;
|
|
473
|
+
background: var(--btn-bg);
|
|
474
|
+
color: var(--btn-fg);
|
|
475
|
+
box-shadow: inset 0 0 0 1px var(--btn-border);
|
|
476
|
+
transition: background-color 100ms, color 100ms, box-shadow 100ms;
|
|
477
|
+
}
|
|
478
|
+
a.button:hover {
|
|
479
|
+
background: var(--btn-hover-bg);
|
|
480
|
+
color: var(--btn-hover-fg);
|
|
481
|
+
box-shadow: inset 0 0 0 1px var(--btn-hover-border);
|
|
482
|
+
}
|
|
483
|
+
a.button:active {
|
|
484
|
+
background: var(--btn-active-bg);
|
|
485
|
+
color: var(--btn-active-fg);
|
|
486
|
+
box-shadow: inset 0 0 0 1px var(--btn-active-border);
|
|
487
|
+
}
|
|
488
|
+
a.button:focus-visible {
|
|
489
|
+
outline: none;
|
|
490
|
+
box-shadow: inset 0 0 0 1px var(--btn-border), 0 0 0 1px var(--bg), 0 0 0 3px var(--focus-ring);
|
|
491
|
+
}
|
|
492
|
+
</style>
|
|
493
|
+
</head>
|
|
494
|
+
<body>
|
|
495
|
+
<main>
|
|
496
|
+
<div class="container">
|
|
497
|
+
<div class="copy">
|
|
498
|
+
<h1>${escapeHtml(title)}</h1>
|
|
499
|
+
<p>${escapeHtml(message)}</p>
|
|
500
|
+
</div>
|
|
501
|
+
<div class="actions">
|
|
502
|
+
<a class="button" href="${escapeHtml(studioPath)}">Open Studio</a>
|
|
503
|
+
</div>
|
|
504
|
+
</div>
|
|
505
|
+
</main>
|
|
506
|
+
</body>
|
|
507
|
+
</html>`;
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* The bar's server side, framework-neutral: each handler takes a web `Request` plus the request's
|
|
511
|
+
* preview state and returns a web `Response`. Framework adapters (`sanity-plugin-visual-editor/sveltekit`,
|
|
512
|
+
* later `/next`) supply that state and the one thing that differs per framework: turning preview
|
|
513
|
+
* mode on and off.
|
|
514
|
+
*/
|
|
515
|
+
const PRIVATE_HEADERS = {
|
|
516
|
+
"cache-control": "private, no-store",
|
|
517
|
+
"x-robots-tag": "noindex"
|
|
518
|
+
};
|
|
519
|
+
function json(body, init = {}) {
|
|
520
|
+
let headers = new Headers(init.headers);
|
|
521
|
+
headers.set("content-type", "application/json");
|
|
522
|
+
for (let [key, value] of Object.entries(PRIVATE_HEADERS)) headers.set(key, value);
|
|
523
|
+
return new Response(JSON.stringify(body), {
|
|
524
|
+
...init,
|
|
525
|
+
headers
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
function status(code, message) {
|
|
529
|
+
return json({ message }, { status: code });
|
|
530
|
+
}
|
|
531
|
+
function sameOrigin(request) {
|
|
532
|
+
return request.headers.get("origin") === new URL(request.url).origin;
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* `handlePreviewMode`'s cookie attributes: `SameSite=None; Secure` so the cookies also work inside
|
|
536
|
+
* the Studio's Presentation iframe, `Lax` on plain-HTTP local development.
|
|
537
|
+
*/
|
|
538
|
+
function previewCookieAttributes(request) {
|
|
539
|
+
return new URL(request.url).protocol === "https:" ? "Path=/; HttpOnly; SameSite=None; Secure" : "Path=/; HttpOnly; SameSite=Lax";
|
|
540
|
+
}
|
|
541
|
+
function setCookieHeader(request, name, value) {
|
|
542
|
+
return `${name}=${encodeURIComponent(value)}; ${previewCookieAttributes(request)}`;
|
|
543
|
+
}
|
|
544
|
+
function deleteCookieHeader(request, name) {
|
|
545
|
+
return `${name}=; Max-Age=0; ${previewCookieAttributes(request)}`;
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* Every content release, read like the Studio's releases store: raw perspective, the API version
|
|
549
|
+
* that introduced releases, no stega or CDN. The client's token needs read access to
|
|
550
|
+
* `system.release` documents.
|
|
551
|
+
*/
|
|
552
|
+
function fetchReleases(client) {
|
|
553
|
+
return client.withConfig({
|
|
554
|
+
apiVersion: "2025-02-19",
|
|
555
|
+
perspective: "raw",
|
|
556
|
+
useCdn: !1,
|
|
557
|
+
stega: !1
|
|
558
|
+
}).fetch(RELEASES_QUERY).then((releases) => releases ?? []);
|
|
559
|
+
}
|
|
560
|
+
function rawClient(client) {
|
|
561
|
+
return client.withConfig({
|
|
562
|
+
perspective: "raw",
|
|
563
|
+
useCdn: !1,
|
|
564
|
+
stega: !1
|
|
565
|
+
});
|
|
566
|
+
}
|
|
567
|
+
function createPreviewBar(options) {
|
|
568
|
+
let studioPath = options.studioPath ?? "/studio", basePath = options.basePath ?? "/__visual-editor", search = options.search || null, links = options.links || null, linkRoute = links ? links.route ?? "/p/" : "/p/", ttlSeconds = links ? assertLinkTtl(links.ttlSeconds ?? 172800) : 0;
|
|
569
|
+
function store() {
|
|
570
|
+
if (!links) throw Error("sanity-visual-editor: short links are not configured");
|
|
571
|
+
return typeof links.store == "function" ? links.store() : links.store;
|
|
572
|
+
}
|
|
573
|
+
/** The bar page's data, or `null` outside preview (render a 404). */
|
|
574
|
+
async function loadBar(ctx) {
|
|
575
|
+
if (!ctx.previewEnabled) return null;
|
|
576
|
+
let [releasesResult, shareSecretResult] = await Promise.allSettled([fetchReleases(ctx.client), links ? rawClient(ctx.client).fetch(fetchSharedAccessQuery) : Promise.resolve(null)]);
|
|
577
|
+
return releasesResult.status === "rejected" && console.error("sanity-visual-editor: could not load content releases", releasesResult.reason), shareSecretResult.status === "rejected" && console.error("sanity-visual-editor: could not read the preview share secret", shareSecretResult.reason), {
|
|
578
|
+
brand: options.brand,
|
|
579
|
+
studioPath,
|
|
580
|
+
projectId: options.projectId ?? ctx.client.config?.().projectId ?? null,
|
|
581
|
+
basePath,
|
|
582
|
+
releases: releasesResult.status === "fulfilled" ? activeReleases(releasesResult.value) : [],
|
|
583
|
+
releasesError: releasesResult.status === "rejected",
|
|
584
|
+
sharing: shareSecretResult.status === "fulfilled" && !!shareSecretResult.value,
|
|
585
|
+
links: !!links,
|
|
586
|
+
perspective: serializePerspective(ctx.perspective),
|
|
587
|
+
search: search ? searchKinds(search) : null,
|
|
588
|
+
pageDocuments: !!options.pageDocuments
|
|
589
|
+
};
|
|
590
|
+
}
|
|
591
|
+
/**
|
|
592
|
+
* POST `{ selected, excluded }`: sets the perspective cookie. The stack is built here from fresh
|
|
593
|
+
* release data, so the client only names a layer to select and layers to hide.
|
|
594
|
+
*/
|
|
595
|
+
async function perspective(ctx) {
|
|
596
|
+
if (!ctx.previewEnabled) return status(404, "Not found");
|
|
597
|
+
if (!sameOrigin(ctx.request)) return status(403, "Forbidden");
|
|
598
|
+
let body = await ctx.request.json().catch(() => ({})), selected = typeof body.selected == "string" ? body.selected : DRAFTS, releases = [];
|
|
599
|
+
if (selected !== "published" && selected !== "drafts") try {
|
|
600
|
+
releases = activeReleases(await fetchReleases(ctx.client));
|
|
601
|
+
} catch (error) {
|
|
602
|
+
return console.error("sanity-visual-editor: could not load content releases", error), status(503, "Could not load content releases");
|
|
603
|
+
}
|
|
604
|
+
let releaseIds = releases.map(releaseIdOf);
|
|
605
|
+
if (selected !== "published" && selected !== "drafts" && !releaseIds.includes(selected)) return status(400, "Unknown perspective");
|
|
606
|
+
let excluded = Array.isArray(body.excluded) ? body.excluded.filter((name) => typeof name == "string" && (name === "drafts" || releaseIds.includes(name))) : [], stack = perspectiveStack({
|
|
607
|
+
selected,
|
|
608
|
+
releases,
|
|
609
|
+
excluded
|
|
610
|
+
});
|
|
611
|
+
return json({ perspective: stack }, { headers: { "set-cookie": setCookieHeader(ctx.request, PERSPECTIVE_COOKIE, serializePerspective(stack)) } });
|
|
612
|
+
}
|
|
613
|
+
/**
|
|
614
|
+
* POST: ends preview mode in place. Clears the perspective cookie; `disablePreview` clears the
|
|
615
|
+
* framework's preview cookie. The bar then asks the host to rerun its data, so no reload.
|
|
616
|
+
*/
|
|
617
|
+
async function exit(ctx, disablePreview) {
|
|
618
|
+
if (!sameOrigin(ctx.request)) return status(403, "Forbidden");
|
|
619
|
+
let headers = new Headers(PRIVATE_HEADERS);
|
|
620
|
+
return headers.append("set-cookie", deleteCookieHeader(ctx.request, PERSPECTIVE_COOKIE)), await disablePreview(headers, ctx.request), new Response(null, {
|
|
621
|
+
status: 204,
|
|
622
|
+
headers
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
/**
|
|
626
|
+
* GET `?type=&id=`: `{ href }`, the page a document opens, for search results picked in the
|
|
627
|
+
* Studio's own search (Studio layer). 404 for a type without a page or a document without a slug.
|
|
628
|
+
*/
|
|
629
|
+
async function resolveHref(ctx) {
|
|
630
|
+
if (!ctx.previewEnabled || !search) return status(404, "Not found");
|
|
631
|
+
let url = new URL(ctx.request.url), type = search.types?.find((candidate) => candidate.type === url.searchParams.get("type")), id = (url.searchParams.get("id") ?? "").replace(/^drafts\./, "").replace(/^versions\.[^.]+\./, "");
|
|
632
|
+
if (!type || !/^[\w.-]{1,128}$/.test(id)) return status(404, "Not found");
|
|
633
|
+
let client = ctx.client.withConfig({
|
|
634
|
+
perspective: ctx.perspective,
|
|
635
|
+
stega: !1,
|
|
636
|
+
useCdn: !1
|
|
637
|
+
}), filter = type.filter ? ` && (${type.filter})` : "", slug = await client.fetch(`*[_id == $id${filter}][0]{"slug": ${type.fields.slug}}.slug`, { id });
|
|
638
|
+
return slug ? json({ href: type.href(slug) }) : status(404, "No page for this document");
|
|
639
|
+
}
|
|
640
|
+
/**
|
|
641
|
+
* GET `?path=`: `{ document: { _id, _type } | null }`, the document the page at `path` shows,
|
|
642
|
+
* from `pageDocuments`. The ID is the published ID, whatever version the perspective shows.
|
|
643
|
+
*/
|
|
644
|
+
async function pageDocument(ctx) {
|
|
645
|
+
if (!ctx.previewEnabled || !options.pageDocuments) return status(404, "Not found");
|
|
646
|
+
let path = new URL(ctx.request.url).searchParams.get("path") ?? "/", rule = findPageDocumentRule(options.pageDocuments, path);
|
|
647
|
+
if (!rule) return json({ document: null });
|
|
648
|
+
let document = await ctx.client.withConfig({
|
|
649
|
+
perspective: ctx.perspective,
|
|
650
|
+
stega: !1,
|
|
651
|
+
useCdn: !1
|
|
652
|
+
}).fetch(`*[${rule.filter}][0]{_id, _type}`, rule.params, { tag: "preview-bar.page-document" });
|
|
653
|
+
return json({ document: document ? {
|
|
654
|
+
_id: document._id.replace(/^drafts\./, "").replace(/^versions\.[^.]+\./, ""),
|
|
655
|
+
_type: document._type
|
|
656
|
+
} : null });
|
|
657
|
+
}
|
|
658
|
+
/**
|
|
659
|
+
* POST `{ pathname }`: mints a short link while Presentation's "Share this preview" is on (409
|
|
660
|
+
* when it is off). The store holds the page and perspective, never a secret. 403 for a session
|
|
661
|
+
* opened from a short link: recipients can't hand out links of their own.
|
|
662
|
+
*/
|
|
663
|
+
async function share(ctx) {
|
|
664
|
+
if (!ctx.previewEnabled || !links) return status(404, "Not found");
|
|
665
|
+
if (!sameOrigin(ctx.request)) return status(403, "Forbidden");
|
|
666
|
+
if (ctx.linkSession) return status(403, "Preview links can’t be shared from a preview link");
|
|
667
|
+
let body = await ctx.request.json().catch(() => ({})), pathname = normalizePreviewPathname(body?.pathname);
|
|
668
|
+
if (!pathname) return status(400, "Invalid pathname");
|
|
669
|
+
if (!await rawClient(ctx.client).fetch(fetchSharedAccessQuery)) return status(409, "Preview sharing is off");
|
|
670
|
+
let link = createPreviewLink({
|
|
671
|
+
code: generatePreviewLinkCode(),
|
|
672
|
+
pathname,
|
|
673
|
+
perspective: serializePerspective(ctx.perspective),
|
|
674
|
+
ttlSeconds,
|
|
675
|
+
route: linkRoute
|
|
676
|
+
});
|
|
677
|
+
try {
|
|
678
|
+
await store().put(link.key, link.value, link.ttlSeconds);
|
|
679
|
+
} catch (err) {
|
|
680
|
+
return console.error("sanity-visual-editor: could not store a preview link", err), status(503, "Preview links are not configured");
|
|
681
|
+
}
|
|
682
|
+
return json({
|
|
683
|
+
url: new URL(link.path, ctx.request.url).href,
|
|
684
|
+
expiresAt: link.expiresAt
|
|
685
|
+
});
|
|
686
|
+
}
|
|
687
|
+
/**
|
|
688
|
+
* Opens `/p/<code>`: a 307 to the stored page with the perspective cookie and, through
|
|
689
|
+
* `enablePreview`, the framework's preview cookie. 404 for an unknown, malformed or expired
|
|
690
|
+
* code; 503 when the store can't be read. Render your expired-link page for those two.
|
|
691
|
+
*/
|
|
692
|
+
async function openLink(request, code, enablePreview) {
|
|
693
|
+
let result = await resolveLink(code);
|
|
694
|
+
if (result.status !== 200) return status(result.status, result.status === 404 ? "Preview link not found" : "Unavailable");
|
|
695
|
+
let { link } = result, headers = new Headers(PRIVATE_HEADERS);
|
|
696
|
+
return headers.set("location", link.pathname), headers.append("set-cookie", setCookieHeader(request, PERSPECTIVE_COOKIE, serializePerspective(link.perspective))), await enablePreview(headers, request, { expiresAt: link.expiresAt }), new Response(null, {
|
|
697
|
+
status: 307,
|
|
698
|
+
headers
|
|
699
|
+
});
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* Looks a short link up: `200` with the stored page, perspective and expiry (ms since the
|
|
703
|
+
* epoch), `404` for an unknown, malformed or expired code, `503` when the store can't be read.
|
|
704
|
+
* Expiry is checked here too (`createdAt` + `ttlSeconds`), so a store that ignores the TTL
|
|
705
|
+
* doesn't make links permanent. For adapters that set cookies through their framework's own
|
|
706
|
+
* API; `openLink` builds the whole response.
|
|
707
|
+
*/
|
|
708
|
+
async function resolveLink(code) {
|
|
709
|
+
if (!links || !isPreviewLinkCode(code)) return { status: 404 };
|
|
710
|
+
let stored;
|
|
711
|
+
try {
|
|
712
|
+
stored = await store().get(previewLinkKey(code));
|
|
713
|
+
} catch (err) {
|
|
714
|
+
return console.error("sanity-visual-editor: could not read a preview link", err), { status: 503 };
|
|
715
|
+
}
|
|
716
|
+
let link = parsePreviewLinkValue(stored);
|
|
717
|
+
if (!link) return { status: 404 };
|
|
718
|
+
let now = Date.now(), expiresAt = previewLinkExpiry(link, ttlSeconds);
|
|
719
|
+
return expiresAt === null || expiresAt <= now || expiresAt > now + ttlSeconds * 1e3 + 6e4 ? { status: 404 } : {
|
|
720
|
+
status: 200,
|
|
721
|
+
link: {
|
|
722
|
+
pathname: link.pathname,
|
|
723
|
+
perspective: parsePerspective(link.perspective),
|
|
724
|
+
expiresAt
|
|
725
|
+
}
|
|
726
|
+
};
|
|
727
|
+
}
|
|
728
|
+
return {
|
|
729
|
+
options: {
|
|
730
|
+
...options,
|
|
731
|
+
studioPath,
|
|
732
|
+
basePath,
|
|
733
|
+
linkRoute
|
|
734
|
+
},
|
|
735
|
+
resolveLink,
|
|
736
|
+
loadBar,
|
|
737
|
+
perspective,
|
|
738
|
+
exit,
|
|
739
|
+
resolveHref,
|
|
740
|
+
pageDocument,
|
|
741
|
+
share,
|
|
742
|
+
openLink
|
|
743
|
+
};
|
|
744
|
+
}
|
|
745
|
+
const createVisualEditor = createPreviewBar;
|
|
746
|
+
export { verifyLinkSession as C, signLinkSession as S, createPreviewHubClient as _, previewCookieAttributes as a, verifyLiveTicket as b, LIVE_TICKET_PARAM as c, LIVE_EDIT_COOKIE as d, LIVE_EDIT_PATH as f, createLiveTicket as g, createLiveEditToken as h, fetchReleases as i, PREVIEW_ROUTES_PATH as l, LIVE_TICKET_TTL_S as m, createVisualEditor as n, setCookieHeader as o, LIVE_EDIT_TTL_S as p, deleteCookieHeader as r, renderPreviewLinkErrorHtml as s, createPreviewBar as t, createPreviewRoutes as u, previewHubName as v, LINK_SESSION_COOKIE as x, verifyLiveEditToken as y };
|
|
747
|
+
|
|
748
|
+
//# sourceMappingURL=server-B8MqMyaN.js.map
|