@websline/cms-view-utils 1.0.5 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@websline/cms-view-utils",
3
- "version": "1.0.5",
3
+ "version": "1.1.0",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "src",
@@ -16,17 +16,18 @@
16
16
  "./dist/*": "./dist/*"
17
17
  },
18
18
  "dependencies": {
19
- "jsonwebtoken": "^9.0.3"
19
+ "jsonwebtoken": "^9.0.3",
20
+ "tailwind-merge": "^3.6.0"
20
21
  },
21
22
  "devDependencies": {
22
- "@eslint/compat": "^2.0.5",
23
+ "@eslint/compat": "^2.1.0",
23
24
  "@eslint/js": "^10.0.1",
24
- "eslint": "^10.3.0",
25
+ "eslint": "^10.4.0",
25
26
  "eslint-config-prettier": "^10.1.8",
26
27
  "eslint-plugin-svelte": "^3.17.1",
27
28
  "globals": "^17.6.0",
28
29
  "prettier": "^3.8.3",
29
- "prettier-plugin-svelte": "^3.5.1",
30
+ "prettier-plugin-svelte": "^3.5.2",
30
31
  "prettier-plugin-tailwindcss": "^0.8.0",
31
32
  "tsup": "^8.5.1"
32
33
  },
@@ -1,4 +1,5 @@
1
1
  <script>
2
+ import { twMerge as tw } from "tailwind-merge";
2
3
  import { EVENTS, notifyCMS } from "../utils/notify.js";
3
4
 
4
5
  let {
@@ -52,7 +53,10 @@
52
53
 
53
54
  <div>
54
55
  <button
55
- class={`group relative flex min-h-32 w-full cursor-pointer items-center justify-center rounded-lg transition-all duration-300 ${className}`}
56
+ class={tw(
57
+ "group relative flex min-h-32 w-full cursor-pointer items-center justify-center rounded-lg transition-all duration-300",
58
+ className,
59
+ )}
56
60
  style={`--block-color: ${color}; --block-hover-color: ${hoverColor}; --block-hover-border-color: ${hoverBorderColor}; --block-text: ${textColor}; --block-icon-background: ${iconBackgroundColor}; --block-icon-color: ${iconColor}; --sublabel-color: ${sublabelColor};`}
57
61
  onclick={handleClick}>
58
62
  <div
@@ -1,4 +1,6 @@
1
1
  <script>
2
+ import { twMerge as tw } from "tailwind-merge";
3
+
2
4
  let { block, children, spacingValues = {} } = $props();
3
5
 
4
6
  const defaultSpacingValues = {
@@ -32,13 +34,6 @@
32
34
  let spacingBottom = $derived(block?.meta?.spacing?.bottom);
33
35
  let spacingTop = $derived(block?.meta?.spacing?.top);
34
36
 
35
- let spacingClass = $derived(
36
- [
37
- spacingMap.top[spacingTop] ?? spacingMap.top.none,
38
- spacingMap.bottom[spacingBottom] ?? spacingMap.bottom.none,
39
- ].join(" "),
40
- );
41
-
42
37
  let backgroundColor = $derived(block?.meta?.background);
43
38
 
44
39
  let style = $derived(
@@ -46,6 +41,12 @@
46
41
  );
47
42
  </script>
48
43
 
49
- <div data-cms-block-wrapper class={`${spacingClass}`} {style}>
44
+ <div
45
+ data-cms-block-wrapper
46
+ class={tw(
47
+ spacingMap.top[spacingTop] ?? spacingMap.top.none,
48
+ spacingMap.bottom[spacingBottom] ?? spacingMap.bottom.none,
49
+ )}
50
+ {style}>
50
51
  {@render children?.()}
51
52
  </div>
@@ -1,5 +1,4 @@
1
1
  <script>
2
- import { onMount } from "svelte";
3
2
  import { EVENTS, notifyCMS } from "../utils/notify.js";
4
3
  import { CMS_ACTIONS } from "../utils/cmsActions.js";
5
4
  import Text from "./skeleton/Text.svelte";
@@ -19,6 +18,7 @@
19
18
  } = $props();
20
19
 
21
20
  let calcBarPosition = $derived.by(() => {
21
+ if (isSticky) return "inside";
22
22
  if (typeof barPosition === "string") return barPosition;
23
23
  if (position === 0) return "inside";
24
24
 
@@ -84,8 +84,20 @@
84
84
  let isActive = $state(false);
85
85
  let skeleton = $derived(block?.meta?.emptyOptions?.skeleton || "text");
86
86
 
87
+ let ref = $state();
88
+ let isSticky = $state(false);
87
89
  let toolbarVisible = $derived(isHovered || isActive);
88
90
 
91
+ const handleScroll = () => {
92
+ if (!toolbarVisible || !ref) {
93
+ isSticky = false;
94
+ return;
95
+ }
96
+
97
+ const { top, bottom } = ref.getBoundingClientRect();
98
+ isSticky = bottom >= 40 && ((top < 0 && "full") || (top < 40 && "pre")); // 40 is the height of the toolbar
99
+ };
100
+
89
101
  let activeTooltip = $state(null);
90
102
  let tooltipLeaveTimer;
91
103
 
@@ -118,21 +130,14 @@
118
130
  isActive = draftBlockUuid === block.uuid;
119
131
  };
120
132
 
121
- onMount(() => {
122
- window.addEventListener("message", handler);
133
+ let isOutside = $derived(calcBarPosition === "outside");
123
134
 
124
- return () => {
125
- window.removeEventListener("message", handler);
126
- };
135
+ let containerShape = $derived.by(() => {
136
+ if (isOutside) return "absolute rounded-t-lg -top-8";
137
+ return `rounded-b-lg top-1.5 ${isSticky === "full" ? "fixed" : "absolute"}`;
127
138
  });
128
139
 
129
- const isOutside = $derived(calcBarPosition === "outside");
130
-
131
- const containerShape = $derived(
132
- isOutside ? "rounded-t-lg -top-8" : "rounded-b-lg top-1.5",
133
- );
134
-
135
- const cornerEdges = $derived(
140
+ let cornerEdges = $derived(
136
141
  isOutside
137
142
  ? "before:bottom-1 before:-left-4 before:shadow-[6px_6px_0_0_var(--block-color)] " +
138
143
  "after:bottom-1 after:-right-4 after:shadow-[-6px_6px_0_0_var(--block-color)]"
@@ -141,7 +146,7 @@
141
146
  );
142
147
 
143
148
  let tooltipClasses = $derived(
144
- `tooltip absolute ${position === 0 ? "-top-9" : "-top-7.5"} bg-[var(--block-color)] leading-none text-xs p-1.5 rounded-tl rounded-tr left-0 whitespace-nowrap transition-opacity duration-150`,
149
+ `tooltip absolute ${isOutside ? "-top-8" : "top-8"} bg-[var(--block-color)] leading-none text-xs p-1.5 rounded left-1/2 -translate-x-1/2 whitespace-nowrap transition-opacity duration-150`,
145
150
  );
146
151
 
147
152
  const labels = {
@@ -170,7 +175,10 @@
170
175
  let t = $derived(labels[locale] ?? labels.de);
171
176
  </script>
172
177
 
178
+ <svelte:window onmessage={handler} onscroll={handleScroll} />
179
+
173
180
  <div
181
+ bind:this={ref}
174
182
  class="relative min-h-13"
175
183
  style={`--block-color: ${color}; --block-text: ${textColor};`}
176
184
  data-cms-block-id={block.uuid}
@@ -187,9 +195,17 @@
187
195
  class:opacity-100={toolbarVisible}
188
196
  class:opacity-0={!toolbarVisible}>
189
197
  </div>
198
+ {#if isSticky === "full"}
199
+ <div
200
+ class="pointer-events-none fixed inset-x-0 top-0 z-9998 h-1.5 transition-opacity duration-100"
201
+ style="background-color: var(--block-color)"
202
+ class:opacity-100={toolbarVisible}
203
+ class:opacity-0={!toolbarVisible}>
204
+ </div>
205
+ {/if}
190
206
 
191
207
  <div
192
- class="absolute left-1/2 z-9999 flex h-9 -translate-x-1/2 items-center justify-center gap-1.5 px-3 transition-opacity duration-100 before:absolute before:h-4 before:w-4 before:rounded-full before:bg-transparent before:content-[''] after:absolute after:h-4 after:w-4 after:rounded-full after:bg-transparent after:content-[''] {containerShape} {cornerEdges}"
208
+ class="left-1/2 z-9999 flex h-9 -translate-x-1/2 items-center justify-center gap-1.5 px-3 transition-opacity duration-100 before:absolute before:h-4 before:w-4 before:rounded-full before:bg-transparent before:content-[''] after:absolute after:h-4 after:w-4 after:rounded-full after:bg-transparent after:content-[''] {containerShape} {cornerEdges}"
193
209
  style="background: var(--block-color); color: var(--block-text);"
194
210
  class:opacity-100={toolbarVisible}
195
211
  class:opacity-0={!toolbarVisible}>
@@ -1,9 +1,9 @@
1
1
  <script>
2
+ import { twMerge as tw } from "tailwind-merge";
3
+
2
4
  let { children, class: className } = $props();
3
5
  </script>
4
6
 
5
- <section
6
- class={`grid grid-cols-1${className ? ` ${className}` : ""}`}
7
- data-cms-page-content>
7
+ <section class={tw("grid grid-cols-1", className)} data-cms-page-content>
8
8
  {@render children?.()}
9
9
  </section>
@@ -1,4 +1,6 @@
1
1
  <script>
2
+ import { twMerge as tw } from "tailwind-merge";
3
+
2
4
  let {
3
5
  class: className,
4
6
  decoding = "async",
@@ -82,6 +84,6 @@
82
84
  height={data.fallbackFormat.height}
83
85
  {loading}
84
86
  {decoding}
85
- class={`h-full w-full object-cover${className ? ` ${className}` : ""}`} />
87
+ class={tw("h-full w-full object-cover", className)} />
86
88
  </picture>
87
89
  {/if}
@@ -0,0 +1,112 @@
1
+ ---
2
+ /**
3
+ * SEO Meta Tags component
4
+ *
5
+ * Reads meta data from Astro.locals.seo and renders the corresponding
6
+ * HTML tags in the <head>.
7
+ *
8
+ * Overrides via props:
9
+ * - title: replaces the title completely
10
+ * - titleTransform: function that transforms the title (e.g. append suffix)
11
+ * - description: replaces the description completely
12
+ * - canonical: replaces the canonical URL completely
13
+ * - image: replaces the image completely (null = explicitly no image)
14
+ * - noIndex: overrides noIndex
15
+ * - noFollow: overrides noFollow
16
+ *
17
+ * Title logic (in this order):
18
+ * 1. If title prop is set → use it
19
+ * 2. Otherwise: use seo.title from Astro.locals
20
+ * 3. If titleTransform is set → apply it to the result
21
+ *
22
+ * Examples:
23
+ * <SeoTags /> → seo.title
24
+ * <SeoTags title="Custom Title" /> → "Custom Title"
25
+ * <SeoTags titleTransform={(t) => `${t} | My Hotel`} /> → "{seo.title} | My Hotel"
26
+ * <SeoTags title="Custom" titleTransform={(t) => `${t} | My Hotel`} />
27
+ * → "Custom | My Hotel"
28
+ *
29
+ * Important: In preview mode, robots is always forced to noindex, nofollow
30
+ * regardless of the page's robots settings. This prevents unpublished drafts
31
+ * from being indexed by search engines.
32
+ */
33
+
34
+ const isPreview = Astro.locals._preview ?? false;
35
+
36
+ const {
37
+ title: titleOverride,
38
+ titleTransform,
39
+ type: typeOverride,
40
+ description: descriptionOverride,
41
+ canonical: canonicalOverride,
42
+ image: imageOverride,
43
+ noIndex: noIndexOverride,
44
+ noFollow: noFollowOverride,
45
+ } = Astro.props;
46
+
47
+ const {
48
+ meta: {
49
+ canonical: seoCanonical,
50
+ description: seoDescription,
51
+ image: seoImage,
52
+ noIndex: seoNoIndex,
53
+ noFollow: seoNoFollow,
54
+ title: seoTitle,
55
+ } = {},
56
+ } = Astro.locals.seo || {};
57
+
58
+ // Title: override takes precedence over SEO value, then optionally apply transform
59
+ const baseTitle = titleOverride ?? seoTitle;
60
+ const finalTitle =
61
+ titleTransform && baseTitle ? titleTransform(baseTitle) : baseTitle;
62
+
63
+ // Other fields: override takes precedence over SEO value
64
+ const finalDescription = descriptionOverride ?? seoDescription;
65
+ const finalCanonical = canonicalOverride ?? seoCanonical;
66
+
67
+ // For image, use explicit undefined check so null can mean "explicitly no image"
68
+ const finalImage = imageOverride !== undefined ? imageOverride : seoImage;
69
+
70
+ // In preview mode, force noindex/nofollow regardless of page settings
71
+ // to prevent unpublished drafts from being indexed
72
+ const finalNoIndex = isPreview ? true : (noIndexOverride ?? seoNoIndex ?? false);
73
+ const finalNoFollow = isPreview ? true : (noFollowOverride ?? seoNoFollow ?? false);
74
+
75
+ // Build robots string only if at least one directive is active
76
+ const robotsDirectives = [];
77
+ if (finalNoIndex) robotsDirectives.push("noindex");
78
+ if (finalNoFollow) robotsDirectives.push("nofollow");
79
+ const robotsContent =
80
+ robotsDirectives.length > 0 ? robotsDirectives.join(", ") : null;
81
+
82
+ const finalType = typeOverride ?? "website";
83
+
84
+ // OG fallbacks (same as meta by default, can be extended via overrides later)
85
+ const ogTitle = finalTitle;
86
+ const ogDescription = finalDescription;
87
+ ---
88
+
89
+ {finalTitle && <title>{finalTitle}</title>}
90
+ {finalDescription && <meta name="description" content={finalDescription} />}
91
+ {finalCanonical && <link rel="canonical" href={finalCanonical} />}
92
+ {robotsContent && <meta name="robots" content={robotsContent} />}
93
+
94
+ {/* Open Graph */}
95
+ {ogTitle && <meta property="og:title" content={ogTitle} />}
96
+ {ogDescription && <meta property="og:description" content={ogDescription} />}
97
+ <meta property="og:type" content={finalType} />
98
+
99
+ {
100
+ finalImage && (
101
+ <>
102
+ <meta property="og:image" content={finalImage.url} />
103
+ <meta property="og:image:width" content={String(finalImage.width)} />
104
+ <meta property="og:image:height" content={String(finalImage.height)} />
105
+ <meta property="og:image:type" content={finalImage.type} />
106
+ {finalImage.alt && <meta property="og:image:alt" content={finalImage.alt} />}
107
+ </>
108
+ )
109
+ }
110
+
111
+ {/* Twitter / X – only the card tag is needed, the rest falls back to OG */}
112
+ <meta name="twitter:card" content="summary_large_image" />
package/src/index.js CHANGED
@@ -5,3 +5,4 @@ export { default as BlockWrapper } from "./components/BlockWrapper.svelte";
5
5
  export { default as EditableBlock } from "./components/EditableBlock.svelte";
6
6
  export { default as PageContent } from "./components/PageContent.svelte";
7
7
  export { default as Picture } from "./components/Picture.svelte";
8
+ export { default as SiteHead } from "./components/SiteHead.astro";
@@ -0,0 +1,59 @@
1
+ import { withRequestFilter } from "./withRequestFilter.js";
2
+ import { withCmsFetch } from "./withCmsFetch.js";
3
+
4
+ const defaultErrorHandler = (context, error, wrap) => {
5
+ const status = error?.status ?? 500;
6
+ const target = [401, 404].includes(status) ? `/errors/${status}` : "/errors/500";
7
+
8
+ return wrap(context, () => context.rewrite(target));
9
+ };
10
+
11
+ /**
12
+ * Composes the standard CMS middleware pipeline.
13
+ *
14
+ * @param {object} [options]
15
+ * @param {(context: import("astro").APIContext) => boolean} [options.shouldSkip] - filter that decides if request bypasses the pipeline
16
+ * @param {(context: import("astro").APIContext) => Promise<void>} [options.fetch] - CMS fetch step
17
+ * @param {(context: import("astro").APIContext, handler: () => any) => Promise<Response>} [options.paraglide] - i18n wrapper (optional)
18
+ * @param {(context: import("astro").APIContext) => Promise<Response | void>} [options.beforeFetch] - hook before CMS fetch
19
+ * @param {(context: import("astro").APIContext) => Promise<Response | void>} [options.afterFetch] - hook after CMS fetch
20
+ * @param {(context: import("astro").APIContext, error: any, wrap: Function) => Promise<Response>} [options.onError] - custom error handler
21
+ */
22
+ const createCmsMiddleware = (options = {}) => {
23
+ const {
24
+ shouldSkip = withRequestFilter(),
25
+ fetch = withCmsFetch(),
26
+ paraglide,
27
+ beforeFetch,
28
+ afterFetch,
29
+ onError = defaultErrorHandler,
30
+ } = options;
31
+
32
+ const wrap = paraglide ?? ((context, handler) => handler());
33
+
34
+ return async (context, next) => {
35
+ if (shouldSkip(context)) {
36
+ return next();
37
+ }
38
+
39
+ try {
40
+ if (beforeFetch) {
41
+ const earlyResponse = await beforeFetch(context);
42
+ if (earlyResponse instanceof Response) return earlyResponse;
43
+ }
44
+
45
+ await fetch(context);
46
+
47
+ if (afterFetch) {
48
+ const earlyResponse = await afterFetch(context);
49
+ if (earlyResponse instanceof Response) return earlyResponse;
50
+ }
51
+
52
+ return wrap(context, () => next());
53
+ } catch (error) {
54
+ return onError(context, error, wrap);
55
+ }
56
+ };
57
+ };
58
+
59
+ export { createCmsMiddleware };
@@ -0,0 +1,11 @@
1
+ import { fetchPage } from "../utils/fetchPage.js";
2
+
3
+ /**
4
+ * Returns the CMS page fetch function for use in createCmsMiddleware.
5
+ * Throws if fetch fails — the wrapping middleware should handle errors.
6
+ *
7
+ * @returns {(context: import("astro").APIContext) => Promise<void>}
8
+ */
9
+ const withCmsFetch = () => fetchPage;
10
+
11
+ export { withCmsFetch };
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Wraps a handler with paraglide locale resolution.
3
+ *
4
+ * Locale priority:
5
+ * 1. CMS-provided locale (configurable via `getCmsLocale`)
6
+ * 2. First URL segment, if it matches a known locale (for error pages)
7
+ * 3. Paraglide baseLocale (handled by paraglide's strategy chain)
8
+ *
9
+ * The resolved locale is:
10
+ * - injected as a request header for paraglide's custom strategy
11
+ * - set as a cookie on the response for client-side hydration consistency
12
+ *
13
+ * @param {object} options
14
+ * @param {Function} options.paraglideMiddleware - paraglide's server middleware
15
+ * @param {string[]} options.locales - list of supported locale codes
16
+ * @param {(context: import("astro").APIContext) => string | undefined} [options.getCmsLocale] - extracts the CMS locale from context
17
+ * @param {string} [options.cookieName="PARAGLIDE_LOCALE"] - name of the locale cookie
18
+ * @param {string} [options.headerName="x-cms-locale"] - name of the header injected for the custom strategy
19
+ */
20
+
21
+ const withParaglide = ({
22
+ paraglideMiddleware,
23
+ locales,
24
+ getCmsLocale = (context) => context?.locals?.seo?.locale,
25
+ cookieName = "PARAGLIDE_LOCALE",
26
+ headerName = "x-cms-locale",
27
+ }) => {
28
+ return async (context, handler) => {
29
+ const locale = resolveLocale(context, locales, getCmsLocale);
30
+
31
+ let request = context.request;
32
+ if (locale) {
33
+ const headers = new Headers(request.headers);
34
+ headers.set(headerName, locale);
35
+ request = new Request(request, { headers });
36
+ }
37
+
38
+ const response = await paraglideMiddleware(request, () => handler());
39
+
40
+ if (locale && response instanceof Response) {
41
+ response.headers.append(
42
+ "Set-Cookie",
43
+ `${cookieName}=${locale}; Path=/; SameSite=Lax`,
44
+ );
45
+ }
46
+
47
+ return response;
48
+ };
49
+ };
50
+
51
+ const resolveLocale = (context, locales, getCmsLocale) => {
52
+ const cmsLocale = getCmsLocale(context);
53
+ if (cmsLocale && locales.includes(cmsLocale)) {
54
+ return cmsLocale;
55
+ }
56
+
57
+ const firstSegment = context.url.pathname.split("/")[1];
58
+ if (locales.includes(firstSegment)) {
59
+ return firstSegment;
60
+ }
61
+
62
+ return undefined;
63
+ };
64
+
65
+ export { withParaglide };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Default request filter — skips non-HTML requests, internal Astro routes,
3
+ * error routes and asset paths.
4
+ *
5
+ * @param {object} [options]
6
+ * @param {string[]} [options.additionalExcludePaths] - extra path prefixes to skip
7
+ * @param {(context: import("astro").APIContext) => boolean} [options.customFilter] - additional skip predicate
8
+ */
9
+
10
+ const withRequestFilter = (options = {}) => {
11
+ const { additionalExcludePaths = [], customFilter } = options;
12
+
13
+ return (context) => {
14
+ const { request, url } = context;
15
+ const accept = request.headers.get("accept") || "";
16
+
17
+ const isHtmlRequest = accept.includes("text/html");
18
+ const isAstroInternal = url.pathname.startsWith("/_astro");
19
+ const isErrorRoute = url.pathname.startsWith("/errors/");
20
+ const hasFileExtension = /\.[a-zA-Z0-9]+$/.test(url.pathname);
21
+ const isExcludedPath = additionalExcludePaths.some((p) =>
22
+ url.pathname.startsWith(p),
23
+ );
24
+
25
+ return (
26
+ request.method !== "GET" ||
27
+ !isHtmlRequest ||
28
+ isAstroInternal ||
29
+ isErrorRoute ||
30
+ hasFileExtension ||
31
+ isExcludedPath ||
32
+ customFilter?.(context) === true
33
+ );
34
+ };
35
+ };
36
+
37
+ export { withRequestFilter };
package/src/server.js CHANGED
@@ -1 +1,8 @@
1
1
  export { fetchPage } from "./utils/fetchPage.js";
2
+
3
+ export { createCmsMiddleware } from "./middleware/createCmsMiddleware.js";
4
+ export { withRequestFilter } from "./middleware/withRequestFilter.js";
5
+ export { withCmsFetch } from "./middleware/withCmsFetch.js";
6
+ export { withParaglide } from "./middleware/withParaglide.js";
7
+ export { createSitemapHandler } from "./utils/sitemapHandler.js";
8
+ export { createRobotsHandler } from "./utils/robotsHandler.js";
@@ -0,0 +1,20 @@
1
+ import { buildCmsSitemapUrl } from "./urlResolver.js";
2
+ import { buildCmsHeaders } from "./headers.js";
3
+ import { HttpError } from "./errors.js";
4
+
5
+ const fetchSitemap = async (request) => {
6
+ const cmsUrl = buildCmsSitemapUrl();
7
+
8
+ const response = await fetch(cmsUrl, {
9
+ method: "GET",
10
+ headers: buildCmsHeaders(request),
11
+ });
12
+
13
+ if (!response.ok) {
14
+ throw new HttpError(response.status, "CMS Error");
15
+ }
16
+
17
+ return response.json();
18
+ };
19
+
20
+ export { fetchSitemap };
@@ -0,0 +1,40 @@
1
+ const buildRobotsTxt = ({ siteUrl, allowIndexing }) => {
2
+ if (!allowIndexing) {
3
+ return `User-agent: *
4
+ Disallow: /
5
+ `;
6
+ }
7
+
8
+ return `User-agent: *
9
+ Allow: /
10
+
11
+ Sitemap: ${siteUrl}/sitemap.xml
12
+ `;
13
+ };
14
+
15
+ const resolveSiteUrl = (request) => {
16
+ const url = new URL(request.url);
17
+ return `${url.protocol}//${url.host}`;
18
+ };
19
+
20
+ // TODO: replace with CMS setting once available
21
+ const resolveAllowIndexing = () => true;
22
+
23
+ const createRobotsHandler =
24
+ () =>
25
+ async ({ request }) => {
26
+ const siteUrl = resolveSiteUrl(request);
27
+ const allowIndexing = resolveAllowIndexing();
28
+
29
+ const body = buildRobotsTxt({ siteUrl, allowIndexing });
30
+
31
+ return new Response(body, {
32
+ status: 200,
33
+ headers: {
34
+ "Content-Type": "text/plain; charset=utf-8",
35
+ "Cache-Control": "public, max-age=3600, s-maxage=3600",
36
+ },
37
+ });
38
+ };
39
+
40
+ export { createRobotsHandler };
@@ -0,0 +1,36 @@
1
+ import { fetchSitemap } from "./fetchSitemap.js";
2
+ import { buildSitemapXml } from "./sitemapXml.js";
3
+ import { HttpError } from "./errors.js";
4
+
5
+ const resolveSiteUrl = (request) => {
6
+ const url = new URL(request.url);
7
+ return `${url.protocol}//${url.host}`;
8
+ };
9
+
10
+ const createSitemapHandler =
11
+ () =>
12
+ async ({ request }) => {
13
+ const siteUrl = resolveSiteUrl(request);
14
+
15
+ try {
16
+ const entries = await fetchSitemap(request);
17
+ const xml = buildSitemapXml(entries, siteUrl);
18
+
19
+ return new Response(xml, {
20
+ status: 200,
21
+ headers: {
22
+ "Content-Type": "application/xml; charset=utf-8",
23
+ "Cache-Control": "public, max-age=3600, s-maxage=3600",
24
+ },
25
+ });
26
+ } catch (error) {
27
+ if (error instanceof HttpError) {
28
+ return new Response(`Sitemap error: ${error.message}`, {
29
+ status: error.status,
30
+ });
31
+ }
32
+ throw error;
33
+ }
34
+ };
35
+
36
+ export { createSitemapHandler };
@@ -0,0 +1,54 @@
1
+ const escapeXml = (value) =>
2
+ String(value).replace(/[<>&'"]/g, (char) => {
3
+ switch (char) {
4
+ case "<":
5
+ return "&lt;";
6
+ case ">":
7
+ return "&gt;";
8
+ case "&":
9
+ return "&amp;";
10
+ case "'":
11
+ return "&apos;";
12
+ case '"':
13
+ return "&quot;";
14
+ default:
15
+ return char;
16
+ }
17
+ });
18
+
19
+ const encodeUrl = (url) => escapeXml(encodeURI(url));
20
+
21
+ const formatLastmod = (timestamp) => {
22
+ // Strip milliseconds: "2026-05-07T12:19:58.487Z" → "2026-05-07T12:19:58Z"
23
+ return timestamp.replace(/\.\d+Z$/, "Z");
24
+ };
25
+
26
+ const buildUrlBlock = (entry, siteUrl) => {
27
+ const loc = encodeUrl(`${siteUrl}${entry.path}`);
28
+ const lastmod = entry.updatedAt
29
+ ? `\n <lastmod>${formatLastmod(entry.updatedAt)}</lastmod>`
30
+ : "";
31
+
32
+ const alternates = (entry.alternates ?? [])
33
+ .map(
34
+ (alt) =>
35
+ `\n <xhtml:link rel="alternate" hreflang="${escapeXml(alt.locale)}" href="${encodeUrl(`${siteUrl}${alt.path}`)}" />`,
36
+ )
37
+ .join("");
38
+
39
+ return ` <url>
40
+ <loc>${loc}</loc>${lastmod}${alternates}
41
+ </url>`;
42
+ };
43
+
44
+ const buildSitemapXml = (entries, siteUrl) => {
45
+ const urls = entries.map((entry) => buildUrlBlock(entry, siteUrl)).join("\n");
46
+
47
+ return `<?xml version="1.0" encoding="UTF-8"?>
48
+ <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"
49
+ xmlns:xhtml="http://www.w3.org/1999/xhtml">
50
+ ${urls}
51
+ </urlset>`;
52
+ };
53
+
54
+ export { buildSitemapXml };
@@ -10,4 +10,10 @@ const buildCmsPageUrl = ({ draftUuid, path }) => {
10
10
  return `${base}/api/public/pages${normalizedPath}`;
11
11
  };
12
12
 
13
- export { buildCmsPageUrl };
13
+ const buildCmsSitemapUrl = () => {
14
+ const base = import.meta.env.CMS_URL;
15
+
16
+ return `${base}/api/public/sitemap`;
17
+ };
18
+
19
+ export { buildCmsPageUrl, buildCmsSitemapUrl };