sanity-plugin-visual-editor 1.0.0 → 1.1.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 (60) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +137 -16
  3. package/TESTING.md +133 -0
  4. package/dist/PreviewBar-D_rw0bhP.js +3503 -0
  5. package/dist/PreviewBar-D_rw0bhP.js.map +1 -0
  6. package/dist/bar.d.ts +22 -0
  7. package/dist/bar.js +67 -0
  8. package/dist/bar.js.map +1 -0
  9. package/dist/cloudflare.d.ts +76 -0
  10. package/dist/cloudflare.js +1071 -0
  11. package/dist/cloudflare.js.map +1 -0
  12. package/dist/data-D0qotTtt.d.ts +177 -0
  13. package/dist/host-DreYJEmR.js +615 -0
  14. package/dist/host-DreYJEmR.js.map +1 -0
  15. package/dist/host.d.ts +160 -0
  16. package/dist/host.js +3 -0
  17. package/dist/index-4Zm_NjhC.d.ts +221 -0
  18. package/dist/index.d.ts +18 -18
  19. package/dist/index.js +7 -8
  20. package/dist/link-search-JtZkxz4k.js +14 -0
  21. package/dist/link-search-JtZkxz4k.js.map +1 -0
  22. package/dist/link-session-Dr4YkKFy.js +52 -0
  23. package/dist/link-session-Dr4YkKFy.js.map +1 -0
  24. package/dist/next-client.d.ts +15 -0
  25. package/dist/next-client.js +78 -0
  26. package/dist/next-client.js.map +1 -0
  27. package/dist/next.d.ts +38 -0
  28. package/dist/next.js +117 -0
  29. package/dist/next.js.map +1 -0
  30. package/dist/node-labels-CDiW5rMq.js +122 -0
  31. package/dist/node-labels-CDiW5rMq.js.map +1 -0
  32. package/dist/page-documents-BFFcH8lD.d.ts +54 -0
  33. package/dist/page-documents-mGfw_flR.js +67 -0
  34. package/dist/page-documents-mGfw_flR.js.map +1 -0
  35. package/dist/perspective-BmS9TVtr.js +106 -0
  36. package/dist/perspective-BmS9TVtr.js.map +1 -0
  37. package/dist/preview-links-BZDZyIey.js +119 -0
  38. package/dist/preview-links-BZDZyIey.js.map +1 -0
  39. package/dist/preview-links-DM6BCiLV.d.ts +87 -0
  40. package/dist/protocol-BNO38gYy.js +280 -0
  41. package/dist/protocol-BNO38gYy.js.map +1 -0
  42. package/dist/protocol-BnRCy2wJ.d.ts +386 -0
  43. package/dist/server.d.ts +4 -0
  44. package/dist/server.js +495 -0
  45. package/dist/server.js.map +1 -0
  46. package/dist/shell-DZotxRXX.d.ts +37 -0
  47. package/dist/studio.d.ts +93 -0
  48. package/dist/studio.js +1263 -0
  49. package/dist/studio.js.map +1 -0
  50. package/dist/sveltekit.d.ts +281 -0
  51. package/dist/sveltekit.js +395 -0
  52. package/dist/sveltekit.js.map +1 -0
  53. package/package.json +120 -39
  54. package/dist/index.d.mts +0 -21
  55. package/dist/index.js.map +0 -1
  56. package/dist/index.mjs +0 -8
  57. package/dist/index.mjs.map +0 -1
  58. package/sanity.json +0 -8
  59. package/src/index.ts +0 -27
  60. package/v2-incompatible.js +0 -11
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Preview perspective: which content layers (published, drafts, content releases) the site renders
3
+ * in Sanity preview mode. Shared by the server, the host and the bar UI, so it imports nothing.
4
+ *
5
+ * Release ordering, stacking, filtering and tones mirror the Studio's global perspective menu in
6
+ * `sanity@6.23` (`sortReleases`, `getReleasesPerspectiveStack`, `useActiveReleases`,
7
+ * `ReleasesList`, `getReleaseTone`). `test/preview-perspective.test.ts` checks `sortReleases`
8
+ * against the installed `sanity` export; re-check the rest when bumping `sanity`.
9
+ */
10
+ /** Same cookie the Studio's Presentation tool sets through `/preview/enable`. */
11
+ const PERSPECTIVE_COOKIE = "sanity-preview-perspective", PUBLISHED = "published", DRAFTS = "drafts", RELEASES_QUERY = "*[_type == \"system.release\" && _id in path(\"_.releases.*\")]{\n _id,\n _createdAt,\n state,\n publishAt,\n \"metadata\": coalesce(metadata, { \"title\": \"\", \"releaseType\": \"undecided\" })\n} | order(_createdAt desc)", ARCHIVED_RELEASE_STATES = ["archived", "published"], RELEASE_TYPES = [
12
+ "asap",
13
+ "scheduled",
14
+ "undecided"
15
+ ], RELEASE_ID = /^[a-zA-Z0-9_-]{1,64}$/, RESERVED = [
16
+ "raw",
17
+ PUBLISHED,
18
+ "previewDrafts"
19
+ ];
20
+ function releaseIdOf(release) {
21
+ return release._id.startsWith("_.releases.") ? release._id.slice(11) : release._id;
22
+ }
23
+ /** `sortReleases` from `sanity`: undecided (newest first), scheduled (latest first), then ASAP. */
24
+ function sortReleases(releases = []) {
25
+ return [...releases].sort((a, b) => {
26
+ let aType = a.metadata.releaseType, bType = b.metadata.releaseType;
27
+ if (aType === "undecided" && bType !== "undecided") return -1;
28
+ if (aType !== "undecided" && bType === "undecided") return 1;
29
+ if (aType === "undecided" && bType === "undecided") return new Date(b._createdAt).getTime() - new Date(a._createdAt).getTime();
30
+ if (aType === "scheduled" && bType === "scheduled") {
31
+ let aPublishAt = a.publishAt || a.metadata.intendedPublishAt;
32
+ if (!aPublishAt) return 1;
33
+ let bPublishAt = b.publishAt || b.metadata.intendedPublishAt;
34
+ return bPublishAt ? new Date(bPublishAt).getTime() - new Date(aPublishAt).getTime() : -1;
35
+ }
36
+ return aType === "asap" && bType !== "asap" ? 1 : aType !== "asap" && bType === "asap" ? -1 : aType === "asap" && bType === "asap" ? new Date(b._createdAt).getTime() - new Date(a._createdAt).getTime() : 0;
37
+ });
38
+ }
39
+ /** `useActiveReleases`: not archived or published, in menu order (ASAP → scheduled → undecided). */
40
+ function activeReleases(releases) {
41
+ return sortReleases(releases.filter((release) => !ARCHIVED_RELEASE_STATES.includes(release.state))).reverse();
42
+ }
43
+ /** The menu hides single-document releases (Scheduled Drafts); the stack still includes them. */
44
+ function isScheduledDraft(release) {
45
+ return release.metadata.cardinality === "one";
46
+ }
47
+ /**
48
+ * `getReleasesPerspectiveStack` (draft model enabled): the selected release, every release that
49
+ * publishes before it, then drafts, minus excluded layers.
50
+ */
51
+ function perspectiveStack({ selected, releases, excluded = [] }) {
52
+ if (!selected || selected === "drafts") return DRAFTS;
53
+ if (selected === "published") return PUBLISHED;
54
+ let sorted = sortReleases(releases).map(releaseIdOf), index = sorted.indexOf(selected);
55
+ return index === -1 ? [selected, DRAFTS] : [...sorted.slice(index), DRAFTS].filter((name) => !excluded.includes(name));
56
+ }
57
+ /** Parses the cookie (`published`, `drafts`, or comma-separated IDs). Invalid values → drafts. */
58
+ function parsePerspective(value) {
59
+ if (!value || value === "drafts") return DRAFTS;
60
+ if (value === "published") return PUBLISHED;
61
+ let stack = value.split(",");
62
+ return stack.length > 32 || stack.some((name) => RESERVED.includes(name)) || !stack.every((name) => name === "drafts" || RELEASE_ID.test(name)) || stack.length === 1 && stack[0] === "drafts" ? DRAFTS : stack;
63
+ }
64
+ function serializePerspective(perspective) {
65
+ return Array.isArray(perspective) ? perspective.join(",") : perspective;
66
+ }
67
+ /**
68
+ * Recovers the menu state from a stored stack: the first layer is the selection, and anything the
69
+ * Studio would have stacked under it but is missing was hidden with the eye toggle.
70
+ */
71
+ function selectionOf(perspective, releases) {
72
+ if (!Array.isArray(perspective)) return {
73
+ selected: perspective,
74
+ excluded: []
75
+ };
76
+ let [selected = DRAFTS] = perspective, full = perspectiveStack({
77
+ selected,
78
+ releases
79
+ });
80
+ return {
81
+ selected,
82
+ excluded: Array.isArray(full) ? full.filter((name) => !perspective.includes(name)) : []
83
+ };
84
+ }
85
+ /**
86
+ * The Studio navbar's tone for a perspective (`RootCard tone={getReleaseTone(selectedPerspective)}`):
87
+ * published is positive, drafts default, a release takes its type's tone.
88
+ */
89
+ function perspectiveTone(perspective, releases) {
90
+ let { selected } = selectionOf(perspective, releases);
91
+ if (selected === "published") return "positive";
92
+ let release = releases.find((candidate) => releaseIdOf(candidate) === selected);
93
+ return release ? releaseTone(release) : "default";
94
+ }
95
+ /** `getReleaseTone` plus `RELEASE_TYPES_TONES`. */
96
+ function releaseTone(release) {
97
+ if (release.state === "archived") return "default";
98
+ switch (release.metadata.releaseType) {
99
+ case "asap": return "caution";
100
+ case "scheduled": return "suggest";
101
+ default: return "neutral";
102
+ }
103
+ }
104
+ export { RELEASE_TYPES as a, parsePerspective as c, releaseIdOf as d, releaseTone as f, sortReleases as h, RELEASES_QUERY as i, perspectiveStack as l, serializePerspective as m, PERSPECTIVE_COOKIE as n, activeReleases as o, selectionOf as p, PUBLISHED as r, isScheduledDraft as s, DRAFTS as t, perspectiveTone as u };
105
+
106
+ //# sourceMappingURL=perspective-BmS9TVtr.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"perspective-BmS9TVtr.js","names":[],"sources":["../src/core/perspective.ts"],"sourcesContent":["/**\n * Preview perspective: which content layers (published, drafts, content releases) the site renders\n * in Sanity preview mode. Shared by the server, the host and the bar UI, so it imports nothing.\n *\n * Release ordering, stacking, filtering and tones mirror the Studio's global perspective menu in\n * `sanity@6.23` (`sortReleases`, `getReleasesPerspectiveStack`, `useActiveReleases`,\n * `ReleasesList`, `getReleaseTone`). `test/preview-perspective.test.ts` checks `sortReleases`\n * against the installed `sanity` export; re-check the rest when bumping `sanity`.\n */\n\n/** Same cookie the Studio's Presentation tool sets through `/preview/enable`. */\nexport const PERSPECTIVE_COOKIE = 'sanity-preview-perspective'\n\nexport const PUBLISHED = 'published'\nexport const DRAFTS = 'drafts'\n\n/** A resolved perspective: `published`, `drafts`, or a stack of release IDs ending in drafts. */\nexport type PreviewPerspective = typeof PUBLISHED | typeof DRAFTS | string[]\n\nexport type ReleaseType = 'asap' | 'scheduled' | 'undecided'\n\nexport type ReleaseDocument = {\n _id: string\n _createdAt: string\n state: string\n publishAt?: string | null\n metadata: {\n title?: string\n releaseType: ReleaseType\n intendedPublishAt?: string | null\n cardinality?: 'one' | 'many'\n }\n}\n\n/** The Studio's releases store query (`_.releases.*`, raw perspective). */\nexport const RELEASES_QUERY = `*[_type == \"system.release\" && _id in path(\"_.releases.*\")]{\n\t_id,\n\t_createdAt,\n\tstate,\n\tpublishAt,\n\t\"metadata\": coalesce(metadata, { \"title\": \"\", \"releaseType\": \"undecided\" })\n} | order(_createdAt desc)`\n\nconst RELEASE_DOCUMENTS_PREFIX = '_.releases.'\nconst ARCHIVED_RELEASE_STATES = ['archived', 'published']\nexport const RELEASE_TYPES: ReleaseType[] = ['asap', 'scheduled', 'undecided']\n/** Release IDs are `r` plus random characters; anything else in the cookie is rejected. */\nconst RELEASE_ID = /^[a-zA-Z0-9_-]{1,64}$/\n/** API perspective names that are not releases and must never appear inside a stack. */\nconst RESERVED = ['raw', PUBLISHED, 'previewDrafts']\n\nexport function releaseIdOf(release: ReleaseDocument) {\n return release._id.startsWith(RELEASE_DOCUMENTS_PREFIX)\n ? release._id.slice(RELEASE_DOCUMENTS_PREFIX.length)\n : release._id\n}\n\n/** `sortReleases` from `sanity`: undecided (newest first), scheduled (latest first), then ASAP. */\nexport function sortReleases(releases: ReleaseDocument[] = []) {\n return [...releases].sort((a, b) => {\n const aType = a.metadata.releaseType\n const bType = b.metadata.releaseType\n if (aType === 'undecided' && bType !== 'undecided') return -1\n if (aType !== 'undecided' && bType === 'undecided') return 1\n if (aType === 'undecided' && bType === 'undecided') {\n return new Date(b._createdAt).getTime() - new Date(a._createdAt).getTime()\n }\n if (aType === 'scheduled' && bType === 'scheduled') {\n const aPublishAt = a.publishAt || a.metadata.intendedPublishAt\n if (!aPublishAt) return 1\n const bPublishAt = b.publishAt || b.metadata.intendedPublishAt\n return bPublishAt ? new Date(bPublishAt).getTime() - new Date(aPublishAt).getTime() : -1\n }\n if (aType === 'asap' && bType !== 'asap') return 1\n if (aType !== 'asap' && bType === 'asap') return -1\n if (aType === 'asap' && bType === 'asap') {\n return new Date(b._createdAt).getTime() - new Date(a._createdAt).getTime()\n }\n return 0\n })\n}\n\n/** `useActiveReleases`: not archived or published, in menu order (ASAP → scheduled → undecided). */\nexport function activeReleases(releases: ReleaseDocument[]) {\n return sortReleases(\n releases.filter((release) => !ARCHIVED_RELEASE_STATES.includes(release.state)),\n ).reverse()\n}\n\n/** The menu hides single-document releases (Scheduled Drafts); the stack still includes them. */\nexport function isScheduledDraft(release: ReleaseDocument) {\n return release.metadata.cardinality === 'one'\n}\n\n/**\n * `getReleasesPerspectiveStack` (draft model enabled): the selected release, every release that\n * publishes before it, then drafts, minus excluded layers.\n */\nexport function perspectiveStack({\n selected,\n releases,\n excluded = [],\n}: {\n selected: string | undefined\n releases: ReleaseDocument[]\n excluded?: string[]\n}): PreviewPerspective {\n if (!selected || selected === DRAFTS) return DRAFTS\n if (selected === PUBLISHED) return PUBLISHED\n const sorted = sortReleases(releases).map(releaseIdOf)\n const index = sorted.indexOf(selected)\n if (index === -1) return [selected, DRAFTS]\n return [...sorted.slice(index), DRAFTS].filter((name) => !excluded.includes(name))\n}\n\n/** Parses the cookie (`published`, `drafts`, or comma-separated IDs). Invalid values → drafts. */\nexport function parsePerspective(value: string | undefined): PreviewPerspective {\n if (!value || value === DRAFTS) return DRAFTS\n if (value === PUBLISHED) return PUBLISHED\n const stack = value.split(',')\n if (stack.length > 32 || stack.some((name) => RESERVED.includes(name))) return DRAFTS\n if (!stack.every((name) => name === DRAFTS || RELEASE_ID.test(name))) return DRAFTS\n return stack.length === 1 && stack[0] === DRAFTS ? DRAFTS : stack\n}\n\nexport function serializePerspective(perspective: PreviewPerspective) {\n return Array.isArray(perspective) ? perspective.join(',') : perspective\n}\n\n/**\n * Recovers the menu state from a stored stack: the first layer is the selection, and anything the\n * Studio would have stacked under it but is missing was hidden with the eye toggle.\n */\nexport function selectionOf(perspective: PreviewPerspective, releases: ReleaseDocument[]) {\n if (!Array.isArray(perspective)) return {selected: perspective, excluded: [] as string[]}\n const [selected = DRAFTS] = perspective\n const full = perspectiveStack({selected, releases})\n const excluded = Array.isArray(full) ? full.filter((name) => !perspective.includes(name)) : []\n return {selected, excluded}\n}\n\n/**\n * The Studio navbar's tone for a perspective (`RootCard tone={getReleaseTone(selectedPerspective)}`):\n * published is positive, drafts default, a release takes its type's tone.\n */\nexport function perspectiveTone(perspective: PreviewPerspective, releases: ReleaseDocument[]) {\n const {selected} = selectionOf(perspective, releases)\n if (selected === PUBLISHED) return 'positive'\n const release = releases.find((candidate) => releaseIdOf(candidate) === selected)\n return release ? releaseTone(release) : 'default'\n}\n\n/** `getReleaseTone` plus `RELEASE_TYPES_TONES`. */\nexport function releaseTone(release: ReleaseDocument) {\n if (release.state === 'archived') return 'default'\n switch (release.metadata.releaseType) {\n case 'asap':\n return 'caution'\n case 'scheduled':\n return 'suggest'\n default:\n return 'neutral'\n }\n}\n"],"mappings":";;;;;;;;;;AAWA,MAAa,qBAAqB,8BAErB,YAAY,aACZ,SAAS,UAqBT,iBAAiB,mOASxB,0BAA0B,CAAC,YAAY,WAAW,GAC3C,gBAA+B;CAAC;CAAQ;CAAa;AAAW,GAEvE,aAAa,yBAEb,WAAW;CAAC;CAAO;CAAW;AAAe;AAEnD,SAAgB,YAAY,SAA0B;CACpD,OAAO,QAAQ,IAAI,WAAW,aAAwB,IAClD,QAAQ,IAAI,MAAM,EAA+B,IACjD,QAAQ;AACd;;AAGA,SAAgB,aAAa,WAA8B,CAAC,GAAG;CAC7D,OAAO,CAAC,GAAG,QAAQ,CAAC,CAAC,MAAM,GAAG,MAAM;EAClC,IAAM,QAAQ,EAAE,SAAS,aACnB,QAAQ,EAAE,SAAS;EACzB,IAAI,UAAU,eAAe,UAAU,aAAa,OAAO;EAC3D,IAAI,UAAU,eAAe,UAAU,aAAa,OAAO;EAC3D,IAAI,UAAU,eAAe,UAAU,aACrC,OAAO,IAAI,KAAK,EAAE,UAAU,CAAC,CAAC,QAAQ,IAAI,IAAI,KAAK,EAAE,UAAU,CAAC,CAAC,QAAQ;EAE3E,IAAI,UAAU,eAAe,UAAU,aAAa;GAClD,IAAM,aAAa,EAAE,aAAa,EAAE,SAAS;GAC7C,IAAI,CAAC,YAAY,OAAO;GACxB,IAAM,aAAa,EAAE,aAAa,EAAE,SAAS;GAC7C,OAAO,aAAa,IAAI,KAAK,UAAU,CAAC,CAAC,QAAQ,IAAI,IAAI,KAAK,UAAU,CAAC,CAAC,QAAQ,IAAI;EACxF;EAMA,OALI,UAAU,UAAU,UAAU,SAAe,IAC7C,UAAU,UAAU,UAAU,SAAe,KAC7C,UAAU,UAAU,UAAU,SACzB,IAAI,KAAK,EAAE,UAAU,CAAC,CAAC,QAAQ,IAAI,IAAI,KAAK,EAAE,UAAU,CAAC,CAAC,QAAQ,IAEpE;CACT,CAAC;AACH;;AAGA,SAAgB,eAAe,UAA6B;CAC1D,OAAO,aACL,SAAS,QAAQ,YAAY,CAAC,wBAAwB,SAAS,QAAQ,KAAK,CAAC,CAC/E,CAAC,CAAC,QAAQ;AACZ;;AAGA,SAAgB,iBAAiB,SAA0B;CACzD,OAAO,QAAQ,SAAS,gBAAgB;AAC1C;;;;;AAMA,SAAgB,iBAAiB,EAC/B,UACA,UACA,WAAW,CAAC,KAKS;CACrB,IAAI,CAAC,YAAY,aAAA,UAAqB,OAAO;CAC7C,IAAI,aAAA,aAAwB,OAAO;CACnC,IAAM,SAAS,aAAa,QAAQ,CAAC,CAAC,IAAI,WAAW,GAC/C,QAAQ,OAAO,QAAQ,QAAQ;CAErC,OADI,UAAU,KAAW,CAAC,UAAU,MAAM,IACnC,CAAC,GAAG,OAAO,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,QAAQ,SAAS,CAAC,SAAS,SAAS,IAAI,CAAC;AACnF;;AAGA,SAAgB,iBAAiB,OAA+C;CAC9E,IAAI,CAAC,SAAS,UAAA,UAAkB,OAAO;CACvC,IAAI,UAAA,aAAqB,OAAO;CAChC,IAAM,QAAQ,MAAM,MAAM,GAAG;CAG7B,OAFI,MAAM,SAAS,MAAM,MAAM,MAAM,SAAS,SAAS,SAAS,IAAI,CAAC,KACjE,CAAC,MAAM,OAAO,SAAS,SAAA,YAAmB,WAAW,KAAK,IAAI,CAAC,KAC5D,MAAM,WAAW,KAAK,MAAM,OAAA,WAD0C,SACjB;AAC9D;AAEA,SAAgB,qBAAqB,aAAiC;CACpE,OAAO,MAAM,QAAQ,WAAW,IAAI,YAAY,KAAK,GAAG,IAAI;AAC9D;;;;;AAMA,SAAgB,YAAY,aAAiC,UAA6B;CACxF,IAAI,CAAC,MAAM,QAAQ,WAAW,GAAG,OAAO;EAAC,UAAU;EAAa,UAAU,CAAC;CAAa;CACxF,IAAM,CAAC,WAAW,UAAU,aACtB,OAAO,iBAAiB;EAAC;EAAU;CAAQ,CAAC;CAElD,OAAO;EAAC;EAAU,UADD,MAAM,QAAQ,IAAI,IAAI,KAAK,QAAQ,SAAS,CAAC,YAAY,SAAS,IAAI,CAAC,IAAI,CAAC;CACnE;AAC5B;;;;;AAMA,SAAgB,gBAAgB,aAAiC,UAA6B;CAC5F,IAAM,EAAC,aAAY,YAAY,aAAa,QAAQ;CACpD,IAAI,aAAA,aAAwB,OAAO;CACnC,IAAM,UAAU,SAAS,MAAM,cAAc,YAAY,SAAS,MAAM,QAAQ;CAChF,OAAO,UAAU,YAAY,OAAO,IAAI;AAC1C;;AAGA,SAAgB,YAAY,SAA0B;CACpD,IAAI,QAAQ,UAAU,YAAY,OAAO;CACzC,QAAQ,QAAQ,SAAS,aAAzB;EACE,KAAK,QACH,OAAO;EACT,KAAK,aACH,OAAO;EACT,SACE,OAAO;CACX;AACF"}
@@ -0,0 +1,119 @@
1
+ import { k as sameOriginPath } from "./protocol-BNO38gYy.js";
2
+ /**
3
+ * Short, expiring preview links (`/p/<code>`), like Shopify's "Share preview". The preview bar asks
4
+ * `/__visual-editor/share` for one while Presentation's "Share this preview" is on; opening it sets the
5
+ * preview cookies and redirects to the stored page. A `PreviewLinkStore` (Workers KV,
6
+ * or anything with a TTL) holds `code → { pathname, perspective, createdAt }`, so no secret ever
7
+ * appears in the URL. The store should expire the entry on its own; the server also checks
8
+ * `createdAt` against the TTL, so a store that keeps entries forever doesn't make links permanent.
9
+ */
10
+ /** Links open for 2 days, like Shopify's preview links. */
11
+ const PREVIEW_LINK_TTL_SECONDS = 172800, PREVIEW_LINK_ROUTE = "/p/", PREVIEW_LINK_KEY_PREFIX = "preview-link:", PREVIEW_LINK_CODE_LENGTH = 12, CODE_PATTERN = /* @__PURE__ */ RegExp("^[A-Za-z0-9]{12}$");
12
+ /**
13
+ * A random code from `crypto.getRandomValues`. Bytes ≥ 248 are dropped (248 = 4 × 62) so every
14
+ * character is equally likely.
15
+ */
16
+ function generatePreviewLinkCode(fillRandom = (array) => crypto.getRandomValues(array)) {
17
+ let code = "";
18
+ for (; code.length < 12;) {
19
+ let bytes = /* @__PURE__ */ new Uint8Array(24);
20
+ fillRandom(bytes);
21
+ for (let byte of bytes) if (!(byte >= 248) && (code += "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"[byte % 62], code.length === 12)) break;
22
+ }
23
+ return code;
24
+ }
25
+ /** Whether `value` could be a code we minted; anything else 404s without a KV read. */
26
+ function isPreviewLinkCode(value) {
27
+ return CODE_PATTERN.test(value);
28
+ }
29
+ function previewLinkKey(code) {
30
+ return `${PREVIEW_LINK_KEY_PREFIX}${code}`;
31
+ }
32
+ /**
33
+ * A root-relative path on this site, normalized (pathname and query, no hash), or `null`. Rejects
34
+ * protocol-relative `//host` and `/\host` (browsers read a backslash as a slash), absolute URLs,
35
+ * control characters and anything that resolves to another origin or to `//host`, before or after
36
+ * dot segments are removed (`/.//host`, `/%2e%2e//host`). See `sameOriginPath`.
37
+ */
38
+ function normalizePreviewPathname(value) {
39
+ if (typeof value != "string" || value.length === 0 || value.length > 2048) return null;
40
+ let path = sameOriginPath(value);
41
+ if (!path) return null;
42
+ let hash = path.indexOf("#");
43
+ return hash === -1 ? path : path.slice(0, hash);
44
+ }
45
+ /** The KV entry and put options for a new link, and when it stops opening. */
46
+ function createPreviewLink({ code, pathname, perspective, now = Date.now(), ttlSeconds = PREVIEW_LINK_TTL_SECONDS, route = "/p/" }) {
47
+ let value = {
48
+ pathname,
49
+ perspective,
50
+ createdAt: new Date(now).toISOString()
51
+ };
52
+ return {
53
+ key: previewLinkKey(code),
54
+ value,
55
+ ttlSeconds,
56
+ path: `${route}${code}`,
57
+ expiresAt: new Date(now + ttlSeconds * 1e3).toISOString()
58
+ };
59
+ }
60
+ /**
61
+ * When a stored link stops opening (ms since the epoch), from its `createdAt` and the TTL, or
62
+ * `null` when `createdAt` isn't a date.
63
+ */
64
+ function previewLinkExpiry(value, ttlSeconds) {
65
+ let createdAt = Date.parse(value.createdAt);
66
+ return Number.isFinite(createdAt) ? createdAt + ttlSeconds * 1e3 : null;
67
+ }
68
+ /** Reads a stored entry back, or `null` when it isn't one of ours (or its path no longer validates). */
69
+ function parsePreviewLinkValue(raw) {
70
+ if (!raw || typeof raw != "object") return null;
71
+ let { pathname, perspective, createdAt } = raw, safePathname = normalizePreviewPathname(pathname);
72
+ return !safePathname || typeof perspective != "string" || typeof createdAt != "string" ? null : {
73
+ pathname: safePathname,
74
+ perspective,
75
+ createdAt
76
+ };
77
+ }
78
+ /** The shortest link lifetime: Workers KV's minimum `expirationTtl`. */
79
+ const MIN_LINK_TTL_SECONDS = 60;
80
+ /**
81
+ * Returns `ttlSeconds` if it's a whole number of seconds, at least `MIN_LINK_TTL_SECONDS`;
82
+ * otherwise throws, so a bad `links.ttlSeconds` fails at startup rather than on every share.
83
+ */
84
+ function assertLinkTtl(ttlSeconds) {
85
+ if (!Number.isInteger(ttlSeconds) || ttlSeconds < 60) throw Error(`sanity-visual-editor: links.ttlSeconds must be a whole number of seconds, at least 60 (got ${String(ttlSeconds)})`);
86
+ return ttlSeconds;
87
+ }
88
+ /** A Cloudflare Workers KV store. KV's minimum TTL is 60 seconds. */
89
+ function kvStore(namespace) {
90
+ return {
91
+ async get(key) {
92
+ if (!namespace) throw Error("sanity-visual-editor: the KV namespace binding is missing");
93
+ return namespace.get(key, "json");
94
+ },
95
+ async put(key, value, ttlSeconds) {
96
+ if (!namespace) throw Error("sanity-visual-editor: the KV namespace binding is missing");
97
+ await namespace.put(key, JSON.stringify(value), { expirationTtl: assertLinkTtl(ttlSeconds) });
98
+ }
99
+ };
100
+ }
101
+ /** An in-memory store for tests and local experiments; entries vanish on restart. */
102
+ function memoryStore(now = Date.now) {
103
+ let entries = /* @__PURE__ */ new Map();
104
+ return {
105
+ async get(key) {
106
+ let entry = entries.get(key);
107
+ return entry ? entry.expiresAt <= now() ? (entries.delete(key), null) : entry.value : null;
108
+ },
109
+ async put(key, value, ttlSeconds) {
110
+ entries.set(key, {
111
+ value,
112
+ expiresAt: now() + ttlSeconds * 1e3
113
+ });
114
+ }
115
+ };
116
+ }
117
+ export { PREVIEW_LINK_TTL_SECONDS as a, generatePreviewLinkCode as c, memoryStore as d, normalizePreviewPathname as f, previewLinkKey as h, PREVIEW_LINK_ROUTE as i, isPreviewLinkCode as l, previewLinkExpiry as m, PREVIEW_LINK_CODE_LENGTH as n, assertLinkTtl as o, parsePreviewLinkValue as p, PREVIEW_LINK_KEY_PREFIX as r, createPreviewLink as s, MIN_LINK_TTL_SECONDS as t, kvStore as u };
118
+
119
+ //# sourceMappingURL=preview-links-BZDZyIey.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"preview-links-BZDZyIey.js","names":[],"sources":["../src/core/preview-links.ts"],"sourcesContent":["/**\n * Short, expiring preview links (`/p/<code>`), like Shopify's \"Share preview\". The preview bar asks\n * `/__visual-editor/share` for one while Presentation's \"Share this preview\" is on; opening it sets the\n * preview cookies and redirects to the stored page. A `PreviewLinkStore` (Workers KV,\n * or anything with a TTL) holds `code → { pathname, perspective, createdAt }`, so no secret ever\n * appears in the URL. The store should expire the entry on its own; the server also checks\n * `createdAt` against the TTL, so a store that keeps entries forever doesn't make links permanent.\n */\n\nimport {sameOriginPath} from './paths'\n\n/** Links open for 2 days, like Shopify's preview links. */\nexport const PREVIEW_LINK_TTL_SECONDS = 2 * 24 * 60 * 60\n\n/** Default route prefix for the short links; disallow it in `robots.txt`. */\nexport const PREVIEW_LINK_ROUTE = '/p/'\n\n/** KV key prefix, so the namespace can hold other kinds of entry later. */\nexport const PREVIEW_LINK_KEY_PREFIX = 'preview-link:'\n\n/** Base62: URL-safe, no punctuation at the ends of a link. 12 characters ≈ 71 bits. */\nconst ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'\nexport const PREVIEW_LINK_CODE_LENGTH = 12\nconst CODE_PATTERN = new RegExp(`^[A-Za-z0-9]{${PREVIEW_LINK_CODE_LENGTH}}$`)\n\n/** Longest page path (with query) a link may store. */\nconst MAX_PATHNAME_LENGTH = 2048\n\nexport type PreviewLinkValue = {\n /** Root-relative page path, with any query string. */\n pathname: string\n /** Serialized perspective, the `sanity-preview-perspective` cookie value. */\n perspective: string\n /** ISO timestamp. */\n createdAt: string\n}\n\n/**\n * A random code from `crypto.getRandomValues`. Bytes ≥ 248 are dropped (248 = 4 × 62) so every\n * character is equally likely.\n */\nexport function generatePreviewLinkCode(\n fillRandom: (array: Uint8Array<ArrayBuffer>) => void = (array) => crypto.getRandomValues(array),\n) {\n let code = ''\n while (code.length < PREVIEW_LINK_CODE_LENGTH) {\n const bytes = new Uint8Array(PREVIEW_LINK_CODE_LENGTH * 2)\n fillRandom(bytes)\n for (const byte of bytes) {\n if (byte >= 248) continue\n code += ALPHABET[byte % ALPHABET.length]\n if (code.length === PREVIEW_LINK_CODE_LENGTH) break\n }\n }\n return code\n}\n\n/** Whether `value` could be a code we minted; anything else 404s without a KV read. */\nexport function isPreviewLinkCode(value: string) {\n return CODE_PATTERN.test(value)\n}\n\nexport function previewLinkKey(code: string) {\n return `${PREVIEW_LINK_KEY_PREFIX}${code}`\n}\n\n/**\n * A root-relative path on this site, normalized (pathname and query, no hash), or `null`. Rejects\n * protocol-relative `//host` and `/\\host` (browsers read a backslash as a slash), absolute URLs,\n * control characters and anything that resolves to another origin or to `//host`, before or after\n * dot segments are removed (`/.//host`, `/%2e%2e//host`). See `sameOriginPath`.\n */\nexport function normalizePreviewPathname(value: unknown): string | null {\n if (typeof value !== 'string' || value.length === 0 || value.length > MAX_PATHNAME_LENGTH) {\n return null\n }\n const path = sameOriginPath(value)\n if (!path) return null\n // Neither a pathname nor a query can hold `#`, so the hash starts at the first one.\n const hash = path.indexOf('#')\n return hash === -1 ? path : path.slice(0, hash)\n}\n\n/** The KV entry and put options for a new link, and when it stops opening. */\nexport function createPreviewLink({\n code,\n pathname,\n perspective,\n now = Date.now(),\n ttlSeconds = PREVIEW_LINK_TTL_SECONDS,\n route = PREVIEW_LINK_ROUTE,\n}: {\n code: string\n pathname: string\n perspective: string\n now?: number\n ttlSeconds?: number\n route?: string\n}) {\n const value: PreviewLinkValue = {pathname, perspective, createdAt: new Date(now).toISOString()}\n return {\n key: previewLinkKey(code),\n value,\n ttlSeconds,\n path: `${route}${code}`,\n expiresAt: new Date(now + ttlSeconds * 1000).toISOString(),\n }\n}\n\n/**\n * When a stored link stops opening (ms since the epoch), from its `createdAt` and the TTL, or\n * `null` when `createdAt` isn't a date.\n */\nexport function previewLinkExpiry(value: Pick<PreviewLinkValue, 'createdAt'>, ttlSeconds: number) {\n const createdAt = Date.parse(value.createdAt)\n return Number.isFinite(createdAt) ? createdAt + ttlSeconds * 1000 : null\n}\n\n/** Reads a stored entry back, or `null` when it isn't one of ours (or its path no longer validates). */\nexport function parsePreviewLinkValue(raw: unknown): PreviewLinkValue | null {\n if (!raw || typeof raw !== 'object') return null\n const {pathname, perspective, createdAt} = raw as Record<string, unknown>\n const safePathname = normalizePreviewPathname(pathname)\n if (!safePathname || typeof perspective !== 'string' || typeof createdAt !== 'string') {\n return null\n }\n return {pathname: safePathname, perspective, createdAt}\n}\n\n/**\n * Where short links live. `get` returns the stored value (parsed JSON) or `null`; `put` stores it\n * for `ttlSeconds` and lets it expire on its own. See `kvStore` and `memoryStore`.\n */\nexport type PreviewLinkStore = {\n get(key: string): Promise<unknown>\n put(key: string, value: PreviewLinkValue, ttlSeconds: number): Promise<void>\n}\n\n/** The slice of a Cloudflare Workers KV namespace the store uses. */\nexport type KVNamespaceLike = {\n get(key: string, type: 'json'): Promise<unknown>\n put(key: string, value: string, options: {expirationTtl: number}): Promise<void>\n}\n\n/** The shortest link lifetime: Workers KV's minimum `expirationTtl`. */\nexport const MIN_LINK_TTL_SECONDS = 60\n\n/**\n * Returns `ttlSeconds` if it's a whole number of seconds, at least `MIN_LINK_TTL_SECONDS`;\n * otherwise throws, so a bad `links.ttlSeconds` fails at startup rather than on every share.\n */\nexport function assertLinkTtl(ttlSeconds: number): number {\n if (!Number.isInteger(ttlSeconds) || ttlSeconds < MIN_LINK_TTL_SECONDS) {\n throw new Error(\n `sanity-visual-editor: links.ttlSeconds must be a whole number of seconds, at least ${MIN_LINK_TTL_SECONDS} (got ${String(ttlSeconds)})`,\n )\n }\n return ttlSeconds\n}\n\n/** A Cloudflare Workers KV store. KV's minimum TTL is 60 seconds. */\nexport function kvStore(namespace: KVNamespaceLike | undefined | null): PreviewLinkStore {\n return {\n async get(key) {\n if (!namespace) throw new Error('sanity-visual-editor: the KV namespace binding is missing')\n return namespace.get(key, 'json')\n },\n async put(key, value, ttlSeconds) {\n if (!namespace) throw new Error('sanity-visual-editor: the KV namespace binding is missing')\n await namespace.put(key, JSON.stringify(value), {expirationTtl: assertLinkTtl(ttlSeconds)})\n },\n }\n}\n\n/** An in-memory store for tests and local experiments; entries vanish on restart. */\nexport function memoryStore(now: () => number = Date.now): PreviewLinkStore {\n const entries = new Map<string, {value: PreviewLinkValue; expiresAt: number}>()\n return {\n async get(key) {\n const entry = entries.get(key)\n if (!entry) return null\n if (entry.expiresAt <= now()) {\n entries.delete(key)\n return null\n }\n return entry.value\n },\n async put(key, value, ttlSeconds) {\n entries.set(key, {value, expiresAt: now() + ttlSeconds * 1000})\n },\n }\n}\n"],"mappings":";;;;;;;;;;AAYA,MAAa,2BAA2B,QAG3B,qBAAqB,OAGrB,0BAA0B,iBAI1B,2BAA2B,IAClC,eAAe,gBAAI,OAAO,mBAA4C;;;;;AAkB5E,SAAgB,wBACd,cAAwD,UAAU,OAAO,gBAAgB,KAAK,GAC9F;CACA,IAAI,OAAO;CACX,OAAO,KAAK,SAAA,KAAmC;EAC7C,IAAM,wBAAQ,IAAI,WAAW,EAA4B;EACzD,WAAW,KAAK;EAChB,KAAK,IAAM,QAAQ,OACjB,IAAI,UAAQ,SACZ,QAAQ,iEAAS,OAAO,KACpB,KAAK,WAAA,KAAqC;CAElD;CACA,OAAO;AACT;;AAGA,SAAgB,kBAAkB,OAAe;CAC/C,OAAO,aAAa,KAAK,KAAK;AAChC;AAEA,SAAgB,eAAe,MAAc;CAC3C,OAAO,GAAG,0BAA0B;AACtC;;;;;;;AAQA,SAAgB,yBAAyB,OAA+B;CACtE,IAAI,OAAO,SAAU,YAAY,MAAM,WAAW,KAAK,MAAM,SAAS,MACpE,OAAO;CAET,IAAM,OAAO,eAAe,KAAK;CACjC,IAAI,CAAC,MAAM,OAAO;CAElB,IAAM,OAAO,KAAK,QAAQ,GAAG;CAC7B,OAAO,SAAS,KAAK,OAAO,KAAK,MAAM,GAAG,IAAI;AAChD;;AAGA,SAAgB,kBAAkB,EAChC,MACA,UACA,aACA,MAAM,KAAK,IAAI,GACf,aAAa,0BACb,QAAA,SAQC;CACD,IAAM,QAA0B;EAAC;EAAU;EAAa,WAAW,IAAI,KAAK,GAAG,CAAC,CAAC,YAAY;CAAC;CAC9F,OAAO;EACL,KAAK,eAAe,IAAI;EACxB;EACA;EACA,MAAM,GAAG,QAAQ;EACjB,WAAW,IAAI,KAAK,MAAM,aAAa,GAAI,CAAC,CAAC,YAAY;CAC3D;AACF;;;;;AAMA,SAAgB,kBAAkB,OAA4C,YAAoB;CAChG,IAAM,YAAY,KAAK,MAAM,MAAM,SAAS;CAC5C,OAAO,OAAO,SAAS,SAAS,IAAI,YAAY,aAAa,MAAO;AACtE;;AAGA,SAAgB,sBAAsB,KAAuC;CAC3E,IAAI,CAAC,OAAO,OAAO,OAAQ,UAAU,OAAO;CAC5C,IAAM,EAAC,UAAU,aAAa,cAAa,KACrC,eAAe,yBAAyB,QAAQ;CAItD,OAHI,CAAC,gBAAgB,OAAO,eAAgB,YAAY,OAAO,aAAc,WACpE,OAEF;EAAC,UAAU;EAAc;EAAa;CAAS;AACxD;;AAkBA,MAAa,uBAAuB;;;;;AAMpC,SAAgB,cAAc,YAA4B;CACxD,IAAI,CAAC,OAAO,UAAU,UAAU,KAAK,aAAA,IACnC,MAAU,MACR,8FAAmH,OAAO,UAAU,EAAE,EACxI;CAEF,OAAO;AACT;;AAGA,SAAgB,QAAQ,WAAiE;CACvF,OAAO;EACL,MAAM,IAAI,KAAK;GACb,IAAI,CAAC,WAAW,MAAU,MAAM,2DAA2D;GAC3F,OAAO,UAAU,IAAI,KAAK,MAAM;EAClC;EACA,MAAM,IAAI,KAAK,OAAO,YAAY;GAChC,IAAI,CAAC,WAAW,MAAU,MAAM,2DAA2D;GAC3F,MAAM,UAAU,IAAI,KAAK,KAAK,UAAU,KAAK,GAAG,EAAC,eAAe,cAAc,UAAU,EAAC,CAAC;EAC5F;CACF;AACF;;AAGA,SAAgB,YAAY,MAAoB,KAAK,KAAuB;CAC1E,IAAM,0BAAU,IAAI,IAA0D;CAC9E,OAAO;EACL,MAAM,IAAI,KAAK;GACb,IAAM,QAAQ,QAAQ,IAAI,GAAG;GAM7B,OALK,QACD,MAAM,aAAa,IAAI,KACzB,QAAQ,OAAO,GAAG,GACX,QAEF,MAAM,QALM;EAMrB;EACA,MAAM,IAAI,KAAK,OAAO,YAAY;GAChC,QAAQ,IAAI,KAAK;IAAC;IAAO,WAAW,IAAI,IAAI,aAAa;GAAI,CAAC;EAChE;CACF;AACF"}
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Short, expiring preview links (`/p/<code>`), like Shopify's "Share preview". The preview bar asks
3
+ * `/__visual-editor/share` for one while Presentation's "Share this preview" is on; opening it sets the
4
+ * preview cookies and redirects to the stored page. A `PreviewLinkStore` (Workers KV,
5
+ * or anything with a TTL) holds `code → { pathname, perspective, createdAt }`, so no secret ever
6
+ * appears in the URL. The store should expire the entry on its own; the server also checks
7
+ * `createdAt` against the TTL, so a store that keeps entries forever doesn't make links permanent.
8
+ */
9
+ /** Links open for 2 days, like Shopify's preview links. */
10
+ declare const PREVIEW_LINK_TTL_SECONDS: number;
11
+ /** Default route prefix for the short links; disallow it in `robots.txt`. */
12
+ declare const PREVIEW_LINK_ROUTE = "/p/";
13
+ /** KV key prefix, so the namespace can hold other kinds of entry later. */
14
+ declare const PREVIEW_LINK_KEY_PREFIX = "preview-link:";
15
+ declare const PREVIEW_LINK_CODE_LENGTH = 12;
16
+ type PreviewLinkValue = {
17
+ /** Root-relative page path, with any query string. */
18
+ pathname: string;
19
+ /** Serialized perspective, the `sanity-preview-perspective` cookie value. */
20
+ perspective: string;
21
+ /** ISO timestamp. */
22
+ createdAt: string;
23
+ };
24
+ /**
25
+ * A random code from `crypto.getRandomValues`. Bytes ≥ 248 are dropped (248 = 4 × 62) so every
26
+ * character is equally likely.
27
+ */
28
+ declare function generatePreviewLinkCode(fillRandom?: (array: Uint8Array<ArrayBuffer>) => void): string;
29
+ /** Whether `value` could be a code we minted; anything else 404s without a KV read. */
30
+ declare function isPreviewLinkCode(value: string): boolean;
31
+ declare function previewLinkKey(code: string): string;
32
+ /**
33
+ * A root-relative path on this site, normalized (pathname and query, no hash), or `null`. Rejects
34
+ * protocol-relative `//host` and `/\host` (browsers read a backslash as a slash), absolute URLs,
35
+ * control characters and anything that resolves to another origin or to `//host`, before or after
36
+ * dot segments are removed (`/.//host`, `/%2e%2e//host`). See `sameOriginPath`.
37
+ */
38
+ declare function normalizePreviewPathname(value: unknown): string | null;
39
+ /** The KV entry and put options for a new link, and when it stops opening. */
40
+ declare function createPreviewLink({ code, pathname, perspective, now, ttlSeconds, route }: {
41
+ code: string;
42
+ pathname: string;
43
+ perspective: string;
44
+ now?: number;
45
+ ttlSeconds?: number;
46
+ route?: string;
47
+ }): {
48
+ key: string;
49
+ value: PreviewLinkValue;
50
+ ttlSeconds: number;
51
+ path: string;
52
+ expiresAt: string;
53
+ };
54
+ /**
55
+ * When a stored link stops opening (ms since the epoch), from its `createdAt` and the TTL, or
56
+ * `null` when `createdAt` isn't a date.
57
+ */
58
+ declare function previewLinkExpiry(value: Pick<PreviewLinkValue, 'createdAt'>, ttlSeconds: number): number | null;
59
+ /** Reads a stored entry back, or `null` when it isn't one of ours (or its path no longer validates). */
60
+ declare function parsePreviewLinkValue(raw: unknown): PreviewLinkValue | null;
61
+ /**
62
+ * Where short links live. `get` returns the stored value (parsed JSON) or `null`; `put` stores it
63
+ * for `ttlSeconds` and lets it expire on its own. See `kvStore` and `memoryStore`.
64
+ */
65
+ type PreviewLinkStore = {
66
+ get(key: string): Promise<unknown>;
67
+ put(key: string, value: PreviewLinkValue, ttlSeconds: number): Promise<void>;
68
+ };
69
+ /** The slice of a Cloudflare Workers KV namespace the store uses. */
70
+ type KVNamespaceLike = {
71
+ get(key: string, type: 'json'): Promise<unknown>;
72
+ put(key: string, value: string, options: {
73
+ expirationTtl: number;
74
+ }): Promise<void>;
75
+ };
76
+ /** The shortest link lifetime: Workers KV's minimum `expirationTtl`. */
77
+ declare const MIN_LINK_TTL_SECONDS = 60;
78
+ /**
79
+ * Returns `ttlSeconds` if it's a whole number of seconds, at least `MIN_LINK_TTL_SECONDS`;
80
+ * otherwise throws, so a bad `links.ttlSeconds` fails at startup rather than on every share.
81
+ */
82
+ declare function assertLinkTtl(ttlSeconds: number): number;
83
+ /** A Cloudflare Workers KV store. KV's minimum TTL is 60 seconds. */
84
+ declare function kvStore(namespace: KVNamespaceLike | undefined | null): PreviewLinkStore;
85
+ /** An in-memory store for tests and local experiments; entries vanish on restart. */
86
+ declare function memoryStore(now?: () => number): PreviewLinkStore;
87
+ export { previewLinkExpiry as _, PREVIEW_LINK_ROUTE as a, PreviewLinkValue as c, generatePreviewLinkCode as d, isPreviewLinkCode as f, parsePreviewLinkValue as g, normalizePreviewPathname as h, PREVIEW_LINK_KEY_PREFIX as i, assertLinkTtl as l, memoryStore as m, MIN_LINK_TTL_SECONDS as n, PREVIEW_LINK_TTL_SECONDS as o, kvStore as p, PREVIEW_LINK_CODE_LENGTH as r, PreviewLinkStore as s, KVNamespaceLike as t, createPreviewLink as u, previewLinkKey as v };
@@ -0,0 +1,280 @@
1
+ /**
2
+ * Same-origin path checks, shared by everything that turns an untrusted string into a page on this
3
+ * site: short links, `postMessage` paths and the Visual Editor's `?preview=` parameter.
4
+ */
5
+ const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/, BASE = "https://same-origin.invalid";
6
+ /**
7
+ * `value` as a root-relative path on this site (pathname, query and hash, normalized), or `null`.
8
+ *
9
+ * Checks the input and the result: browsers read `\` as `/` and drop tabs and newlines, and
10
+ * resolving dot segments can turn `/.//host` or `/%2e%2e//host` into `//host`, which is another
11
+ * site once it lands in a `Location` header or `new URL(path, origin)`. A path whose first segment
12
+ * starts with an encoded slash or backslash (`/%2f…`, `/%5c…`) is refused too, since a server that
13
+ * decodes it before redirecting would do the same.
14
+ */
15
+ function sameOriginPath(value) {
16
+ if (typeof value != "string" || !value.startsWith("/") || value.startsWith("//") || value.includes("\\") || CONTROL_CHARACTERS.test(value)) return null;
17
+ let url;
18
+ try {
19
+ url = new URL(value, BASE);
20
+ } catch {
21
+ return null;
22
+ }
23
+ if (url.origin !== BASE) return null;
24
+ let { pathname } = url;
25
+ return !pathname.startsWith("/") || pathname.startsWith("//") || pathname.includes("\\") || /^\/%(2f|5c)/i.test(pathname) ? null : `${pathname}${url.search}${url.hash}`;
26
+ }
27
+ /** Whether `value` is a root-relative path that stays on this site; see `sameOriginPath`. */
28
+ function isSameOriginPath(value) {
29
+ return sameOriginPath(value) !== null;
30
+ }
31
+ /**
32
+ * The `data-sanity` attribute that marks an element as editable, and its path, without
33
+ * dependencies. Storefronts write it with `createDataAttribute({id, type, path})` or by hand:
34
+ *
35
+ * data-sanity="id=page-home;type=page;path=sections:k1.heading"
36
+ *
37
+ * `base=` and `workspace=` may follow; they're read but unused. `path` is Sanity's URL path form:
38
+ * `.` between segments, `field:key` for a keyed array item, and `field:3` (up to 9 digits) for an
39
+ * index, so `sections:k1.heading` is `sections[_key=="k1"].heading`.
40
+ */
41
+ const SANITY_NODE_ATTRIBUTE = "data-sanity", MAX_EDIT_PATH_LENGTH = 1e3, INDEX = /^\d{1,9}$/;
42
+ function decode(value) {
43
+ try {
44
+ return decodeURIComponent(value);
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
49
+ /**
50
+ * Reads a `data-sanity` value: pairs split on `;`, each on its first `=`, values URI-decoded.
51
+ * Returns `null` unless `id`, `type` and `path` are all present and non-empty.
52
+ */
53
+ function parseSanityNode(value) {
54
+ if (!value) return null;
55
+ let fields = {};
56
+ for (let pair of value.split(";")) {
57
+ let separator = pair.indexOf("=");
58
+ if (separator < 0) continue;
59
+ let key = pair.slice(0, separator).trim(), decoded = decode(pair.slice(separator + 1));
60
+ key && decoded !== null && (fields[key] = decoded);
61
+ }
62
+ let { id, type, path, base, workspace } = fields;
63
+ if (!id || !type || !path || path.length > 1e3) return null;
64
+ let node = {
65
+ id,
66
+ type,
67
+ path
68
+ };
69
+ return base && (node.base = base), workspace && (node.workspace = workspace), node;
70
+ }
71
+ /**
72
+ * Sanity's URL path form to a Studio path: `sections:k1.heading` →
73
+ * `['sections', {_key: 'k1'}, 'heading']`, `items:3` → `['items', 3]`. Chained items
74
+ * (`rows:r1:c2`) are nested arrays. Returns `null` for an empty or malformed path.
75
+ */
76
+ function toStudioPath(urlPath) {
77
+ if (!urlPath) return null;
78
+ let path = [];
79
+ for (let segment of urlPath.split(".")) {
80
+ let [field, ...items] = segment.split(":");
81
+ if (!field) return null;
82
+ path.push(field);
83
+ for (let item of items) {
84
+ if (!item) return null;
85
+ path.push(INDEX.test(item) ? Number(item) : { _key: item });
86
+ }
87
+ }
88
+ return path;
89
+ }
90
+ /**
91
+ * A Studio path as the document pane's `path` param reads it (`@sanity/util/paths` `toString`):
92
+ * `sections[_key=="k1"].heading`, `items[3]`.
93
+ */
94
+ function studioPathToString(path) {
95
+ let result = "";
96
+ for (let segment of path) result += typeof segment == "string" ? result ? `.${segment}` : segment : typeof segment == "number" ? `[${segment}]` : `[_key=="${segment._key}"]`;
97
+ return result;
98
+ }
99
+ /** The pane param for a URL-form path, or `null` when it doesn't parse. */
100
+ function toPanePath(urlPath) {
101
+ let path = toStudioPath(urlPath);
102
+ return path ? studioPathToString(path) : null;
103
+ }
104
+ /** `heroImage` → `Hero image`, `section_title` → `Section title`. */
105
+ function humanizeFieldName(name) {
106
+ let words = name.replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").split(/[\s_-]+/).filter(Boolean);
107
+ return words.length ? words.map((word, index) => {
108
+ if (word.length > 1 && word === word.toUpperCase()) return word;
109
+ let lower = word.toLowerCase();
110
+ return index === 0 ? lower.charAt(0).toUpperCase() + lower.slice(1) : lower;
111
+ }).join(" ") : name;
112
+ }
113
+ /**
114
+ * A label for a path's last segment: the field's name, humanized (`sections:k1.heading` →
115
+ * `Heading`), or `Sections item` when it ends in an array item.
116
+ */
117
+ function describeSanityPath(urlPath) {
118
+ let path = toStudioPath(urlPath);
119
+ if (!path?.length) return urlPath;
120
+ let last = path[path.length - 1];
121
+ if (typeof last == "string") return humanizeFieldName(last);
122
+ for (let index = path.length - 1; index >= 0; index--) {
123
+ let segment = path[index];
124
+ if (typeof segment == "string") return `${humanizeFieldName(segment)} item`;
125
+ }
126
+ return urlPath;
127
+ }
128
+ /** A document's published ID (`drafts.` and `versions.<release>.` prefixes removed). */
129
+ function publishedDocumentId(id) {
130
+ return id.replace(/^drafts\./, "").replace(/^versions\.[^.]+\./, "");
131
+ }
132
+ /** A Studio path in Sanity's URL form: `['sections', {_key: 'k1'}, 'heading']` → `sections:k1.heading`. */
133
+ function toUrlPath(path) {
134
+ let result = "";
135
+ for (let segment of path) result += typeof segment == "string" ? result ? `.${segment}` : segment : `:${typeof segment == "number" ? segment : segment._key}`;
136
+ return result;
137
+ }
138
+ /** Formats a `SanityNode` into a `data-sanity` attribute value (`id=...;type=...;path=...`). */
139
+ function encodeSanityNode(node) {
140
+ let parts = [
141
+ `id=${encodeURIComponent(publishedDocumentId(node.id))}`,
142
+ `type=${encodeURIComponent(node.type)}`,
143
+ `path=${encodeURIComponent(node.path)}`
144
+ ];
145
+ return node.base && parts.push(`base=${encodeURIComponent(node.base)}`), node.workspace && parts.push(`workspace=${encodeURIComponent(node.workspace)}`), parts.join(";");
146
+ }
147
+ /**
148
+ * Returns `{ 'data-sanity': '...' }` for click-to-edit overlays, or `{}` when `enabled` is `false`
149
+ * or `doc`/`path` is incomplete. Spread directly onto any Svelte or JSX element:
150
+ *
151
+ * <h1 {...sanityAttr(page, 'heading', { enabled: preview })}>
152
+ * <section {...sanityAttr(page, ['sections', { _key: section._key }, 'title'])}>
153
+ */
154
+ function sanityAttr(doc, path, options) {
155
+ if (options?.enabled === !1 || !doc) return {};
156
+ let id = "_id" in doc ? doc._id : "id" in doc ? doc.id : void 0, type = "_type" in doc ? doc._type : "type" in doc ? doc.type : void 0, urlPath = typeof path == "string" ? path : toUrlPath(path);
157
+ return !id || !type || !urlPath || urlPath.length > 1e3 ? {} : { [SANITY_NODE_ATTRIBUTE]: encodeSanityNode({
158
+ id,
159
+ type,
160
+ path: urlPath,
161
+ ...options?.base ? { base: options.base } : {},
162
+ ...options?.workspace ? { workspace: options.workspace } : {}
163
+ }) };
164
+ }
165
+ /**
166
+ * Scoped `sanityAttr` bound to one document and option set:
167
+ *
168
+ * const attr = createSanityAttr(page, { enabled: preview })
169
+ * <h1 {...attr('heading')}>
170
+ */
171
+ function createSanityAttr(doc, options) {
172
+ return (path) => sanityAttr(doc, path, options);
173
+ }
174
+ function sameSegment(a, b) {
175
+ return typeof a == "string" || typeof a == "number" ? a === b : typeof b == "object" && a._key === b._key;
176
+ }
177
+ /**
178
+ * The nodes that show a focused field: those of the same document whose path is the longest
179
+ * prefix of the focused path (the field itself, or the nearest annotated element around it).
180
+ * A field can render more than once (a desktop and a mobile variant), so all of them match.
181
+ */
182
+ function matchFocusedNodes(items, focus) {
183
+ let focused = toStudioPath(focus.path);
184
+ if (!focused) return [];
185
+ let id = publishedDocumentId(focus.id), best = 0, matches = [];
186
+ for (let item of items) {
187
+ if (publishedDocumentId(item.node.id) !== id) continue;
188
+ let path = toStudioPath(item.node.path);
189
+ !path || path.length > focused.length || path.length < best || path.every((segment, index) => sameSegment(segment, focused[index])) && (path.length > best && (best = path.length, matches = []), matches.push(item));
190
+ }
191
+ return matches;
192
+ }
193
+ /** Most nodes one `describe` or `labels` message carries. */
194
+ const MAX_DESCRIBE_NODES = 500, PREVIEW_BAR_ROUTE = "/__visual-editor", STUDIO_PREVIEW_PARAM = "studio-preview", PREVIEW_BAR_HEIGHT = 50, PREVIEW_PANEL_MIN_PAGE_WIDTH = 360, PREVIEW_BAR_POSITION_PARAM = "position";
195
+ function readPreviewBarPosition(search) {
196
+ return new URLSearchParams(search).get("position") === "top" ? "top" : "bottom";
197
+ }
198
+ const PREVIEW_BAR_CONTEXT_PARAM = "context";
199
+ function readPreviewBarContext(search) {
200
+ return new URLSearchParams(search).get("context") === "tool" ? "tool" : "site";
201
+ }
202
+ /**
203
+ * The Visual Editor tool frames the site under this window name. It survives navigation inside
204
+ * the frame, so the site can tell it's in the tool (not another embed) on every page.
205
+ */
206
+ const PREVIEW_BAR_FRAME_NAME = "sanity-plugin-visual-editor-frame";
207
+ /**
208
+ * Whether this window is the site framed by the Visual Editor tool, where the page reads like a
209
+ * normal preview tab and mounts `mountPreviewBarFrame` instead of the host.
210
+ */
211
+ function isPreviewBarFrame() {
212
+ return typeof window < "u" && window.self !== window.top && window.name === "sanity-plugin-visual-editor-frame";
213
+ }
214
+ /** ⌘⇧I / Ctrl+Shift+I: the inspector's shortcut, in the bar and on the framed page. */
215
+ function isInspectorShortcut(event) {
216
+ return (event.key.toLowerCase() === "i" || event.code === "KeyI") && (event.metaKey || event.ctrlKey) && event.shiftKey && !event.altKey && !event.repeat;
217
+ }
218
+ function isPreviewBarMessage(data) {
219
+ if (typeof data != "object" || !data || !("type" in data)) return !1;
220
+ switch (data.type) {
221
+ case "sanity-visual-editor:ready":
222
+ case "sanity-visual-editor:hide":
223
+ case "sanity-visual-editor:refresh":
224
+ case "sanity-visual-editor:refreshed":
225
+ case "sanity-visual-editor:search":
226
+ case "sanity-visual-editor:pane":
227
+ case "sanity-visual-editor:studio-home":
228
+ case "sanity-visual-editor:open-editor":
229
+ case "sanity-visual-editor:close-editor":
230
+ case "sanity-visual-editor:toggle-inspector": return !0;
231
+ case "sanity-visual-editor:inspector": return "active" in data && typeof data.active == "boolean";
232
+ case "sanity-visual-editor:navigate": return "href" in data && isRootRelative(data.href);
233
+ case "sanity-visual-editor:menu": return "open" in data && typeof data.open == "boolean";
234
+ case "sanity-visual-editor:panel": return "open" in data && typeof data.open == "boolean" && "width" in data && typeof data.width == "number" && Number.isFinite(data.width) && data.width >= 0 && "side" in data && (data.side === "left" || data.side === "right");
235
+ case "sanity-visual-editor:path":
236
+ case "sanity-visual-editor:frame-path": return "path" in data && isRootRelative(data.path);
237
+ case "sanity-visual-editor:page-document": return "document" in data && (data.document === null || typeof data.document == "object" && typeof data.document.id == "string" && typeof data.document.type == "string");
238
+ case "sanity-visual-editor:open-document": return "document" in data && isDocument(data.document);
239
+ case "sanity-visual-editor:editor-state": return "open" in data && typeof data.open == "boolean" && (!("available" in data) || data.available === void 0 || typeof data.available == "boolean") && (!("toggle" in data) || data.toggle === void 0 || typeof data.toggle == "boolean");
240
+ case "sanity-visual-editor:viewport": return "mode" in data && (data.mode === "desktop" || data.mode === "tablet" || data.mode === "mobile");
241
+ case "sanity-visual-editor:perspective":
242
+ case "sanity-visual-editor:set-perspective": return "selection" in data && isSelection(data.selection);
243
+ case "sanity-visual-editor:edit": return "id" in data && isNonEmptyString(data.id) && "documentType" in data && isNonEmptyString(data.documentType) && "path" in data && isNonEmptyString(data.path) && data.path.length <= 1e3;
244
+ case "sanity-visual-editor:focus": return "id" in data && typeof data.id == "string" && "path" in data && typeof data.path == "string" && data.path.length <= 1e3;
245
+ case "sanity-visual-editor:describe": return "nodes" in data && Array.isArray(data.nodes) && data.nodes.length <= 500 && data.nodes.every(isNode);
246
+ case "sanity-visual-editor:labels": return "labels" in data && Array.isArray(data.labels) && data.labels.length <= 500 && data.labels.every(isLabel);
247
+ case "sanity-visual-editor:live-status": return "status" in data && (data.status === "connected" || data.status === "polling" || data.status === "offline");
248
+ default: return !1;
249
+ }
250
+ }
251
+ function isNode(value) {
252
+ if (typeof value != "object" || !value) return !1;
253
+ let node = value;
254
+ return isNonEmptyString(node.id) && isNonEmptyString(node.type) && isNonEmptyString(node.path) && node.path.length <= 1e3;
255
+ }
256
+ function isLabel(value) {
257
+ if (typeof value != "object" || !value) return !1;
258
+ let label = value;
259
+ return isNonEmptyString(label.id) && isNonEmptyString(label.path) && label.path.length <= 1e3 && typeof label.label == "string" && label.label.length <= 200 && (label.missing === void 0 || typeof label.missing == "boolean");
260
+ }
261
+ function isDocument(value) {
262
+ if (typeof value != "object" || !value) return !1;
263
+ let doc = value;
264
+ return typeof doc.id == "string" && doc.id.length > 0 && typeof doc.type == "string" && doc.type.length > 0 && (doc.template === void 0 || typeof doc.template == "string") && (doc.templateParameters === void 0 || typeof doc.templateParameters == "object" && doc.templateParameters !== null);
265
+ }
266
+ function isSelection(value) {
267
+ if (typeof value != "object" || !value) return !1;
268
+ let selection = value;
269
+ return typeof selection.selected == "string" && Array.isArray(selection.excluded) && selection.excluded.every((id) => typeof id == "string");
270
+ }
271
+ function isNonEmptyString(value) {
272
+ return typeof value == "string" && value.length > 0;
273
+ }
274
+ /** Same-site paths only: the bar builds links from them and the host navigates to them. */
275
+ function isRootRelative(value) {
276
+ return isSameOriginPath(value);
277
+ }
278
+ export { sanityAttr as C, toUrlPath as D, toStudioPath as E, isSameOriginPath as O, publishedDocumentId as S, toPanePath as T, describeSanityPath as _, PREVIEW_BAR_POSITION_PARAM as a, matchFocusedNodes as b, STUDIO_PREVIEW_PARAM as c, isPreviewBarMessage as d, readPreviewBarContext as f, createSanityAttr as g, SANITY_NODE_ATTRIBUTE as h, PREVIEW_BAR_HEIGHT as i, sameOriginPath as k, isInspectorShortcut as l, MAX_EDIT_PATH_LENGTH as m, PREVIEW_BAR_CONTEXT_PARAM as n, PREVIEW_BAR_ROUTE as o, readPreviewBarPosition as p, PREVIEW_BAR_FRAME_NAME as r, PREVIEW_PANEL_MIN_PAGE_WIDTH as s, MAX_DESCRIBE_NODES as t, isPreviewBarFrame as u, encodeSanityNode as v, studioPathToString as w, parseSanityNode as x, humanizeFieldName as y };
279
+
280
+ //# sourceMappingURL=protocol-BNO38gYy.js.map