@vulcantech/blog 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,115 @@
1
+ # @vulcantech/blog
2
+
3
+ Server-side blog fetch layer for VulcanTech consumer sites. Reads published posts from the CMS with Next.js ISR tags, and supports signed draft-preview tokens so unpublished posts can be reviewed on the live site. Shared so each site stops duplicating `lib/cms/blog.ts`.
4
+
5
+ **Exports**: `fetchBlogPosts`, `fetchBlogPostBySlug`, `resolvePreviewToken`, `GET` (the draft-preview route handler), `tagsForBlogList` / `tagsForBlogPost`, and the `CMSBlogPost` / `CMSBlogAuthor` types.
6
+
7
+ **Server-only** — uses `VULCANTECH_API_KEY`; import from server components / route handlers only.
8
+
9
+ ## Integration
10
+
11
+ Wire blog into a consumer site (Next.js App Router):
12
+
13
+ **1. Add the dependency** (`package.json`):
14
+ ```json
15
+ "@vulcantech/blog": "*"
16
+ ```
17
+
18
+ **2. Transpile + alias it** (`next.config.js`):
19
+ ```js
20
+ transpilePackages: ["@vulcantech/blog", /* ... */],
21
+ webpack: (config) => {
22
+ config.resolve.alias["@vulcantech/blog"] = path.join(__dirname, "../../packages/blog");
23
+ return config;
24
+ },
25
+ turbopack: {
26
+ resolveAlias: { "@vulcantech/blog": "./../../packages/blog/src/index.ts" },
27
+ },
28
+ ```
29
+
30
+ **3. (Optional) thin re-export** `src/lib/cms/blog.ts` to preserve `@/lib/cms/blog` import paths:
31
+ ```ts
32
+ export * from "@vulcantech/blog";
33
+ ```
34
+
35
+ **4. Blog pages** — list + single post (server components):
36
+ ```tsx
37
+ import { fetchBlogPosts, fetchBlogPostBySlug, resolvePreviewToken } from "@vulcantech/blog";
38
+
39
+ // app/blog/page.tsx
40
+ const posts = await fetchBlogPosts();
41
+
42
+ // app/blog/[slug]/page.tsx — resolve the preview token (Draft Mode) and pass it through
43
+ const previewToken = await resolvePreviewToken();
44
+ const post = await fetchBlogPostBySlug(slug, { previewToken });
45
+ ```
46
+
47
+ In `generateMetadata`, prefer the post's derived `keywords` string (the CMS
48
+ builds it from the post's dedicated SEO keyword fields — target keyword first)
49
+ and fall back to `tags`:
50
+ ```ts
51
+ keywords: post.keywords || (post.tags?.length ? post.tags : [post.title, "Brand"]),
52
+ ```
53
+
54
+ **5. Draft-preview route** `src/app/api/preview/route.ts` — one line, shared implementation:
55
+ ```ts
56
+ export { GET } from "@vulcantech/blog";
57
+ ```
58
+ 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.
59
+
60
+ **6. ISR invalidation** — ensure `src/app/api/revalidate/route.ts` exists; the CMS purges `blog:{projectId}` (list) and `blog:{projectId}:{slug}` (single) on edit.
61
+
62
+ ## Scoped routes (`routePrefix`)
63
+
64
+ Posts carry an optional `routePrefix` that decides which URL space they live in
65
+ on the consumer site: `"blog"` → `/blog/<slug>` (the default; legacy posts with
66
+ no prefix count as blog), `"legal"` → `/legal/<slug>`, `"documentation"` →
67
+ `/documentation/<slug>`, etc. Editors set it per-post in the CMS dashboard. One
68
+ Firestore collection powers all of them — the split happens at fetch/render time.
69
+
70
+ Wiring a scoped route (e.g. documentation) takes three pieces:
71
+
72
+ **1. A scope predicate — keep `/blog` clean.** `fetchBlogPosts()` returns every
73
+ published post regardless of prefix, so the blog list/related-posts must filter,
74
+ or scoped posts leak onto `/blog`. Centralize the predicate instead of scattering
75
+ `!== "legal"` checks (canonical example: `apps/dry-ice-pro-auto/src/lib/cms/postScope.ts`):
76
+
77
+ ```ts
78
+ export const BLOG_ROUTE_PREFIX = "blog";
79
+ /** Legacy posts predate the field, so no prefix also means "blog". */
80
+ export function isBlogPost(post: { routePrefix?: string }): boolean {
81
+ return !post.routePrefix || post.routePrefix === BLOG_ROUTE_PREFIX;
82
+ }
83
+ ```
84
+
85
+ New prefixes are then excluded from `/blog` automatically, with no further edits.
86
+
87
+ **2. The scoped pages.** List pages fetch with the prefix; the `[slug]` page
88
+ must ALSO guard the prefix so a blog slug can never render on the scoped route:
89
+
90
+ ```ts
91
+ // app/documentation/page.tsx
92
+ const docs = await fetchBlogPosts({ routePrefix: "documentation" });
93
+
94
+ // app/documentation/[slug]/page.tsx
95
+ const post = await fetchBlogPostBySlug(slug);
96
+ if (!post || post.routePrefix !== "documentation") notFound();
97
+ ```
98
+
99
+ `generateStaticParams` should use the same `fetchBlogPosts({ routePrefix })` call.
100
+
101
+ **3. Revalidation.** Nothing extra — the CMS purges the same `blog:{projectId}`
102
+ tags on edit, so scoped pages revalidate with the blog as long as they use this
103
+ package's fetchers (which attach those tags).
104
+
105
+ Live examples: `apps/dry-ice-pro-auto/src/app/legal/` (prefix `"legal"`, with the
106
+ `postScope.ts` predicate keeping `/blog` scoped) and the CMS's own
107
+ `apps/vulcantech-cms/src/app/(theme)/documentation/` (prefix `"documentation"` —
108
+ note the CMS reads its own Firestore via Admin SDK in `src/lib/blog/posts.ts`
109
+ instead of this package, but the scoping workflow is identical).
110
+
111
+ ### Required env
112
+ `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).
113
+
114
+ ### Per-app values
115
+ None beyond env — all blog logic is shared.
@@ -0,0 +1,163 @@
1
+ import { NextRequest } from 'next/server';
2
+
3
+ /**
4
+ * HTML sanitizer for user-generated (TipTap) content.
5
+ *
6
+ * MIRROR of packages/ui/sanitize.ts — keep in sync. Duplicated rather than
7
+ * imported so this package stays dependency-free (no `ui` workspace coupling).
8
+ *
9
+ * Defense-in-depth only. As of audit L4 / BL-023, blog HTML is sanitized ON
10
+ * WRITE by the CMS's parser-based DOMPurify sanitizer
11
+ * (apps/vulcantech-cms/src/lib/html/sanitizeHtml.ts), so the content this
12
+ * package fetches is already clean. This boundary pass is a safety net for
13
+ * legacy/unexpected data, not the primary guarantee.
14
+ *
15
+ * Strips dangerous tags and attributes and neutralizes dangerous URL schemes,
16
+ * decoding HTML entities first so entity-encoded `javascript:` payloads can't
17
+ * slip past the scheme check.
18
+ */
19
+ /**
20
+ * Sanitize HTML by removing dangerous tags/attributes and neutralizing unsafe
21
+ * URL schemes. Returns the cleaned HTML string.
22
+ */
23
+ declare function sanitizeHtml(html: string): string;
24
+
25
+ /**
26
+ * @vulcantech/blog — server-side blog fetch layer for VulcanTech consumer
27
+ * sites.
28
+ *
29
+ * Reads published blog posts from the CMS with Next.js ISR tags so the CMS
30
+ * can purge a post (via /api/revalidate) the moment it changes, and supports
31
+ * signed draft-preview tokens so an unpublished post can be rendered on the
32
+ * real site for review.
33
+ *
34
+ * Config comes from the same env vars every consumer already sets — no
35
+ * per-app wiring beyond importing this package:
36
+ * VULCANTECH_CMS_URL (default https://cms.vulcantech.io)
37
+ * VULCANTECH_PROJECT_ID (required)
38
+ * VULCANTECH_API_KEY (required)
39
+ * VULCANTECH_BLOG_NO_CACHE ("1" | "true" → bypass ISR everywhere)
40
+ *
41
+ * SERVER-ONLY: relies on VULCANTECH_API_KEY (no NEXT_PUBLIC_ prefix), so it
42
+ * must only be imported from server components / route handlers.
43
+ *
44
+ * Errors are graceful by design — a CMS hiccup returns [] / null and logs a
45
+ * warning rather than throwing, so a marketing site never hard-crashes on a
46
+ * transient CMS outage.
47
+ *
48
+ * Draft preview (Next.js Draft Mode):
49
+ * - Re-export `GET` from app/api/preview/route.ts on each consumer.
50
+ * - Call `resolvePreviewToken()` in the blog post page and pass the result
51
+ * to fetchBlogPostBySlug as { previewToken }.
52
+ * The public /blog/[slug] route stays static/ISR; only a request carrying
53
+ * the Draft Mode cookie renders the unpublished draft.
54
+ */
55
+
56
+ interface CMSBlogAuthor {
57
+ uid?: string;
58
+ name: string;
59
+ avatar?: string;
60
+ }
61
+ interface CMSBlogPost {
62
+ id: string;
63
+ projectId: string;
64
+ title: string;
65
+ slug: string;
66
+ /** HTML content (TipTap output). */
67
+ content: string;
68
+ excerpt: string;
69
+ category?: string;
70
+ /** URL route segment the post lives under, e.g. "blog" or "documentation". */
71
+ routePrefix?: string;
72
+ tags: string[];
73
+ /**
74
+ * Comma-separated SEO keywords the CMS derives from the post's dedicated
75
+ * keyword fields (target keyword first). Feed straight into
76
+ * `Metadata.keywords`; absent when the post has no keywords set.
77
+ */
78
+ keywords?: string;
79
+ author: CMSBlogAuthor;
80
+ featuredImage?: string;
81
+ status: "draft" | "in_review" | "published" | "archived";
82
+ publishedAt?: string;
83
+ scheduledAt?: string;
84
+ createdAt: string;
85
+ updatedAt: string;
86
+ seoTitle?: string;
87
+ seoDescription?: string;
88
+ ogImage?: string;
89
+ postType?: "article" | "case-study" | "announcement";
90
+ metadata?: {
91
+ label: string;
92
+ value: string;
93
+ }[];
94
+ }
95
+ interface FetchOptions {
96
+ /** Override the per-fetch revalidate window. Default: 60 seconds. */
97
+ revalidate?: number;
98
+ /** Extra ISR tags to attach to the fetch. */
99
+ extraTags?: string[];
100
+ /** Skip Next's ISR cache for this call. */
101
+ noStore?: boolean;
102
+ }
103
+ interface FetchPostsOptions extends FetchOptions {
104
+ category?: string;
105
+ /** Only return posts under this route prefix (e.g. "documentation"). */
106
+ routePrefix?: string;
107
+ tag?: string;
108
+ search?: string;
109
+ limit?: number;
110
+ startAfter?: string;
111
+ }
112
+ interface FetchPostOptions extends FetchOptions {
113
+ /**
114
+ * A signed preview token (from the CMS) that unlocks an unpublished post.
115
+ * When set, the cache is bypassed automatically — preview content must
116
+ * never be cached or served to the public.
117
+ */
118
+ previewToken?: string;
119
+ }
120
+
121
+ /** ISR tag for a project's blog list. */
122
+ declare function tagsForBlogList(projectId: string): string[];
123
+ /** ISR tags for a single post (post-specific + project-wide). */
124
+ declare function tagsForBlogPost(projectId: string, slug: string): string[];
125
+ /**
126
+ * Fetch published posts for the configured project. Optional filters
127
+ * (category/tag/search/limit/startAfter) are forwarded to the CMS.
128
+ */
129
+ declare function fetchBlogPosts(options?: FetchPostsOptions): Promise<CMSBlogPost[]>;
130
+ /**
131
+ * Fetch a single post by slug. Returns null when not found.
132
+ *
133
+ * Pass `previewToken` (minted by the CMS) to render an unpublished draft for
134
+ * review — that automatically bypasses the cache.
135
+ */
136
+ declare function fetchBlogPostBySlug(slug: string, options?: FetchPostOptions): Promise<CMSBlogPost | null>;
137
+ /**
138
+ * Route handler for `/api/preview?token=…&slug=…`.
139
+ *
140
+ * Validates the token against the CMS, enables Next Draft Mode, stores the
141
+ * token in an httpOnly cookie, and redirects to the post — which then renders
142
+ * the draft (see resolvePreviewToken). On an invalid/expired token it just
143
+ * redirects to the public page (which 404s if the post isn't published).
144
+ *
145
+ * Each consumer wires it up with one line:
146
+ * // app/api/preview/route.ts
147
+ * export { GET } from "@vulcantech/blog";
148
+ */
149
+ declare function GET(request: NextRequest): Promise<Response>;
150
+ /**
151
+ * Page helper: returns the active preview token when Draft Mode is on, else
152
+ * undefined. Call it in the blog post server component and spread the result
153
+ * into the fetch:
154
+ *
155
+ * const previewToken = await resolvePreviewToken();
156
+ * const post = await fetchBlogPostBySlug(slug, { previewToken });
157
+ *
158
+ * Reading the cookie only happens when Draft Mode is enabled, so the public
159
+ * route stays statically rendered for normal visitors.
160
+ */
161
+ declare function resolvePreviewToken(): Promise<string | undefined>;
162
+
163
+ export { type CMSBlogAuthor, type CMSBlogPost, type FetchOptions, type FetchPostOptions, type FetchPostsOptions, GET, fetchBlogPostBySlug, fetchBlogPosts, resolvePreviewToken, sanitizeHtml, tagsForBlogList, tagsForBlogPost };
@@ -0,0 +1,163 @@
1
+ import { NextRequest } from 'next/server';
2
+
3
+ /**
4
+ * HTML sanitizer for user-generated (TipTap) content.
5
+ *
6
+ * MIRROR of packages/ui/sanitize.ts — keep in sync. Duplicated rather than
7
+ * imported so this package stays dependency-free (no `ui` workspace coupling).
8
+ *
9
+ * Defense-in-depth only. As of audit L4 / BL-023, blog HTML is sanitized ON
10
+ * WRITE by the CMS's parser-based DOMPurify sanitizer
11
+ * (apps/vulcantech-cms/src/lib/html/sanitizeHtml.ts), so the content this
12
+ * package fetches is already clean. This boundary pass is a safety net for
13
+ * legacy/unexpected data, not the primary guarantee.
14
+ *
15
+ * Strips dangerous tags and attributes and neutralizes dangerous URL schemes,
16
+ * decoding HTML entities first so entity-encoded `javascript:` payloads can't
17
+ * slip past the scheme check.
18
+ */
19
+ /**
20
+ * Sanitize HTML by removing dangerous tags/attributes and neutralizing unsafe
21
+ * URL schemes. Returns the cleaned HTML string.
22
+ */
23
+ declare function sanitizeHtml(html: string): string;
24
+
25
+ /**
26
+ * @vulcantech/blog — server-side blog fetch layer for VulcanTech consumer
27
+ * sites.
28
+ *
29
+ * Reads published blog posts from the CMS with Next.js ISR tags so the CMS
30
+ * can purge a post (via /api/revalidate) the moment it changes, and supports
31
+ * signed draft-preview tokens so an unpublished post can be rendered on the
32
+ * real site for review.
33
+ *
34
+ * Config comes from the same env vars every consumer already sets — no
35
+ * per-app wiring beyond importing this package:
36
+ * VULCANTECH_CMS_URL (default https://cms.vulcantech.io)
37
+ * VULCANTECH_PROJECT_ID (required)
38
+ * VULCANTECH_API_KEY (required)
39
+ * VULCANTECH_BLOG_NO_CACHE ("1" | "true" → bypass ISR everywhere)
40
+ *
41
+ * SERVER-ONLY: relies on VULCANTECH_API_KEY (no NEXT_PUBLIC_ prefix), so it
42
+ * must only be imported from server components / route handlers.
43
+ *
44
+ * Errors are graceful by design — a CMS hiccup returns [] / null and logs a
45
+ * warning rather than throwing, so a marketing site never hard-crashes on a
46
+ * transient CMS outage.
47
+ *
48
+ * Draft preview (Next.js Draft Mode):
49
+ * - Re-export `GET` from app/api/preview/route.ts on each consumer.
50
+ * - Call `resolvePreviewToken()` in the blog post page and pass the result
51
+ * to fetchBlogPostBySlug as { previewToken }.
52
+ * The public /blog/[slug] route stays static/ISR; only a request carrying
53
+ * the Draft Mode cookie renders the unpublished draft.
54
+ */
55
+
56
+ interface CMSBlogAuthor {
57
+ uid?: string;
58
+ name: string;
59
+ avatar?: string;
60
+ }
61
+ interface CMSBlogPost {
62
+ id: string;
63
+ projectId: string;
64
+ title: string;
65
+ slug: string;
66
+ /** HTML content (TipTap output). */
67
+ content: string;
68
+ excerpt: string;
69
+ category?: string;
70
+ /** URL route segment the post lives under, e.g. "blog" or "documentation". */
71
+ routePrefix?: string;
72
+ tags: string[];
73
+ /**
74
+ * Comma-separated SEO keywords the CMS derives from the post's dedicated
75
+ * keyword fields (target keyword first). Feed straight into
76
+ * `Metadata.keywords`; absent when the post has no keywords set.
77
+ */
78
+ keywords?: string;
79
+ author: CMSBlogAuthor;
80
+ featuredImage?: string;
81
+ status: "draft" | "in_review" | "published" | "archived";
82
+ publishedAt?: string;
83
+ scheduledAt?: string;
84
+ createdAt: string;
85
+ updatedAt: string;
86
+ seoTitle?: string;
87
+ seoDescription?: string;
88
+ ogImage?: string;
89
+ postType?: "article" | "case-study" | "announcement";
90
+ metadata?: {
91
+ label: string;
92
+ value: string;
93
+ }[];
94
+ }
95
+ interface FetchOptions {
96
+ /** Override the per-fetch revalidate window. Default: 60 seconds. */
97
+ revalidate?: number;
98
+ /** Extra ISR tags to attach to the fetch. */
99
+ extraTags?: string[];
100
+ /** Skip Next's ISR cache for this call. */
101
+ noStore?: boolean;
102
+ }
103
+ interface FetchPostsOptions extends FetchOptions {
104
+ category?: string;
105
+ /** Only return posts under this route prefix (e.g. "documentation"). */
106
+ routePrefix?: string;
107
+ tag?: string;
108
+ search?: string;
109
+ limit?: number;
110
+ startAfter?: string;
111
+ }
112
+ interface FetchPostOptions extends FetchOptions {
113
+ /**
114
+ * A signed preview token (from the CMS) that unlocks an unpublished post.
115
+ * When set, the cache is bypassed automatically — preview content must
116
+ * never be cached or served to the public.
117
+ */
118
+ previewToken?: string;
119
+ }
120
+
121
+ /** ISR tag for a project's blog list. */
122
+ declare function tagsForBlogList(projectId: string): string[];
123
+ /** ISR tags for a single post (post-specific + project-wide). */
124
+ declare function tagsForBlogPost(projectId: string, slug: string): string[];
125
+ /**
126
+ * Fetch published posts for the configured project. Optional filters
127
+ * (category/tag/search/limit/startAfter) are forwarded to the CMS.
128
+ */
129
+ declare function fetchBlogPosts(options?: FetchPostsOptions): Promise<CMSBlogPost[]>;
130
+ /**
131
+ * Fetch a single post by slug. Returns null when not found.
132
+ *
133
+ * Pass `previewToken` (minted by the CMS) to render an unpublished draft for
134
+ * review — that automatically bypasses the cache.
135
+ */
136
+ declare function fetchBlogPostBySlug(slug: string, options?: FetchPostOptions): Promise<CMSBlogPost | null>;
137
+ /**
138
+ * Route handler for `/api/preview?token=…&slug=…`.
139
+ *
140
+ * Validates the token against the CMS, enables Next Draft Mode, stores the
141
+ * token in an httpOnly cookie, and redirects to the post — which then renders
142
+ * the draft (see resolvePreviewToken). On an invalid/expired token it just
143
+ * redirects to the public page (which 404s if the post isn't published).
144
+ *
145
+ * Each consumer wires it up with one line:
146
+ * // app/api/preview/route.ts
147
+ * export { GET } from "@vulcantech/blog";
148
+ */
149
+ declare function GET(request: NextRequest): Promise<Response>;
150
+ /**
151
+ * Page helper: returns the active preview token when Draft Mode is on, else
152
+ * undefined. Call it in the blog post server component and spread the result
153
+ * into the fetch:
154
+ *
155
+ * const previewToken = await resolvePreviewToken();
156
+ * const post = await fetchBlogPostBySlug(slug, { previewToken });
157
+ *
158
+ * Reading the cookie only happens when Draft Mode is enabled, so the public
159
+ * route stays statically rendered for normal visitors.
160
+ */
161
+ declare function resolvePreviewToken(): Promise<string | undefined>;
162
+
163
+ export { type CMSBlogAuthor, type CMSBlogPost, type FetchOptions, type FetchPostOptions, type FetchPostsOptions, GET, fetchBlogPostBySlug, fetchBlogPosts, resolvePreviewToken, sanitizeHtml, tagsForBlogList, tagsForBlogPost };
package/dist/index.js ADDED
@@ -0,0 +1,230 @@
1
+ 'use strict';
2
+
3
+ var headers = require('next/headers');
4
+ var server = require('next/server');
5
+
6
+ // src/index.ts
7
+
8
+ // src/sanitize.ts
9
+ var DANGEROUS_TAGS = [
10
+ "script",
11
+ "iframe",
12
+ "object",
13
+ "embed",
14
+ "form",
15
+ "input",
16
+ "textarea",
17
+ "button",
18
+ "select",
19
+ "option",
20
+ "link",
21
+ "meta",
22
+ "base",
23
+ "applet",
24
+ "frame",
25
+ "frameset",
26
+ "layer",
27
+ "style",
28
+ "svg",
29
+ "math",
30
+ "xmp",
31
+ "noscript",
32
+ "template"
33
+ ];
34
+ function safeCodePoint(n) {
35
+ if (!Number.isFinite(n) || n < 0 || n > 1114111) return "";
36
+ try {
37
+ return String.fromCodePoint(n);
38
+ } catch {
39
+ return "";
40
+ }
41
+ }
42
+ function decodeEntities(s) {
43
+ return s.replace(/&#x([0-9a-f]+);?/gi, (_, h) => safeCodePoint(parseInt(h, 16))).replace(/&#(\d+);?/g, (_, d) => safeCodePoint(parseInt(d, 10))).replace(/&colon;/gi, ":").replace(/&tab;/gi, " ").replace(/&newline;/gi, "\n").replace(/&amp;/gi, "&");
44
+ }
45
+ function stripBlankAndControl(s) {
46
+ let out = "";
47
+ for (const ch of s) {
48
+ if (ch.codePointAt(0) > 32) out += ch;
49
+ }
50
+ return out;
51
+ }
52
+ function sanitizeHtml(html) {
53
+ if (!html) return "";
54
+ let clean = html.replace(
55
+ /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
56
+ ""
57
+ );
58
+ for (const tag of DANGEROUS_TAGS) {
59
+ clean = clean.replace(
60
+ new RegExp(`<${tag}\\b[^>]*>[\\s\\S]*?<\\/${tag}>`, "gi"),
61
+ ""
62
+ );
63
+ clean = clean.replace(new RegExp(`<${tag}\\b[^>]*\\/?>`, "gi"), "");
64
+ }
65
+ clean = clean.replace(
66
+ /\s+on\w+\s*=\s*("[^"]*"|'[^']*'|[^\s>]*)/gi,
67
+ ""
68
+ );
69
+ clean = clean.replace(
70
+ /\s+style\s*=\s*("[^"]*"|'[^']*'|[^\s>]*)/gi,
71
+ ""
72
+ );
73
+ clean = clean.replace(
74
+ /\b(href|src)\s*=\s*("([^"]*)"|'([^']*)'|([^\s>]+))/gi,
75
+ (match, attr, _raw, dq, sq, uq) => {
76
+ const value = dq ?? sq ?? uq ?? "";
77
+ const decoded = stripBlankAndControl(decodeEntities(value)).toLowerCase();
78
+ if (/^(javascript|data|vbscript):/.test(decoded)) {
79
+ return `${attr}="about:blank"`;
80
+ }
81
+ return match;
82
+ }
83
+ );
84
+ return clean;
85
+ }
86
+
87
+ // src/index.ts
88
+ var DEFAULT_REVALIDATE_SECONDS = 60;
89
+ function cmsUrl() {
90
+ return process.env.VULCANTECH_CMS_URL || "https://cms.vulcantech.io";
91
+ }
92
+ function bypassCache() {
93
+ return process.env.VULCANTECH_BLOG_NO_CACHE === "1" || process.env.VULCANTECH_BLOG_NO_CACHE === "true";
94
+ }
95
+ function assertConfig() {
96
+ const projectId = process.env.VULCANTECH_PROJECT_ID;
97
+ const apiKey = process.env.VULCANTECH_API_KEY;
98
+ if (!projectId || !apiKey) {
99
+ console.warn(
100
+ "[cms/blog] CMS not configured \u2014 set VULCANTECH_PROJECT_ID and VULCANTECH_API_KEY"
101
+ );
102
+ return null;
103
+ }
104
+ return { projectId, apiKey };
105
+ }
106
+ function sanitizePost(post) {
107
+ if (post && typeof post.content === "string") {
108
+ return { ...post, content: sanitizeHtml(post.content) };
109
+ }
110
+ return post;
111
+ }
112
+ function tagsForBlogList(projectId) {
113
+ return [`blog:${projectId}`];
114
+ }
115
+ function tagsForBlogPost(projectId, slug) {
116
+ return [`blog:${projectId}:${slug}`, `blog:${projectId}`];
117
+ }
118
+ function buildInit(tags, options) {
119
+ const skipCache = options.noStore || bypassCache();
120
+ if (skipCache) return { cache: "no-store" };
121
+ return {
122
+ next: {
123
+ revalidate: options.revalidate ?? DEFAULT_REVALIDATE_SECONDS,
124
+ tags: [...tags, ...options.extraTags ?? []]
125
+ }
126
+ };
127
+ }
128
+ async function fetchBlogPosts(options = {}) {
129
+ const config = assertConfig();
130
+ if (!config) return [];
131
+ const { projectId, apiKey } = config;
132
+ const params = new URLSearchParams({ projectId, apiKey, status: "published" });
133
+ if (options.category) params.set("category", options.category);
134
+ if (options.routePrefix) params.set("routePrefix", options.routePrefix);
135
+ if (options.tag) params.set("tag", options.tag);
136
+ if (options.search) params.set("search", options.search);
137
+ if (options.limit) params.set("limit", String(options.limit));
138
+ if (options.startAfter) params.set("startAfter", options.startAfter);
139
+ const url = `${cmsUrl()}/api/blog?${params.toString()}`;
140
+ const init = buildInit(tagsForBlogList(projectId), options);
141
+ let res;
142
+ try {
143
+ res = await fetch(url, init);
144
+ } catch (err) {
145
+ console.warn("[cms/blog] CMS unreachable:", err.message);
146
+ return [];
147
+ }
148
+ if (res.status === 404) {
149
+ console.warn("[cms/blog] /api/blog returned 404 \u2014 CMS may need redeployment");
150
+ return [];
151
+ }
152
+ if (!res.ok) {
153
+ console.warn(`[cms/blog] /api/blog returned ${res.status}`);
154
+ return [];
155
+ }
156
+ const json = await res.json();
157
+ return (json.posts ?? []).map(sanitizePost);
158
+ }
159
+ async function fetchBlogPostBySlug(slug, options = {}) {
160
+ const config = assertConfig();
161
+ if (!config) return null;
162
+ const { projectId, apiKey } = config;
163
+ const params = new URLSearchParams({ projectId, apiKey });
164
+ if (options.previewToken) params.set("preview", options.previewToken);
165
+ const url = `${cmsUrl()}/api/blog/${encodeURIComponent(slug)}?${params.toString()}`;
166
+ const init = buildInit(tagsForBlogPost(projectId, slug), {
167
+ ...options,
168
+ noStore: options.noStore || !!options.previewToken
169
+ });
170
+ let res;
171
+ try {
172
+ res = await fetch(url, init);
173
+ } catch (err) {
174
+ console.warn(
175
+ `[cms/blog] CMS unreachable for "${slug}":`,
176
+ err.message
177
+ );
178
+ return null;
179
+ }
180
+ if (res.status === 404) return null;
181
+ if (!res.ok) {
182
+ console.warn(`[cms/blog] /api/blog/${slug} returned ${res.status}`);
183
+ return null;
184
+ }
185
+ const json = await res.json();
186
+ return json.post ? sanitizePost(json.post) : null;
187
+ }
188
+ var PREVIEW_COOKIE = "vt_preview_token";
189
+ var PREVIEW_MAX_AGE_SECONDS = 2 * 60 * 60;
190
+ async function GET(request) {
191
+ const { searchParams } = new URL(request.url);
192
+ const token = searchParams.get("token");
193
+ const slug = searchParams.get("slug");
194
+ if (!token || !slug) {
195
+ return server.NextResponse.json(
196
+ { error: "token and slug are required" },
197
+ { status: 400 }
198
+ );
199
+ }
200
+ const target = new URL(`/blog/${encodeURIComponent(slug)}`, request.url);
201
+ const post = await fetchBlogPostBySlug(slug, { previewToken: token });
202
+ if (!post) {
203
+ return server.NextResponse.redirect(target);
204
+ }
205
+ (await headers.draftMode()).enable();
206
+ (await headers.cookies()).set(PREVIEW_COOKIE, token, {
207
+ httpOnly: true,
208
+ sameSite: "lax",
209
+ secure: process.env.NODE_ENV === "production",
210
+ path: "/",
211
+ maxAge: PREVIEW_MAX_AGE_SECONDS
212
+ });
213
+ return server.NextResponse.redirect(target);
214
+ }
215
+ async function resolvePreviewToken() {
216
+ const { isEnabled } = await headers.draftMode();
217
+ if (!isEnabled) return void 0;
218
+ const store = await headers.cookies();
219
+ return store.get(PREVIEW_COOKIE)?.value;
220
+ }
221
+
222
+ exports.GET = GET;
223
+ exports.fetchBlogPostBySlug = fetchBlogPostBySlug;
224
+ exports.fetchBlogPosts = fetchBlogPosts;
225
+ exports.resolvePreviewToken = resolvePreviewToken;
226
+ exports.sanitizeHtml = sanitizeHtml;
227
+ exports.tagsForBlogList = tagsForBlogList;
228
+ exports.tagsForBlogPost = tagsForBlogPost;
229
+ //# sourceMappingURL=index.js.map
230
+ //# sourceMappingURL=index.js.map