@vulcantech/blog 0.2.1 → 0.3.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/README.md CHANGED
@@ -25,12 +25,12 @@ interface CMSBlogPost {
25
25
  keywords?: string; // comma-separated SEO keywords, target keyword first
26
26
  featuredImage?: string; // in-page hero / card image
27
27
  featuredVideo?: CMSVideoDescriptor; // advisory; most posts have none (see step 8)
28
- ogImage?: string; // social card; fall back: ogImage ?? featuredImage
29
- seoTitle?: string; // fall back: seoTitle ?? title
30
- seoDescription?: string; // fall back: seoDescription ?? excerpt
31
- status: "draft" | "in_review" | "published" | "archived";
28
+ ogImage?: string; // social card override — read via postSeoMeta()
29
+ seoTitle?: string; // SERP title override — read via postSeoMeta()
30
+ seoDescription?: string; // description override — read via postSeoMeta()
31
+ status: "draft" | "in_review" | "scheduled" | "published" | "archived";
32
32
  publishedAt?: string; // ISO 8601; always present on published posts
33
- scheduledAt?: string; // ISO 8601
33
+ scheduledAt?: string; // ISO 8601; when a "scheduled" post goes live
34
34
  createdAt: string; // ISO 8601
35
35
  updatedAt: string; // ISO 8601
36
36
  postType?: "article" | "case-study" | "announcement"; // absent = "article"
@@ -40,9 +40,20 @@ interface CMSBlogPost {
40
40
 
41
41
  Field notes:
42
42
 
43
- - **`seoTitle` / `seoDescription` / `ogImage`** are per-post SEO overrides. In `generateMetadata`, use the fallback chains shown above — that is the convention every VulcanTech site follows.
43
+ - **`seoTitle` / `seoDescription` / `ogImage`** are per-post SEO overrides, and a cleared one arrives as `""` — so `seoTitle ?? title` ships an empty `<title>`. Read them through `postSeoMeta(post)`, which treats blanks as unset and returns `{ title, titleIsOverride, description, ogImage }`. A `seoTitle` is a complete SERP title: emit it as `{ absolute }` so the layout's title template doesn't brand it twice. Use `description` for JSON-LD too (listing pages included), not the raw excerpt:
44
+
45
+ ```ts
46
+ import { postSeoMeta } from "@vulcantech/blog";
47
+
48
+ const seo = postSeoMeta(post);
49
+ return {
50
+ title: seo.titleIsOverride ? { absolute: seo.title } : seo.title,
51
+ description: seo.description,
52
+ openGraph: { title: seo.title, description: seo.description, images: seo.ogImage ? [seo.ogImage] : undefined },
53
+ };
54
+ ```
44
55
  - **`metadata`** is a case-study spec sheet (e.g. `Make: 1969 Camaro`, `Engine: LS3`). The CMS only offers the editor when `postType` is `"case-study"`; render it as a spec/details table on case-study layouts and ignore it everywhere else — do not dump it onto regular articles.
45
- - **`status`** — the public fetchers only ever return `published` posts (or a token-unlocked draft in preview mode), so you never need to filter by status yourself.
56
+ - **`status`** — the public fetchers only ever return `published` posts (or a token-unlocked draft in preview mode), so you never need to filter by status yourself. `published` means live now. A post waiting for its date is `scheduled` + `scheduledAt`; the CMS flips it to `published` (stamping `publishedAt`) when the time arrives, so it is never served early. Anything writing posts directly (seed scripts, Admin SDK) must follow the same rule — a `published` doc with a future `publishedAt` is live immediately, not scheduled.
46
57
 
47
58
  ### What's inside `content`
48
59
 
@@ -111,9 +122,9 @@ keywords: post.keywords || (post.tags?.length ? post.tags : [post.title, "Brand"
111
122
  ```ts
112
123
  export { GET } from "@vulcantech/blog";
113
124
  ```
114
- The CMS mints a signed token and links to `/api/preview?token=…&slug=…`; the handler validates it, enables Next Draft Mode, and redirects to the post. Reading the token opts the render dynamic — keep the public `[slug]` route static/ISR and let Draft Mode switch it.
125
+ The CMS mints a signed token and links to `/api/preview?token=…&slug=…&prefix=…`; the handler validates it, enables Next Draft Mode, and redirects to the post at `/{routePrefix}/{slug}` (the post's own `routePrefix`, falling back to `prefix`, then `blog`) — so a post in a `policies` or `legal` space previews on its own route. Pages on those routes must call `resolvePreviewToken()` like the blog post page does, or drafts there will 404. Reading the token opts the render dynamic — keep the public `[slug]` route static/ISR and let Draft Mode switch it.
115
126
 
116
- **6. ISR invalidation** — ensure `src/app/api/revalidate/route.ts` exists; the CMS purges `blog:{projectId}` (list) and `blog:{projectId}:{slug}` (single) on edit.
127
+ **6. ISR invalidation** — ensure `src/app/api/revalidate/route.ts` exists, set `VULCANTECH_REVALIDATE_SECRET`, and register the site under **Settings → Form Consumers (ISR Revalidation)** in the CMS. That list serves every integration, not just forms — skip it and blog edits wait out the 60s window instead of purging instantly. The CMS purges `blog:{projectId}` (list) and `blog:{projectId}:{slug}` (single) on edit. Route contract and reference copy: the `@vulcantech/cms` README, [ISR revalidation](../cms/README.md#isr-revalidation).
117
128
 
118
129
  **7. (Optional) video styling** — authors can drop videos into post content. They
119
130
  arrive as real, playable markup (`<video class="cms-video">` for CMS-hosted files,
@@ -208,7 +219,7 @@ tags on edit, so scoped pages revalidate with the blog as long as they use this
208
219
  package's fetchers (which attach those tags).
209
220
 
210
221
  ### Required env
211
- `VULCANTECH_PROJECT_ID`, `VULCANTECH_API_KEY` (required) · `VULCANTECH_CMS_URL` (optional, default `https://cms.vulcantech.io`) · `VULCANTECH_BLOG_NO_CACHE` (optional, `1`/`true` to bypass ISR while debugging).
222
+ `VULCANTECH_PROJECT_ID`, `VULCANTECH_API_KEY` (required) · `VULCANTECH_REVALIDATE_SECRET` (required for instant ISR purges; see step 6) · `VULCANTECH_CMS_URL` (optional, default `https://cms.vulcantech.io`) · `VULCANTECH_BLOG_NO_CACHE` (optional, `1`/`true` to bypass ISR while debugging).
212
223
 
213
224
  ### Per-app values
214
225
  None beyond env — all blog logic is shared.
package/dist/index.d.mts CHANGED
@@ -26,6 +26,58 @@ import { NextRequest } from 'next/server';
26
26
  */
27
27
  declare function sanitizeHtml(html: string): string;
28
28
 
29
+ /**
30
+ * Blank-safe SEO fallbacks for a CMS blog post.
31
+ *
32
+ * The CMS editor saves a cleared SEO-panel field as `""`, not as an absent
33
+ * field, so a `seoTitle ?? title` chain keeps the empty string and the page
34
+ * ships an empty `<title>` / description. Every consumer reads its overrides
35
+ * through `postSeoMeta` instead, so the fallback rules live in one place.
36
+ *
37
+ * Pure (no `next/*` imports) — safe anywhere, including client components.
38
+ */
39
+ /** The post fields `postSeoMeta` reads — any `CMSBlogPost` satisfies it. */
40
+ interface PostSeoSource {
41
+ title: string;
42
+ excerpt?: string;
43
+ seoTitle?: string;
44
+ seoDescription?: string;
45
+ ogImage?: string;
46
+ featuredImage?: string;
47
+ }
48
+ /** Resolved SEO values for one post. */
49
+ interface PostSeoMeta {
50
+ /** The author's `seoTitle` when set, else the post title. */
51
+ title: string;
52
+ /**
53
+ * True when `title` is the author's `seoTitle`. That is a complete SERP
54
+ * title, so emit it as `title: { absolute: title }` — otherwise the
55
+ * layout's `%s - Site` template brands it a second time.
56
+ */
57
+ titleIsOverride: boolean;
58
+ /** The `seoDescription` override when set, else the excerpt ("" if neither). */
59
+ description: string;
60
+ /** Social-card image: the `ogImage` override, else `featuredImage`. */
61
+ ogImage?: string;
62
+ }
63
+ /**
64
+ * Resolves a post's title, meta description and social image from its CMS
65
+ * SEO overrides, treating blank overrides as unset.
66
+ *
67
+ * @param post - A CMS blog post (or any object with the same SEO fields).
68
+ * @returns The resolved title (plus whether it is an override), description
69
+ * and optional og image.
70
+ *
71
+ * @example
72
+ * const seo = postSeoMeta(post);
73
+ * return {
74
+ * title: seo.titleIsOverride ? { absolute: seo.title } : seo.title,
75
+ * description: seo.description,
76
+ * openGraph: { images: seo.ogImage ? [seo.ogImage] : undefined },
77
+ * };
78
+ */
79
+ declare function postSeoMeta(post: PostSeoSource): PostSeoMeta;
80
+
29
81
  /**
30
82
  * @vulcantech/blog — server-side blog fetch layer for VulcanTech consumer
31
83
  * sites.
@@ -104,7 +156,7 @@ interface CMSBlogPost {
104
156
  * sanitizers, so bring your own typography (e.g. a `prose` wrapper).
105
157
  */
106
158
  content: string;
107
- /** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */
159
+ /** Plain-text summary. Meta-description fallback — read it via `postSeoMeta`. */
108
160
  excerpt: string;
109
161
  /** Single editorial bucket (one per post) — distinct from the free-form `tags`. */
110
162
  category?: string;
@@ -119,7 +171,7 @@ interface CMSBlogPost {
119
171
  keywords?: string;
120
172
  /** An object, not a string — display `author.name`. */
121
173
  author: CMSBlogAuthor;
122
- /** In-page hero / card image URL. For social cards use `ogImage ?? featuredImage`. */
174
+ /** In-page hero / card image URL. For social cards use `postSeoMeta(post).ogImage`. */
123
175
  featuredImage?: string;
124
176
  /**
125
177
  * Optional supplementary video for the post. Purely advisory — render it as a
@@ -128,21 +180,33 @@ interface CMSBlogPost {
128
180
  * arrive as playable markup within `content` instead.
129
181
  */
130
182
  featuredVideo?: CMSVideoDescriptor;
131
- /** The public fetchers only ever return "published" posts (or a token-unlocked draft). */
132
- status: "draft" | "in_review" | "published" | "archived";
133
- /** ISO 8601 timestamp. Always present on published posts. */
183
+ /**
184
+ * The public fetchers only ever return "published" posts (or a token-unlocked
185
+ * draft in preview). `"scheduled"` means "goes live at `scheduledAt`": the
186
+ * CMS flips it to `"published"` at that time, and until then it is never
187
+ * served — so a consumer never needs to compare dates itself.
188
+ */
189
+ status: "draft" | "in_review" | "scheduled" | "published" | "archived";
190
+ /**
191
+ * ISO 8601 timestamp the post went live; drives sort order. Always present
192
+ * on published posts (for a formerly scheduled post it equals `scheduledAt`
193
+ * unless an author set it explicitly).
194
+ */
134
195
  publishedAt?: string;
135
- /** ISO 8601 timestamp for scheduled publishing; the post stays hidden until then. */
196
+ /** ISO 8601 timestamp a `scheduled` post goes live; kept as a record after it does. */
136
197
  scheduledAt?: string;
137
198
  /** ISO 8601 timestamp. */
138
199
  createdAt: string;
139
200
  /** ISO 8601 timestamp. */
140
201
  updatedAt: string;
141
- /** SERP/social title override. Canonical fallback: `seoTitle ?? title`. */
202
+ /**
203
+ * SERP/social title override — may be `""` when an author clears it. Read
204
+ * it via `postSeoMeta`, never `seoTitle ?? title` (keeps the blank).
205
+ */
142
206
  seoTitle?: string;
143
- /** Meta-description override. Canonical fallback: `seoDescription ?? excerpt`. */
207
+ /** Meta-description override — may be `""`. Read it via `postSeoMeta`. */
144
208
  seoDescription?: string;
145
- /** Social-share card image URL. Canonical fallback: `ogImage ?? featuredImage`. */
209
+ /** Social-share card image URL — may be `""`. Read it via `postSeoMeta`. */
146
210
  ogImage?: string;
147
211
  /** Defaults to "article" when absent (the field predates postType). */
148
212
  postType?: "article" | "case-study" | "announcement";
@@ -234,6 +298,12 @@ declare function fetchBlogPostBySlug(slug: string, options?: FetchPostOptions):
234
298
  * the draft (see resolvePreviewToken). On an invalid/expired token it just
235
299
  * redirects to the public page (which 404s if the post isn't published).
236
300
  *
301
+ * The redirect honours the post's `routePrefix`: a post in the `policies`
302
+ * space lands on `/policies/{slug}`, not `/blog/{slug}`. When the token is
303
+ * invalid the post cannot be read, so the CMS also sends the prefix as
304
+ * `?prefix=`; with neither, `/blog` is assumed. The prefix is validated as
305
+ * plain path segments so the query string can never redirect off-site.
306
+ *
237
307
  * Each consumer wires it up with one line:
238
308
  * // app/api/preview/route.ts
239
309
  * export { GET } from "@vulcantech/blog";
@@ -252,4 +322,4 @@ declare function GET(request: NextRequest): Promise<Response>;
252
322
  */
253
323
  declare function resolvePreviewToken(): Promise<string | undefined>;
254
324
 
255
- export { type CMSBlogAuthor, type CMSBlogPost, type CMSVideoDescriptor, type FetchOptions, type FetchPostOptions, type FetchPostsOptions, GET, fetchBlogPostBySlug, fetchBlogPosts, resolvePreviewToken, sanitizeHtml, tagsForBlogList, tagsForBlogPost };
325
+ export { type CMSBlogAuthor, type CMSBlogPost, type CMSVideoDescriptor, type FetchOptions, type FetchPostOptions, type FetchPostsOptions, GET, type PostSeoMeta, type PostSeoSource, fetchBlogPostBySlug, fetchBlogPosts, postSeoMeta, resolvePreviewToken, sanitizeHtml, tagsForBlogList, tagsForBlogPost };
package/dist/index.d.ts CHANGED
@@ -26,6 +26,58 @@ import { NextRequest } from 'next/server';
26
26
  */
27
27
  declare function sanitizeHtml(html: string): string;
28
28
 
29
+ /**
30
+ * Blank-safe SEO fallbacks for a CMS blog post.
31
+ *
32
+ * The CMS editor saves a cleared SEO-panel field as `""`, not as an absent
33
+ * field, so a `seoTitle ?? title` chain keeps the empty string and the page
34
+ * ships an empty `<title>` / description. Every consumer reads its overrides
35
+ * through `postSeoMeta` instead, so the fallback rules live in one place.
36
+ *
37
+ * Pure (no `next/*` imports) — safe anywhere, including client components.
38
+ */
39
+ /** The post fields `postSeoMeta` reads — any `CMSBlogPost` satisfies it. */
40
+ interface PostSeoSource {
41
+ title: string;
42
+ excerpt?: string;
43
+ seoTitle?: string;
44
+ seoDescription?: string;
45
+ ogImage?: string;
46
+ featuredImage?: string;
47
+ }
48
+ /** Resolved SEO values for one post. */
49
+ interface PostSeoMeta {
50
+ /** The author's `seoTitle` when set, else the post title. */
51
+ title: string;
52
+ /**
53
+ * True when `title` is the author's `seoTitle`. That is a complete SERP
54
+ * title, so emit it as `title: { absolute: title }` — otherwise the
55
+ * layout's `%s - Site` template brands it a second time.
56
+ */
57
+ titleIsOverride: boolean;
58
+ /** The `seoDescription` override when set, else the excerpt ("" if neither). */
59
+ description: string;
60
+ /** Social-card image: the `ogImage` override, else `featuredImage`. */
61
+ ogImage?: string;
62
+ }
63
+ /**
64
+ * Resolves a post's title, meta description and social image from its CMS
65
+ * SEO overrides, treating blank overrides as unset.
66
+ *
67
+ * @param post - A CMS blog post (or any object with the same SEO fields).
68
+ * @returns The resolved title (plus whether it is an override), description
69
+ * and optional og image.
70
+ *
71
+ * @example
72
+ * const seo = postSeoMeta(post);
73
+ * return {
74
+ * title: seo.titleIsOverride ? { absolute: seo.title } : seo.title,
75
+ * description: seo.description,
76
+ * openGraph: { images: seo.ogImage ? [seo.ogImage] : undefined },
77
+ * };
78
+ */
79
+ declare function postSeoMeta(post: PostSeoSource): PostSeoMeta;
80
+
29
81
  /**
30
82
  * @vulcantech/blog — server-side blog fetch layer for VulcanTech consumer
31
83
  * sites.
@@ -104,7 +156,7 @@ interface CMSBlogPost {
104
156
  * sanitizers, so bring your own typography (e.g. a `prose` wrapper).
105
157
  */
106
158
  content: string;
107
- /** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */
159
+ /** Plain-text summary. Meta-description fallback — read it via `postSeoMeta`. */
108
160
  excerpt: string;
109
161
  /** Single editorial bucket (one per post) — distinct from the free-form `tags`. */
110
162
  category?: string;
@@ -119,7 +171,7 @@ interface CMSBlogPost {
119
171
  keywords?: string;
120
172
  /** An object, not a string — display `author.name`. */
121
173
  author: CMSBlogAuthor;
122
- /** In-page hero / card image URL. For social cards use `ogImage ?? featuredImage`. */
174
+ /** In-page hero / card image URL. For social cards use `postSeoMeta(post).ogImage`. */
123
175
  featuredImage?: string;
124
176
  /**
125
177
  * Optional supplementary video for the post. Purely advisory — render it as a
@@ -128,21 +180,33 @@ interface CMSBlogPost {
128
180
  * arrive as playable markup within `content` instead.
129
181
  */
130
182
  featuredVideo?: CMSVideoDescriptor;
131
- /** The public fetchers only ever return "published" posts (or a token-unlocked draft). */
132
- status: "draft" | "in_review" | "published" | "archived";
133
- /** ISO 8601 timestamp. Always present on published posts. */
183
+ /**
184
+ * The public fetchers only ever return "published" posts (or a token-unlocked
185
+ * draft in preview). `"scheduled"` means "goes live at `scheduledAt`": the
186
+ * CMS flips it to `"published"` at that time, and until then it is never
187
+ * served — so a consumer never needs to compare dates itself.
188
+ */
189
+ status: "draft" | "in_review" | "scheduled" | "published" | "archived";
190
+ /**
191
+ * ISO 8601 timestamp the post went live; drives sort order. Always present
192
+ * on published posts (for a formerly scheduled post it equals `scheduledAt`
193
+ * unless an author set it explicitly).
194
+ */
134
195
  publishedAt?: string;
135
- /** ISO 8601 timestamp for scheduled publishing; the post stays hidden until then. */
196
+ /** ISO 8601 timestamp a `scheduled` post goes live; kept as a record after it does. */
136
197
  scheduledAt?: string;
137
198
  /** ISO 8601 timestamp. */
138
199
  createdAt: string;
139
200
  /** ISO 8601 timestamp. */
140
201
  updatedAt: string;
141
- /** SERP/social title override. Canonical fallback: `seoTitle ?? title`. */
202
+ /**
203
+ * SERP/social title override — may be `""` when an author clears it. Read
204
+ * it via `postSeoMeta`, never `seoTitle ?? title` (keeps the blank).
205
+ */
142
206
  seoTitle?: string;
143
- /** Meta-description override. Canonical fallback: `seoDescription ?? excerpt`. */
207
+ /** Meta-description override — may be `""`. Read it via `postSeoMeta`. */
144
208
  seoDescription?: string;
145
- /** Social-share card image URL. Canonical fallback: `ogImage ?? featuredImage`. */
209
+ /** Social-share card image URL — may be `""`. Read it via `postSeoMeta`. */
146
210
  ogImage?: string;
147
211
  /** Defaults to "article" when absent (the field predates postType). */
148
212
  postType?: "article" | "case-study" | "announcement";
@@ -234,6 +298,12 @@ declare function fetchBlogPostBySlug(slug: string, options?: FetchPostOptions):
234
298
  * the draft (see resolvePreviewToken). On an invalid/expired token it just
235
299
  * redirects to the public page (which 404s if the post isn't published).
236
300
  *
301
+ * The redirect honours the post's `routePrefix`: a post in the `policies`
302
+ * space lands on `/policies/{slug}`, not `/blog/{slug}`. When the token is
303
+ * invalid the post cannot be read, so the CMS also sends the prefix as
304
+ * `?prefix=`; with neither, `/blog` is assumed. The prefix is validated as
305
+ * plain path segments so the query string can never redirect off-site.
306
+ *
237
307
  * Each consumer wires it up with one line:
238
308
  * // app/api/preview/route.ts
239
309
  * export { GET } from "@vulcantech/blog";
@@ -252,4 +322,4 @@ declare function GET(request: NextRequest): Promise<Response>;
252
322
  */
253
323
  declare function resolvePreviewToken(): Promise<string | undefined>;
254
324
 
255
- export { type CMSBlogAuthor, type CMSBlogPost, type CMSVideoDescriptor, type FetchOptions, type FetchPostOptions, type FetchPostsOptions, GET, fetchBlogPostBySlug, fetchBlogPosts, resolvePreviewToken, sanitizeHtml, tagsForBlogList, tagsForBlogPost };
325
+ export { type CMSBlogAuthor, type CMSBlogPost, type CMSVideoDescriptor, type FetchOptions, type FetchPostOptions, type FetchPostsOptions, GET, type PostSeoMeta, type PostSeoSource, fetchBlogPostBySlug, fetchBlogPosts, postSeoMeta, resolvePreviewToken, sanitizeHtml, tagsForBlogList, tagsForBlogPost };
package/dist/index.js CHANGED
@@ -96,6 +96,21 @@ function sanitizeHtml(html) {
96
96
  return clean;
97
97
  }
98
98
 
99
+ // src/seo.ts
100
+ function present(value) {
101
+ const trimmed = value?.trim();
102
+ return trimmed ? trimmed : void 0;
103
+ }
104
+ function postSeoMeta(post) {
105
+ const seoTitle = present(post.seoTitle);
106
+ return {
107
+ title: seoTitle ?? post.title,
108
+ titleIsOverride: seoTitle !== void 0,
109
+ description: present(post.seoDescription) ?? present(post.excerpt) ?? "",
110
+ ogImage: present(post.ogImage) ?? present(post.featuredImage)
111
+ };
112
+ }
113
+
99
114
  // src/index.ts
100
115
  var DEFAULT_REVALIDATE_SECONDS = 60;
101
116
  function cmsUrl() {
@@ -211,6 +226,14 @@ async function fetchBlogPostBySlug(slug, options = {}) {
211
226
  }
212
227
  var PREVIEW_COOKIE = "vt_preview_token";
213
228
  var PREVIEW_MAX_AGE_SECONDS = 2 * 60 * 60;
229
+ var DEFAULT_ROUTE_PREFIX = "blog";
230
+ function safeRoutePrefix(value) {
231
+ if (!value) return null;
232
+ return /^[a-z0-9-]+(?:\/[a-z0-9-]+)*$/.test(value) ? value : null;
233
+ }
234
+ function redirectSameOrigin(path) {
235
+ return new server.NextResponse(null, { status: 307, headers: { Location: path } });
236
+ }
214
237
  async function GET(request) {
215
238
  const { searchParams } = new URL(request.url);
216
239
  const token = searchParams.get("token");
@@ -221,10 +244,11 @@ async function GET(request) {
221
244
  { status: 400 }
222
245
  );
223
246
  }
224
- const target = new URL(`/blog/${encodeURIComponent(slug)}`, request.url);
225
247
  const post = await fetchBlogPostBySlug(slug, { previewToken: token });
248
+ const prefix = safeRoutePrefix(post?.routePrefix) ?? safeRoutePrefix(searchParams.get("prefix")) ?? DEFAULT_ROUTE_PREFIX;
249
+ const target = `/${prefix}/${encodeURIComponent(slug)}`;
226
250
  if (!post) {
227
- return server.NextResponse.redirect(target);
251
+ return redirectSameOrigin(target);
228
252
  }
229
253
  (await headers.draftMode()).enable();
230
254
  (await headers.cookies()).set(PREVIEW_COOKIE, token, {
@@ -234,7 +258,7 @@ async function GET(request) {
234
258
  path: "/",
235
259
  maxAge: PREVIEW_MAX_AGE_SECONDS
236
260
  });
237
- return server.NextResponse.redirect(target);
261
+ return redirectSameOrigin(target);
238
262
  }
239
263
  async function resolvePreviewToken() {
240
264
  const { isEnabled } = await headers.draftMode();
@@ -246,6 +270,7 @@ async function resolvePreviewToken() {
246
270
  exports.GET = GET;
247
271
  exports.fetchBlogPostBySlug = fetchBlogPostBySlug;
248
272
  exports.fetchBlogPosts = fetchBlogPosts;
273
+ exports.postSeoMeta = postSeoMeta;
249
274
  exports.resolvePreviewToken = resolvePreviewToken;
250
275
  exports.sanitizeHtml = sanitizeHtml;
251
276
  exports.tagsForBlogList = tagsForBlogList;
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sanitize.ts","../src/index.ts"],"names":["NextResponse","draftMode","cookies"],"mappings":";;;;;;;;AAiBA,IAAM,cAAA,GAAiB;AAAA,EACrB,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,OAAA;AAAA,EAAS,MAAA;AAAA,EAAQ,OAAA;AAAA,EAAS,UAAA;AAAA,EAC9C,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,MAAA;AAAA,EAAQ,MAAA;AAAA,EAAQ,MAAA;AAAA,EAAQ,QAAA;AAAA,EACtD,OAAA;AAAA,EAAS,UAAA;AAAA,EAAY,OAAA;AAAA,EAAS,OAAA;AAAA,EAAS,KAAA;AAAA,EAAO,MAAA;AAAA,EAAQ,KAAA;AAAA,EACtD,UAAA;AAAA,EAAY;AACd,CAAA;AASA,IAAM,iBAAA,GACJ,qGAAA;AAEF,SAAS,cAAc,CAAA,EAAmB;AACxC,EAAA,IAAI,CAAC,OAAO,QAAA,CAAS,CAAC,KAAK,CAAA,GAAI,CAAA,IAAK,CAAA,GAAI,OAAA,EAAU,OAAO,EAAA;AACzD,EAAA,IAAI;AACF,IAAA,OAAO,MAAA,CAAO,cAAc,CAAC,CAAA;AAAA,EAC/B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAA;AAAA,E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AAA,OAAOF,mBAAA,CAAa,SAAS,MAAM,CAAA;AACrC;AAaA,eAAsB,mBAAA,GAAmD;AACvE,EAAA,MAAM,EAAE,SAAA,EAAU,GAAI,MAAMC,iBAAA,EAAU;AACtC,EAAA,IAAI,CAAC,WAAW,OAAO,MAAA;AACvB,EAAA,MAAM,KAAA,GAAQ,MAAMC,eAAA,EAAQ;AAC5B,EAAA,OAAO,KAAA,CAAM,GAAA,CAAI,cAAc,CAAA,EAAG,KAAA;AACpC","file":"index.js","sourcesContent":["/**\n * HTML sanitizer for user-generated (TipTap) content.\n *\n * MIRROR of packages/ui/sanitize.ts — keep in sync. Duplicated rather than\n * imported so this package stays dependency-free (no `ui` workspace coupling).\n *\n * Defense-in-depth only. As of audit L4 / BL-023, blog HTML is sanitized ON\n * WRITE by the CMS's parser-based DOMPurify sanitizer\n * (apps/vulcantech-cms/src/lib/html/sanitizeHtml.ts), so the content this\n * package fetches is already clean. This boundary pass is a safety net for\n * legacy/unexpected data, not the primary guarantee.\n *\n * Strips dangerous tags and attributes and neutralizes dangerous URL schemes,\n * decoding HTML entities first so entity-encoded `javascript:` payloads can't\n * slip past the scheme check.\n */\n\nconst DANGEROUS_TAGS = [\n \"script\", \"object\", \"embed\", \"form\", \"input\", \"textarea\",\n \"button\", \"select\", \"option\", \"link\", \"meta\", \"base\", \"applet\",\n \"frame\", \"frameset\", \"layer\", \"style\", \"svg\", \"math\", \"xmp\",\n \"noscript\", \"template\",\n];\n\n/**\n * `iframe` is NOT in the blocklist above: blog HTML may carry a YouTube video\n * embed (BL-321). It is filtered by origin instead — an iframe pointing\n * anywhere but YouTube's embed path is deleted, element and content alike, by\n * {@link stripForeignIframes}. `<video>` needs no rule: it was never blocked\n * here, and its `src` still goes through the URL-scheme pass below.\n */\nconst YOUTUBE_EMBED_SRC =\n /^https:\\/\\/(?:www\\.)?(?:youtube-nocookie\\.com|youtube\\.com)\\/embed\\/[A-Za-z0-9_-]{6,20}(?:[?#].*)?$/;\n\nfunction safeCodePoint(n: number): string {\n if (!Number.isFinite(n) || n < 0 || n > 0x10ffff) return \"\";\n try {\n return String.fromCodePoint(n);\n } catch {\n return \"\";\n }\n}\n\n/** Decode numeric and a few named HTML entities used to obfuscate URL schemes. */\nfunction decodeEntities(s: string): string {\n return s\n .replace(/&#x([0-9a-f]+);?/gi, (_, h) => safeCodePoint(parseInt(h, 16)))\n .replace(/&#(\\d+);?/g, (_, d) => safeCodePoint(parseInt(d, 10)))\n .replace(/&colon;/gi, \":\")\n .replace(/&tab;/gi, \"\\t\")\n .replace(/&newline;/gi, \"\\n\")\n .replace(/&amp;/gi, \"&\");\n}\n\n/** Drop spaces and C0 control chars (code point <= 0x20) used to break up schemes. */\nfunction stripBlankAndControl(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch.codePointAt(0)! > 0x20) out += ch;\n }\n return out;\n}\n\n/**\n * Remove every `<iframe>` whose `src` is not a YouTube embed URL, taking any\n * content between the tags with it.\n */\nfunction stripForeignIframes(html: string): string {\n return html.replace(\n /<iframe\\b[^>]*>(?:[\\s\\S]*?<\\/iframe>)?/gi,\n (element) => {\n const match = /\\bsrc\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/i.exec(element);\n const raw = match ? (match[2] ?? match[3] ?? match[4] ?? \"\") : \"\";\n const src = stripBlankAndControl(decodeEntities(raw));\n return YOUTUBE_EMBED_SRC.test(src) ? element : \"\";\n },\n );\n}\n\n/**\n * Sanitize HTML by removing dangerous tags/attributes and neutralizing unsafe\n * URL schemes. Returns the cleaned HTML string.\n *\n * The package's fetchers already run every post's `content` through this, so\n * call it only for CMS HTML obtained some other way (legacy exports, custom\n * endpoints).\n */\nexport function sanitizeHtml(html: string): string {\n if (!html) return \"\";\n\n let clean = html.replace(\n /<script\\b[^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>/gi,\n \"\",\n );\n\n for (const tag of DANGEROUS_TAGS) {\n clean = clean.replace(\n new RegExp(`<${tag}\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/${tag}>`, \"gi\"),\n \"\",\n );\n clean = clean.replace(new RegExp(`<${tag}\\\\b[^>]*\\\\/?>`, \"gi\"), \"\");\n }\n\n // Keep YouTube video embeds, drop every other iframe.\n clean = stripForeignIframes(clean);\n\n clean = clean.replace(\n /\\s+on\\w+\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\s+style\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\b(href|src)\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/gi,\n (match, attr, _raw, dq, sq, uq) => {\n const value = dq ?? sq ?? uq ?? \"\";\n const decoded = stripBlankAndControl(decodeEntities(value)).toLowerCase();\n if (/^(javascript|data|vbscript):/.test(decoded)) {\n return `${attr}=\"about:blank\"`;\n }\n return match;\n },\n );\n\n return clean;\n}\n","/**\n * @vulcantech/blog — server-side blog fetch layer for VulcanTech consumer\n * sites.\n *\n * Reads published blog posts from the CMS with Next.js ISR tags so the CMS\n * can purge a post (via /api/revalidate) the moment it changes, and supports\n * signed draft-preview tokens so an unpublished post can be rendered on the\n * real site for review.\n *\n * Config comes from the same env vars every consumer already sets — no\n * per-app wiring beyond importing this package:\n * VULCANTECH_CMS_URL (default https://cms.vulcantech.io)\n * VULCANTECH_PROJECT_ID (required)\n * VULCANTECH_API_KEY (required)\n * VULCANTECH_BLOG_NO_CACHE (\"1\" | \"true\" → bypass ISR everywhere)\n *\n * SERVER-ONLY: relies on VULCANTECH_API_KEY (no NEXT_PUBLIC_ prefix), so it\n * must only be imported from server components / route handlers.\n *\n * Errors are graceful by design — a CMS hiccup returns [] / null and logs a\n * warning rather than throwing, so a marketing site never hard-crashes on a\n * transient CMS outage.\n *\n * Draft preview (Next.js Draft Mode):\n * - Re-export `GET` from app/api/preview/route.ts on each consumer.\n * - Call `resolvePreviewToken()` in the blog post page and pass the result\n * to fetchBlogPostBySlug as { previewToken }.\n * The public /blog/[slug] route stays static/ISR; only a request carrying\n * the Draft Mode cookie renders the unpublished draft.\n */\n\nimport { cookies, draftMode } from \"next/headers\";\nimport { NextResponse, type NextRequest } from \"next/server\";\nimport { sanitizeHtml } from \"./sanitize\";\n\nconst DEFAULT_REVALIDATE_SECONDS = 60;\n\nexport interface CMSBlogAuthor {\n uid?: string;\n name: string;\n avatar?: string;\n}\n\n/**\n * A supplementary video attached to a post, normalized by the CMS.\n *\n * Structural copy of the CMS's canonical `VideoDescriptor`\n * (`packages/blog-editor-shared/src/lib/video.ts`) — inlined rather than\n * imported so this package stays dependency-free for consumer sites. Keep the\n * shape in sync; the CMS validates every write against the original.\n *\n * `videoId` is safe to interpolate into a YouTube embed URL and `url` is always\n * on the CMS media host — the CMS pins both, so a consumer never has to\n * re-validate before rendering.\n */\nexport type CMSVideoDescriptor =\n | { provider: \"youtube\"; videoId: string }\n | { provider: \"youtube-short\"; videoId: string }\n | { provider: \"file\"; url: string; poster?: string };\n\nexport interface CMSBlogPost {\n id: string;\n projectId: string;\n title: string;\n slug: string;\n /**\n * Sanitized HTML (TipTap editor output) — NOT markdown. Render with\n * `dangerouslySetInnerHTML`; do not run it through a markdown renderer.\n * Sanitized on write by the CMS and re-sanitized by this package's fetchers,\n * so it is safe to inject as-is.\n *\n * Markup contract (see the README's \"What's inside content\" for the full\n * story): headings start at h2 (h1 is yours, for the title); images are\n * plain `<img>` with no dimensions — `next/image` is not usable here, style\n * `img` with CSS; galleries are empty `div.cms-gallery[data-gallery]` nodes\n * that render as nothing unless hydrated; inline `style` never survives the\n * sanitizers, so bring your own typography (e.g. a `prose` wrapper).\n */\n content: string;\n /** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */\n excerpt: string;\n /** Single editorial bucket (one per post) — distinct from the free-form `tags`. */\n category?: string;\n /** URL route segment the post lives under, e.g. \"blog\" or \"documentation\". */\n routePrefix?: string;\n tags: string[];\n /**\n * Comma-separated SEO keywords the CMS derives from the post's dedicated\n * keyword fields (target keyword first). Feed straight into\n * `Metadata.keywords`; absent when the post has no keywords set.\n */\n keywords?: string;\n /** An object, not a string — display `author.name`. */\n author: CMSBlogAuthor;\n /** In-page hero / card image URL. For social cards use `ogImage ?? featuredImage`. */\n featuredImage?: string;\n /**\n * Optional supplementary video for the post. Purely advisory — render it as a\n * hero player, a card thumbnail, or ignore it; nothing breaks when it's\n * absent, and it is absent on most posts. Videos placed *inside* the article\n * arrive as playable markup within `content` instead.\n */\n featuredVideo?: CMSVideoDescriptor;\n /** The public fetchers only ever return \"published\" posts (or a token-unlocked draft). */\n status: \"draft\" | \"in_review\" | \"published\" | \"archived\";\n /** ISO 8601 timestamp. Always present on published posts. */\n publishedAt?: string;\n /** ISO 8601 timestamp for scheduled publishing; the post stays hidden until then. */\n scheduledAt?: string;\n /** ISO 8601 timestamp. */\n createdAt: string;\n /** ISO 8601 timestamp. */\n updatedAt: string;\n /** SERP/social title override. Canonical fallback: `seoTitle ?? title`. */\n seoTitle?: string;\n /** Meta-description override. Canonical fallback: `seoDescription ?? excerpt`. */\n seoDescription?: string;\n /** Social-share card image URL. Canonical fallback: `ogImage ?? featuredImage`. */\n ogImage?: string;\n /** Defaults to \"article\" when absent (the field predates postType). */\n postType?: \"article\" | \"case-study\" | \"announcement\";\n /**\n * Spec-sheet pairs for case studies (e.g. `{ label: \"Make\", value: \"1969\n * Camaro\" }`) — the CMS only shows this editor when `postType` is\n * \"case-study\". Render as a spec table on case-study layouts; ignore\n * everywhere else.\n */\n metadata?: { label: string; value: string }[];\n}\n\nexport interface FetchOptions {\n /** Override the per-fetch revalidate window. Default: 60 seconds. */\n revalidate?: number;\n /** Extra ISR tags to attach to the fetch. */\n extraTags?: string[];\n /** Skip Next's ISR cache for this call. */\n noStore?: boolean;\n}\n\n/**\n * List filters, all applied server-side by the CMS — prefer these over\n * fetching everything and filtering client-side.\n */\nexport interface FetchPostsOptions extends FetchOptions {\n /** Exact-match on the post's `category`. */\n category?: string;\n /**\n * Only return posts under this route prefix (e.g. \"documentation\"). Don't\n * pass \"blog\" for the blog itself — legacy posts predate the field and have\n * no prefix, so they'd be excluded; filter the blog list client-side instead\n * (see the README's Scoped routes section).\n */\n routePrefix?: string;\n /** Posts whose `tags` include this tag. */\n tag?: string;\n /** Full-text search across title/content. */\n search?: string;\n /**\n * Page size; combine with `startAfter` to paginate. The response carries no\n * `hasMore`/`total` — fetch `limit + 1`, and if more than `limit` arrive\n * there is another page (drop the extra).\n */\n limit?: number;\n /** Pagination cursor: the `id` of the last post from the previous page. */\n startAfter?: string;\n}\n\nexport interface FetchPostOptions extends FetchOptions {\n /**\n * A signed preview token (from the CMS) that unlocks an unpublished post.\n * When set, the cache is bypassed automatically — preview content must\n * never be cached or served to the public.\n */\n previewToken?: string;\n}\n\nfunction cmsUrl(): string {\n return process.env.VULCANTECH_CMS_URL || \"https://cms.vulcantech.io\";\n}\n\nfunction bypassCache(): boolean {\n return (\n process.env.VULCANTECH_BLOG_NO_CACHE === \"1\" ||\n process.env.VULCANTECH_BLOG_NO_CACHE === \"true\"\n );\n}\n\nfunction assertConfig(): { projectId: string; apiKey: string } | null {\n const projectId = process.env.VULCANTECH_PROJECT_ID;\n const apiKey = process.env.VULCANTECH_API_KEY;\n if (!projectId || !apiKey) {\n console.warn(\n \"[cms/blog] CMS not configured — set VULCANTECH_PROJECT_ID and VULCANTECH_API_KEY\",\n );\n return null;\n }\n return { projectId, apiKey };\n}\n\nexport { sanitizeHtml };\n\n/** Sanitize a post's HTML body so every consumer render is safe by default. */\nfunction sanitizePost(post: CMSBlogPost): CMSBlogPost {\n if (post && typeof post.content === \"string\") {\n return { ...post, content: sanitizeHtml(post.content) };\n }\n return post;\n}\n\n/** ISR tag for a project's blog list. */\nexport function tagsForBlogList(projectId: string): string[] {\n return [`blog:${projectId}`];\n}\n\n/** ISR tags for a single post (post-specific + project-wide). */\nexport function tagsForBlogPost(projectId: string, slug: string): string[] {\n return [`blog:${projectId}:${slug}`, `blog:${projectId}`];\n}\n\nfunction buildInit(\n tags: string[],\n options: FetchOptions,\n): RequestInit & { next?: { revalidate?: number; tags?: string[] } } {\n const skipCache = options.noStore || bypassCache();\n if (skipCache) return { cache: \"no-store\" };\n return {\n next: {\n revalidate: options.revalidate ?? DEFAULT_REVALIDATE_SECONDS,\n tags: [...tags, ...(options.extraTags ?? [])],\n },\n };\n}\n\n/**\n * Fetch published posts for the configured project, newest-first by\n * `publishedAt` (the CMS orders them — no client-side sort needed). Optional\n * filters (category/routePrefix/tag/search/limit/startAfter) are forwarded to\n * the CMS.\n *\n * Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it\n * logs a warning and returns `[]` — render an empty state instead of wrapping\n * in try/catch.\n */\nexport async function fetchBlogPosts(\n options: FetchPostsOptions = {},\n): Promise<CMSBlogPost[]> {\n const config = assertConfig();\n if (!config) return [];\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey, status: \"published\" });\n if (options.category) params.set(\"category\", options.category);\n if (options.routePrefix) params.set(\"routePrefix\", options.routePrefix);\n if (options.tag) params.set(\"tag\", options.tag);\n if (options.search) params.set(\"search\", options.search);\n if (options.limit) params.set(\"limit\", String(options.limit));\n if (options.startAfter) params.set(\"startAfter\", options.startAfter);\n\n const url = `${cmsUrl()}/api/blog?${params.toString()}`;\n const init = buildInit(tagsForBlogList(projectId), options);\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\"[cms/blog] CMS unreachable:\", (err as Error).message);\n return [];\n }\n if (res.status === 404) {\n console.warn(\"[cms/blog] /api/blog returned 404 — CMS may need redeployment\");\n return [];\n }\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog returned ${res.status}`);\n return [];\n }\n\n let json: { posts: CMSBlogPost[] };\n try {\n json = (await res.json()) as { posts: CMSBlogPost[] };\n } catch (err) {\n console.warn(\"[cms/blog] /api/blog returned non-JSON:\", (err as Error).message);\n return [];\n }\n return (json.posts ?? []).map(sanitizePost);\n}\n\n/**\n * Fetch a single post by slug. Returns null when not found.\n *\n * Never throws: CMS errors also return `null` (with a logged warning), so\n * treat `null` as \"show notFound()\" rather than catching exceptions.\n *\n * Pass `previewToken` (minted by the CMS) to render an unpublished draft for\n * review — that automatically bypasses the cache.\n */\nexport async function fetchBlogPostBySlug(\n slug: string,\n options: FetchPostOptions = {},\n): Promise<CMSBlogPost | null> {\n const config = assertConfig();\n if (!config) return null;\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey });\n if (options.previewToken) params.set(\"preview\", options.previewToken);\n\n const url = `${cmsUrl()}/api/blog/${encodeURIComponent(slug)}?${params.toString()}`;\n // Preview responses must never be cached.\n const init = buildInit(tagsForBlogPost(projectId, slug), {\n ...options,\n noStore: options.noStore || !!options.previewToken,\n });\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\n `[cms/blog] CMS unreachable for \"${slug}\":`,\n (err as Error).message,\n );\n return null;\n }\n if (res.status === 404) return null;\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog/${slug} returned ${res.status}`);\n return null;\n }\n\n let json: { post: CMSBlogPost };\n try {\n json = (await res.json()) as { post: CMSBlogPost };\n } catch (err) {\n console.warn(`[cms/blog] /api/blog/${slug} returned non-JSON:`, (err as Error).message);\n return null;\n }\n return json.post ? sanitizePost(json.post) : null;\n}\n\n/* ─── Draft preview (Next.js Draft Mode) ─── */\n\nconst PREVIEW_COOKIE = \"vt_preview_token\";\nconst PREVIEW_MAX_AGE_SECONDS = 2 * 60 * 60; // 2 hours\n\n/**\n * Route handler for `/api/preview?token=…&slug=…`.\n *\n * Validates the token against the CMS, enables Next Draft Mode, stores the\n * token in an httpOnly cookie, and redirects to the post — which then renders\n * the draft (see resolvePreviewToken). On an invalid/expired token it just\n * redirects to the public page (which 404s if the post isn't published).\n *\n * Each consumer wires it up with one line:\n * // app/api/preview/route.ts\n * export { GET } from \"@vulcantech/blog\";\n */\nexport async function GET(request: NextRequest): Promise<Response> {\n const { searchParams } = new URL(request.url);\n const token = searchParams.get(\"token\");\n const slug = searchParams.get(\"slug\");\n\n if (!token || !slug) {\n return NextResponse.json(\n { error: \"token and slug are required\" },\n { status: 400 },\n );\n }\n\n const target = new URL(`/blog/${encodeURIComponent(slug)}`, request.url);\n\n // Validate by asking the CMS to resolve the draft with this token.\n const post = await fetchBlogPostBySlug(slug, { previewToken: token });\n if (!post) {\n return NextResponse.redirect(target);\n }\n\n (await draftMode()).enable();\n (await cookies()).set(PREVIEW_COOKIE, token, {\n httpOnly: true,\n sameSite: \"lax\",\n secure: process.env.NODE_ENV === \"production\",\n path: \"/\",\n maxAge: PREVIEW_MAX_AGE_SECONDS,\n });\n\n return NextResponse.redirect(target);\n}\n\n/**\n * Page helper: returns the active preview token when Draft Mode is on, else\n * undefined. Call it in the blog post server component and spread the result\n * into the fetch:\n *\n * const previewToken = await resolvePreviewToken();\n * const post = await fetchBlogPostBySlug(slug, { previewToken });\n *\n * Reading the cookie only happens when Draft Mode is enabled, so the public\n * route stays statically rendered for normal visitors.\n */\nexport async function resolvePreviewToken(): Promise<string | undefined> {\n const { isEnabled } = await draftMode();\n if (!isEnabled) return undefined;\n const store = await cookies();\n return store.get(PREVIEW_COOKIE)?.value;\n}\n"]}
1
+ {"version":3,"sources":["../src/sanitize.ts","../src/seo.ts","../src/index.ts"],"names":["NextResponse","draftMode","cookies"],"mappings":";;;;;;;;AAiBA,IAAM,cAAA,GAAiB;AAAA,EACrB,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,OAAA;AAAA,EAAS,MAAA;AAAA,EAAQ,OAAA;AAAA,EAAS,UAAA;AAAA,EAC9C,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,MAAA;AAAA,EAAQ,MAAA;AAAA,EAAQ,MAAA;AAAA,EAAQ,QAAA;AAAA,EACtD,OAAA;AAAA,EAAS,UAAA;AAAA,EAAY,OAAA;AAAA,EAAS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;AAAA,IAC3C,QAAA,EAAU,IAAA;AAAA,IACV,QAAA,EAAU,KAAA;AAAA,IACV,MAAA,EAAQ,OAAA,CAAQ,GAAA,CAAI,QAAA,KAAa,YAAA;AAAA,IACjC,IAAA,EAAM,GAAA;AAAA,IACN,MAAA,EAAQ;AAAA,GACT,CAAA;AAED,EAAA,OAAO,mBAAmB,MAAM,CAAA;AAClC;AAaA,eAAsB,mBAAA,GAAmD;AACvE,EAAA,MAAM,EAAE,SAAA,EAAU,GAAI,MAAMD,iBAAA,EAAU;AACtC,EAAA,IAAI,CAAC,WAAW,OAAO,MAAA;AACvB,EAAA,MAAM,KAAA,GAAQ,MAAMC,eAAA,EAAQ;AAC5B,EAAA,OAAO,KAAA,CAAM,GAAA,CAAI,cAAc,CAAA,EAAG,KAAA;AACpC","file":"index.js","sourcesContent":["/**\n * HTML sanitizer for user-generated (TipTap) content.\n *\n * MIRROR of packages/ui/sanitize.ts — keep in sync. Duplicated rather than\n * imported so this package stays dependency-free (no `ui` workspace coupling).\n *\n * Defense-in-depth only. As of audit L4 / BL-023, blog HTML is sanitized ON\n * WRITE by the CMS's parser-based DOMPurify sanitizer\n * (apps/vulcantech-cms/src/lib/html/sanitizeHtml.ts), so the content this\n * package fetches is already clean. This boundary pass is a safety net for\n * legacy/unexpected data, not the primary guarantee.\n *\n * Strips dangerous tags and attributes and neutralizes dangerous URL schemes,\n * decoding HTML entities first so entity-encoded `javascript:` payloads can't\n * slip past the scheme check.\n */\n\nconst DANGEROUS_TAGS = [\n \"script\", \"object\", \"embed\", \"form\", \"input\", \"textarea\",\n \"button\", \"select\", \"option\", \"link\", \"meta\", \"base\", \"applet\",\n \"frame\", \"frameset\", \"layer\", \"style\", \"svg\", \"math\", \"xmp\",\n \"noscript\", \"template\",\n];\n\n/**\n * `iframe` is NOT in the blocklist above: blog HTML may carry a YouTube video\n * embed (BL-321). It is filtered by origin instead — an iframe pointing\n * anywhere but YouTube's embed path is deleted, element and content alike, by\n * {@link stripForeignIframes}. `<video>` needs no rule: it was never blocked\n * here, and its `src` still goes through the URL-scheme pass below.\n */\nconst YOUTUBE_EMBED_SRC =\n /^https:\\/\\/(?:www\\.)?(?:youtube-nocookie\\.com|youtube\\.com)\\/embed\\/[A-Za-z0-9_-]{6,20}(?:[?#].*)?$/;\n\nfunction safeCodePoint(n: number): string {\n if (!Number.isFinite(n) || n < 0 || n > 0x10ffff) return \"\";\n try {\n return String.fromCodePoint(n);\n } catch {\n return \"\";\n }\n}\n\n/** Decode numeric and a few named HTML entities used to obfuscate URL schemes. */\nfunction decodeEntities(s: string): string {\n return s\n .replace(/&#x([0-9a-f]+);?/gi, (_, h) => safeCodePoint(parseInt(h, 16)))\n .replace(/&#(\\d+);?/g, (_, d) => safeCodePoint(parseInt(d, 10)))\n .replace(/&colon;/gi, \":\")\n .replace(/&tab;/gi, \"\\t\")\n .replace(/&newline;/gi, \"\\n\")\n .replace(/&amp;/gi, \"&\");\n}\n\n/** Drop spaces and C0 control chars (code point <= 0x20) used to break up schemes. */\nfunction stripBlankAndControl(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch.codePointAt(0)! > 0x20) out += ch;\n }\n return out;\n}\n\n/**\n * Remove every `<iframe>` whose `src` is not a YouTube embed URL, taking any\n * content between the tags with it.\n */\nfunction stripForeignIframes(html: string): string {\n return html.replace(\n /<iframe\\b[^>]*>(?:[\\s\\S]*?<\\/iframe>)?/gi,\n (element) => {\n const match = /\\bsrc\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/i.exec(element);\n const raw = match ? (match[2] ?? match[3] ?? match[4] ?? \"\") : \"\";\n const src = stripBlankAndControl(decodeEntities(raw));\n return YOUTUBE_EMBED_SRC.test(src) ? element : \"\";\n },\n );\n}\n\n/**\n * Sanitize HTML by removing dangerous tags/attributes and neutralizing unsafe\n * URL schemes. Returns the cleaned HTML string.\n *\n * The package's fetchers already run every post's `content` through this, so\n * call it only for CMS HTML obtained some other way (legacy exports, custom\n * endpoints).\n */\nexport function sanitizeHtml(html: string): string {\n if (!html) return \"\";\n\n let clean = html.replace(\n /<script\\b[^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>/gi,\n \"\",\n );\n\n for (const tag of DANGEROUS_TAGS) {\n clean = clean.replace(\n new RegExp(`<${tag}\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/${tag}>`, \"gi\"),\n \"\",\n );\n clean = clean.replace(new RegExp(`<${tag}\\\\b[^>]*\\\\/?>`, \"gi\"), \"\");\n }\n\n // Keep YouTube video embeds, drop every other iframe.\n clean = stripForeignIframes(clean);\n\n clean = clean.replace(\n /\\s+on\\w+\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\s+style\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\b(href|src)\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/gi,\n (match, attr, _raw, dq, sq, uq) => {\n const value = dq ?? sq ?? uq ?? \"\";\n const decoded = stripBlankAndControl(decodeEntities(value)).toLowerCase();\n if (/^(javascript|data|vbscript):/.test(decoded)) {\n return `${attr}=\"about:blank\"`;\n }\n return match;\n },\n );\n\n return clean;\n}\n","/**\n * Blank-safe SEO fallbacks for a CMS blog post.\n *\n * The CMS editor saves a cleared SEO-panel field as `\"\"`, not as an absent\n * field, so a `seoTitle ?? title` chain keeps the empty string and the page\n * ships an empty `<title>` / description. Every consumer reads its overrides\n * through `postSeoMeta` instead, so the fallback rules live in one place.\n *\n * Pure (no `next/*` imports) — safe anywhere, including client components.\n */\n\n/** The post fields `postSeoMeta` reads — any `CMSBlogPost` satisfies it. */\nexport interface PostSeoSource {\n title: string;\n excerpt?: string;\n seoTitle?: string;\n seoDescription?: string;\n ogImage?: string;\n featuredImage?: string;\n}\n\n/** Resolved SEO values for one post. */\nexport interface PostSeoMeta {\n /** The author's `seoTitle` when set, else the post title. */\n title: string;\n /**\n * True when `title` is the author's `seoTitle`. That is a complete SERP\n * title, so emit it as `title: { absolute: title }` — otherwise the\n * layout's `%s - Site` template brands it a second time.\n */\n titleIsOverride: boolean;\n /** The `seoDescription` override when set, else the excerpt (\"\" if neither). */\n description: string;\n /** Social-card image: the `ogImage` override, else `featuredImage`. */\n ogImage?: string;\n}\n\n/** Trims a value to `undefined` when it is missing or whitespace-only. */\nfunction present(value: string | undefined | null): string | undefined {\n const trimmed = value?.trim();\n return trimmed ? trimmed : undefined;\n}\n\n/**\n * Resolves a post's title, meta description and social image from its CMS\n * SEO overrides, treating blank overrides as unset.\n *\n * @param post - A CMS blog post (or any object with the same SEO fields).\n * @returns The resolved title (plus whether it is an override), description\n * and optional og image.\n *\n * @example\n * const seo = postSeoMeta(post);\n * return {\n * title: seo.titleIsOverride ? { absolute: seo.title } : seo.title,\n * description: seo.description,\n * openGraph: { images: seo.ogImage ? [seo.ogImage] : undefined },\n * };\n */\nexport function postSeoMeta(post: PostSeoSource): PostSeoMeta {\n const seoTitle = present(post.seoTitle);\n return {\n title: seoTitle ?? post.title,\n titleIsOverride: seoTitle !== undefined,\n description: present(post.seoDescription) ?? present(post.excerpt) ?? \"\",\n ogImage: present(post.ogImage) ?? present(post.featuredImage),\n };\n}\n","/**\n * @vulcantech/blog — server-side blog fetch layer for VulcanTech consumer\n * sites.\n *\n * Reads published blog posts from the CMS with Next.js ISR tags so the CMS\n * can purge a post (via /api/revalidate) the moment it changes, and supports\n * signed draft-preview tokens so an unpublished post can be rendered on the\n * real site for review.\n *\n * Config comes from the same env vars every consumer already sets — no\n * per-app wiring beyond importing this package:\n * VULCANTECH_CMS_URL (default https://cms.vulcantech.io)\n * VULCANTECH_PROJECT_ID (required)\n * VULCANTECH_API_KEY (required)\n * VULCANTECH_BLOG_NO_CACHE (\"1\" | \"true\" → bypass ISR everywhere)\n *\n * SERVER-ONLY: relies on VULCANTECH_API_KEY (no NEXT_PUBLIC_ prefix), so it\n * must only be imported from server components / route handlers.\n *\n * Errors are graceful by design — a CMS hiccup returns [] / null and logs a\n * warning rather than throwing, so a marketing site never hard-crashes on a\n * transient CMS outage.\n *\n * Draft preview (Next.js Draft Mode):\n * - Re-export `GET` from app/api/preview/route.ts on each consumer.\n * - Call `resolvePreviewToken()` in the blog post page and pass the result\n * to fetchBlogPostBySlug as { previewToken }.\n * The public /blog/[slug] route stays static/ISR; only a request carrying\n * the Draft Mode cookie renders the unpublished draft.\n */\n\nimport { cookies, draftMode } from \"next/headers\";\nimport { NextResponse, type NextRequest } from \"next/server\";\nimport { sanitizeHtml } from \"./sanitize\";\n\nconst DEFAULT_REVALIDATE_SECONDS = 60;\n\nexport interface CMSBlogAuthor {\n uid?: string;\n name: string;\n avatar?: string;\n}\n\n/**\n * A supplementary video attached to a post, normalized by the CMS.\n *\n * Structural copy of the CMS's canonical `VideoDescriptor`\n * (`packages/blog-editor-shared/src/lib/video.ts`) — inlined rather than\n * imported so this package stays dependency-free for consumer sites. Keep the\n * shape in sync; the CMS validates every write against the original.\n *\n * `videoId` is safe to interpolate into a YouTube embed URL and `url` is always\n * on the CMS media host — the CMS pins both, so a consumer never has to\n * re-validate before rendering.\n */\nexport type CMSVideoDescriptor =\n | { provider: \"youtube\"; videoId: string }\n | { provider: \"youtube-short\"; videoId: string }\n | { provider: \"file\"; url: string; poster?: string };\n\nexport interface CMSBlogPost {\n id: string;\n projectId: string;\n title: string;\n slug: string;\n /**\n * Sanitized HTML (TipTap editor output) — NOT markdown. Render with\n * `dangerouslySetInnerHTML`; do not run it through a markdown renderer.\n * Sanitized on write by the CMS and re-sanitized by this package's fetchers,\n * so it is safe to inject as-is.\n *\n * Markup contract (see the README's \"What's inside content\" for the full\n * story): headings start at h2 (h1 is yours, for the title); images are\n * plain `<img>` with no dimensions — `next/image` is not usable here, style\n * `img` with CSS; galleries are empty `div.cms-gallery[data-gallery]` nodes\n * that render as nothing unless hydrated; inline `style` never survives the\n * sanitizers, so bring your own typography (e.g. a `prose` wrapper).\n */\n content: string;\n /** Plain-text summary. Meta-description fallback — read it via `postSeoMeta`. */\n excerpt: string;\n /** Single editorial bucket (one per post) — distinct from the free-form `tags`. */\n category?: string;\n /** URL route segment the post lives under, e.g. \"blog\" or \"documentation\". */\n routePrefix?: string;\n tags: string[];\n /**\n * Comma-separated SEO keywords the CMS derives from the post's dedicated\n * keyword fields (target keyword first). Feed straight into\n * `Metadata.keywords`; absent when the post has no keywords set.\n */\n keywords?: string;\n /** An object, not a string — display `author.name`. */\n author: CMSBlogAuthor;\n /** In-page hero / card image URL. For social cards use `postSeoMeta(post).ogImage`. */\n featuredImage?: string;\n /**\n * Optional supplementary video for the post. Purely advisory — render it as a\n * hero player, a card thumbnail, or ignore it; nothing breaks when it's\n * absent, and it is absent on most posts. Videos placed *inside* the article\n * arrive as playable markup within `content` instead.\n */\n featuredVideo?: CMSVideoDescriptor;\n /**\n * The public fetchers only ever return \"published\" posts (or a token-unlocked\n * draft in preview). `\"scheduled\"` means \"goes live at `scheduledAt`\": the\n * CMS flips it to `\"published\"` at that time, and until then it is never\n * served — so a consumer never needs to compare dates itself.\n */\n status: \"draft\" | \"in_review\" | \"scheduled\" | \"published\" | \"archived\";\n /**\n * ISO 8601 timestamp the post went live; drives sort order. Always present\n * on published posts (for a formerly scheduled post it equals `scheduledAt`\n * unless an author set it explicitly).\n */\n publishedAt?: string;\n /** ISO 8601 timestamp a `scheduled` post goes live; kept as a record after it does. */\n scheduledAt?: string;\n /** ISO 8601 timestamp. */\n createdAt: string;\n /** ISO 8601 timestamp. */\n updatedAt: string;\n /**\n * SERP/social title override — may be `\"\"` when an author clears it. Read\n * it via `postSeoMeta`, never `seoTitle ?? title` (keeps the blank).\n */\n seoTitle?: string;\n /** Meta-description override — may be `\"\"`. Read it via `postSeoMeta`. */\n seoDescription?: string;\n /** Social-share card image URL — may be `\"\"`. Read it via `postSeoMeta`. */\n ogImage?: string;\n /** Defaults to \"article\" when absent (the field predates postType). */\n postType?: \"article\" | \"case-study\" | \"announcement\";\n /**\n * Spec-sheet pairs for case studies (e.g. `{ label: \"Make\", value: \"1969\n * Camaro\" }`) — the CMS only shows this editor when `postType` is\n * \"case-study\". Render as a spec table on case-study layouts; ignore\n * everywhere else.\n */\n metadata?: { label: string; value: string }[];\n}\n\nexport interface FetchOptions {\n /** Override the per-fetch revalidate window. Default: 60 seconds. */\n revalidate?: number;\n /** Extra ISR tags to attach to the fetch. */\n extraTags?: string[];\n /** Skip Next's ISR cache for this call. */\n noStore?: boolean;\n}\n\n/**\n * List filters, all applied server-side by the CMS — prefer these over\n * fetching everything and filtering client-side.\n */\nexport interface FetchPostsOptions extends FetchOptions {\n /** Exact-match on the post's `category`. */\n category?: string;\n /**\n * Only return posts under this route prefix (e.g. \"documentation\"). Don't\n * pass \"blog\" for the blog itself — legacy posts predate the field and have\n * no prefix, so they'd be excluded; filter the blog list client-side instead\n * (see the README's Scoped routes section).\n */\n routePrefix?: string;\n /** Posts whose `tags` include this tag. */\n tag?: string;\n /** Full-text search across title/content. */\n search?: string;\n /**\n * Page size; combine with `startAfter` to paginate. The response carries no\n * `hasMore`/`total` — fetch `limit + 1`, and if more than `limit` arrive\n * there is another page (drop the extra).\n */\n limit?: number;\n /** Pagination cursor: the `id` of the last post from the previous page. */\n startAfter?: string;\n}\n\nexport interface FetchPostOptions extends FetchOptions {\n /**\n * A signed preview token (from the CMS) that unlocks an unpublished post.\n * When set, the cache is bypassed automatically — preview content must\n * never be cached or served to the public.\n */\n previewToken?: string;\n}\n\nfunction cmsUrl(): string {\n return process.env.VULCANTECH_CMS_URL || \"https://cms.vulcantech.io\";\n}\n\nfunction bypassCache(): boolean {\n return (\n process.env.VULCANTECH_BLOG_NO_CACHE === \"1\" ||\n process.env.VULCANTECH_BLOG_NO_CACHE === \"true\"\n );\n}\n\nfunction assertConfig(): { projectId: string; apiKey: string } | null {\n const projectId = process.env.VULCANTECH_PROJECT_ID;\n const apiKey = process.env.VULCANTECH_API_KEY;\n if (!projectId || !apiKey) {\n console.warn(\n \"[cms/blog] CMS not configured — set VULCANTECH_PROJECT_ID and VULCANTECH_API_KEY\",\n );\n return null;\n }\n return { projectId, apiKey };\n}\n\nexport { sanitizeHtml };\nexport { postSeoMeta, type PostSeoMeta, type PostSeoSource } from \"./seo\";\n\n/** Sanitize a post's HTML body so every consumer render is safe by default. */\nfunction sanitizePost(post: CMSBlogPost): CMSBlogPost {\n if (post && typeof post.content === \"string\") {\n return { ...post, content: sanitizeHtml(post.content) };\n }\n return post;\n}\n\n/** ISR tag for a project's blog list. */\nexport function tagsForBlogList(projectId: string): string[] {\n return [`blog:${projectId}`];\n}\n\n/** ISR tags for a single post (post-specific + project-wide). */\nexport function tagsForBlogPost(projectId: string, slug: string): string[] {\n return [`blog:${projectId}:${slug}`, `blog:${projectId}`];\n}\n\nfunction buildInit(\n tags: string[],\n options: FetchOptions,\n): RequestInit & { next?: { revalidate?: number; tags?: string[] } } {\n const skipCache = options.noStore || bypassCache();\n if (skipCache) return { cache: \"no-store\" };\n return {\n next: {\n revalidate: options.revalidate ?? DEFAULT_REVALIDATE_SECONDS,\n tags: [...tags, ...(options.extraTags ?? [])],\n },\n };\n}\n\n/**\n * Fetch published posts for the configured project, newest-first by\n * `publishedAt` (the CMS orders them — no client-side sort needed). Optional\n * filters (category/routePrefix/tag/search/limit/startAfter) are forwarded to\n * the CMS.\n *\n * Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it\n * logs a warning and returns `[]` — render an empty state instead of wrapping\n * in try/catch.\n */\nexport async function fetchBlogPosts(\n options: FetchPostsOptions = {},\n): Promise<CMSBlogPost[]> {\n const config = assertConfig();\n if (!config) return [];\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey, status: \"published\" });\n if (options.category) params.set(\"category\", options.category);\n if (options.routePrefix) params.set(\"routePrefix\", options.routePrefix);\n if (options.tag) params.set(\"tag\", options.tag);\n if (options.search) params.set(\"search\", options.search);\n if (options.limit) params.set(\"limit\", String(options.limit));\n if (options.startAfter) params.set(\"startAfter\", options.startAfter);\n\n const url = `${cmsUrl()}/api/blog?${params.toString()}`;\n const init = buildInit(tagsForBlogList(projectId), options);\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\"[cms/blog] CMS unreachable:\", (err as Error).message);\n return [];\n }\n if (res.status === 404) {\n console.warn(\"[cms/blog] /api/blog returned 404 — CMS may need redeployment\");\n return [];\n }\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog returned ${res.status}`);\n return [];\n }\n\n let json: { posts: CMSBlogPost[] };\n try {\n json = (await res.json()) as { posts: CMSBlogPost[] };\n } catch (err) {\n console.warn(\"[cms/blog] /api/blog returned non-JSON:\", (err as Error).message);\n return [];\n }\n return (json.posts ?? []).map(sanitizePost);\n}\n\n/**\n * Fetch a single post by slug. Returns null when not found.\n *\n * Never throws: CMS errors also return `null` (with a logged warning), so\n * treat `null` as \"show notFound()\" rather than catching exceptions.\n *\n * Pass `previewToken` (minted by the CMS) to render an unpublished draft for\n * review — that automatically bypasses the cache.\n */\nexport async function fetchBlogPostBySlug(\n slug: string,\n options: FetchPostOptions = {},\n): Promise<CMSBlogPost | null> {\n const config = assertConfig();\n if (!config) return null;\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey });\n if (options.previewToken) params.set(\"preview\", options.previewToken);\n\n const url = `${cmsUrl()}/api/blog/${encodeURIComponent(slug)}?${params.toString()}`;\n // Preview responses must never be cached.\n const init = buildInit(tagsForBlogPost(projectId, slug), {\n ...options,\n noStore: options.noStore || !!options.previewToken,\n });\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\n `[cms/blog] CMS unreachable for \"${slug}\":`,\n (err as Error).message,\n );\n return null;\n }\n if (res.status === 404) return null;\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog/${slug} returned ${res.status}`);\n return null;\n }\n\n let json: { post: CMSBlogPost };\n try {\n json = (await res.json()) as { post: CMSBlogPost };\n } catch (err) {\n console.warn(`[cms/blog] /api/blog/${slug} returned non-JSON:`, (err as Error).message);\n return null;\n }\n return json.post ? sanitizePost(json.post) : null;\n}\n\n/* ─── Draft preview (Next.js Draft Mode) ─── */\n\nconst PREVIEW_COOKIE = \"vt_preview_token\";\nconst PREVIEW_MAX_AGE_SECONDS = 2 * 60 * 60; // 2 hours\n\n/** Route prefix assumed when neither the post nor the CMS names one. */\nconst DEFAULT_ROUTE_PREFIX = \"blog\";\n\n/**\n * Accept a route prefix only if it is one or more plain lowercase path\n * segments (`blog`, `policies`, `legal/eu`). Anything else — empty, absolute,\n * dotted, or carrying a scheme — is rejected so the preview redirect can only\n * ever point at a same-origin page.\n *\n * @param value Candidate prefix from the post record or the query string.\n * @returns The prefix when it is safe to interpolate into a path, else null.\n */\nfunction safeRoutePrefix(value: string | null | undefined): string | null {\n if (!value) return null;\n return /^[a-z0-9-]+(?:\\/[a-z0-9-]+)*$/.test(value) ? value : null;\n}\n\n/**\n * 307 to a path on whatever origin the browser used. The Location stays\n * relative on purpose: behind a proxy, a standalone Next server builds\n * `request.url` from its bind address (`HOSTNAME=0.0.0.0`, port 3000), so an\n * absolute redirect resolved against it sent previews to\n * `https://0.0.0.0:3000/…` (BL-974). Browsers resolve a relative Location\n * against the URL they actually requested.\n *\n * @param path Absolute path (leading slash) on the current site.\n * @returns A redirect response that carries any cookies set in the handler.\n */\nfunction redirectSameOrigin(path: string): Response {\n return new NextResponse(null, { status: 307, headers: { Location: path } });\n}\n\n/**\n * Route handler for `/api/preview?token=…&slug=…`.\n *\n * Validates the token against the CMS, enables Next Draft Mode, stores the\n * token in an httpOnly cookie, and redirects to the post — which then renders\n * the draft (see resolvePreviewToken). On an invalid/expired token it just\n * redirects to the public page (which 404s if the post isn't published).\n *\n * The redirect honours the post's `routePrefix`: a post in the `policies`\n * space lands on `/policies/{slug}`, not `/blog/{slug}`. When the token is\n * invalid the post cannot be read, so the CMS also sends the prefix as\n * `?prefix=`; with neither, `/blog` is assumed. The prefix is validated as\n * plain path segments so the query string can never redirect off-site.\n *\n * Each consumer wires it up with one line:\n * // app/api/preview/route.ts\n * export { GET } from \"@vulcantech/blog\";\n */\nexport async function GET(request: NextRequest): Promise<Response> {\n const { searchParams } = new URL(request.url);\n const token = searchParams.get(\"token\");\n const slug = searchParams.get(\"slug\");\n\n if (!token || !slug) {\n return NextResponse.json(\n { error: \"token and slug are required\" },\n { status: 400 },\n );\n }\n\n // Validate by asking the CMS to resolve the draft with this token.\n const post = await fetchBlogPostBySlug(slug, { previewToken: token });\n\n const prefix =\n safeRoutePrefix(post?.routePrefix) ??\n safeRoutePrefix(searchParams.get(\"prefix\")) ??\n DEFAULT_ROUTE_PREFIX;\n const target = `/${prefix}/${encodeURIComponent(slug)}`;\n\n if (!post) {\n return redirectSameOrigin(target);\n }\n\n (await draftMode()).enable();\n (await cookies()).set(PREVIEW_COOKIE, token, {\n httpOnly: true,\n sameSite: \"lax\",\n secure: process.env.NODE_ENV === \"production\",\n path: \"/\",\n maxAge: PREVIEW_MAX_AGE_SECONDS,\n });\n\n return redirectSameOrigin(target);\n}\n\n/**\n * Page helper: returns the active preview token when Draft Mode is on, else\n * undefined. Call it in the blog post server component and spread the result\n * into the fetch:\n *\n * const previewToken = await resolvePreviewToken();\n * const post = await fetchBlogPostBySlug(slug, { previewToken });\n *\n * Reading the cookie only happens when Draft Mode is enabled, so the public\n * route stays statically rendered for normal visitors.\n */\nexport async function resolvePreviewToken(): Promise<string | undefined> {\n const { isEnabled } = await draftMode();\n if (!isEnabled) return undefined;\n const store = await cookies();\n return store.get(PREVIEW_COOKIE)?.value;\n}\n"]}
package/dist/index.mjs CHANGED
@@ -94,6 +94,21 @@ function sanitizeHtml(html) {
94
94
  return clean;
95
95
  }
96
96
 
97
+ // src/seo.ts
98
+ function present(value) {
99
+ const trimmed = value?.trim();
100
+ return trimmed ? trimmed : void 0;
101
+ }
102
+ function postSeoMeta(post) {
103
+ const seoTitle = present(post.seoTitle);
104
+ return {
105
+ title: seoTitle ?? post.title,
106
+ titleIsOverride: seoTitle !== void 0,
107
+ description: present(post.seoDescription) ?? present(post.excerpt) ?? "",
108
+ ogImage: present(post.ogImage) ?? present(post.featuredImage)
109
+ };
110
+ }
111
+
97
112
  // src/index.ts
98
113
  var DEFAULT_REVALIDATE_SECONDS = 60;
99
114
  function cmsUrl() {
@@ -209,6 +224,14 @@ async function fetchBlogPostBySlug(slug, options = {}) {
209
224
  }
210
225
  var PREVIEW_COOKIE = "vt_preview_token";
211
226
  var PREVIEW_MAX_AGE_SECONDS = 2 * 60 * 60;
227
+ var DEFAULT_ROUTE_PREFIX = "blog";
228
+ function safeRoutePrefix(value) {
229
+ if (!value) return null;
230
+ return /^[a-z0-9-]+(?:\/[a-z0-9-]+)*$/.test(value) ? value : null;
231
+ }
232
+ function redirectSameOrigin(path) {
233
+ return new NextResponse(null, { status: 307, headers: { Location: path } });
234
+ }
212
235
  async function GET(request) {
213
236
  const { searchParams } = new URL(request.url);
214
237
  const token = searchParams.get("token");
@@ -219,10 +242,11 @@ async function GET(request) {
219
242
  { status: 400 }
220
243
  );
221
244
  }
222
- const target = new URL(`/blog/${encodeURIComponent(slug)}`, request.url);
223
245
  const post = await fetchBlogPostBySlug(slug, { previewToken: token });
246
+ const prefix = safeRoutePrefix(post?.routePrefix) ?? safeRoutePrefix(searchParams.get("prefix")) ?? DEFAULT_ROUTE_PREFIX;
247
+ const target = `/${prefix}/${encodeURIComponent(slug)}`;
224
248
  if (!post) {
225
- return NextResponse.redirect(target);
249
+ return redirectSameOrigin(target);
226
250
  }
227
251
  (await draftMode()).enable();
228
252
  (await cookies()).set(PREVIEW_COOKIE, token, {
@@ -232,7 +256,7 @@ async function GET(request) {
232
256
  path: "/",
233
257
  maxAge: PREVIEW_MAX_AGE_SECONDS
234
258
  });
235
- return NextResponse.redirect(target);
259
+ return redirectSameOrigin(target);
236
260
  }
237
261
  async function resolvePreviewToken() {
238
262
  const { isEnabled } = await draftMode();
@@ -241,6 +265,6 @@ async function resolvePreviewToken() {
241
265
  return store.get(PREVIEW_COOKIE)?.value;
242
266
  }
243
267
 
244
- export { GET, fetchBlogPostBySlug, fetchBlogPosts, resolvePreviewToken, sanitizeHtml, tagsForBlogList, tagsForBlogPost };
268
+ export { GET, fetchBlogPostBySlug, fetchBlogPosts, postSeoMeta, resolvePreviewToken, sanitizeHtml, tagsForBlogList, tagsForBlogPost };
245
269
  //# sourceMappingURL=index.mjs.map
246
270
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/sanitize.ts","../src/index.ts"],"names":[],"mappings":";;;;;;AAiBA,IAAM,cAAA,GAAiB;AAAA,EACrB,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,OAAA;AAAA,EAAS,MAAA;AAAA,EAAQ,OAAA;AAAA,EAAS,UAAA;AAAA,EAC9C,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,MAAA;AAAA,EAAQ,MAAA;AAAA,EAAQ,MAAA;AAAA,EAAQ,QAAA;AAAA,EACtD,OAAA;AAAA,EAAS,UAAA;AAAA,EAAY,OAAA;AAAA,EAAS,OAAA;AAAA,EAAS,KAAA;AAAA,EAAO,MAAA;AAAA,EAAQ,KAAA;AAAA,EACtD,UAAA;AAAA,EAAY;AACd,CAAA;AASA,IAAM,iBAAA,GACJ,qGAAA;AAEF,SAAS,cAAc,CAAA,EAAmB;AACxC,EAAA,IAAI,CAAC,OAAO,QAAA,CAAS,CAAC,KAAK,CAAA,GAAI,CAAA,IAAK,CAAA,GAAI,OAAA,EAAU,OAAO,EAAA;AACzD,EAAA,IAAI;AACF,IAAA,OAAO,MAAA,CAAO,cAAc,CAAC,CAAA;AAAA,EAC/B,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAA;AAAA,EACT;AACF;AAGA,SAAS,eAAe,CAAA,EAAmB;AACzC,EAAA,OAAO,EACJ,OAAA,CAAQ,oBAAA,EAAsB,CAAC,CAAA,EAAG,MAAM,aAAA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EAAU;AACtC,EAAA,IAAI,CAAC,WAAW,OAAO,MAAA;AACvB,EAAA,MAAM,KAAA,GAAQ,MAAM,OAAA,EAAQ;AAC5B,EAAA,OAAO,KAAA,CAAM,GAAA,CAAI,cAAc,CAAA,EAAG,KAAA;AACpC","file":"index.mjs","sourcesContent":["/**\n * HTML sanitizer for user-generated (TipTap) content.\n *\n * MIRROR of packages/ui/sanitize.ts — keep in sync. Duplicated rather than\n * imported so this package stays dependency-free (no `ui` workspace coupling).\n *\n * Defense-in-depth only. As of audit L4 / BL-023, blog HTML is sanitized ON\n * WRITE by the CMS's parser-based DOMPurify sanitizer\n * (apps/vulcantech-cms/src/lib/html/sanitizeHtml.ts), so the content this\n * package fetches is already clean. This boundary pass is a safety net for\n * legacy/unexpected data, not the primary guarantee.\n *\n * Strips dangerous tags and attributes and neutralizes dangerous URL schemes,\n * decoding HTML entities first so entity-encoded `javascript:` payloads can't\n * slip past the scheme check.\n */\n\nconst DANGEROUS_TAGS = [\n \"script\", \"object\", \"embed\", \"form\", \"input\", \"textarea\",\n \"button\", \"select\", \"option\", \"link\", \"meta\", \"base\", \"applet\",\n \"frame\", \"frameset\", \"layer\", \"style\", \"svg\", \"math\", \"xmp\",\n \"noscript\", \"template\",\n];\n\n/**\n * `iframe` is NOT in the blocklist above: blog HTML may carry a YouTube video\n * embed (BL-321). It is filtered by origin instead — an iframe pointing\n * anywhere but YouTube's embed path is deleted, element and content alike, by\n * {@link stripForeignIframes}. `<video>` needs no rule: it was never blocked\n * here, and its `src` still goes through the URL-scheme pass below.\n */\nconst YOUTUBE_EMBED_SRC =\n /^https:\\/\\/(?:www\\.)?(?:youtube-nocookie\\.com|youtube\\.com)\\/embed\\/[A-Za-z0-9_-]{6,20}(?:[?#].*)?$/;\n\nfunction safeCodePoint(n: number): string {\n if (!Number.isFinite(n) || n < 0 || n > 0x10ffff) return \"\";\n try {\n return String.fromCodePoint(n);\n } catch {\n return \"\";\n }\n}\n\n/** Decode numeric and a few named HTML entities used to obfuscate URL schemes. */\nfunction decodeEntities(s: string): string {\n return s\n .replace(/&#x([0-9a-f]+);?/gi, (_, h) => safeCodePoint(parseInt(h, 16)))\n .replace(/&#(\\d+);?/g, (_, d) => safeCodePoint(parseInt(d, 10)))\n .replace(/&colon;/gi, \":\")\n .replace(/&tab;/gi, \"\\t\")\n .replace(/&newline;/gi, \"\\n\")\n .replace(/&amp;/gi, \"&\");\n}\n\n/** Drop spaces and C0 control chars (code point <= 0x20) used to break up schemes. */\nfunction stripBlankAndControl(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch.codePointAt(0)! > 0x20) out += ch;\n }\n return out;\n}\n\n/**\n * Remove every `<iframe>` whose `src` is not a YouTube embed URL, taking any\n * content between the tags with it.\n */\nfunction stripForeignIframes(html: string): string {\n return html.replace(\n /<iframe\\b[^>]*>(?:[\\s\\S]*?<\\/iframe>)?/gi,\n (element) => {\n const match = /\\bsrc\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/i.exec(element);\n const raw = match ? (match[2] ?? match[3] ?? match[4] ?? \"\") : \"\";\n const src = stripBlankAndControl(decodeEntities(raw));\n return YOUTUBE_EMBED_SRC.test(src) ? element : \"\";\n },\n );\n}\n\n/**\n * Sanitize HTML by removing dangerous tags/attributes and neutralizing unsafe\n * URL schemes. Returns the cleaned HTML string.\n *\n * The package's fetchers already run every post's `content` through this, so\n * call it only for CMS HTML obtained some other way (legacy exports, custom\n * endpoints).\n */\nexport function sanitizeHtml(html: string): string {\n if (!html) return \"\";\n\n let clean = html.replace(\n /<script\\b[^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>/gi,\n \"\",\n );\n\n for (const tag of DANGEROUS_TAGS) {\n clean = clean.replace(\n new RegExp(`<${tag}\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/${tag}>`, \"gi\"),\n \"\",\n );\n clean = clean.replace(new RegExp(`<${tag}\\\\b[^>]*\\\\/?>`, \"gi\"), \"\");\n }\n\n // Keep YouTube video embeds, drop every other iframe.\n clean = stripForeignIframes(clean);\n\n clean = clean.replace(\n /\\s+on\\w+\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\s+style\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\b(href|src)\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/gi,\n (match, attr, _raw, dq, sq, uq) => {\n const value = dq ?? sq ?? uq ?? \"\";\n const decoded = stripBlankAndControl(decodeEntities(value)).toLowerCase();\n if (/^(javascript|data|vbscript):/.test(decoded)) {\n return `${attr}=\"about:blank\"`;\n }\n return match;\n },\n );\n\n return clean;\n}\n","/**\n * @vulcantech/blog — server-side blog fetch layer for VulcanTech consumer\n * sites.\n *\n * Reads published blog posts from the CMS with Next.js ISR tags so the CMS\n * can purge a post (via /api/revalidate) the moment it changes, and supports\n * signed draft-preview tokens so an unpublished post can be rendered on the\n * real site for review.\n *\n * Config comes from the same env vars every consumer already sets — no\n * per-app wiring beyond importing this package:\n * VULCANTECH_CMS_URL (default https://cms.vulcantech.io)\n * VULCANTECH_PROJECT_ID (required)\n * VULCANTECH_API_KEY (required)\n * VULCANTECH_BLOG_NO_CACHE (\"1\" | \"true\" → bypass ISR everywhere)\n *\n * SERVER-ONLY: relies on VULCANTECH_API_KEY (no NEXT_PUBLIC_ prefix), so it\n * must only be imported from server components / route handlers.\n *\n * Errors are graceful by design — a CMS hiccup returns [] / null and logs a\n * warning rather than throwing, so a marketing site never hard-crashes on a\n * transient CMS outage.\n *\n * Draft preview (Next.js Draft Mode):\n * - Re-export `GET` from app/api/preview/route.ts on each consumer.\n * - Call `resolvePreviewToken()` in the blog post page and pass the result\n * to fetchBlogPostBySlug as { previewToken }.\n * The public /blog/[slug] route stays static/ISR; only a request carrying\n * the Draft Mode cookie renders the unpublished draft.\n */\n\nimport { cookies, draftMode } from \"next/headers\";\nimport { NextResponse, type NextRequest } from \"next/server\";\nimport { sanitizeHtml } from \"./sanitize\";\n\nconst DEFAULT_REVALIDATE_SECONDS = 60;\n\nexport interface CMSBlogAuthor {\n uid?: string;\n name: string;\n avatar?: string;\n}\n\n/**\n * A supplementary video attached to a post, normalized by the CMS.\n *\n * Structural copy of the CMS's canonical `VideoDescriptor`\n * (`packages/blog-editor-shared/src/lib/video.ts`) — inlined rather than\n * imported so this package stays dependency-free for consumer sites. Keep the\n * shape in sync; the CMS validates every write against the original.\n *\n * `videoId` is safe to interpolate into a YouTube embed URL and `url` is always\n * on the CMS media host — the CMS pins both, so a consumer never has to\n * re-validate before rendering.\n */\nexport type CMSVideoDescriptor =\n | { provider: \"youtube\"; videoId: string }\n | { provider: \"youtube-short\"; videoId: string }\n | { provider: \"file\"; url: string; poster?: string };\n\nexport interface CMSBlogPost {\n id: string;\n projectId: string;\n title: string;\n slug: string;\n /**\n * Sanitized HTML (TipTap editor output) — NOT markdown. Render with\n * `dangerouslySetInnerHTML`; do not run it through a markdown renderer.\n * Sanitized on write by the CMS and re-sanitized by this package's fetchers,\n * so it is safe to inject as-is.\n *\n * Markup contract (see the README's \"What's inside content\" for the full\n * story): headings start at h2 (h1 is yours, for the title); images are\n * plain `<img>` with no dimensions — `next/image` is not usable here, style\n * `img` with CSS; galleries are empty `div.cms-gallery[data-gallery]` nodes\n * that render as nothing unless hydrated; inline `style` never survives the\n * sanitizers, so bring your own typography (e.g. a `prose` wrapper).\n */\n content: string;\n /** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */\n excerpt: string;\n /** Single editorial bucket (one per post) — distinct from the free-form `tags`. */\n category?: string;\n /** URL route segment the post lives under, e.g. \"blog\" or \"documentation\". */\n routePrefix?: string;\n tags: string[];\n /**\n * Comma-separated SEO keywords the CMS derives from the post's dedicated\n * keyword fields (target keyword first). Feed straight into\n * `Metadata.keywords`; absent when the post has no keywords set.\n */\n keywords?: string;\n /** An object, not a string — display `author.name`. */\n author: CMSBlogAuthor;\n /** In-page hero / card image URL. For social cards use `ogImage ?? featuredImage`. */\n featuredImage?: string;\n /**\n * Optional supplementary video for the post. Purely advisory — render it as a\n * hero player, a card thumbnail, or ignore it; nothing breaks when it's\n * absent, and it is absent on most posts. Videos placed *inside* the article\n * arrive as playable markup within `content` instead.\n */\n featuredVideo?: CMSVideoDescriptor;\n /** The public fetchers only ever return \"published\" posts (or a token-unlocked draft). */\n status: \"draft\" | \"in_review\" | \"published\" | \"archived\";\n /** ISO 8601 timestamp. Always present on published posts. */\n publishedAt?: string;\n /** ISO 8601 timestamp for scheduled publishing; the post stays hidden until then. */\n scheduledAt?: string;\n /** ISO 8601 timestamp. */\n createdAt: string;\n /** ISO 8601 timestamp. */\n updatedAt: string;\n /** SERP/social title override. Canonical fallback: `seoTitle ?? title`. */\n seoTitle?: string;\n /** Meta-description override. Canonical fallback: `seoDescription ?? excerpt`. */\n seoDescription?: string;\n /** Social-share card image URL. Canonical fallback: `ogImage ?? featuredImage`. */\n ogImage?: string;\n /** Defaults to \"article\" when absent (the field predates postType). */\n postType?: \"article\" | \"case-study\" | \"announcement\";\n /**\n * Spec-sheet pairs for case studies (e.g. `{ label: \"Make\", value: \"1969\n * Camaro\" }`) — the CMS only shows this editor when `postType` is\n * \"case-study\". Render as a spec table on case-study layouts; ignore\n * everywhere else.\n */\n metadata?: { label: string; value: string }[];\n}\n\nexport interface FetchOptions {\n /** Override the per-fetch revalidate window. Default: 60 seconds. */\n revalidate?: number;\n /** Extra ISR tags to attach to the fetch. */\n extraTags?: string[];\n /** Skip Next's ISR cache for this call. */\n noStore?: boolean;\n}\n\n/**\n * List filters, all applied server-side by the CMS — prefer these over\n * fetching everything and filtering client-side.\n */\nexport interface FetchPostsOptions extends FetchOptions {\n /** Exact-match on the post's `category`. */\n category?: string;\n /**\n * Only return posts under this route prefix (e.g. \"documentation\"). Don't\n * pass \"blog\" for the blog itself — legacy posts predate the field and have\n * no prefix, so they'd be excluded; filter the blog list client-side instead\n * (see the README's Scoped routes section).\n */\n routePrefix?: string;\n /** Posts whose `tags` include this tag. */\n tag?: string;\n /** Full-text search across title/content. */\n search?: string;\n /**\n * Page size; combine with `startAfter` to paginate. The response carries no\n * `hasMore`/`total` — fetch `limit + 1`, and if more than `limit` arrive\n * there is another page (drop the extra).\n */\n limit?: number;\n /** Pagination cursor: the `id` of the last post from the previous page. */\n startAfter?: string;\n}\n\nexport interface FetchPostOptions extends FetchOptions {\n /**\n * A signed preview token (from the CMS) that unlocks an unpublished post.\n * When set, the cache is bypassed automatically — preview content must\n * never be cached or served to the public.\n */\n previewToken?: string;\n}\n\nfunction cmsUrl(): string {\n return process.env.VULCANTECH_CMS_URL || \"https://cms.vulcantech.io\";\n}\n\nfunction bypassCache(): boolean {\n return (\n process.env.VULCANTECH_BLOG_NO_CACHE === \"1\" ||\n process.env.VULCANTECH_BLOG_NO_CACHE === \"true\"\n );\n}\n\nfunction assertConfig(): { projectId: string; apiKey: string } | null {\n const projectId = process.env.VULCANTECH_PROJECT_ID;\n const apiKey = process.env.VULCANTECH_API_KEY;\n if (!projectId || !apiKey) {\n console.warn(\n \"[cms/blog] CMS not configured — set VULCANTECH_PROJECT_ID and VULCANTECH_API_KEY\",\n );\n return null;\n }\n return { projectId, apiKey };\n}\n\nexport { sanitizeHtml };\n\n/** Sanitize a post's HTML body so every consumer render is safe by default. */\nfunction sanitizePost(post: CMSBlogPost): CMSBlogPost {\n if (post && typeof post.content === \"string\") {\n return { ...post, content: sanitizeHtml(post.content) };\n }\n return post;\n}\n\n/** ISR tag for a project's blog list. */\nexport function tagsForBlogList(projectId: string): string[] {\n return [`blog:${projectId}`];\n}\n\n/** ISR tags for a single post (post-specific + project-wide). */\nexport function tagsForBlogPost(projectId: string, slug: string): string[] {\n return [`blog:${projectId}:${slug}`, `blog:${projectId}`];\n}\n\nfunction buildInit(\n tags: string[],\n options: FetchOptions,\n): RequestInit & { next?: { revalidate?: number; tags?: string[] } } {\n const skipCache = options.noStore || bypassCache();\n if (skipCache) return { cache: \"no-store\" };\n return {\n next: {\n revalidate: options.revalidate ?? DEFAULT_REVALIDATE_SECONDS,\n tags: [...tags, ...(options.extraTags ?? [])],\n },\n };\n}\n\n/**\n * Fetch published posts for the configured project, newest-first by\n * `publishedAt` (the CMS orders them — no client-side sort needed). Optional\n * filters (category/routePrefix/tag/search/limit/startAfter) are forwarded to\n * the CMS.\n *\n * Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it\n * logs a warning and returns `[]` — render an empty state instead of wrapping\n * in try/catch.\n */\nexport async function fetchBlogPosts(\n options: FetchPostsOptions = {},\n): Promise<CMSBlogPost[]> {\n const config = assertConfig();\n if (!config) return [];\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey, status: \"published\" });\n if (options.category) params.set(\"category\", options.category);\n if (options.routePrefix) params.set(\"routePrefix\", options.routePrefix);\n if (options.tag) params.set(\"tag\", options.tag);\n if (options.search) params.set(\"search\", options.search);\n if (options.limit) params.set(\"limit\", String(options.limit));\n if (options.startAfter) params.set(\"startAfter\", options.startAfter);\n\n const url = `${cmsUrl()}/api/blog?${params.toString()}`;\n const init = buildInit(tagsForBlogList(projectId), options);\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\"[cms/blog] CMS unreachable:\", (err as Error).message);\n return [];\n }\n if (res.status === 404) {\n console.warn(\"[cms/blog] /api/blog returned 404 — CMS may need redeployment\");\n return [];\n }\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog returned ${res.status}`);\n return [];\n }\n\n let json: { posts: CMSBlogPost[] };\n try {\n json = (await res.json()) as { posts: CMSBlogPost[] };\n } catch (err) {\n console.warn(\"[cms/blog] /api/blog returned non-JSON:\", (err as Error).message);\n return [];\n }\n return (json.posts ?? []).map(sanitizePost);\n}\n\n/**\n * Fetch a single post by slug. Returns null when not found.\n *\n * Never throws: CMS errors also return `null` (with a logged warning), so\n * treat `null` as \"show notFound()\" rather than catching exceptions.\n *\n * Pass `previewToken` (minted by the CMS) to render an unpublished draft for\n * review — that automatically bypasses the cache.\n */\nexport async function fetchBlogPostBySlug(\n slug: string,\n options: FetchPostOptions = {},\n): Promise<CMSBlogPost | null> {\n const config = assertConfig();\n if (!config) return null;\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey });\n if (options.previewToken) params.set(\"preview\", options.previewToken);\n\n const url = `${cmsUrl()}/api/blog/${encodeURIComponent(slug)}?${params.toString()}`;\n // Preview responses must never be cached.\n const init = buildInit(tagsForBlogPost(projectId, slug), {\n ...options,\n noStore: options.noStore || !!options.previewToken,\n });\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\n `[cms/blog] CMS unreachable for \"${slug}\":`,\n (err as Error).message,\n );\n return null;\n }\n if (res.status === 404) return null;\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog/${slug} returned ${res.status}`);\n return null;\n }\n\n let json: { post: CMSBlogPost };\n try {\n json = (await res.json()) as { post: CMSBlogPost };\n } catch (err) {\n console.warn(`[cms/blog] /api/blog/${slug} returned non-JSON:`, (err as Error).message);\n return null;\n }\n return json.post ? sanitizePost(json.post) : null;\n}\n\n/* ─── Draft preview (Next.js Draft Mode) ─── */\n\nconst PREVIEW_COOKIE = \"vt_preview_token\";\nconst PREVIEW_MAX_AGE_SECONDS = 2 * 60 * 60; // 2 hours\n\n/**\n * Route handler for `/api/preview?token=…&slug=…`.\n *\n * Validates the token against the CMS, enables Next Draft Mode, stores the\n * token in an httpOnly cookie, and redirects to the post — which then renders\n * the draft (see resolvePreviewToken). On an invalid/expired token it just\n * redirects to the public page (which 404s if the post isn't published).\n *\n * Each consumer wires it up with one line:\n * // app/api/preview/route.ts\n * export { GET } from \"@vulcantech/blog\";\n */\nexport async function GET(request: NextRequest): Promise<Response> {\n const { searchParams } = new URL(request.url);\n const token = searchParams.get(\"token\");\n const slug = searchParams.get(\"slug\");\n\n if (!token || !slug) {\n return NextResponse.json(\n { error: \"token and slug are required\" },\n { status: 400 },\n );\n }\n\n const target = new URL(`/blog/${encodeURIComponent(slug)}`, request.url);\n\n // Validate by asking the CMS to resolve the draft with this token.\n const post = await fetchBlogPostBySlug(slug, { previewToken: token });\n if (!post) {\n return NextResponse.redirect(target);\n }\n\n (await draftMode()).enable();\n (await cookies()).set(PREVIEW_COOKIE, token, {\n httpOnly: true,\n sameSite: \"lax\",\n secure: process.env.NODE_ENV === \"production\",\n path: \"/\",\n maxAge: PREVIEW_MAX_AGE_SECONDS,\n });\n\n return NextResponse.redirect(target);\n}\n\n/**\n * Page helper: returns the active preview token when Draft Mode is on, else\n * undefined. Call it in the blog post server component and spread the result\n * into the fetch:\n *\n * const previewToken = await resolvePreviewToken();\n * const post = await fetchBlogPostBySlug(slug, { previewToken });\n *\n * Reading the cookie only happens when Draft Mode is enabled, so the public\n * route stays statically rendered for normal visitors.\n */\nexport async function resolvePreviewToken(): Promise<string | undefined> {\n const { isEnabled } = await draftMode();\n if (!isEnabled) return undefined;\n const store = await cookies();\n return store.get(PREVIEW_COOKIE)?.value;\n}\n"]}
1
+ {"version":3,"sources":["../src/sanitize.ts","../src/seo.ts","../src/index.ts"],"names":[],"mappings":";;;;;;AAiBA,IAAM,cAAA,GAAiB;AAAA,EACrB,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,OAAA;AAAA,EAAS,MAAA;AAAA,EAAQ,OAAA;AAAA,EAAS,UAAA;AAAA,EAC9C,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,QAAA;AAAA,EAAU,MAAA;AAAA,EAAQ,MAAA;AAAA,EAAQ,MAAA;AAAA,EAAQ,QAAA;AAAA,EACtD,OAAA;AAAA,EAAS,UAAA;AAAA,EAAY,OAAA;AAAA,EAAS,OAAA;AAAA,EAAS,KAAA;AAAA,EAAO,MAAA;AAAA,EAAQ,KAAA;AAAA,EACtD,UAAA;AAAA,EAAY;AACd,CAAA;AASA,IAAM,iBAAA,GACJ,qGAAA;AAEF,SAAS,cAAc,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AA,IACN,MAAA,EAAQ;AAAA,GACT,CAAA;AAED,EAAA,OAAO,mBAAmB,MAAM,CAAA;AAClC;AAaA,eAAsB,mBAAA,GAAmD;AACvE,EAAA,MAAM,EAAE,SAAA,EAAU,GAAI,MAAM,SAAA,EAAU;AACtC,EAAA,IAAI,CAAC,WAAW,OAAO,MAAA;AACvB,EAAA,MAAM,KAAA,GAAQ,MAAM,OAAA,EAAQ;AAC5B,EAAA,OAAO,KAAA,CAAM,GAAA,CAAI,cAAc,CAAA,EAAG,KAAA;AACpC","file":"index.mjs","sourcesContent":["/**\n * HTML sanitizer for user-generated (TipTap) content.\n *\n * MIRROR of packages/ui/sanitize.ts — keep in sync. Duplicated rather than\n * imported so this package stays dependency-free (no `ui` workspace coupling).\n *\n * Defense-in-depth only. As of audit L4 / BL-023, blog HTML is sanitized ON\n * WRITE by the CMS's parser-based DOMPurify sanitizer\n * (apps/vulcantech-cms/src/lib/html/sanitizeHtml.ts), so the content this\n * package fetches is already clean. This boundary pass is a safety net for\n * legacy/unexpected data, not the primary guarantee.\n *\n * Strips dangerous tags and attributes and neutralizes dangerous URL schemes,\n * decoding HTML entities first so entity-encoded `javascript:` payloads can't\n * slip past the scheme check.\n */\n\nconst DANGEROUS_TAGS = [\n \"script\", \"object\", \"embed\", \"form\", \"input\", \"textarea\",\n \"button\", \"select\", \"option\", \"link\", \"meta\", \"base\", \"applet\",\n \"frame\", \"frameset\", \"layer\", \"style\", \"svg\", \"math\", \"xmp\",\n \"noscript\", \"template\",\n];\n\n/**\n * `iframe` is NOT in the blocklist above: blog HTML may carry a YouTube video\n * embed (BL-321). It is filtered by origin instead — an iframe pointing\n * anywhere but YouTube's embed path is deleted, element and content alike, by\n * {@link stripForeignIframes}. `<video>` needs no rule: it was never blocked\n * here, and its `src` still goes through the URL-scheme pass below.\n */\nconst YOUTUBE_EMBED_SRC =\n /^https:\\/\\/(?:www\\.)?(?:youtube-nocookie\\.com|youtube\\.com)\\/embed\\/[A-Za-z0-9_-]{6,20}(?:[?#].*)?$/;\n\nfunction safeCodePoint(n: number): string {\n if (!Number.isFinite(n) || n < 0 || n > 0x10ffff) return \"\";\n try {\n return String.fromCodePoint(n);\n } catch {\n return \"\";\n }\n}\n\n/** Decode numeric and a few named HTML entities used to obfuscate URL schemes. */\nfunction decodeEntities(s: string): string {\n return s\n .replace(/&#x([0-9a-f]+);?/gi, (_, h) => safeCodePoint(parseInt(h, 16)))\n .replace(/&#(\\d+);?/g, (_, d) => safeCodePoint(parseInt(d, 10)))\n .replace(/&colon;/gi, \":\")\n .replace(/&tab;/gi, \"\\t\")\n .replace(/&newline;/gi, \"\\n\")\n .replace(/&amp;/gi, \"&\");\n}\n\n/** Drop spaces and C0 control chars (code point <= 0x20) used to break up schemes. */\nfunction stripBlankAndControl(s: string): string {\n let out = \"\";\n for (const ch of s) {\n if (ch.codePointAt(0)! > 0x20) out += ch;\n }\n return out;\n}\n\n/**\n * Remove every `<iframe>` whose `src` is not a YouTube embed URL, taking any\n * content between the tags with it.\n */\nfunction stripForeignIframes(html: string): string {\n return html.replace(\n /<iframe\\b[^>]*>(?:[\\s\\S]*?<\\/iframe>)?/gi,\n (element) => {\n const match = /\\bsrc\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/i.exec(element);\n const raw = match ? (match[2] ?? match[3] ?? match[4] ?? \"\") : \"\";\n const src = stripBlankAndControl(decodeEntities(raw));\n return YOUTUBE_EMBED_SRC.test(src) ? element : \"\";\n },\n );\n}\n\n/**\n * Sanitize HTML by removing dangerous tags/attributes and neutralizing unsafe\n * URL schemes. Returns the cleaned HTML string.\n *\n * The package's fetchers already run every post's `content` through this, so\n * call it only for CMS HTML obtained some other way (legacy exports, custom\n * endpoints).\n */\nexport function sanitizeHtml(html: string): string {\n if (!html) return \"\";\n\n let clean = html.replace(\n /<script\\b[^<]*(?:(?!<\\/script>)<[^<]*)*<\\/script>/gi,\n \"\",\n );\n\n for (const tag of DANGEROUS_TAGS) {\n clean = clean.replace(\n new RegExp(`<${tag}\\\\b[^>]*>[\\\\s\\\\S]*?<\\\\/${tag}>`, \"gi\"),\n \"\",\n );\n clean = clean.replace(new RegExp(`<${tag}\\\\b[^>]*\\\\/?>`, \"gi\"), \"\");\n }\n\n // Keep YouTube video embeds, drop every other iframe.\n clean = stripForeignIframes(clean);\n\n clean = clean.replace(\n /\\s+on\\w+\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\s+style\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s>]*)/gi,\n \"\",\n );\n\n clean = clean.replace(\n /\\b(href|src)\\s*=\\s*(\"([^\"]*)\"|'([^']*)'|([^\\s>]+))/gi,\n (match, attr, _raw, dq, sq, uq) => {\n const value = dq ?? sq ?? uq ?? \"\";\n const decoded = stripBlankAndControl(decodeEntities(value)).toLowerCase();\n if (/^(javascript|data|vbscript):/.test(decoded)) {\n return `${attr}=\"about:blank\"`;\n }\n return match;\n },\n );\n\n return clean;\n}\n","/**\n * Blank-safe SEO fallbacks for a CMS blog post.\n *\n * The CMS editor saves a cleared SEO-panel field as `\"\"`, not as an absent\n * field, so a `seoTitle ?? title` chain keeps the empty string and the page\n * ships an empty `<title>` / description. Every consumer reads its overrides\n * through `postSeoMeta` instead, so the fallback rules live in one place.\n *\n * Pure (no `next/*` imports) — safe anywhere, including client components.\n */\n\n/** The post fields `postSeoMeta` reads — any `CMSBlogPost` satisfies it. */\nexport interface PostSeoSource {\n title: string;\n excerpt?: string;\n seoTitle?: string;\n seoDescription?: string;\n ogImage?: string;\n featuredImage?: string;\n}\n\n/** Resolved SEO values for one post. */\nexport interface PostSeoMeta {\n /** The author's `seoTitle` when set, else the post title. */\n title: string;\n /**\n * True when `title` is the author's `seoTitle`. That is a complete SERP\n * title, so emit it as `title: { absolute: title }` — otherwise the\n * layout's `%s - Site` template brands it a second time.\n */\n titleIsOverride: boolean;\n /** The `seoDescription` override when set, else the excerpt (\"\" if neither). */\n description: string;\n /** Social-card image: the `ogImage` override, else `featuredImage`. */\n ogImage?: string;\n}\n\n/** Trims a value to `undefined` when it is missing or whitespace-only. */\nfunction present(value: string | undefined | null): string | undefined {\n const trimmed = value?.trim();\n return trimmed ? trimmed : undefined;\n}\n\n/**\n * Resolves a post's title, meta description and social image from its CMS\n * SEO overrides, treating blank overrides as unset.\n *\n * @param post - A CMS blog post (or any object with the same SEO fields).\n * @returns The resolved title (plus whether it is an override), description\n * and optional og image.\n *\n * @example\n * const seo = postSeoMeta(post);\n * return {\n * title: seo.titleIsOverride ? { absolute: seo.title } : seo.title,\n * description: seo.description,\n * openGraph: { images: seo.ogImage ? [seo.ogImage] : undefined },\n * };\n */\nexport function postSeoMeta(post: PostSeoSource): PostSeoMeta {\n const seoTitle = present(post.seoTitle);\n return {\n title: seoTitle ?? post.title,\n titleIsOverride: seoTitle !== undefined,\n description: present(post.seoDescription) ?? present(post.excerpt) ?? \"\",\n ogImage: present(post.ogImage) ?? present(post.featuredImage),\n };\n}\n","/**\n * @vulcantech/blog — server-side blog fetch layer for VulcanTech consumer\n * sites.\n *\n * Reads published blog posts from the CMS with Next.js ISR tags so the CMS\n * can purge a post (via /api/revalidate) the moment it changes, and supports\n * signed draft-preview tokens so an unpublished post can be rendered on the\n * real site for review.\n *\n * Config comes from the same env vars every consumer already sets — no\n * per-app wiring beyond importing this package:\n * VULCANTECH_CMS_URL (default https://cms.vulcantech.io)\n * VULCANTECH_PROJECT_ID (required)\n * VULCANTECH_API_KEY (required)\n * VULCANTECH_BLOG_NO_CACHE (\"1\" | \"true\" → bypass ISR everywhere)\n *\n * SERVER-ONLY: relies on VULCANTECH_API_KEY (no NEXT_PUBLIC_ prefix), so it\n * must only be imported from server components / route handlers.\n *\n * Errors are graceful by design — a CMS hiccup returns [] / null and logs a\n * warning rather than throwing, so a marketing site never hard-crashes on a\n * transient CMS outage.\n *\n * Draft preview (Next.js Draft Mode):\n * - Re-export `GET` from app/api/preview/route.ts on each consumer.\n * - Call `resolvePreviewToken()` in the blog post page and pass the result\n * to fetchBlogPostBySlug as { previewToken }.\n * The public /blog/[slug] route stays static/ISR; only a request carrying\n * the Draft Mode cookie renders the unpublished draft.\n */\n\nimport { cookies, draftMode } from \"next/headers\";\nimport { NextResponse, type NextRequest } from \"next/server\";\nimport { sanitizeHtml } from \"./sanitize\";\n\nconst DEFAULT_REVALIDATE_SECONDS = 60;\n\nexport interface CMSBlogAuthor {\n uid?: string;\n name: string;\n avatar?: string;\n}\n\n/**\n * A supplementary video attached to a post, normalized by the CMS.\n *\n * Structural copy of the CMS's canonical `VideoDescriptor`\n * (`packages/blog-editor-shared/src/lib/video.ts`) — inlined rather than\n * imported so this package stays dependency-free for consumer sites. Keep the\n * shape in sync; the CMS validates every write against the original.\n *\n * `videoId` is safe to interpolate into a YouTube embed URL and `url` is always\n * on the CMS media host — the CMS pins both, so a consumer never has to\n * re-validate before rendering.\n */\nexport type CMSVideoDescriptor =\n | { provider: \"youtube\"; videoId: string }\n | { provider: \"youtube-short\"; videoId: string }\n | { provider: \"file\"; url: string; poster?: string };\n\nexport interface CMSBlogPost {\n id: string;\n projectId: string;\n title: string;\n slug: string;\n /**\n * Sanitized HTML (TipTap editor output) — NOT markdown. Render with\n * `dangerouslySetInnerHTML`; do not run it through a markdown renderer.\n * Sanitized on write by the CMS and re-sanitized by this package's fetchers,\n * so it is safe to inject as-is.\n *\n * Markup contract (see the README's \"What's inside content\" for the full\n * story): headings start at h2 (h1 is yours, for the title); images are\n * plain `<img>` with no dimensions — `next/image` is not usable here, style\n * `img` with CSS; galleries are empty `div.cms-gallery[data-gallery]` nodes\n * that render as nothing unless hydrated; inline `style` never survives the\n * sanitizers, so bring your own typography (e.g. a `prose` wrapper).\n */\n content: string;\n /** Plain-text summary. Meta-description fallback — read it via `postSeoMeta`. */\n excerpt: string;\n /** Single editorial bucket (one per post) — distinct from the free-form `tags`. */\n category?: string;\n /** URL route segment the post lives under, e.g. \"blog\" or \"documentation\". */\n routePrefix?: string;\n tags: string[];\n /**\n * Comma-separated SEO keywords the CMS derives from the post's dedicated\n * keyword fields (target keyword first). Feed straight into\n * `Metadata.keywords`; absent when the post has no keywords set.\n */\n keywords?: string;\n /** An object, not a string — display `author.name`. */\n author: CMSBlogAuthor;\n /** In-page hero / card image URL. For social cards use `postSeoMeta(post).ogImage`. */\n featuredImage?: string;\n /**\n * Optional supplementary video for the post. Purely advisory — render it as a\n * hero player, a card thumbnail, or ignore it; nothing breaks when it's\n * absent, and it is absent on most posts. Videos placed *inside* the article\n * arrive as playable markup within `content` instead.\n */\n featuredVideo?: CMSVideoDescriptor;\n /**\n * The public fetchers only ever return \"published\" posts (or a token-unlocked\n * draft in preview). `\"scheduled\"` means \"goes live at `scheduledAt`\": the\n * CMS flips it to `\"published\"` at that time, and until then it is never\n * served — so a consumer never needs to compare dates itself.\n */\n status: \"draft\" | \"in_review\" | \"scheduled\" | \"published\" | \"archived\";\n /**\n * ISO 8601 timestamp the post went live; drives sort order. Always present\n * on published posts (for a formerly scheduled post it equals `scheduledAt`\n * unless an author set it explicitly).\n */\n publishedAt?: string;\n /** ISO 8601 timestamp a `scheduled` post goes live; kept as a record after it does. */\n scheduledAt?: string;\n /** ISO 8601 timestamp. */\n createdAt: string;\n /** ISO 8601 timestamp. */\n updatedAt: string;\n /**\n * SERP/social title override — may be `\"\"` when an author clears it. Read\n * it via `postSeoMeta`, never `seoTitle ?? title` (keeps the blank).\n */\n seoTitle?: string;\n /** Meta-description override — may be `\"\"`. Read it via `postSeoMeta`. */\n seoDescription?: string;\n /** Social-share card image URL — may be `\"\"`. Read it via `postSeoMeta`. */\n ogImage?: string;\n /** Defaults to \"article\" when absent (the field predates postType). */\n postType?: \"article\" | \"case-study\" | \"announcement\";\n /**\n * Spec-sheet pairs for case studies (e.g. `{ label: \"Make\", value: \"1969\n * Camaro\" }`) — the CMS only shows this editor when `postType` is\n * \"case-study\". Render as a spec table on case-study layouts; ignore\n * everywhere else.\n */\n metadata?: { label: string; value: string }[];\n}\n\nexport interface FetchOptions {\n /** Override the per-fetch revalidate window. Default: 60 seconds. */\n revalidate?: number;\n /** Extra ISR tags to attach to the fetch. */\n extraTags?: string[];\n /** Skip Next's ISR cache for this call. */\n noStore?: boolean;\n}\n\n/**\n * List filters, all applied server-side by the CMS — prefer these over\n * fetching everything and filtering client-side.\n */\nexport interface FetchPostsOptions extends FetchOptions {\n /** Exact-match on the post's `category`. */\n category?: string;\n /**\n * Only return posts under this route prefix (e.g. \"documentation\"). Don't\n * pass \"blog\" for the blog itself — legacy posts predate the field and have\n * no prefix, so they'd be excluded; filter the blog list client-side instead\n * (see the README's Scoped routes section).\n */\n routePrefix?: string;\n /** Posts whose `tags` include this tag. */\n tag?: string;\n /** Full-text search across title/content. */\n search?: string;\n /**\n * Page size; combine with `startAfter` to paginate. The response carries no\n * `hasMore`/`total` — fetch `limit + 1`, and if more than `limit` arrive\n * there is another page (drop the extra).\n */\n limit?: number;\n /** Pagination cursor: the `id` of the last post from the previous page. */\n startAfter?: string;\n}\n\nexport interface FetchPostOptions extends FetchOptions {\n /**\n * A signed preview token (from the CMS) that unlocks an unpublished post.\n * When set, the cache is bypassed automatically — preview content must\n * never be cached or served to the public.\n */\n previewToken?: string;\n}\n\nfunction cmsUrl(): string {\n return process.env.VULCANTECH_CMS_URL || \"https://cms.vulcantech.io\";\n}\n\nfunction bypassCache(): boolean {\n return (\n process.env.VULCANTECH_BLOG_NO_CACHE === \"1\" ||\n process.env.VULCANTECH_BLOG_NO_CACHE === \"true\"\n );\n}\n\nfunction assertConfig(): { projectId: string; apiKey: string } | null {\n const projectId = process.env.VULCANTECH_PROJECT_ID;\n const apiKey = process.env.VULCANTECH_API_KEY;\n if (!projectId || !apiKey) {\n console.warn(\n \"[cms/blog] CMS not configured — set VULCANTECH_PROJECT_ID and VULCANTECH_API_KEY\",\n );\n return null;\n }\n return { projectId, apiKey };\n}\n\nexport { sanitizeHtml };\nexport { postSeoMeta, type PostSeoMeta, type PostSeoSource } from \"./seo\";\n\n/** Sanitize a post's HTML body so every consumer render is safe by default. */\nfunction sanitizePost(post: CMSBlogPost): CMSBlogPost {\n if (post && typeof post.content === \"string\") {\n return { ...post, content: sanitizeHtml(post.content) };\n }\n return post;\n}\n\n/** ISR tag for a project's blog list. */\nexport function tagsForBlogList(projectId: string): string[] {\n return [`blog:${projectId}`];\n}\n\n/** ISR tags for a single post (post-specific + project-wide). */\nexport function tagsForBlogPost(projectId: string, slug: string): string[] {\n return [`blog:${projectId}:${slug}`, `blog:${projectId}`];\n}\n\nfunction buildInit(\n tags: string[],\n options: FetchOptions,\n): RequestInit & { next?: { revalidate?: number; tags?: string[] } } {\n const skipCache = options.noStore || bypassCache();\n if (skipCache) return { cache: \"no-store\" };\n return {\n next: {\n revalidate: options.revalidate ?? DEFAULT_REVALIDATE_SECONDS,\n tags: [...tags, ...(options.extraTags ?? [])],\n },\n };\n}\n\n/**\n * Fetch published posts for the configured project, newest-first by\n * `publishedAt` (the CMS orders them — no client-side sort needed). Optional\n * filters (category/routePrefix/tag/search/limit/startAfter) are forwarded to\n * the CMS.\n *\n * Never throws: on any CMS error (unreachable, non-2xx, unconfigured env) it\n * logs a warning and returns `[]` — render an empty state instead of wrapping\n * in try/catch.\n */\nexport async function fetchBlogPosts(\n options: FetchPostsOptions = {},\n): Promise<CMSBlogPost[]> {\n const config = assertConfig();\n if (!config) return [];\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey, status: \"published\" });\n if (options.category) params.set(\"category\", options.category);\n if (options.routePrefix) params.set(\"routePrefix\", options.routePrefix);\n if (options.tag) params.set(\"tag\", options.tag);\n if (options.search) params.set(\"search\", options.search);\n if (options.limit) params.set(\"limit\", String(options.limit));\n if (options.startAfter) params.set(\"startAfter\", options.startAfter);\n\n const url = `${cmsUrl()}/api/blog?${params.toString()}`;\n const init = buildInit(tagsForBlogList(projectId), options);\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\"[cms/blog] CMS unreachable:\", (err as Error).message);\n return [];\n }\n if (res.status === 404) {\n console.warn(\"[cms/blog] /api/blog returned 404 — CMS may need redeployment\");\n return [];\n }\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog returned ${res.status}`);\n return [];\n }\n\n let json: { posts: CMSBlogPost[] };\n try {\n json = (await res.json()) as { posts: CMSBlogPost[] };\n } catch (err) {\n console.warn(\"[cms/blog] /api/blog returned non-JSON:\", (err as Error).message);\n return [];\n }\n return (json.posts ?? []).map(sanitizePost);\n}\n\n/**\n * Fetch a single post by slug. Returns null when not found.\n *\n * Never throws: CMS errors also return `null` (with a logged warning), so\n * treat `null` as \"show notFound()\" rather than catching exceptions.\n *\n * Pass `previewToken` (minted by the CMS) to render an unpublished draft for\n * review — that automatically bypasses the cache.\n */\nexport async function fetchBlogPostBySlug(\n slug: string,\n options: FetchPostOptions = {},\n): Promise<CMSBlogPost | null> {\n const config = assertConfig();\n if (!config) return null;\n const { projectId, apiKey } = config;\n\n const params = new URLSearchParams({ projectId, apiKey });\n if (options.previewToken) params.set(\"preview\", options.previewToken);\n\n const url = `${cmsUrl()}/api/blog/${encodeURIComponent(slug)}?${params.toString()}`;\n // Preview responses must never be cached.\n const init = buildInit(tagsForBlogPost(projectId, slug), {\n ...options,\n noStore: options.noStore || !!options.previewToken,\n });\n\n let res: Response;\n try {\n res = await fetch(url, init);\n } catch (err) {\n console.warn(\n `[cms/blog] CMS unreachable for \"${slug}\":`,\n (err as Error).message,\n );\n return null;\n }\n if (res.status === 404) return null;\n if (!res.ok) {\n console.warn(`[cms/blog] /api/blog/${slug} returned ${res.status}`);\n return null;\n }\n\n let json: { post: CMSBlogPost };\n try {\n json = (await res.json()) as { post: CMSBlogPost };\n } catch (err) {\n console.warn(`[cms/blog] /api/blog/${slug} returned non-JSON:`, (err as Error).message);\n return null;\n }\n return json.post ? sanitizePost(json.post) : null;\n}\n\n/* ─── Draft preview (Next.js Draft Mode) ─── */\n\nconst PREVIEW_COOKIE = \"vt_preview_token\";\nconst PREVIEW_MAX_AGE_SECONDS = 2 * 60 * 60; // 2 hours\n\n/** Route prefix assumed when neither the post nor the CMS names one. */\nconst DEFAULT_ROUTE_PREFIX = \"blog\";\n\n/**\n * Accept a route prefix only if it is one or more plain lowercase path\n * segments (`blog`, `policies`, `legal/eu`). Anything else — empty, absolute,\n * dotted, or carrying a scheme — is rejected so the preview redirect can only\n * ever point at a same-origin page.\n *\n * @param value Candidate prefix from the post record or the query string.\n * @returns The prefix when it is safe to interpolate into a path, else null.\n */\nfunction safeRoutePrefix(value: string | null | undefined): string | null {\n if (!value) return null;\n return /^[a-z0-9-]+(?:\\/[a-z0-9-]+)*$/.test(value) ? value : null;\n}\n\n/**\n * 307 to a path on whatever origin the browser used. The Location stays\n * relative on purpose: behind a proxy, a standalone Next server builds\n * `request.url` from its bind address (`HOSTNAME=0.0.0.0`, port 3000), so an\n * absolute redirect resolved against it sent previews to\n * `https://0.0.0.0:3000/…` (BL-974). Browsers resolve a relative Location\n * against the URL they actually requested.\n *\n * @param path Absolute path (leading slash) on the current site.\n * @returns A redirect response that carries any cookies set in the handler.\n */\nfunction redirectSameOrigin(path: string): Response {\n return new NextResponse(null, { status: 307, headers: { Location: path } });\n}\n\n/**\n * Route handler for `/api/preview?token=…&slug=…`.\n *\n * Validates the token against the CMS, enables Next Draft Mode, stores the\n * token in an httpOnly cookie, and redirects to the post — which then renders\n * the draft (see resolvePreviewToken). On an invalid/expired token it just\n * redirects to the public page (which 404s if the post isn't published).\n *\n * The redirect honours the post's `routePrefix`: a post in the `policies`\n * space lands on `/policies/{slug}`, not `/blog/{slug}`. When the token is\n * invalid the post cannot be read, so the CMS also sends the prefix as\n * `?prefix=`; with neither, `/blog` is assumed. The prefix is validated as\n * plain path segments so the query string can never redirect off-site.\n *\n * Each consumer wires it up with one line:\n * // app/api/preview/route.ts\n * export { GET } from \"@vulcantech/blog\";\n */\nexport async function GET(request: NextRequest): Promise<Response> {\n const { searchParams } = new URL(request.url);\n const token = searchParams.get(\"token\");\n const slug = searchParams.get(\"slug\");\n\n if (!token || !slug) {\n return NextResponse.json(\n { error: \"token and slug are required\" },\n { status: 400 },\n );\n }\n\n // Validate by asking the CMS to resolve the draft with this token.\n const post = await fetchBlogPostBySlug(slug, { previewToken: token });\n\n const prefix =\n safeRoutePrefix(post?.routePrefix) ??\n safeRoutePrefix(searchParams.get(\"prefix\")) ??\n DEFAULT_ROUTE_PREFIX;\n const target = `/${prefix}/${encodeURIComponent(slug)}`;\n\n if (!post) {\n return redirectSameOrigin(target);\n }\n\n (await draftMode()).enable();\n (await cookies()).set(PREVIEW_COOKIE, token, {\n httpOnly: true,\n sameSite: \"lax\",\n secure: process.env.NODE_ENV === \"production\",\n path: \"/\",\n maxAge: PREVIEW_MAX_AGE_SECONDS,\n });\n\n return redirectSameOrigin(target);\n}\n\n/**\n * Page helper: returns the active preview token when Draft Mode is on, else\n * undefined. Call it in the blog post server component and spread the result\n * into the fetch:\n *\n * const previewToken = await resolvePreviewToken();\n * const post = await fetchBlogPostBySlug(slug, { previewToken });\n *\n * Reading the cookie only happens when Draft Mode is enabled, so the public\n * route stays statically rendered for normal visitors.\n */\nexport async function resolvePreviewToken(): Promise<string | undefined> {\n const { isEnabled } = await draftMode();\n if (!isEnabled) return undefined;\n const store = await cookies();\n return store.get(PREVIEW_COOKIE)?.value;\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vulcantech/blog",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Server-side blog fetch layer for VulcanTech consumer sites — ISR-tagged reads from the CMS, with signed draft-preview support. Shared so each site doesn't duplicate the fetch code.",
5
5
  "license": "MIT",
6
6
  "source": "./src/index.ts",
@@ -30,7 +30,7 @@
30
30
  "next": ">=14.0.0"
31
31
  },
32
32
  "devDependencies": {
33
- "next": "16.3.1",
33
+ "next": "16.3.7",
34
34
  "tsup": "^8.0.0",
35
35
  "typescript": "^5.9.3"
36
36
  },
package/src/index.ts CHANGED
@@ -77,7 +77,7 @@ export interface CMSBlogPost {
77
77
  * sanitizers, so bring your own typography (e.g. a `prose` wrapper).
78
78
  */
79
79
  content: string;
80
- /** Plain-text summary. Canonical meta-description fallback: `seoDescription ?? excerpt`. */
80
+ /** Plain-text summary. Meta-description fallback — read it via `postSeoMeta`. */
81
81
  excerpt: string;
82
82
  /** Single editorial bucket (one per post) — distinct from the free-form `tags`. */
83
83
  category?: string;
@@ -92,7 +92,7 @@ export interface CMSBlogPost {
92
92
  keywords?: string;
93
93
  /** An object, not a string — display `author.name`. */
94
94
  author: CMSBlogAuthor;
95
- /** In-page hero / card image URL. For social cards use `ogImage ?? featuredImage`. */
95
+ /** In-page hero / card image URL. For social cards use `postSeoMeta(post).ogImage`. */
96
96
  featuredImage?: string;
97
97
  /**
98
98
  * Optional supplementary video for the post. Purely advisory — render it as a
@@ -101,21 +101,33 @@ export interface CMSBlogPost {
101
101
  * arrive as playable markup within `content` instead.
102
102
  */
103
103
  featuredVideo?: CMSVideoDescriptor;
104
- /** The public fetchers only ever return "published" posts (or a token-unlocked draft). */
105
- status: "draft" | "in_review" | "published" | "archived";
106
- /** ISO 8601 timestamp. Always present on published posts. */
104
+ /**
105
+ * The public fetchers only ever return "published" posts (or a token-unlocked
106
+ * draft in preview). `"scheduled"` means "goes live at `scheduledAt`": the
107
+ * CMS flips it to `"published"` at that time, and until then it is never
108
+ * served — so a consumer never needs to compare dates itself.
109
+ */
110
+ status: "draft" | "in_review" | "scheduled" | "published" | "archived";
111
+ /**
112
+ * ISO 8601 timestamp the post went live; drives sort order. Always present
113
+ * on published posts (for a formerly scheduled post it equals `scheduledAt`
114
+ * unless an author set it explicitly).
115
+ */
107
116
  publishedAt?: string;
108
- /** ISO 8601 timestamp for scheduled publishing; the post stays hidden until then. */
117
+ /** ISO 8601 timestamp a `scheduled` post goes live; kept as a record after it does. */
109
118
  scheduledAt?: string;
110
119
  /** ISO 8601 timestamp. */
111
120
  createdAt: string;
112
121
  /** ISO 8601 timestamp. */
113
122
  updatedAt: string;
114
- /** SERP/social title override. Canonical fallback: `seoTitle ?? title`. */
123
+ /**
124
+ * SERP/social title override — may be `""` when an author clears it. Read
125
+ * it via `postSeoMeta`, never `seoTitle ?? title` (keeps the blank).
126
+ */
115
127
  seoTitle?: string;
116
- /** Meta-description override. Canonical fallback: `seoDescription ?? excerpt`. */
128
+ /** Meta-description override — may be `""`. Read it via `postSeoMeta`. */
117
129
  seoDescription?: string;
118
- /** Social-share card image URL. Canonical fallback: `ogImage ?? featuredImage`. */
130
+ /** Social-share card image URL — may be `""`. Read it via `postSeoMeta`. */
119
131
  ogImage?: string;
120
132
  /** Defaults to "article" when absent (the field predates postType). */
121
133
  postType?: "article" | "case-study" | "announcement";
@@ -198,6 +210,7 @@ function assertConfig(): { projectId: string; apiKey: string } | null {
198
210
  }
199
211
 
200
212
  export { sanitizeHtml };
213
+ export { postSeoMeta, type PostSeoMeta, type PostSeoSource } from "./seo";
201
214
 
202
215
  /** Sanitize a post's HTML body so every consumer render is safe by default. */
203
216
  function sanitizePost(post: CMSBlogPost): CMSBlogPost {
@@ -343,6 +356,38 @@ export async function fetchBlogPostBySlug(
343
356
  const PREVIEW_COOKIE = "vt_preview_token";
344
357
  const PREVIEW_MAX_AGE_SECONDS = 2 * 60 * 60; // 2 hours
345
358
 
359
+ /** Route prefix assumed when neither the post nor the CMS names one. */
360
+ const DEFAULT_ROUTE_PREFIX = "blog";
361
+
362
+ /**
363
+ * Accept a route prefix only if it is one or more plain lowercase path
364
+ * segments (`blog`, `policies`, `legal/eu`). Anything else — empty, absolute,
365
+ * dotted, or carrying a scheme — is rejected so the preview redirect can only
366
+ * ever point at a same-origin page.
367
+ *
368
+ * @param value Candidate prefix from the post record or the query string.
369
+ * @returns The prefix when it is safe to interpolate into a path, else null.
370
+ */
371
+ function safeRoutePrefix(value: string | null | undefined): string | null {
372
+ if (!value) return null;
373
+ return /^[a-z0-9-]+(?:\/[a-z0-9-]+)*$/.test(value) ? value : null;
374
+ }
375
+
376
+ /**
377
+ * 307 to a path on whatever origin the browser used. The Location stays
378
+ * relative on purpose: behind a proxy, a standalone Next server builds
379
+ * `request.url` from its bind address (`HOSTNAME=0.0.0.0`, port 3000), so an
380
+ * absolute redirect resolved against it sent previews to
381
+ * `https://0.0.0.0:3000/…` (BL-974). Browsers resolve a relative Location
382
+ * against the URL they actually requested.
383
+ *
384
+ * @param path Absolute path (leading slash) on the current site.
385
+ * @returns A redirect response that carries any cookies set in the handler.
386
+ */
387
+ function redirectSameOrigin(path: string): Response {
388
+ return new NextResponse(null, { status: 307, headers: { Location: path } });
389
+ }
390
+
346
391
  /**
347
392
  * Route handler for `/api/preview?token=…&slug=…`.
348
393
  *
@@ -351,6 +396,12 @@ const PREVIEW_MAX_AGE_SECONDS = 2 * 60 * 60; // 2 hours
351
396
  * the draft (see resolvePreviewToken). On an invalid/expired token it just
352
397
  * redirects to the public page (which 404s if the post isn't published).
353
398
  *
399
+ * The redirect honours the post's `routePrefix`: a post in the `policies`
400
+ * space lands on `/policies/{slug}`, not `/blog/{slug}`. When the token is
401
+ * invalid the post cannot be read, so the CMS also sends the prefix as
402
+ * `?prefix=`; with neither, `/blog` is assumed. The prefix is validated as
403
+ * plain path segments so the query string can never redirect off-site.
404
+ *
354
405
  * Each consumer wires it up with one line:
355
406
  * // app/api/preview/route.ts
356
407
  * export { GET } from "@vulcantech/blog";
@@ -367,12 +418,17 @@ export async function GET(request: NextRequest): Promise<Response> {
367
418
  );
368
419
  }
369
420
 
370
- const target = new URL(`/blog/${encodeURIComponent(slug)}`, request.url);
371
-
372
421
  // Validate by asking the CMS to resolve the draft with this token.
373
422
  const post = await fetchBlogPostBySlug(slug, { previewToken: token });
423
+
424
+ const prefix =
425
+ safeRoutePrefix(post?.routePrefix) ??
426
+ safeRoutePrefix(searchParams.get("prefix")) ??
427
+ DEFAULT_ROUTE_PREFIX;
428
+ const target = `/${prefix}/${encodeURIComponent(slug)}`;
429
+
374
430
  if (!post) {
375
- return NextResponse.redirect(target);
431
+ return redirectSameOrigin(target);
376
432
  }
377
433
 
378
434
  (await draftMode()).enable();
@@ -384,7 +440,7 @@ export async function GET(request: NextRequest): Promise<Response> {
384
440
  maxAge: PREVIEW_MAX_AGE_SECONDS,
385
441
  });
386
442
 
387
- return NextResponse.redirect(target);
443
+ return redirectSameOrigin(target);
388
444
  }
389
445
 
390
446
  /**
package/src/seo.ts ADDED
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Blank-safe SEO fallbacks for a CMS blog post.
3
+ *
4
+ * The CMS editor saves a cleared SEO-panel field as `""`, not as an absent
5
+ * field, so a `seoTitle ?? title` chain keeps the empty string and the page
6
+ * ships an empty `<title>` / description. Every consumer reads its overrides
7
+ * through `postSeoMeta` instead, so the fallback rules live in one place.
8
+ *
9
+ * Pure (no `next/*` imports) — safe anywhere, including client components.
10
+ */
11
+
12
+ /** The post fields `postSeoMeta` reads — any `CMSBlogPost` satisfies it. */
13
+ export interface PostSeoSource {
14
+ title: string;
15
+ excerpt?: string;
16
+ seoTitle?: string;
17
+ seoDescription?: string;
18
+ ogImage?: string;
19
+ featuredImage?: string;
20
+ }
21
+
22
+ /** Resolved SEO values for one post. */
23
+ export interface PostSeoMeta {
24
+ /** The author's `seoTitle` when set, else the post title. */
25
+ title: string;
26
+ /**
27
+ * True when `title` is the author's `seoTitle`. That is a complete SERP
28
+ * title, so emit it as `title: { absolute: title }` — otherwise the
29
+ * layout's `%s - Site` template brands it a second time.
30
+ */
31
+ titleIsOverride: boolean;
32
+ /** The `seoDescription` override when set, else the excerpt ("" if neither). */
33
+ description: string;
34
+ /** Social-card image: the `ogImage` override, else `featuredImage`. */
35
+ ogImage?: string;
36
+ }
37
+
38
+ /** Trims a value to `undefined` when it is missing or whitespace-only. */
39
+ function present(value: string | undefined | null): string | undefined {
40
+ const trimmed = value?.trim();
41
+ return trimmed ? trimmed : undefined;
42
+ }
43
+
44
+ /**
45
+ * Resolves a post's title, meta description and social image from its CMS
46
+ * SEO overrides, treating blank overrides as unset.
47
+ *
48
+ * @param post - A CMS blog post (or any object with the same SEO fields).
49
+ * @returns The resolved title (plus whether it is an override), description
50
+ * and optional og image.
51
+ *
52
+ * @example
53
+ * const seo = postSeoMeta(post);
54
+ * return {
55
+ * title: seo.titleIsOverride ? { absolute: seo.title } : seo.title,
56
+ * description: seo.description,
57
+ * openGraph: { images: seo.ogImage ? [seo.ogImage] : undefined },
58
+ * };
59
+ */
60
+ export function postSeoMeta(post: PostSeoSource): PostSeoMeta {
61
+ const seoTitle = present(post.seoTitle);
62
+ return {
63
+ title: seoTitle ?? post.title,
64
+ titleIsOverride: seoTitle !== undefined,
65
+ description: present(post.seoDescription) ?? present(post.excerpt) ?? "",
66
+ ogImage: present(post.ogImage) ?? present(post.featuredImage),
67
+ };
68
+ }