@xexr/blog-platform 1.0.1 → 1.0.2

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/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import Ne from'next/link';import Ve from'next/image';import {clsx}from'clsx';import {twMerge}from'tailwind-merge';import {ChevronLeftIcon,ChevronRightIcon,MoreHorizontalIcon,ChevronsLeft,ChevronsRight,ArrowLeft}from'lucide-react';import {Slot}from'@radix-ui/react-slot';import {cva}from'class-variance-authority';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {formatDistanceToNow,format}from'date-fns';import {MDXRemote}from'next-mdx-remote-client/rsc';import*as je from'react';import*as we from'@radix-ui/react-separator';import {Ratelimit}from'@upstash/ratelimit';import {Redis}from'@upstash/redis';import {eq,and,desc,sql}from'drizzle-orm';import {sqliteTable,integer,text,uniqueIndex}from'drizzle-orm/sqlite-core';import {NextResponse}from'next/server';function x(...e){return twMerge(clsx(e))}var te=cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",destructive:"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9"}},defaultVariants:{variant:"default",size:"default"}});function pt({className:e,variant:t,size:r,asChild:n=false,...s}){return jsx(n?Slot:"button",{"data-slot":"button",className:x(te({variant:t,size:r,className:e})),...s})}function de({className:e,...t}){return jsx("nav",{role:"navigation","aria-label":"pagination","data-slot":"pagination",className:x("mx-auto flex w-full justify-center",e),...t})}function ge({className:e,...t}){return jsx("ul",{"data-slot":"pagination-content",className:x("flex flex-row items-center gap-1",e),...t})}function E({...e}){return jsx("li",{"data-slot":"pagination-item",...e})}function $({className:e,isActive:t,size:r="icon",...n}){return jsx("a",{"aria-current":t?"page":void 0,"data-slot":"pagination-link","data-active":t,className:x(te({variant:t?"outline":"ghost",size:r}),e),...n})}function fe({className:e,...t}){return jsxs($,{"aria-label":"Go to previous page",size:"default",className:x("gap-1 px-2.5 sm:pl-2.5",e),...t,children:[jsx(ChevronLeftIcon,{}),jsx("span",{className:"hidden sm:block",children:"Previous"})]})}function he({className:e,...t}){return jsxs($,{"aria-label":"Go to next page",size:"default",className:x("gap-1 px-2.5 sm:pr-2.5",e),...t,children:[jsx("span",{className:"hidden sm:block",children:"Next"}),jsx(ChevronRightIcon,{})]})}function re({className:e,...t}){return jsxs("span",{"aria-hidden":true,"data-slot":"pagination-ellipsis",className:x("flex size-9 items-center justify-center",e),...t,children:[jsx(MoreHorizontalIcon,{className:"size-4"}),jsx("span",{className:"sr-only",children:"More pages"})]})}function ne({currentPage:e,totalPages:t,baseUrl:r,className:n,maxVisiblePages:s=5,showPrevNext:i=true,showFirstLast:o=true}){if(t<=1)return null;let a=()=>{let u=Math.floor(s/2),d=Math.max(1,e-u),b=Math.min(t,d+s-1);return b-d+1<s&&(d=Math.max(1,b-s+1)),{start:d,end:b}},{start:c,end:l}=a(),p=Array.from({length:l-c+1},(u,d)=>c+d),m=u=>u===1?r:`${r}?page=${u}`,P=e>1,h=e<t;return jsxs(de,{className:n,children:[jsxs(ge,{children:[o&&e>2&&jsxs(Fragment,{children:[jsx(E,{children:jsx($,{href:m(1),"aria-label":"Go to first page",children:jsx(ChevronsLeft,{className:"h-4 w-4"})})}),c>2&&jsx(E,{children:jsx(re,{})})]}),i&&jsx(E,{children:P?jsx(fe,{href:m(e-1)}):jsx("span",{className:"flex h-9 items-center justify-center gap-1 px-2.5 text-muted-foreground sm:pl-2.5",children:jsx("span",{className:"hidden sm:block",children:"Previous"})})}),p.map(u=>jsx(E,{children:jsx($,{href:m(u),isActive:u===e,children:u})},u)),i&&jsx(E,{children:h?jsx(he,{href:m(e+1)}):jsx("span",{className:"flex h-9 items-center justify-center gap-1 px-2.5 text-muted-foreground sm:pr-2.5",children:jsx("span",{className:"hidden sm:block",children:"Next"})})}),o&&e<t-1&&jsxs(Fragment,{children:[l<t-1&&jsx(E,{children:jsx(re,{})}),jsx(E,{children:jsx($,{href:m(t),"aria-label":"Go to last page",children:jsx(ChevronsRight,{className:"h-4 w-4"})})})]})]}),jsxs("div",{className:"sr-only","aria-live":"polite",children:["Page ",e," of ",t]})]})}function xt(e,t=10){let r=e.page,n=Array.isArray(r)?r[0]:r,s=Math.max(1,parseInt(n??"1",10)),i=(s-1)*t;return {currentPage:s,itemsPerPage:t,offset:i,calculateTotalPages:a=>Math.ceil(a/t)}}function Pt(e,t,r,n){let s=n?`${n}${e===1?r:`${r}?page=${e}`}`:void 0,i=e>1&&n?`${n}${e===2?r:`${r}?page=${e-1}`}`:void 0,o=e<t&&n?`${n}${r}?page=${e+1}`:void 0;return {alternates:{...s&&{canonical:s}},other:{...i&&{prev:i},...o&&{next:o}}}}function ie(e,t={}){let{customDomain:r,pathPrefix:n="/blog",language:s,isAccessibleForFree:i=true,includeOptionalProperties:o=true}=t,a=r??e.site.domain,c=r?`https://${a}${n}/${e.slug}`:e.meta.canonicalUrl??`https://${a}${n}/${e.slug}`,l=e.author?De(e.author,{customDomain:r,pathPrefix:n}):void 0,p=ye(e.site,{customDomain:r,pathPrefix:n}),P=`PT${Math.max(1,Math.ceil(e.readingSeconds/60))}M`,h={"@context":"https://schema.org","@type":"BlogPosting","@id":`${c}#article`,headline:e.title,description:e.excerpt,datePublished:e.publishedAt,dateModified:e.updatedAt,author:l,publisher:p,mainEntityOfPage:{"@type":"WebPage","@id":c},wordCount:e.wordCount,timeRequired:P,isAccessibleForFree:i};return o&&(e.featuredImage&&(h.image=e.featuredImage),e.meta.keywords.length>0&&(h.keywords=[...e.meta.keywords]),(s??e.site.locale)&&(h.inLanguage=s??e.site.locale),e.site.toneAdjectives.length>0&&(h.about=e.site.toneAdjectives.map(u=>({"@type":"Thing",name:u}))),e.site.toneAdjectives.length>0&&(h.genre=[...e.site.toneAdjectives])),h}function De(e,t={}){let{customDomain:r,pathPrefix:n="/blog"}=t,s={"@context":"https://schema.org","@type":"Person","@id":`#author-${e.id}`,name:e.name,identifier:e.id};if(e.bio&&(s.description=e.bio),e.slug?.trim()){let i=r?`https://${r}${n}/authors/${e.slug}`:`${n}/authors/${e.slug}`;s.url=i;}return e.isGuest&&(s.additionalType="GuestAuthor"),e.toneAdjectives&&e.toneAdjectives.length>0&&(s.knowsAbout=[...e.toneAdjectives]),s}function ye(e,t={}){let{customDomain:r,pathPrefix:n="/blog"}=t,i=`https://${r??e.domain}${n}`,o={"@context":"https://schema.org","@type":"Organization","@id":`${i}#organization`,name:e.name,url:i};return e.description?.trim()&&(o.description=e.description),e.tagline?.trim()&&(o.description=o.description?`${o.description}. ${e.tagline}`:e.tagline),o}function xe(e,t={}){let{customDomain:r,pathPrefix:n="/blog",language:s,includeSearchAction:i=true}=t,a=`https://${r??e.domain}${n}`,c=ye(e,t),l={"@context":"https://schema.org","@type":"WebSite","@id":`${a}#website`,name:e.name,url:a,publisher:c};return e.description?.trim()&&(l.description=e.description),(s??e.locale)&&(l.inLanguage=s??e.locale),i&&(l.potentialAction={"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:`${a}?search={search_term_string}`},"query-input":"required name=search_term_string"}),l}function Me(e,t={}){let{customDomain:r}=t;return {"@context":"https://schema.org","@type":"BreadcrumbList",itemListElement:e.map((n,s)=>({"@type":"ListItem",position:s+1,name:n.name,item:r&&!n.url.startsWith("http")?`https://${r}${n.url}`:n.url}))}}function Pe(e,t={}){let r=[];r.push(ie(e,t)),r.push(xe(e.site,t));let n=t.pathPrefix??"/blog",s=[{name:"Home",url:"/"},{name:e.site.name,url:n},{name:e.title,url:`${n}/${e.slug}`}];return r.push(Me(s,t)),r}function Se(e,t=[],r={}){let n=[];if(n.push(xe(e,r)),t.length>0){let s=t.slice(0,5).map(i=>ie(i,r));n.push(...s);}return n}function $e(e){let t=[];if(e["@context"]?e["@context"]!=="https://schema.org"&&t.push("@context must be 'https://schema.org'"):t.push("Missing required @context property"),e["@type"]||t.push("Missing required @type property"),e["@type"]==="BlogPosting"){let r=e;r.headline||t.push("BlogPosting: Missing required headline"),r.datePublished||t.push("BlogPosting: Missing required datePublished"),r.author||t.push("BlogPosting: Missing required author"),r.publisher||t.push("BlogPosting: Missing required publisher");}return e["@type"]==="Person"&&(e.name||t.push("Person: Missing required name")),e["@type"]==="Organization"&&(e.name||t.push("Organization: Missing required name")),{isValid:t.length===0,errors:t}}function Ue(e){return JSON.stringify(e,null,0)}function X(e){return {type:"application/ld+json",dangerouslySetInnerHTML:{__html:Ue(e)}}}function St(e){let t=new Set;return e.meta.keywords.forEach(r=>t.add(r)),e.site.toneAdjectives.forEach(r=>t.add(r)),e.author&&e.author.toneAdjectives.forEach(r=>t.add(r)),Array.from(t)}var W=class extends Error{constructor(r,n,s){super(r);this.code=n;this.details=s;this.name="StructuredDataError";}};function Rt(e,t={}){try{let r=ie(e,t),n=$e(r);return n.isValid?{schema:r}:{error:new W("Generated schema validation failed","VALIDATION_FAILED",n.errors)}}catch(r){return {error:new W("Failed to generate structured data","GENERATION_FAILED",r)}}}function He({articles:e,siteName:t,siteTagline:r,className:n,site:s,includeStructuredData:i=false,pagination:o}){return jsxs("div",{className:x("blog-home-page container mx-auto max-w-5xl px-4 py-8 sm:px-6 sm:py-12 lg:px-8 lg:py-16",n),children:[t&&jsxs("header",{className:"blog-header mb-8 text-center sm:mb-12 lg:mb-16",children:[jsx("h1",{className:"blog-title text-foreground mb-2 text-3xl font-light tracking-tight sm:text-4xl lg:text-5xl",children:t}),r&&jsx("p",{className:"blog-tagline text-muted-foreground text-base sm:text-lg",children:r})]}),jsxs("main",{className:"articles-list",children:[e.length===0?jsxs("div",{className:"no-articles text-muted-foreground py-16 text-center sm:py-24 lg:py-32",children:[jsx("h2",{className:"mb-3 text-xl font-light sm:mb-4 sm:text-2xl lg:text-3xl",children:"No articles yet"}),jsx("p",{className:"text-muted-foreground/70 mx-auto max-w-md text-base sm:text-lg",children:"This blog doesn't have any published articles yet."})]}):jsx("div",{className:"space-y-0",children:e.map(a=>jsx(Nt,{article:a},a.id))}),o&&o.totalPages>1&&jsx("div",{className:"pagination-wrapper mt-12",children:jsx(ne,{currentPage:o.currentPage,totalPages:o.totalPages,baseUrl:o.baseUrl??"/blog",className:"justify-center"})})]}),i&&s&&(()=>{let a=X(Se(s,e.slice(0,5)));return jsx("script",{type:a.type,dangerouslySetInnerHTML:a.dangerouslySetInnerHTML})})()]})}function wt(e){return `${Math.ceil(e/60)} min read`}function Nt({article:e}){let t=`/blog/${e.slug}`,r=formatDistanceToNow(new Date(e.publishedAt),{addSuffix:true}),n=wt(e.readingSeconds),s=e.featuredImage;return jsx("article",{className:"group border-border mb-6 block border-b pb-6 last:mb-0 last:border-b-0 last:pb-0 sm:mb-8 sm:pb-8",children:jsxs(Ne,{href:t,className:"focus-visible:ring-ring block rounded-lg hover:no-underline focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none","aria-label":`Read article: ${e.title}`,children:[jsxs("div",{className:"space-y-4 lg:hidden",children:[s&&jsx("div",{className:"relative aspect-[16/10] w-full overflow-hidden rounded-lg",children:jsx(Ve,{src:s,alt:e.featuredImageAlt??`Featured image for ${e.title}`,width:400,height:250,className:"h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"})}),jsxs("div",{className:"space-y-3",children:[jsx("h2",{className:"group-hover:text-primary text-lg leading-tight font-bold transition-colors sm:text-xl md:text-2xl",children:e.title}),jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-sm text-muted-foreground",children:[e.author&&jsxs(Fragment,{children:[jsx("span",{className:"font-medium",children:e.author.name}),jsx("span",{className:"text-border",children:"\u2022"})]}),jsx("time",{dateTime:e.publishedAt,className:"font-medium","aria-label":`Published ${r}`,children:r}),jsx("span",{className:"text-border",children:"\u2022"}),jsx("span",{className:"font-medium",children:n})]}),e.excerpt&&jsx("p",{className:"text-muted-foreground line-clamp-3 text-sm leading-relaxed sm:text-base",children:e.excerpt})]})]}),jsxs("div",{className:"hidden items-start gap-6 lg:flex xl:gap-8",children:[s&&jsx("div",{className:"relative aspect-[16/10] w-64 shrink-0 overflow-hidden rounded-lg xl:w-72",children:jsx(Ve,{src:s,alt:e.featuredImageAlt??`Featured image for ${e.title}`,width:288,height:180,className:"h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"})}),jsxs("div",{className:"flex min-h-[180px] flex-1 flex-col justify-between space-y-4 xl:min-h-[200px]",children:[jsxs("div",{className:"space-y-4",children:[jsx("h2",{className:"group-hover:text-primary text-2xl leading-tight font-bold transition-colors xl:text-3xl",children:e.title}),e.excerpt&&jsx("p",{className:"text-muted-foreground line-clamp-3 text-base leading-relaxed xl:text-lg",children:e.excerpt})]}),jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-1 text-sm text-muted-foreground",children:[e.author&&jsxs(Fragment,{children:[jsx("span",{className:"font-medium",children:e.author.name}),jsx("span",{className:"text-border",children:"\u2022"})]}),jsx("time",{dateTime:e.publishedAt,className:"font-medium","aria-label":`Published ${r}`,children:r}),jsx("span",{className:"text-border",children:"\u2022"}),jsx("span",{className:"font-medium",children:n})]})]})]})]})})}function Tt(e,t,r,n){let s=e?`${e} - Blog`:"Blog",i=n&&n.currentPage>1?`${s} - Page ${n.currentPage}`:s,o=t??"Read our latest articles and insights.",a="/blog",c=r?`${r}${n&&n.currentPage>1?`${a}?page=${n.currentPage}`:a}`:void 0,l=n&&n.currentPage>1&&r?`${r}${n.currentPage===2?a:`${a}?page=${n.currentPage-1}`}`:void 0,p=n&&n.currentPage<n.totalPages&&r?`${r}${a}?page=${n.currentPage+1}`:void 0;return {title:i,description:o,openGraph:{title:i,description:o,type:"website",...r&&{url:c}},twitter:{card:"summary_large_image",title:i,description:o},alternates:{...c&&{canonical:c}},other:{...l&&{prev:l},...p&&{next:p}}}}var Ot=cva("inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function Re({className:e,variant:t,...r}){return jsx("div",{className:x(Ot({variant:t}),e),...r})}function K({className:e,...t}){return jsx("div",{"data-slot":"card",className:x("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Ae({className:e,...t}){return jsx("div",{"data-slot":"card-header",className:x("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function ve({className:e,...t}){return jsx("div",{"data-slot":"card-title",className:x("leading-none font-semibold",e),...t})}function _t({className:e,...t}){return jsx("div",{"data-slot":"card-description",className:x("text-muted-foreground text-sm",e),...t})}function J({className:e,...t}){return jsx("div",{"data-slot":"card-content",className:x("px-6",e),...t})}function Et({className:e,...t}){return jsx("div",{"data-slot":"card-footer",className:x("flex items-center px-6 [.border-t]:pt-6",e),...t})}var se=je.forwardRef(({className:e,orientation:t="horizontal",decorative:r=true,...n},s)=>jsx(we.Root,{ref:s,decorative:r,orientation:t,className:x("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...n}));se.displayName=we.Root.displayName;function Ut(e){return `${Math.ceil(e/60)} min read`}function Fe({article:e,className:t,navigation:r}){let n=new Date(e.publishedAt),s=new Date(e.updatedAt),i=s.getTime()!==n.getTime(),o=formatDistanceToNow(n,{addSuffix:true}),a=Ut(e.readingSeconds),c=e.featuredImage;return jsxs("article",{className:x("article-page mx-auto max-w-4xl px-4 py-6 pb-12 sm:px-6 sm:py-8 sm:pb-16 lg:px-8 lg:py-12 lg:pb-24",t),children:[r?.backToHome&&jsx("header",{className:"mb-8 sm:mb-12 lg:mb-16",children:jsxs(Ne,{href:r.backToHome.url,className:"text-muted-foreground hover:text-foreground group focus-visible:ring-ring inline-flex touch-manipulation items-center space-x-2 rounded-md px-2 py-1 transition-colors focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none sm:space-x-3","aria-label":r.backToHome.label??"Return to blog",children:[jsx(ArrowLeft,{className:"h-4 w-4 transition-transform group-hover:-translate-x-1 sm:h-5 sm:w-5","aria-hidden":"true"}),jsxs("span",{className:"text-sm font-medium sm:text-base",children:[jsx("span",{className:"hidden sm:inline",children:r.backToHome.label??"Back to all articles"}),jsx("span",{className:"sm:hidden",children:"Back"})]})]})}),jsxs("header",{className:"article-header mb-6 space-y-4 text-center sm:mb-8 sm:space-y-6 lg:mb-12 lg:space-y-8",children:[jsx("h1",{className:"article-title text-foreground px-4 text-2xl leading-tight font-light tracking-tight sm:px-0 sm:text-3xl md:text-4xl lg:text-5xl xl:text-6xl",children:e.title}),e.excerpt&&jsx("p",{className:"article-excerpt text-muted-foreground mx-auto mt-6 max-w-xs px-4 text-base leading-relaxed sm:mt-8 sm:max-w-lg sm:px-0 sm:text-lg md:max-w-2xl md:text-xl lg:max-w-4xl lg:text-2xl",children:e.excerpt}),jsxs("div",{className:"article-meta text-muted-foreground flex flex-col items-center gap-2 text-sm sm:gap-3 sm:text-base",children:[e.author&&jsxs("div",{className:"flex items-center gap-2",children:[jsx("span",{className:"sr-only",children:"Author"}),jsx("span",{className:"font-medium",children:e.author.name}),e.author.isGuest&&jsx(Re,{variant:"outline",className:"text-xs",children:"Guest Author"})]}),jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-3 gap-y-1",children:[jsxs("time",{dateTime:e.publishedAt,className:"font-medium","aria-label":`Published ${o}`,children:["Published ",o]}),jsx("span",{className:"text-border",children:"\u2022"}),jsx("span",{className:"font-medium",children:a})]}),i&&jsxs("time",{dateTime:e.updatedAt,className:"text-xs",children:["Updated ",format(s,"MMMM d, yyyy")]}),jsx("div",{className:"bg-border h-px w-6 sm:w-8","aria-hidden":"true"}),jsxs("span",{className:"text-xs tracking-wider uppercase sm:text-sm",role:"text",children:["From ",e.site.name]})]})]}),c&&jsx("div",{className:"article-featured-image relative my-8 aspect-[16/9] w-full overflow-hidden rounded-lg sm:my-12 lg:my-16",children:jsx(Ve,{src:c,alt:e.featuredImageAlt??`Featured image for ${e.title}`,className:"h-full w-full object-cover",width:800,height:450,priority:true})}),jsx("div",{className:"article-content",children:jsx("div",{className:"prose prose-sm sm:prose-base lg:prose-lg xl:prose-xl prose-gray dark:prose-invert prose-headings:scroll-mt-20 prose-headings:font-light prose-h1:text-2xl sm:prose-h1:text-3xl lg:prose-h1:text-4xl prose-h2:text-xl sm:prose-h2:text-2xl lg:prose-h2:text-3xl prose-h3:text-lg sm:prose-h3:text-xl lg:prose-h3:text-2xl prose-p:leading-relaxed prose-img:mx-auto prose-img:rounded-lg prose-a:transition-colors max-w-none",children:jsx(MDXRemote,{source:e.content})})}),e.author?.bio&&jsxs("div",{className:"author-bio mt-12",children:[jsx(se,{className:"mb-8"}),jsxs(K,{children:[jsx(Ae,{children:jsxs(ve,{className:"flex items-center gap-2",children:["About ",e.author.name,e.author.isGuest&&jsx(Re,{variant:"outline",className:"text-xs",children:"Guest Author"})]})}),jsx(J,{children:jsx("div",{className:"prose dark:prose-invert",children:jsx("p",{className:"text-muted-foreground",children:e.author.bio})})})]})]}),(!!r?.previousArticle||!!r?.nextArticle)&&jsxs("nav",{className:"article-nav mt-12",children:[jsx(se,{className:"mb-8"}),jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2",children:[r?.previousArticle&&jsx(K,{className:"group hover:bg-accent/50 cursor-pointer transition-colors",children:jsx(Ne,{href:r.previousArticle.url,className:"block",children:jsxs(J,{className:"p-4",children:[jsx("div",{className:"text-muted-foreground mb-2 text-sm font-medium",children:"\u2190 Previous Article"}),jsx("div",{className:"text-foreground group-hover:text-primary transition-colors",children:r.previousArticle.title})]})})}),r?.nextArticle&&jsx(K,{className:x("group hover:bg-accent/50 cursor-pointer transition-colors",!r?.previousArticle&&"md:col-start-2"),children:jsx(Ne,{href:r.nextArticle.url,className:"block",children:jsxs(J,{className:"p-4 md:text-right",children:[jsx("div",{className:"text-muted-foreground mb-2 text-sm font-medium",children:"Next Article \u2192"}),jsx("div",{className:"text-foreground group-hover:text-primary transition-colors",children:r.nextArticle.title})]})})})]})]}),(()=>{let l=X(Pe(e));return jsx("script",{type:l.type,dangerouslySetInnerHTML:l.dangerouslySetInnerHTML})})()]})}function Vt(e){let t=e.meta.title??e.title,r=e.meta.description??e.excerpt,n=e.meta.canonicalUrl??`${e.site.domain}/blog/${e.slug}`,s=e.meta.ogImage??e.featuredImage;return {title:t,description:r,keywords:e.meta.keywords.join(", "),authors:e.author?[{name:e.author.name}]:void 0,openGraph:{title:t,description:r,type:"article",url:n,images:s?[{url:s,alt:e.featuredImageAlt??t}]:void 0,publishedTime:e.publishedAt,modifiedTime:e.updatedAt,authors:e.author?[e.author.name]:void 0,siteName:e.site.name},twitter:{card:"summary_large_image",title:t,description:r,images:s?[s]:void 0},alternates:{canonical:n}}}function Te(e){let t=e.headers.get("Authorization");if(!t)return null;let n=/^Bearer\s+(.+)$/i.exec(t);if(n?.[1])return n[1];let i=/^Token\s+(.+)$/i.exec(t);return i?.[1]?i[1]:null}var oe=class{validApiKeys;constructor(t){this.validApiKeys=new Set(t);}async validateToken(t){return t?.trim()?this.validApiKeys.has(t)?{valid:true,context:{tokenHash:this.hashToken(t)}}:{valid:false,errorCode:"invalid"}:{valid:false,errorCode:"missing"}}extractToken=t=>Te(t);hashToken(t){return t.substring(0,8)+"..."}},G=class extends oe{constructor(t="BLOG_PLATFORM_API_KEYS"){let r=process.env[t];!r&&t==="BLOG_PLATFORM_API_KEYS"&&(r=process.env.BLOG_AUTH_TOKEN);let n=r?r.split(",").map(s=>s.trim()).filter(Boolean):[];n.length===0&&console.warn(`\u26A0\uFE0F No API keys found in environment variable ${t}${t==="BLOG_PLATFORM_API_KEYS"?" (set BLOG_PLATFORM_API_KEYS or BLOG_AUTH_TOKEN)":""}. Authentication will fail for all requests.`),super(n);}},Y=class{async validateToken(){return {valid:true,context:{development:true}}}extractToken(){return "development-mode"}},ae=class{hasWarned=false;async validateToken(t){return this.hasWarned||(console.error("\u274C SECURITY WARNING: Blog platform authentication not initialized! All requests will be rejected. Call initBlogPlatform() to configure authentication."),this.hasWarned=true),{valid:false,errorCode:"invalid"}}};function Gt(){return globalThis.__BLOG_PLATFORM_AUTH_CONFIG__??=new ae,globalThis.__BLOG_PLATFORM_AUTH_CONFIG__}function le(e){globalThis.__BLOG_PLATFORM_AUTH_CONFIG__=e;}function Ce(){return globalThis.__BLOG_PLATFORM_AUTH_CONFIG__??Gt()}function Ht(e){le(new G(e));}async function B(e){let t=Ce(),r=t.extractToken?t.extractToken(e):Te(e);if(!r)return {authenticated:false,result:{valid:false,errorCode:"missing"},token:null};let n=await t.validateToken(r);return {authenticated:n.valid,result:n,token:r}}function jt(e,t=""){let n=Ce().errorMessages??{},s,i;switch(e.errorCode){case "missing":s=n.missing??"Authentication token is required",i="PUB005";break;case "expired":s=n.expired??"Authentication token has expired",i="PUB005";break;case "invalid":default:s=n.invalid??"Invalid authentication credentials",i="PUB005";break}return {success:false,error:{code:i,message:s,details:{authError:e.errorCode??"invalid"}},idempotencyKey:t}}async function k(e){let t=await B(e);return t.authenticated?{authenticated:true,context:t.result.context}:{authenticated:false,error:jt(t.result)}}function Ft(){let e=process.env.SKIP_BLOG_PLATFORM_AUTH;return e==="true"||e==="1"||process.env.NODE_ENV==="test"}var ce=class{articles=new Map;operations=new Map;async saveArticle(t,r){let n=await this.checkIdempotency(r);if(n)if(n.success){if(Array.from(this.articles.values()).some(o=>o.id===t.id))return n}else return n;if(this.articles.has(t.slug)){let i={success:false,error:{code:"PUB003",message:"This URL is already in use. Please choose another."},idempotencyKey:r};return await this.storeOperationResult(r,i),i}this.articles.set(t.slug,t);let s={success:true,url:`/${t.slug}`,platformPostId:t.id,publishedAt:t.publishedAt,idempotencyKey:r};return await this.storeOperationResult(r,s),s}async getArticle(t){return this.articles.get(t)??null}async listArticles(t={}){let{limit:r=10,offset:n=0,sortBy:s="publishedAt",order:i="desc"}=t,o=Array.from(this.articles.values());return o.sort((c,l)=>{let p=new Date(c[s]).getTime(),m=new Date(l[s]).getTime();return i==="desc"?m-p:p-m}),{articles:o.slice(n,n+r),total:o.length}}async removeArticle(t,r){let n=await this.checkIdempotency(r);if(n)if(n.success){if(!this.articles.has(t))return n}else return n;if(!this.articles.has(t)){let i={success:false,error:{code:"PUB007",message:"Article not found"},idempotencyKey:r};return await this.storeOperationResult(r,i),i}this.articles.delete(t);let s={success:true,idempotencyKey:r};return await this.storeOperationResult(r,s),s}async checkIdempotency(t){return this.operations.get(t)??null}async storeOperationResult(t,r){this.operations.set(t,r);}};function qt(){let e=globalThis;if(e.__BLOG_PLATFORM_STORAGE_WARNED__)return;e.__BLOG_PLATFORM_STORAGE_WARNED__=true;let t="Blog platform: No storage provider configured. Falling back to in-memory storage (data is not persisted).";process.env.NODE_ENV==="production"?console.error(`${t} Call initBlogPlatform({ storage: /* your persistent adapter */ }) to avoid data loss.`):console.warn(t);}function zt(){let e=globalThis;e.__BLOG_PLATFORM_STORAGE__||(qt(),e.__BLOG_PLATFORM_STORAGE__=new ce);let t=e.__BLOG_PLATFORM_STORAGE__;if(!t)throw new Error("Blog platform storage not initialized");return t}function D(){return zt()}function Oe(e){let t=globalThis;t.__BLOG_PLATFORM_STORAGE__=e;}function Xt(){return globalThis.__BLOG_PLATFORM_RATE_LIMITER__??null}function Kt(e){let t=globalThis;t.__BLOG_PLATFORM_RATE_LIMITER__=e;}function ue(e){let{redisUrl:t,redisToken:r,requestsPerMinute:n=5,keyPrefix:s="blog-platform-ratelimit",analytics:i=true}=e,o=new Redis({url:t,token:r}),a=new Ratelimit({redis:o,analytics:i,prefix:s,limiter:Ratelimit.slidingWindow(n,"1m")});Kt(a);}function Le(){let e=process.env.UPSTASH_REDIS_REST_URL,t=process.env.UPSTASH_REDIS_REST_TOKEN;if(!e||!t){console.warn("Blog platform: No Upstash Redis configuration found. Rate limiting disabled.");return}ue({redisUrl:e,redisToken:t}),console.log("Blog platform: Rate limiting configured (5 requests per minute per token)");}async function ze(e){let t=Xt();if(!t)return console.warn("Blog platform: Rate limiter not configured. All requests allowed."),{success:true,remaining:999,reset:Date.now()+6e4,limit:5,count:0};try{let r=await t.limit(e);return {success:r.success,remaining:r.remaining,reset:r.reset,limit:r.limit,count:r.limit-r.remaining}}catch(r){return console.error("Blog platform: Rate limit check failed:",r),{success:true,remaining:0,reset:Date.now()+6e4,limit:5,count:0}}}function We(e,t=""){let r=Math.ceil((e.reset-Date.now())/6e4);return {success:false,error:{code:"PUB011",message:`Rate limit exceeded. You can make ${e.limit} requests per minute. Try again in ${r} minute(s).`,details:{rateLimit:e}},idempotencyKey:t}}async function I(e,t=""){let r=await ze(e);return r.success?{allowed:true,rateLimitResult:r}:{allowed:false,errorResponse:We(r,t)}}function N(e){return {"X-RateLimit-Limit":e.limit.toString(),"X-RateLimit-Remaining":e.remaining.toString(),"X-RateLimit-Reset":e.reset.toString(),"Retry-After":Math.ceil((e.reset-Date.now())/1e3).toString()}}function me(e){let{auth:t,storage:r,rateLimit:n,autoRateLimit:s=true}=e;if(!t)throw new Error(`Blog platform initialization failed: 'auth' is required.
1
+ import Ce from'next/link';import He from'next/image';import {clsx}from'clsx';import {twMerge}from'tailwind-merge';import {ChevronLeftIcon,ChevronRightIcon,MoreHorizontalIcon,ChevronsLeft,ChevronsRight,ArrowLeft}from'lucide-react';import {Slot}from'@radix-ui/react-slot';import {cva}from'class-variance-authority';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {formatDistanceToNow,format}from'date-fns';import {MDXRemote}from'next-mdx-remote-client/rsc';import*as qe from'react';import*as Te from'@radix-ui/react-separator';import $t from'remark-gfm';import Ut from'remark-toc';import {Ratelimit}from'@upstash/ratelimit';import {Redis}from'@upstash/redis';import {eq,and,desc,sql}from'drizzle-orm';import {sqliteTable,integer,text,uniqueIndex}from'drizzle-orm/sqlite-core';import {NextResponse}from'next/server';function x(...e){return twMerge(clsx(e))}var ne=cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive",{variants:{variant:{default:"bg-primary text-primary-foreground shadow-xs hover:bg-primary/90",destructive:"bg-destructive text-white shadow-xs hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50",secondary:"bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-9 px-4 py-2 has-[>svg]:px-3",sm:"h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5",lg:"h-10 rounded-md px-6 has-[>svg]:px-4",icon:"size-9"}},defaultVariants:{variant:"default",size:"default"}});function ft({className:e,variant:t,size:r,asChild:n=false,...o}){return jsx(n?Slot:"button",{"data-slot":"button",className:x(ne({variant:t,size:r,className:e})),...o})}function fe({className:e,...t}){return jsx("nav",{role:"navigation","aria-label":"pagination","data-slot":"pagination",className:x("mx-auto flex w-full justify-center",e),...t})}function he({className:e,...t}){return jsx("ul",{"data-slot":"pagination-content",className:x("flex flex-row items-center gap-1",e),...t})}function B({...e}){return jsx("li",{"data-slot":"pagination-item",...e})}function U({className:e,isActive:t,size:r="icon",...n}){return jsx("a",{"aria-current":t?"page":void 0,"data-slot":"pagination-link","data-active":t,className:x(ne({variant:t?"outline":"ghost",size:r}),e),...n})}function be({className:e,...t}){return jsxs(U,{"aria-label":"Go to previous page",size:"default",className:x("gap-1 px-2.5 sm:pl-2.5",e),...t,children:[jsx(ChevronLeftIcon,{}),jsx("span",{className:"hidden sm:block",children:"Previous"})]})}function ye({className:e,...t}){return jsxs(U,{"aria-label":"Go to next page",size:"default",className:x("gap-1 px-2.5 sm:pr-2.5",e),...t,children:[jsx("span",{className:"hidden sm:block",children:"Next"}),jsx(ChevronRightIcon,{})]})}function ie({className:e,...t}){return jsxs("span",{"aria-hidden":true,"data-slot":"pagination-ellipsis",className:x("flex size-9 items-center justify-center",e),...t,children:[jsx(MoreHorizontalIcon,{className:"size-4"}),jsx("span",{className:"sr-only",children:"More pages"})]})}function oe({currentPage:e,totalPages:t,baseUrl:r,className:n,maxVisiblePages:o=5,showPrevNext:i=true,showFirstLast:s=true}){if(t<=1)return null;let a=()=>{let m=Math.floor(o/2),d=Math.max(1,e-m),b=Math.min(t,d+o-1);return b-d+1<o&&(d=Math.max(1,b-o+1)),{start:d,end:b}},{start:c,end:l}=a(),p=Array.from({length:l-c+1},(m,d)=>c+d),u=m=>m===1?r:`${r}?page=${m}`,P=e>1,h=e<t;return jsxs(fe,{className:n,children:[jsxs(he,{children:[s&&e>2&&jsxs(Fragment,{children:[jsx(B,{children:jsx(U,{href:u(1),"aria-label":"Go to first page",children:jsx(ChevronsLeft,{className:"h-4 w-4"})})}),c>2&&jsx(B,{children:jsx(ie,{})})]}),i&&jsx(B,{children:P?jsx(be,{href:u(e-1)}):jsx("span",{className:"flex h-9 items-center justify-center gap-1 px-2.5 text-muted-foreground sm:pl-2.5",children:jsx("span",{className:"hidden sm:block",children:"Previous"})})}),p.map(m=>jsx(B,{children:jsx(U,{href:u(m),isActive:m===e,children:m})},m)),i&&jsx(B,{children:h?jsx(ye,{href:u(e+1)}):jsx("span",{className:"flex h-9 items-center justify-center gap-1 px-2.5 text-muted-foreground sm:pr-2.5",children:jsx("span",{className:"hidden sm:block",children:"Next"})})}),s&&e<t-1&&jsxs(Fragment,{children:[l<t-1&&jsx(B,{children:jsx(ie,{})}),jsx(B,{children:jsx(U,{href:u(t),"aria-label":"Go to last page",children:jsx(ChevronsRight,{className:"h-4 w-4"})})})]})]}),jsxs("div",{className:"sr-only","aria-live":"polite",children:["Page ",e," of ",t]})]})}function Rt(e,t=10){let r=e.page,n=Array.isArray(r)?r[0]:r,o=Math.max(1,parseInt(n??"1",10)),i=(o-1)*t;return {currentPage:o,itemsPerPage:t,offset:i,calculateTotalPages:a=>Math.ceil(a/t)}}function At(e,t,r,n){let o=n?`${n}${e===1?r:`${r}?page=${e}`}`:void 0,i=e>1&&n?`${n}${e===2?r:`${r}?page=${e-1}`}`:void 0,s=e<t&&n?`${n}${r}?page=${e+1}`:void 0;return {alternates:{...o&&{canonical:o}},other:{...i&&{prev:i},...s&&{next:s}}}}function se(e,t={}){let{customDomain:r,pathPrefix:n="/blog",language:o,isAccessibleForFree:i=true,includeOptionalProperties:s=true}=t,a=r??e.site.domain,c=r?`https://${a}${n}/${e.slug}`:e.meta.canonicalUrl??`https://${a}${n}/${e.slug}`,l=e.author?$e(e.author,{customDomain:r,pathPrefix:n}):void 0,p=Pe(e.site,{customDomain:r,pathPrefix:n}),P=`PT${Math.max(1,Math.ceil(e.readingSeconds/60))}M`,h={"@context":"https://schema.org","@type":"BlogPosting","@id":`${c}#article`,headline:e.title,description:e.excerpt,datePublished:e.publishedAt,dateModified:e.updatedAt,author:l,publisher:p,mainEntityOfPage:{"@type":"WebPage","@id":c},wordCount:e.wordCount,timeRequired:P,isAccessibleForFree:i};return s&&(e.featuredImage&&(h.image=e.featuredImage),e.meta.keywords.length>0&&(h.keywords=[...e.meta.keywords]),(o??e.site.locale)&&(h.inLanguage=o??e.site.locale),e.site.toneAdjectives.length>0&&(h.about=e.site.toneAdjectives.map(m=>({"@type":"Thing",name:m}))),e.site.toneAdjectives.length>0&&(h.genre=[...e.site.toneAdjectives])),h}function $e(e,t={}){let{customDomain:r,pathPrefix:n="/blog"}=t,o={"@context":"https://schema.org","@type":"Person","@id":`#author-${e.id}`,name:e.name,identifier:e.id};if(e.bio&&(o.description=e.bio),e.slug?.trim()){let i=r?`https://${r}${n}/authors/${e.slug}`:`${n}/authors/${e.slug}`;o.url=i;}return e.isGuest&&(o.additionalType="GuestAuthor"),e.toneAdjectives&&e.toneAdjectives.length>0&&(o.knowsAbout=[...e.toneAdjectives]),o}function Pe(e,t={}){let{customDomain:r,pathPrefix:n="/blog"}=t,i=`https://${r??e.domain}${n}`,s={"@context":"https://schema.org","@type":"Organization","@id":`${i}#organization`,name:e.name,url:i};return e.description?.trim()&&(s.description=e.description),e.tagline?.trim()&&(s.description=s.description?`${s.description}. ${e.tagline}`:e.tagline),s}function Se(e,t={}){let{customDomain:r,pathPrefix:n="/blog",language:o,includeSearchAction:i=true}=t,a=`https://${r??e.domain}${n}`,c=Pe(e,t),l={"@context":"https://schema.org","@type":"WebSite","@id":`${a}#website`,name:e.name,url:a,publisher:c};return e.description?.trim()&&(l.description=e.description),(o??e.locale)&&(l.inLanguage=o??e.locale),i&&(l.potentialAction={"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:`${a}?search={search_term_string}`},"query-input":"required name=search_term_string"}),l}function Ue(e,t={}){let{customDomain:r}=t;return {"@context":"https://schema.org","@type":"BreadcrumbList",itemListElement:e.map((n,o)=>({"@type":"ListItem",position:o+1,name:n.name,item:r&&!n.url.startsWith("http")?`https://${r}${n.url}`:n.url}))}}function Re(e,t={}){let r=[];r.push(se(e,t)),r.push(Se(e.site,t));let n=t.pathPrefix??"/blog",o=[{name:"Home",url:"/"},{name:e.site.name,url:n},{name:e.title,url:`${n}/${e.slug}`}];return r.push(Ue(o,t)),r}function Ae(e,t=[],r={}){let n=[];if(n.push(Se(e,r)),t.length>0){let o=t.slice(0,5).map(i=>se(i,r));n.push(...o);}return n}function Ve(e){let t=[];if(e["@context"]?e["@context"]!=="https://schema.org"&&t.push("@context must be 'https://schema.org'"):t.push("Missing required @context property"),e["@type"]||t.push("Missing required @type property"),e["@type"]==="BlogPosting"){let r=e;r.headline||t.push("BlogPosting: Missing required headline"),r.datePublished||t.push("BlogPosting: Missing required datePublished"),r.author||t.push("BlogPosting: Missing required author"),r.publisher||t.push("BlogPosting: Missing required publisher");}return e["@type"]==="Person"&&(e.name||t.push("Person: Missing required name")),e["@type"]==="Organization"&&(e.name||t.push("Organization: Missing required name")),{isValid:t.length===0,errors:t}}function Ge(e){return JSON.stringify(e,null,0)}function K(e){return {type:"application/ld+json",dangerouslySetInnerHTML:{__html:Ge(e)}}}function vt(e){let t=new Set;return e.meta.keywords.forEach(r=>t.add(r)),e.site.toneAdjectives.forEach(r=>t.add(r)),e.author&&e.author.toneAdjectives.forEach(r=>t.add(r)),Array.from(t)}var X=class extends Error{constructor(r,n,o){super(r);this.code=n;this.details=o;this.name="StructuredDataError";}code;details};function wt(e,t={}){try{let r=se(e,t),n=Ve(r);return n.isValid?{schema:r}:{error:new X("Generated schema validation failed","VALIDATION_FAILED",n.errors)}}catch(r){return {error:new X("Failed to generate structured data","GENERATION_FAILED",r)}}}function k(e="/blog"){let t=e.trim();return !t||t==="/"?"":t.replace(/^(?!\/)/,"/").replace(/\/+$/,"")}function J(e,t){let r=k(e),n=t?.replace(/^\/+/,"").replace(/\/+$/,"");return n?`${r}/${n}`.replace(/\/+/g,"/"):r||"/"}function Nt(e){let t=new URL(e);return k(t.pathname)}function Fe({articles:e,siteName:t,siteTagline:r,className:n,site:o,includeStructuredData:i=false,basePath:s="/blog",pagination:a}){let c=k(s)||"/";return jsxs("div",{className:x("blog-home-page container mx-auto max-w-5xl px-4 py-8 sm:px-6 sm:py-12 lg:px-8 lg:py-16",n),children:[t&&jsxs("header",{className:"blog-header mb-8 text-center sm:mb-12 lg:mb-16",children:[jsx("h1",{className:"blog-title text-foreground mb-2 text-3xl font-light tracking-tight sm:text-4xl lg:text-5xl",children:t}),r&&jsx("p",{className:"blog-tagline text-muted-foreground text-base sm:text-lg",children:r})]}),jsxs("main",{className:"articles-list",children:[e.length===0?jsxs("div",{className:"no-articles text-muted-foreground py-16 text-center sm:py-24 lg:py-32",children:[jsx("h2",{className:"mb-3 text-xl font-light sm:mb-4 sm:text-2xl lg:text-3xl",children:"No articles yet"}),jsx("p",{className:"text-muted-foreground/70 mx-auto max-w-md text-base sm:text-lg",children:"This blog doesn't have any published articles yet."})]}):jsx("div",{className:"space-y-0",children:e.map(l=>jsx(Lt,{article:l,basePath:c},l.id))}),a&&a.totalPages>1&&jsx("div",{className:"pagination-wrapper mt-12",children:jsx(oe,{currentPage:a.currentPage,totalPages:a.totalPages,baseUrl:a.baseUrl??c,className:"justify-center"})})]}),i&&o&&(()=>{let l=K(Ae(o,e.slice(0,5),{pathPrefix:c}));return jsx("script",{type:l.type,dangerouslySetInnerHTML:l.dangerouslySetInnerHTML})})()]})}function Ot(e){return `${Math.ceil(e/60)} min read`}function Lt({article:e,basePath:t}){let r=J(t,e.slug),n=formatDistanceToNow(new Date(e.publishedAt),{addSuffix:true}),o=Ot(e.readingSeconds),i=e.featuredImage;return jsx("article",{className:"group border-border mb-6 block border-b pb-6 last:mb-0 last:border-b-0 last:pb-0 sm:mb-8 sm:pb-8",children:jsxs(Ce,{href:r,className:"focus-visible:ring-ring block rounded-lg hover:no-underline focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none","aria-label":`Read article: ${e.title}`,children:[jsxs("div",{className:"space-y-4 lg:hidden",children:[i&&jsx("div",{className:"relative aspect-[16/10] w-full overflow-hidden rounded-lg",children:jsx(He,{src:i,alt:e.featuredImageAlt??`Featured image for ${e.title}`,width:400,height:250,className:"h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"})}),jsxs("div",{className:"space-y-3",children:[jsx("h2",{className:"group-hover:text-primary text-lg leading-tight font-bold transition-colors sm:text-xl md:text-2xl",children:e.title}),jsxs("div",{className:"text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1 text-sm",children:[e.author&&jsxs(Fragment,{children:[jsx("span",{className:"font-medium",children:e.author.name}),jsx("span",{className:"text-border",children:"\u2022"})]}),jsx("time",{dateTime:e.publishedAt,className:"font-medium","aria-label":`Published ${n}`,children:n}),jsx("span",{className:"text-border",children:"\u2022"}),jsx("span",{className:"font-medium",children:o})]}),e.excerpt&&jsx("p",{className:"text-muted-foreground line-clamp-3 text-sm leading-relaxed sm:text-base",children:e.excerpt})]})]}),jsxs("div",{className:"hidden items-start gap-6 lg:flex xl:gap-8",children:[i&&jsx("div",{className:"relative aspect-[16/10] w-64 shrink-0 overflow-hidden rounded-lg xl:w-72",children:jsx(He,{src:i,alt:e.featuredImageAlt??`Featured image for ${e.title}`,width:288,height:180,className:"h-full w-full object-cover transition-transform duration-300 group-hover:scale-105"})}),jsxs("div",{className:"flex min-h-[180px] flex-1 flex-col justify-between space-y-4 xl:min-h-[200px]",children:[jsxs("div",{className:"space-y-4",children:[jsx("h2",{className:"group-hover:text-primary text-2xl leading-tight font-bold transition-colors xl:text-3xl",children:e.title}),e.excerpt&&jsx("p",{className:"text-muted-foreground line-clamp-3 text-base leading-relaxed xl:text-lg",children:e.excerpt})]}),jsxs("div",{className:"text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1 text-sm",children:[e.author&&jsxs(Fragment,{children:[jsx("span",{className:"font-medium",children:e.author.name}),jsx("span",{className:"text-border",children:"\u2022"})]}),jsx("time",{dateTime:e.publishedAt,className:"font-medium","aria-label":`Published ${n}`,children:n}),jsx("span",{className:"text-border",children:"\u2022"}),jsx("span",{className:"font-medium",children:o})]})]})]})]})})}function _t(e,t,r,n,o="/blog"){let i=e?`${e} - Blog`:"Blog",s=n&&n.currentPage>1?`${i} - Page ${n.currentPage}`:i,a=t??"Read our latest articles and insights.",c=k(o)||"/",l=r?`${r}${n&&n.currentPage>1?`${c}?page=${n.currentPage}`:c}`:void 0,p=n&&n.currentPage>1&&r?`${r}${n.currentPage===2?c:`${c}?page=${n.currentPage-1}`}`:void 0,u=n&&n.currentPage<n.totalPages&&r?`${r}${c}?page=${n.currentPage+1}`:void 0;return {title:s,description:a,openGraph:{title:s,description:a,type:"website",...r&&{url:l}},twitter:{card:"summary_large_image",title:s,description:a},alternates:{...l&&{canonical:l}},other:{...p&&{prev:p},...u&&{next:u}}}}var Et=cva("inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",secondary:"border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",destructive:"border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",outline:"text-foreground"}},defaultVariants:{variant:"default"}});function ve({className:e,variant:t,...r}){return jsx("div",{className:x(Et({variant:t}),e),...r})}function Y({className:e,...t}){return jsx("div",{"data-slot":"card",className:x("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function we({className:e,...t}){return jsx("div",{"data-slot":"card-header",className:x("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",e),...t})}function Ne({className:e,...t}){return jsx("div",{"data-slot":"card-title",className:x("leading-none font-semibold",e),...t})}function kt({className:e,...t}){return jsx("div",{"data-slot":"card-description",className:x("text-muted-foreground text-sm",e),...t})}function Q({className:e,...t}){return jsx("div",{"data-slot":"card-content",className:x("px-6",e),...t})}function Mt({className:e,...t}){return jsx("div",{"data-slot":"card-footer",className:x("flex items-center px-6 [.border-t]:pt-6",e),...t})}var ae=qe.forwardRef(({className:e,orientation:t="horizontal",decorative:r=true,...n},o)=>jsx(Te.Root,{ref:o,decorative:r,orientation:t,className:x("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...n}));ae.displayName=Te.Root.displayName;var ze={mdxOptions:{remarkPlugins:[Ut,$t]}};function qt(e){return `${Math.ceil(e/60)} min read`}function We({article:e,className:t,navigation:r,basePath:n="/blog"}){let o=k(n)||"/",i=new Date(e.publishedAt),s=new Date(e.updatedAt),a=s.getTime()!==i.getTime(),c=formatDistanceToNow(i,{addSuffix:true}),l=qt(e.readingSeconds),p=e.featuredImage;return jsxs("article",{className:x("article-page mx-auto max-w-4xl px-4 py-6 pb-12 sm:px-6 sm:py-8 sm:pb-16 lg:px-8 lg:py-12 lg:pb-24",t),children:[r?.backToHome&&jsx("header",{className:"mb-8 sm:mb-12 lg:mb-16",children:jsxs(Ce,{href:r.backToHome.url,className:"text-muted-foreground hover:text-foreground group focus-visible:ring-ring inline-flex touch-manipulation items-center space-x-2 rounded-md px-2 py-1 transition-colors focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none sm:space-x-3","aria-label":r.backToHome.label??"Return to blog",children:[jsx(ArrowLeft,{className:"h-4 w-4 transition-transform group-hover:-translate-x-1 sm:h-5 sm:w-5","aria-hidden":"true"}),jsxs("span",{className:"text-sm font-medium sm:text-base",children:[jsx("span",{className:"hidden sm:inline",children:r.backToHome.label??"Back to all articles"}),jsx("span",{className:"sm:hidden",children:"Back"})]})]})}),jsxs("header",{className:"article-header mb-6 space-y-4 text-center sm:mb-8 sm:space-y-6 lg:mb-12 lg:space-y-8",children:[jsx("h1",{className:"article-title text-foreground px-4 text-2xl leading-tight font-light tracking-tight sm:px-0 sm:text-3xl md:text-4xl lg:text-5xl xl:text-6xl",children:e.title}),e.excerpt&&jsx("p",{className:"article-excerpt text-muted-foreground mx-auto mt-6 max-w-xs px-4 text-base leading-relaxed sm:mt-8 sm:max-w-lg sm:px-0 sm:text-lg md:max-w-2xl md:text-xl lg:max-w-4xl lg:text-2xl",children:e.excerpt}),jsxs("div",{className:"article-meta text-muted-foreground flex flex-col items-center gap-2 text-sm sm:gap-3 sm:text-base",children:[e.author&&jsxs("div",{className:"flex items-center gap-2",children:[jsx("span",{className:"sr-only",children:"Author"}),jsx("span",{className:"font-medium",children:e.author.name}),e.author.isGuest&&jsx(ve,{variant:"outline",className:"text-xs",children:"Guest Author"})]}),jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-3 gap-y-1",children:[jsxs("time",{dateTime:e.publishedAt,className:"font-medium","aria-label":`Published ${c}`,children:["Published ",c]}),jsx("span",{className:"text-border",children:"\u2022"}),jsx("span",{className:"font-medium",children:l})]}),a&&jsxs("time",{dateTime:e.updatedAt,className:"text-xs",children:["Updated ",format(s,"MMMM d, yyyy")]}),jsx("div",{className:"bg-border h-px w-6 sm:w-8","aria-hidden":"true"}),jsxs("span",{className:"text-xs tracking-wider uppercase sm:text-sm",role:"text",children:["From ",e.site.name]})]})]}),p&&jsx("div",{className:"article-featured-image relative my-8 aspect-[16/9] w-full overflow-hidden rounded-lg sm:my-12 lg:my-16",children:jsx(He,{src:p,alt:e.featuredImageAlt??`Featured image for ${e.title}`,className:"h-full w-full object-cover",width:800,height:450,priority:true})}),jsx("div",{className:"article-content",children:jsx("div",{className:"prose prose-sm sm:prose-base lg:prose-lg xl:prose-xl prose-gray dark:prose-invert prose-headings:scroll-mt-20 prose-headings:font-light prose-h1:text-2xl sm:prose-h1:text-3xl lg:prose-h1:text-4xl prose-h2:text-xl sm:prose-h2:text-2xl lg:prose-h2:text-3xl prose-h3:text-lg sm:prose-h3:text-xl lg:prose-h3:text-2xl prose-p:leading-relaxed prose-img:mx-auto prose-img:rounded-lg prose-a:transition-colors max-w-none",children:jsx(MDXRemote,{source:e.content,options:ze})})}),e.author?.bio&&jsxs("div",{className:"author-bio mt-12",children:[jsx(ae,{className:"mb-8"}),jsxs(Y,{children:[jsx(we,{children:jsxs(Ne,{className:"flex items-center gap-2",children:["About ",e.author.name,e.author.isGuest&&jsx(ve,{variant:"outline",className:"text-xs",children:"Guest Author"})]})}),jsx(Q,{children:jsx("div",{className:"prose dark:prose-invert",children:jsx("p",{className:"text-muted-foreground",children:e.author.bio})})})]})]}),(!!r?.previousArticle||!!r?.nextArticle)&&jsxs("nav",{className:"article-nav mt-12",children:[jsx(ae,{className:"mb-8"}),jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2",children:[r?.previousArticle&&jsx(Y,{className:"group hover:bg-accent/50 cursor-pointer transition-colors",children:jsx(Ce,{href:r.previousArticle.url,className:"block",children:jsxs(Q,{className:"p-4",children:[jsx("div",{className:"text-muted-foreground mb-2 text-sm font-medium",children:"\u2190 Previous Article"}),jsx("div",{className:"text-foreground group-hover:text-primary transition-colors",children:r.previousArticle.title})]})})}),r?.nextArticle&&jsx(Y,{className:x("group hover:bg-accent/50 cursor-pointer transition-colors",!r?.previousArticle&&"md:col-start-2"),children:jsx(Ce,{href:r.nextArticle.url,className:"block",children:jsxs(Q,{className:"p-4 md:text-right",children:[jsx("div",{className:"text-muted-foreground mb-2 text-sm font-medium",children:"Next Article \u2192"}),jsx("div",{className:"text-foreground group-hover:text-primary transition-colors",children:r.nextArticle.title})]})})})]})]}),(()=>{let u=K(Re(e,{pathPrefix:o}));return jsx("script",{type:u.type,dangerouslySetInnerHTML:u.dangerouslySetInnerHTML})})()]})}function zt(e,t="/blog"){let r=e.meta.title??e.title,n=e.meta.description??e.excerpt,o=e.meta.canonicalUrl??`${e.site.domain}${J(t,e.slug)}`,i=e.meta.ogImage??e.featuredImage;return {title:r,description:n,keywords:e.meta.keywords.join(", "),authors:e.author?[{name:e.author.name}]:void 0,openGraph:{title:r,description:n,type:"article",url:o,images:i?[{url:i,alt:e.featuredImageAlt??r}]:void 0,publishedTime:e.publishedAt,modifiedTime:e.updatedAt,authors:e.author?[e.author.name]:void 0,siteName:e.site.name},twitter:{card:"summary_large_image",title:r,description:n,images:i?[i]:void 0},alternates:{canonical:o}}}function Oe(e){let t=e.headers.get("Authorization");if(!t)return null;let n=/^Bearer\s+(.+)$/i.exec(t);if(n?.[1])return n[1];let i=/^Token\s+(.+)$/i.exec(t);return i?.[1]?i[1]:null}var le=class{validApiKeys;constructor(t){this.validApiKeys=new Set(t);}async validateToken(t){return t?.trim()?this.validApiKeys.has(t)?{valid:true,context:{tokenHash:this.hashToken(t)}}:{valid:false,errorCode:"invalid"}:{valid:false,errorCode:"missing"}}extractToken=t=>Oe(t);hashToken(t){return t.substring(0,8)+"..."}},H=class extends le{constructor(t="BLOG_PLATFORM_API_KEYS"){let r=process.env[t];!r&&t==="BLOG_PLATFORM_API_KEYS"&&(r=process.env.BLOG_AUTH_TOKEN);let n=r?r.split(",").map(o=>o.trim()).filter(Boolean):[];n.length===0&&console.warn(`\u26A0\uFE0F No API keys found in environment variable ${t}${t==="BLOG_PLATFORM_API_KEYS"?" (set BLOG_PLATFORM_API_KEYS or BLOG_AUTH_TOKEN)":""}. Authentication will fail for all requests.`),super(n);}},Z=class{async validateToken(){return {valid:true,context:{development:true}}}extractToken(){return "development-mode"}},ce=class{hasWarned=false;async validateToken(t){return this.hasWarned||(console.error("\u274C SECURITY WARNING: Blog platform authentication not initialized! All requests will be rejected. Call initBlogPlatform() to configure authentication."),this.hasWarned=true),{valid:false,errorCode:"invalid"}}};function Wt(){return globalThis.__BLOG_PLATFORM_AUTH_CONFIG__??=new ce,globalThis.__BLOG_PLATFORM_AUTH_CONFIG__}function ue(e){globalThis.__BLOG_PLATFORM_AUTH_CONFIG__=e;}function Le(){return globalThis.__BLOG_PLATFORM_AUTH_CONFIG__??Wt()}function Xt(e){ue(new H(e));}async function E(e){let t=Le(),r=t.extractToken?t.extractToken(e):Oe(e);if(!r)return {authenticated:false,result:{valid:false,errorCode:"missing"},token:null};let n=await t.validateToken(r);return {authenticated:n.valid,result:n,token:r}}function Kt(e,t=""){let n=Le().errorMessages??{},o,i;switch(e.errorCode){case "missing":o=n.missing??"Authentication token is required",i="PUB005";break;case "expired":o=n.expired??"Authentication token has expired",i="PUB005";break;default:o=n.invalid??"Invalid authentication credentials",i="PUB005";break}return {success:false,error:{code:i,message:o,details:{authError:e.errorCode??"invalid"}},idempotencyKey:t}}async function M(e){let t=await E(e);return t.authenticated?{authenticated:true,context:t.result.context}:{authenticated:false,error:Kt(t.result)}}function Jt(){let e=process.env.SKIP_BLOG_PLATFORM_AUTH;return e==="true"||e==="1"||process.env.NODE_ENV==="test"}var me=class{articles=new Map;operations=new Map;async saveArticle(t,r){let n=await this.checkIdempotency(r);if(n)if(n.success){if(Array.from(this.articles.values()).some(s=>s.id===t.id))return n}else return n;if(this.articles.has(t.slug)){let i={success:false,error:{code:"PUB003",message:"This URL is already in use. Please choose another."},idempotencyKey:r};return await this.storeOperationResult(r,i),i}this.articles.set(t.slug,t);let o={success:true,url:`/${t.slug}`,platformPostId:t.id,publishedAt:t.publishedAt,idempotencyKey:r};return await this.storeOperationResult(r,o),o}async getArticle(t){return this.articles.get(t)??null}async listArticles(t={}){let{limit:r=10,offset:n=0,sortBy:o="publishedAt",order:i="desc"}=t,s=Array.from(this.articles.values());return s.sort((c,l)=>{let p=new Date(c[o]).getTime(),u=new Date(l[o]).getTime();return i==="desc"?u-p:p-u}),{articles:s.slice(n,n+r),total:s.length}}async removeArticle(t,r){let n=await this.checkIdempotency(r);if(n)if(n.success){if(!this.articles.has(t))return n}else return n;if(!this.articles.has(t)){let i={success:false,error:{code:"PUB007",message:"Article not found"},idempotencyKey:r};return await this.storeOperationResult(r,i),i}this.articles.delete(t);let o={success:true,idempotencyKey:r};return await this.storeOperationResult(r,o),o}async checkIdempotency(t){return this.operations.get(t)??null}async storeOperationResult(t,r){this.operations.set(t,r);}};function Yt(){let e=globalThis;if(e.__BLOG_PLATFORM_STORAGE_WARNED__)return;e.__BLOG_PLATFORM_STORAGE_WARNED__=true;let t="Blog platform: No storage provider configured. Falling back to in-memory storage (data is not persisted).";process.env.NODE_ENV==="production"?console.error(`${t} Call initBlogPlatform({ storage: /* your persistent adapter */ }) to avoid data loss.`):console.warn(t);}function Qt(){let e=globalThis;e.__BLOG_PLATFORM_STORAGE__||(Yt(),e.__BLOG_PLATFORM_STORAGE__=new me);let t=e.__BLOG_PLATFORM_STORAGE__;if(!t)throw new Error("Blog platform storage not initialized");return t}function D(){return Qt()}function _e(e){let t=globalThis;t.__BLOG_PLATFORM_STORAGE__=e;}function er(){return globalThis.__BLOG_PLATFORM_RATE_LIMITER__??null}function tr(e){let t=globalThis;t.__BLOG_PLATFORM_RATE_LIMITER__=e;}function pe(e){let{redisUrl:t,redisToken:r,requestsPerMinute:n=5,keyPrefix:o="blog-platform-ratelimit",analytics:i=true}=e,s=new Redis({url:t,token:r}),a=new Ratelimit({redis:s,analytics:i,prefix:o,limiter:Ratelimit.slidingWindow(n,"1m")});tr(a);}function Be(){let e=process.env.UPSTASH_REDIS_REST_URL,t=process.env.UPSTASH_REDIS_REST_TOKEN;if(!e||!t){console.warn("Blog platform: No Upstash Redis configuration found. Rate limiting disabled.");return}pe({redisUrl:e,redisToken:t}),console.log("Blog platform: Rate limiting configured (5 requests per minute per token)");}async function Ke(e){let t=er();if(!t)return console.warn("Blog platform: Rate limiter not configured. All requests allowed."),{success:true,remaining:999,reset:Date.now()+6e4,limit:5,count:0};try{let r=await t.limit(e);return {success:r.success,remaining:r.remaining,reset:r.reset,limit:r.limit,count:r.limit-r.remaining}}catch(r){return console.error("Blog platform: Rate limit check failed:",r),{success:true,remaining:0,reset:Date.now()+6e4,limit:5,count:0}}}function Je(e,t=""){let r=Math.ceil((e.reset-Date.now())/6e4);return {success:false,error:{code:"PUB011",message:`Rate limit exceeded. You can make ${e.limit} requests per minute. Try again in ${r} minute(s).`,details:{rateLimit:e}},idempotencyKey:t}}async function I(e,t=""){let r=await Ke(e);return r.success?{allowed:true,rateLimitResult:r}:{allowed:false,errorResponse:Je(r,t)}}function N(e){return {"X-RateLimit-Limit":e.limit.toString(),"X-RateLimit-Remaining":e.remaining.toString(),"X-RateLimit-Reset":e.reset.toString(),"Retry-After":Math.ceil((e.reset-Date.now())/1e3).toString()}}function de(e){let{auth:t,storage:r,rateLimit:n,autoRateLimit:o=true}=e;if(!t)throw new Error(`Blog platform initialization failed: 'auth' is required.
2
2
  Example: initBlogPlatform({ auth: new EnvAuth() })
3
- See https://github.com/xexr/blog-platform#authentication for more details.`);console.log("Blog platform: Setting up authentication"),le(t),n?(console.log("Blog platform: Using custom rate limiting configuration"),ue(n)):s?(console.log("Blog platform: Auto-configuring rate limiting from environment"),Le()):console.log("Blog platform: Rate limiting disabled"),r?(console.log("Blog platform: Using custom storage provider"),Oe(r)):console.log("Blog platform: Using default in-memory storage (not suitable for production)"),console.log("Blog platform initialized successfully"),globalThis.__BLOG_PLATFORM_INITIALISED__=true;}function Jt(e){if(globalThis.__BLOG_PLATFORM_INITIALISED__){console.log("Blog platform: Already initialized, skipping");return}console.log("Blog platform: Initializing blog platform once"),me(e);}function Yt(){me({auth:new Y,autoRateLimit:false}),console.log("Blog platform: Development mode enabled (no auth, in-memory storage, no rate limiting)");}function Qt(e){let t=e??"BLOG_PLATFORM_API_KEYS";if(!process.env[t])throw new Error(`Missing required environment variable: ${t}. Set this to a comma-separated list of API keys for blog platform authentication.`);me({auth:new G(t),autoRateLimit:true}),console.log("Blog platform: Production mode enabled (environment-based auth, rate limiting)");}var S=sqliteTable("bp_articles",{id:text("id").primaryKey(),slug:text("slug").notNull(),title:text("title").notNull(),excerpt:text("excerpt").notNull(),content:text("content").notNull(),readingSeconds:integer("reading_seconds").notNull(),wordCount:integer("word_count").notNull(),publishedAt:text("published_at").notNull(),updatedAt:text("updated_at").notNull(),featuredImage:text("featured_image"),featuredImageAlt:text("featured_image_alt"),authorJson:text("author_json"),siteJson:text("site_json").notNull(),metaJson:text("meta_json").notNull(),version:integer("version").notNull()},e=>({slugUniqueIdx:uniqueIndex("bp_articles_slug_unique").on(e.slug)})),H=sqliteTable("bp_operations",{key:text("key").primaryKey(),resultJson:text("result_json").notNull(),createdAt:integer("created_at",{mode:"timestamp_ms"}).notNull(),expiresAt:integer("expires_at",{mode:"timestamp_ms"})});function nr(e){return {id:e.id,slug:e.slug,title:e.title,excerpt:e.excerpt,content:e.content,readingSeconds:e.readingSeconds,wordCount:e.wordCount,publishedAt:e.publishedAt,updatedAt:e.updatedAt,featuredImage:e.featuredImage??null,featuredImageAlt:e.featuredImageAlt??null,authorJson:e.author?JSON.stringify(e.author):null,siteJson:JSON.stringify(e.site),metaJson:JSON.stringify(e.meta),version:e.version}}function Xe(e){return {id:e.id,slug:e.slug,title:e.title,excerpt:e.excerpt,content:e.content,readingSeconds:e.readingSeconds,wordCount:e.wordCount,publishedAt:e.publishedAt,updatedAt:e.updatedAt,featuredImage:e.featuredImage??void 0,featuredImageAlt:e.featuredImageAlt??void 0,author:e.authorJson?JSON.parse(e.authorJson):null,site:JSON.parse(e.siteJson),meta:JSON.parse(e.metaJson),version:e.version}}var _e=class{db;options;constructor(t,r={}){this.db=t,this.options=r;}async saveArticle(t,r){let n=await this.checkIdempotency(r);if(n)if(n.success){if((await this.db.select({id:S.id}).from(S).where(eq(S.id,t.id)).limit(1)).length!==0)return n}else return n;let s=await this.db.select().from(S).where(eq(S.slug,t.slug)).limit(1),i=s[0];if(i&&i.id!==t.id){let c={success:false,error:{code:"PUB003",message:"This URL is already in use. Please choose another."},idempotencyKey:r};return await this.storeOperationResult(r,c),c}let o=nr(t);s.length===0?await this.db.insert(S).values(o).run():await this.db.update(S).set({title:o.title,excerpt:o.excerpt,content:o.content,readingSeconds:o.readingSeconds,wordCount:o.wordCount,updatedAt:o.updatedAt,featuredImage:o.featuredImage,featuredImageAlt:o.featuredImageAlt,authorJson:o.authorJson,siteJson:o.siteJson,metaJson:o.metaJson,version:o.version}).where(and(eq(S.id,o.id),eq(S.slug,o.slug))).run();let a={success:true,url:`/${t.slug}`,platformPostId:t.id,publishedAt:t.publishedAt,idempotencyKey:r};return await this.storeOperationResult(r,a),a}async getArticle(t){let r=await this.db.select().from(S).where(eq(S.slug,t)).limit(1);return r[0]?Xe(r[0]):null}async listArticles(t={}){let{limit:r=10,offset:n=0,sortBy:s="publishedAt",order:i="desc"}=t,o=s==="publishedAt"?S.publishedAt:S.updatedAt,a=i==="desc"?desc(o):o,c=await this.db.select().from(S).orderBy(a).limit(r).offset(n),l=await this.db.select({c:sql`count(*)`}).from(S),p=Number(l?.[0]?.c??0);return {articles:c.map(Xe),total:p}}async removeArticle(t,r){let n=await this.checkIdempotency(r);if(n)if(n.success){if(!((await this.db.select({id:S.id}).from(S).where(eq(S.slug,t)).limit(1)).length>0))return n}else return n;if(!(await this.db.select().from(S).where(eq(S.slug,t)).limit(1))[0]){let o={success:false,error:{code:"PUB007",message:"Article not found"},idempotencyKey:r};return await this.storeOperationResult(r,o),o}await this.db.delete(S).where(eq(S.slug,t)).run();let i={success:true,idempotencyKey:r};return await this.storeOperationResult(r,i),i}async checkIdempotency(t){let r=await this.db.select().from(H).where(eq(H.key,t)).limit(1);if(!r[0])return null;try{return JSON.parse(r[0].resultJson)}catch{return null}}async storeOperationResult(t,r){let n=Date.now(),s=this.options.operationTtlMs?n+this.options.operationTtlMs:null;await this.db.delete(H).where(eq(H.key,t)).run(),await this.db.insert(H).values({key:t,resultJson:JSON.stringify(r),createdAt:new Date(n),expiresAt:s?new Date(s):null}).run();}};function ir(){return {createArticles:`CREATE TABLE IF NOT EXISTS bp_articles (
3
+ See https://github.com/xexr/blog-platform#authentication for more details.`);console.log("Blog platform: Setting up authentication"),ue(t),n?(console.log("Blog platform: Using custom rate limiting configuration"),pe(n)):o?(console.log("Blog platform: Auto-configuring rate limiting from environment"),Be()):console.log("Blog platform: Rate limiting disabled"),r?(console.log("Blog platform: Using custom storage provider"),_e(r)):console.log("Blog platform: Using default in-memory storage (not suitable for production)"),console.log("Blog platform initialized successfully"),globalThis.__BLOG_PLATFORM_INITIALISED__=true;}function rr(e){if(globalThis.__BLOG_PLATFORM_INITIALISED__){console.log("Blog platform: Already initialized, skipping");return}console.log("Blog platform: Initializing blog platform once"),de(e);}function nr(){de({auth:new Z,autoRateLimit:false}),console.log("Blog platform: Development mode enabled (no auth, in-memory storage, no rate limiting)");}function ir(e){let t=e??"BLOG_PLATFORM_API_KEYS";if(!process.env[t])throw new Error(`Missing required environment variable: ${t}. Set this to a comma-separated list of API keys for blog platform authentication.`);de({auth:new H(t),autoRateLimit:true}),console.log("Blog platform: Production mode enabled (environment-based auth, rate limiting)");}var S=sqliteTable("bp_articles",{id:text("id").primaryKey(),slug:text("slug").notNull(),title:text("title").notNull(),excerpt:text("excerpt").notNull(),content:text("content").notNull(),readingSeconds:integer("reading_seconds").notNull(),wordCount:integer("word_count").notNull(),publishedAt:text("published_at").notNull(),updatedAt:text("updated_at").notNull(),featuredImage:text("featured_image"),featuredImageAlt:text("featured_image_alt"),authorJson:text("author_json"),siteJson:text("site_json").notNull(),metaJson:text("meta_json").notNull(),version:integer("version").notNull()},e=>({slugUniqueIdx:uniqueIndex("bp_articles_slug_unique").on(e.slug)})),j=sqliteTable("bp_operations",{key:text("key").primaryKey(),resultJson:text("result_json").notNull(),createdAt:integer("created_at",{mode:"timestamp_ms"}).notNull(),expiresAt:integer("expires_at",{mode:"timestamp_ms"})});function cr(e){return {id:e.id,slug:e.slug,title:e.title,excerpt:e.excerpt,content:e.content,readingSeconds:e.readingSeconds,wordCount:e.wordCount,publishedAt:e.publishedAt,updatedAt:e.updatedAt,featuredImage:e.featuredImage??null,featuredImageAlt:e.featuredImageAlt??null,authorJson:e.author?JSON.stringify(e.author):null,siteJson:JSON.stringify(e.site),metaJson:JSON.stringify(e.meta),version:e.version}}function Ye(e){return {id:e.id,slug:e.slug,title:e.title,excerpt:e.excerpt,content:e.content,readingSeconds:e.readingSeconds,wordCount:e.wordCount,publishedAt:e.publishedAt,updatedAt:e.updatedAt,featuredImage:e.featuredImage??void 0,featuredImageAlt:e.featuredImageAlt??void 0,author:e.authorJson?JSON.parse(e.authorJson):null,site:JSON.parse(e.siteJson),meta:JSON.parse(e.metaJson),version:e.version}}var Ee=class{db;options;constructor(t,r={}){this.db=t,this.options=r;}async saveArticle(t,r){let n=await this.checkIdempotency(r);if(n)if(n.success){if((await this.db.select({id:S.id}).from(S).where(eq(S.id,t.id)).limit(1)).length!==0)return n}else return n;let o=await this.db.select().from(S).where(eq(S.slug,t.slug)).limit(1),i=o[0];if(i&&i.id!==t.id){let c={success:false,error:{code:"PUB003",message:"This URL is already in use. Please choose another."},idempotencyKey:r};return await this.storeOperationResult(r,c),c}let s=cr(t);o.length===0?await this.db.insert(S).values(s).run():await this.db.update(S).set({title:s.title,excerpt:s.excerpt,content:s.content,readingSeconds:s.readingSeconds,wordCount:s.wordCount,updatedAt:s.updatedAt,featuredImage:s.featuredImage,featuredImageAlt:s.featuredImageAlt,authorJson:s.authorJson,siteJson:s.siteJson,metaJson:s.metaJson,version:s.version}).where(and(eq(S.id,s.id),eq(S.slug,s.slug))).run();let a={success:true,url:`/${t.slug}`,platformPostId:t.id,publishedAt:t.publishedAt,idempotencyKey:r};return await this.storeOperationResult(r,a),a}async getArticle(t){let r=await this.db.select().from(S).where(eq(S.slug,t)).limit(1);return r[0]?Ye(r[0]):null}async listArticles(t={}){let{limit:r=10,offset:n=0,sortBy:o="publishedAt",order:i="desc"}=t,s=o==="publishedAt"?S.publishedAt:S.updatedAt,a=i==="desc"?desc(s):s,c=await this.db.select().from(S).orderBy(a).limit(r).offset(n),l=await this.db.select({c:sql`count(*)`}).from(S),p=Number(l?.[0]?.c??0);return {articles:c.map(Ye),total:p}}async removeArticle(t,r){let n=await this.checkIdempotency(r);if(n)if(n.success){if(!((await this.db.select({id:S.id}).from(S).where(eq(S.slug,t)).limit(1)).length>0))return n}else return n;if(!(await this.db.select().from(S).where(eq(S.slug,t)).limit(1))[0]){let s={success:false,error:{code:"PUB007",message:"Article not found"},idempotencyKey:r};return await this.storeOperationResult(r,s),s}await this.db.delete(S).where(eq(S.slug,t)).run();let i={success:true,idempotencyKey:r};return await this.storeOperationResult(r,i),i}async checkIdempotency(t){let r=await this.db.select().from(j).where(eq(j.key,t)).limit(1);if(!r[0])return null;try{return JSON.parse(r[0].resultJson)}catch{return null}}async storeOperationResult(t,r){let n=Date.now(),o=this.options.operationTtlMs?n+this.options.operationTtlMs:null;await this.db.delete(j).where(eq(j.key,t)).run(),await this.db.insert(j).values({key:t,resultJson:JSON.stringify(r),createdAt:new Date(n),expiresAt:o?new Date(o):null}).run();}};function ur(){return {createArticles:`CREATE TABLE IF NOT EXISTS bp_articles (
4
4
  id TEXT PRIMARY KEY,
5
5
  slug TEXT NOT NULL UNIQUE,
6
6
  title TEXT NOT NULL,
@@ -21,11 +21,11 @@ See https://github.com/xexr/blog-platform#authentication for more details.`);con
21
21
  result_json TEXT NOT NULL,
22
22
  created_at INTEGER NOT NULL,
23
23
  expires_at INTEGER
24
- );`}}function j(e,t=true){let r=e.trim();return r=r.replace(/\/+$/,""),/^https?:\/\//.exec(r)||(r=`${t?"https":"http"}://${r}`),t&&r.startsWith("http://")&&(r=r.replace("http://","https://")),r}function Je(e){let t=e.trim();if(!t)throw new Error("Slug cannot be empty");if(!/^[a-z0-9-]+$/.test(t))throw new Error("Slug can only contain lowercase letters, numbers, and hyphens");let n=t.replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!n)throw new Error("Slug cannot consist only of hyphens");return n}function U(e,t={}){let{forceHttps:r=true,removeTrailingSlash:n=true,domain:s=e.site.domain,pathPrefix:i="/blog"}=t;if(!s)throw new Error("Domain is required for canonical URL generation");if(!e.slug)throw new Error("Article slug is required for canonical URL generation");let o=j(s,r),a=Je(e.slug),c=i.replace(/^(?!\/)/,"/").replace(/\/+$/,""),l=`${o}${c}/${a}`;return n&&(l=l.replace(/\/+$/,"")),l}function sr(e,t,r={}){return U({slug:t,site:e},r)}function or(e){try{let t=new URL(e);return !(!["http:","https:"].includes(t.protocol)||!t.hostname||t.hostname.length===0||/^https?:\/\/\//.exec(e)&&!/^https?:\/\/[^\/]/.exec(e)||e.includes(" "))}catch{return false}}function ar(e){try{let t=new URL(e);return `${t.protocol}//${t.host}`}catch{throw new Error("Invalid canonical URL provided")}}function lr(e,t={}){let r=U(e,t);return {...e,meta:{...e.meta,canonicalUrl:r}}}function cr(e,t={},r){let n=r?.path??"/blog",i=`https://${t.canonical?.domain??e.domain}${n}`,o=r?.title?`${r.title} | ${e.name}`:e.name,a=r?.description??e.description,c=t.openGraph?.siteName??e.name,l=[{name:"description",content:a},{name:"author",content:c}];r?.pageNumber&&r.pageNumber>1&&l.push({name:"page",content:r.pageNumber.toString()}),t.meta?.robots&&l.push({name:"robots",content:t.meta.robots}),t.meta?.viewport&&l.push({name:"viewport",content:t.meta.viewport}),t.meta?.themeColor&&l.push({name:"theme-color",content:t.meta.themeColor}),t.meta?.applicationName&&l.push({name:"application-name",content:t.meta.applicationName});let p=[{property:"og:title",content:o},{property:"og:description",content:a},{property:"og:url",content:i},{property:"og:site_name",content:c},{property:"og:locale",content:t.openGraph?.locale??e.locale},{property:"og:type",content:t.openGraph?.type??"website"}];t.openGraph?.defaultImage&&p.push({property:"og:image",content:t.openGraph.defaultImage},{property:"og:image:alt",content:`${c} - ${e.tagline}`});let m=ur(null,{site:t.twitter?.site,creator:t.twitter?.creator,cardType:t.twitter?.cardType??"summary"},{title:o,description:a,image:t.openGraph?.defaultImage});return {meta:l,openGraph:p,twitter:m,links:[{rel:"canonical",href:i}],title:o,description:a,canonicalUrl:i}}function ur(e,t,r){let n=r?.title??e?.meta.title??e?.title??"",s=r?.description??e?.meta.description??e?.excerpt??"",i=r?.image??e?.meta.ogImage??e?.featuredImage,o=[{name:"twitter:card",content:t.cardType},{name:"twitter:title",content:n},{name:"twitter:description",content:s}];return t.site&&o.push({name:"twitter:site",content:t.site}),t.creator&&o.push({name:"twitter:creator",content:t.creator}),i&&(o.push({name:"twitter:image",content:i}),e?.featuredImageAlt),o}function mr(e){let t=[];return t.push(`<title>${T(e.title)}</title>`),e.meta.forEach(r=>{let n=[];r.name&&n.push(`name="${T(r.name)}"`),r.property&&n.push(`property="${T(r.property)}"`),r.httpEquiv&&n.push(`http-equiv="${T(r.httpEquiv)}"`),n.push(`content="${T(r.content)}"`),t.push(`<meta ${n.join(" ")} />`);}),e.openGraph.forEach(r=>{t.push(`<meta property="${T(r.property)}" content="${T(r.content)}" />`);}),e.twitter.forEach(r=>{t.push(`<meta name="${T(r.name)}" content="${T(r.content)}" />`);}),e.links.forEach(r=>{let n=[];n.push(`rel="${T(r.rel)}"`),n.push(`href="${T(r.href)}"`),r.type&&n.push(`type="${T(r.type)}"`),r.title&&n.push(`title="${T(r.title)}"`),t.push(`<link ${n.join(" ")} />`);}),t.join(`
25
- `)}function T(e){let t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;"};return e.replace(/[&<>"']/g,r=>t[r]??r)}function pr(e){let t=[],r=[];return e.title?e.title.length>60?r.push("Title longer than 60 characters may be truncated in search results"):e.title.length<30&&r.push("Title shorter than 30 characters may not be descriptive enough"):t.push("Title is required"),e.description?e.description.length>160?r.push("Meta description longer than 160 characters may be truncated"):e.description.length<120&&r.push("Meta description shorter than 120 characters may not be descriptive enough"):t.push("Meta description is required"),e.canonicalUrl?e.canonicalUrl.startsWith("https://")||r.push("Canonical URL should use HTTPS for better SEO"):t.push("Canonical URL is required"),e.openGraph.find(i=>i.property==="og:image")||r.push("OpenGraph image missing - social media sharing will not show image preview"),e.twitter.find(i=>i.name==="twitter:card")||r.push("Twitter Card type missing - Twitter sharing may not display properly"),{valid:t.length===0,errors:t,warnings:r}}async function Ee(e,t,r=[],n={}){let{includeAuthorPages:s=true,includePaginationPages:i=true,articlesPerPage:o=10,maxEntries:a=5e4,changeFrequency:c={},priority:l={}}=n,p=[],m=j(n.canonical?.domain??e.domain,n.canonical?.forceHttps??true),P=n.canonical?.pathPrefix??"/blog";if(p.push({url:`${m}${P}`,lastModified:F(t),changeFrequency:c.homePage??"daily",priority:l.homePage??1}),t.forEach(h=>{if(p.length>=a)return;let u=U(h,n.canonical);p.push({url:u,lastModified:h.updatedAt,changeFrequency:c.articles??"monthly",priority:l.articles??.8});}),s&&r.forEach(h=>{if(p.length>=a)return;let u=`${m}${P}/authors/${h.slug}`,d=t.filter(C=>C.author?.id===h.id),b=F(d);p.push({url:u,lastModified:b,changeFrequency:c.authorPages??"weekly",priority:l.authorPages??.6});}),i&&t.length>o){let h=Math.ceil(t.length/o);for(let u=2;u<=h&&!(p.length>=a);u++)p.push({url:`${m}${P}?page=${u}`,lastModified:F(t),changeFrequency:c.paginationPages??"daily",priority:l.paginationPages??.5});}return p}function dr(e,t,r=[],n={}){let{includeAuthorPages:s=true,includePaginationPages:i=true,articlesPerPage:o=10,maxEntries:a=5e4,changeFrequency:c={},priority:l={}}=n,p=[],m=j(n.canonical?.domain??e.domain,n.canonical?.forceHttps??true),P=n.canonical?.pathPrefix??"/blog",h=new Date().toISOString(),u=1;if(u+=t.length,s&&(u+=r.length),i&&t.length>o){let b=Math.ceil(t.length/o);u+=b-1;}let d=u>a;if(p.push({loc:`${m}${P}`,lastmod:F(t),changefreq:c.homePage??"daily",priority:l.homePage??1}),t.forEach(b=>{if(p.length>=a)return;let C=U(b,n.canonical);p.push({loc:C,lastmod:b.updatedAt,changefreq:c.articles??"monthly",priority:l.articles??.8});}),s&&r.forEach(b=>{if(p.length>=a)return;let C=`${m}${P}/authors/${b.slug}`,st=t.filter(at=>at.author?.id===b.id),ot=F(st);p.push({loc:C,lastmod:ot,changefreq:c.authorPages??"weekly",priority:l.authorPages??.6});}),i&&t.length>o){let b=Math.ceil(t.length/o);for(let C=2;C<=b&&!(p.length>=a);C++)p.push({loc:`${m}${P}?page=${C}`,lastmod:F(t),changefreq:c.paginationPages??"daily",priority:l.paginationPages??.5});}return {entries:p,totalEntries:p.length,truncated:d,generatedAt:h,baseUrl:m}}function Ye(e){let t='<?xml version="1.0" encoding="UTF-8"?>',r='<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',n="</urlset>",s=e.entries.map(i=>{let o=[];return o.push(" <url>"),o.push(` <loc>${Z(i.loc)}</loc>`),i.lastmod&&o.push(` <lastmod>${Z(i.lastmod)}</lastmod>`),i.changefreq&&o.push(` <changefreq>${Z(i.changefreq)}</changefreq>`),i.priority!==void 0&&o.push(` <priority>${i.priority.toFixed(1)}</priority>`),o.push(" </url>"),o.join(`
26
- `)});return [t,r,...s,n].join(`
27
- `)}function gr(e,t){let r='<?xml version="1.0" encoding="UTF-8"?>',n='<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',s="</sitemapindex>",i=e.map(o=>{let a=[];return a.push(" <sitemap>"),a.push(` <loc>${Z(o.url)}</loc>`),o.lastmod&&a.push(` <lastmod>${Z(o.lastmod)}</lastmod>`),a.push(" </sitemap>"),a.join(`
28
- `)});return [r,n,...i,s].join(`
29
- `)}function fr(e){let t=[],r=[];e.entries.length===0?t.push("Sitemap must contain at least one URL"):e.entries.length>5e4&&t.push("Sitemap contains more than 50,000 URLs (Google limit)"),e.truncated&&r.push("Sitemap was truncated due to size limits"),e.entries.forEach((s,i)=>{try{new URL(s.loc);}catch{t.push(`Invalid URL at entry ${i+1}: ${s.loc}`);}s.priority!==void 0&&(s.priority<0||s.priority>1)&&t.push(`Invalid priority at entry ${i+1}: must be between 0.0 and 1.0`),s.lastmod&&!yr(s.lastmod)&&t.push(`Invalid lastmod date at entry ${i+1}: ${s.lastmod}`),s.loc.length>2048&&r.push(`URL at entry ${i+1} exceeds 2048 character limit`);});let n=new Map;return e.entries.forEach(s=>{let i=n.get(s.loc)??0;n.set(s.loc,i+1);}),n.forEach((s,i)=>{s>1&&t.push(`Duplicate URL found: ${i} (appears ${s} times)`);}),{valid:t.length===0,errors:t,warnings:r}}function F(e){return e.length===0?new Date().toISOString():e.reduce((r,n)=>{let s=new Date(n.updatedAt);return s>r?s:r},new Date(e[0].updatedAt)).toISOString()}function hr(e,t,r=[],n={}){return async function(){let o=(await Ee(e,t,r,n)).map(l=>({loc:l.url,lastmod:typeof l.lastModified=="string"?l.lastModified:l.lastModified?.toISOString(),changefreq:l.changeFrequency,priority:l.priority})),a={entries:o,totalEntries:o.length,generatedAt:new Date().toISOString(),baseUrl:j(n.canonical?.domain??e.domain,n.canonical?.forceHttps??true)},c=Ye(a);return new Response(c,{headers:{"Content-Type":"application/xml","Cache-Control":"public, max-age=3600, s-maxage=3600"}})}}function br(e){return async function(){let r=await e.getSite(),n=await e.getArticles(),s=e.getAuthors?await e.getAuthors():[];return Ee(r,n,s,e.options)}}function Z(e){let t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;"};return e.replace(/[&<>"']/g,r=>t[r]??r)}function yr(e){try{let t=new Date(e),r=t.toISOString(),n=e.endsWith("Z")&&!e.includes(".")?e.replace("Z",".000Z"):e;return r===n&&!isNaN(t.getTime())}catch{return false}}var q={name:"@xexr/blog-platform",version:"1.0.1"};function Qe(e){let r=e.replace(/^v/,"").split(".");if(r.length<3)throw new Error(`Invalid version format: ${e}`);let n=parseInt(r[0]??"0",10),s=parseInt(r[1]??"0",10),i=parseInt(r[2]?.split("-")[0]??"0",10);if(isNaN(n)||isNaN(s)||isNaN(i))throw new Error(`Invalid version format: ${e}`);return {major:n,minor:s,patch:i}}function O(){let e=Qe(q.version);return {name:q.name,version:q.version,...e}}function M(e){try{let t=e.split(" "),r={};for(let n of t){let[s,i]=n.split("/");if(!s||!i)continue;let o=Qe(i),a={name:s,version:i,...o};s==="bloggy"?r.bloggyVersion=a:s==="platform"&&(r.platformVersion=a);}return r}catch{return null}}function Ze(e,t){try{return e.major!==t.major?{compatible:!1,errorCode:"PUB009",errorMessage:`Major version incompatibility: ${e.name} ${e.version} is not compatible with ${t.name} ${t.version}. Please upgrade.`}:e.minor!==t.minor?{compatible:!0,errorCode:"PUB010",warning:`Minor version difference: ${e.name} ${e.version} with ${t.name} ${t.version}. Some features may not be available.`}:{compatible:!0}}catch(r){return {compatible:false,errorMessage:`Failed to check version compatibility: ${r instanceof Error?r.message:"Unknown error"}`}}}var et={enableCSP:true,cspDirectives:{"default-src":"'self'","script-src":"'self' 'unsafe-inline'","style-src":"'self' 'unsafe-inline'","img-src":"'self' data: https:","font-src":"'self' https:","connect-src":"'self'","media-src":"'self'","object-src":"'none'","base-uri":"'self'","form-action":"'self'","frame-ancestors":"'none'","upgrade-insecure-requests":""},enableFrameOptions:true,frameOptions:"DENY",enableContentTypeOptions:true,enableXSSProtection:true,enableReferrerPolicy:true,referrerPolicy:"strict-origin-when-cross-origin",enableHSTS:true,hstsMaxAge:31536e3,hstsIncludeSubdomains:true,enablePermissionsPolicy:true,permissionsPolicyDirectives:{camera:"()",microphone:"()",geolocation:"()",payment:"()",usb:"()",accelerometer:"()",gyroscope:"()",magnetometer:"()"}};function Pr(){let e=process.env.BLOG_PLATFORM_DISABLE_CSP==="true",t=process.env.BLOG_PLATFORM_FRAME_OPTIONS,r=process.env.BLOG_PLATFORM_DISABLE_HSTS==="true";return {...et,enableCSP:!e,frameOptions:t??et.frameOptions,enableHSTS:!r}}function Sr(e){return Object.entries(e).map(([t,r])=>r?`${t} ${r}`:t).join("; ")}function Rr(e){return Object.entries(e).map(([t,r])=>`${t}=${r}`).join(", ")}function Ar(e,t={}){let r={...Pr(),...t},n={};if(r.enableCSP){let s={...r.cspDirectives,...t.cspDirectives??{}};n["Content-Security-Policy"]=Sr(s);}if(r.enableFrameOptions&&(n["X-Frame-Options"]=r.frameOptions),r.enableContentTypeOptions&&(n["X-Content-Type-Options"]="nosniff"),r.enableXSSProtection&&(n["X-XSS-Protection"]="1; mode=block"),r.enableReferrerPolicy&&(n["Referrer-Policy"]=r.referrerPolicy),r.enableHSTS&&vr(e)){let s=[`max-age=${r.hstsMaxAge}`,r.hstsIncludeSubdomains?"includeSubDomains":""].filter(Boolean).join("; ");n["Strict-Transport-Security"]=s;}if(r.enablePermissionsPolicy){let s={...r.permissionsPolicyDirectives,...t.permissionsPolicyDirectives??{}};n["Permissions-Policy"]=Rr(s);}return n}function vr(e){return !!(e.url.startsWith("https://")||e.headers.get("x-forwarded-proto")==="https"||e.headers.get("cf-visitor")?.includes('"scheme":"https"'))}function pe(e,t={}){return Ar(e,{...t,cspDirectives:{...{"default-src":"'none'","frame-ancestors":"'none'","base-uri":"'none'"},...t.cspDirectives??{}}})}var tt={allowedOrigins:["http://localhost:3000","https://localhost:3000","http://127.0.0.1:3000","https://127.0.0.1:3000"],allowWildcard:false,allowCredentials:false,maxAge:86400,securityConfig:{}};function rt(){let e=process.env.BLOG_PLATFORM_ALLOWED_ORIGINS,t=process.env.BLOG_PLATFORM_ALLOW_WILDCARD==="true",r=process.env.BLOG_PLATFORM_ALLOW_CREDENTIALS==="true";return {...tt,allowedOrigins:e?e.split(",").map(n=>n.trim()):tt.allowedOrigins,allowWildcard:t,allowCredentials:r}}function nt(e,t){return e?t.allowWildcard?true:t.allowedOrigins.includes(e):false}function it(e,t){let r=e.headers.get("origin"),n={};return t.allowWildcard?n["Access-Control-Allow-Origin"]="*":r&&nt(r,t)&&(n["Access-Control-Allow-Origin"]=r),t.allowCredentials&&!t.allowWildcard&&(n["Access-Control-Allow-Credentials"]="true"),t.allowWildcard||(n.Vary="Origin"),n}function wr(e,t,r,n){return {...it(e,t),"Access-Control-Allow-Methods":r.join(", "),"Access-Control-Allow-Headers":n.join(", "),"Access-Control-Max-Age":t.maxAge.toString()}}var Nr=["Content-Type","X-Bloggy-Version","X-Idempotency-Key","Authorization","X-Requested-With"];function f(e,t,r={}){let{status:n=200,headers:s={},corsConfig:i={}}=r,o={...rt(),...i},a=it(e,o),c=pe(e,o.securityConfig),l={"Content-Type":"application/json",...a,...c,...s};return NextResponse.json(t,{status:n,headers:l})}function ee(e,t,r={}){let{allowedHeaders:n=Nr,corsConfig:s={}}=r,i={...rt(),...s},o=e.headers.get("origin");if(o&&!i.allowWildcard&&!nt(o,i)){let l=pe(e,i.securityConfig);return new NextResponse(null,{status:403,headers:{"Content-Type":"text/plain",...l}})}let a=wr(e,i,[...t,"OPTIONS"],n),c=pe(e,i.securityConfig);return new NextResponse(null,{status:200,headers:{...a,...c}})}async function Tr(e){try{let t=await B(e);if(!t.authenticated){let d=await k(e);return f(e,d.error,{status:401})}let r=t.token??"anonymous",n=await I(r);if(!n.allowed){let d=n.errorResponse.error?.details?.rateLimit,b=d&&typeof d=="object"&&"limit"in d&&"remaining"in d&&"reset"in d&&"count"in d&&"success"in d?d:{limit:10,remaining:0,reset:Date.now()+6e4,count:10,success:!1},C=N(b);return f(e,n.errorResponse,{status:429,headers:C})}if(!e.headers.get("content-type")?.includes("application/json"))return f(e,{success:!1,error:{code:"PUB001",message:"Content-Type must be application/json"},idempotencyKey:""},{status:400});let i;try{i=await e.json();}catch{return f(e,{success:!1,error:{code:"PUB001",message:"Invalid JSON in request body"},idempotencyKey:""},{status:400})}let o=Cr(i);if(o.length>0)return f(e,{success:!1,error:{code:"PUB001",message:"Missing required fields",details:{errors:o}},idempotencyKey:i.idempotencyKey??""},{status:400});let a=e.headers.get("X-Bloggy-Version");if(a){let d=M(a);if(d?.platformVersion){let b=O();if(d.platformVersion.major!==b.major)return f(e,{success:!1,error:{code:"PUB009",message:"Major version incompatibility. Please upgrade your blog platform package.",details:{clientVersion:d.platformVersion.version,serverVersion:b.version}},idempotencyKey:i.idempotencyKey},{status:409})}}if(i.dryRun){let d=[];return i.article.wordCount<50&&d.push("Article has fewer than 50 words, which may affect SEO"),(!i.article.excerpt||i.article.excerpt.length<120)&&d.push("Article excerpt is shorter than recommended 120 characters"),i.article.meta.keywords.length||d.push("No SEO keywords provided"),f(e,{success:!0,warnings:d,idempotencyKey:i.idempotencyKey},{status:200})}let c={...i.article,slug:i.slug??i.article.slug,meta:{...i.article.meta,description:i.metaDescription??i.article.meta.description}};if(!Ie(c.slug))return f(e,{success:!1,error:{code:"PUB002",message:"Slug can only contain lowercase letters, numbers, and hyphens"},idempotencyKey:i.idempotencyKey},{status:400});let p=await D().saveArticle(c,i.idempotencyKey),m=O(),P=N(n.rateLimitResult),h={"X-Bloggy-Version":`platform/${m.version}`,"X-Idempotency-Key":i.idempotencyKey,...P};p.success&&(h.Location=p.url??`/${c.slug}`);let u=p.success?201:p.error?.code==="PUB003"?409:400;return f(e,p,{status:u,headers:h})}catch(t){return console.error("Publish endpoint error:",t),f(e,{success:false,error:{code:"PUB007",message:"Internal server error during publishing"},idempotencyKey:""},{status:500})}}function Cr(e){let t=[];if(!e||typeof e!="object")return t.push("Request body must be a valid object"),t;let r=e;if((!r.article||typeof r.article!="object")&&t.push("Missing required field: article"),(!r.idempotencyKey||typeof r.idempotencyKey!="string")&&t.push("Missing required field: idempotencyKey"),r.article&&typeof r.article=="object"){let n=r.article,s=["id","slug","title","content","publishedAt","site"];for(let i of s)n[i]||t.push(`Missing required article field: ${i}`);if(n.site&&typeof n.site=="object"){let i=n.site,o=["id","name","domain"];for(let a of o)i[a]||t.push(`Missing required site field: ${a}`);}if(n.meta&&typeof n.meta=="object"){let i=n.meta;Array.isArray(i.keywords)||t.push("Article meta.keywords must be an array");}}return t}function Ie(e){return !e||typeof e!="string"?false:/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)&&e.length>=1&&e.length<=100}async function Lr(e){try{let t=await B(e);if(!t.authenticated){let u=await k(e);return NextResponse.json(u.error,{status:401})}let r=t.token??"anonymous",n=await I(r);if(!n.allowed){let u=n.errorResponse.error?.details?.rateLimit,d=u&&typeof u=="object"&&"limit"in u&&"remaining"in u&&"reset"in u&&"count"in u&&"success"in u?u:{limit:10,remaining:0,reset:Date.now()+6e4,count:10,success:!1},b=N(d);return f(e,n.errorResponse,{status:429,headers:b})}if(!e.headers.get("content-type")?.includes("application/json"))return f(e,{success:!1,error:{code:"PUB001",message:"Content-Type must be application/json"},idempotencyKey:""},{status:400});let i;try{i=await e.json();}catch{return f(e,{success:!1,error:{code:"PUB001",message:"Invalid JSON in request body"},idempotencyKey:""},{status:400})}let o=_r(i);if(o.length>0)return f(e,{success:!1,error:{code:"PUB001",message:"Missing required fields",details:{errors:o}},idempotencyKey:i.idempotencyKey??""},{status:400});let a=e.headers.get("X-Bloggy-Version");if(a){let u=M(a);if(u?.platformVersion){let d=O();if(u.platformVersion.major!==d.major)return f(e,{success:!1,error:{code:"PUB009",message:"Major version incompatibility. Please upgrade your blog platform package.",details:{clientVersion:u.platformVersion.version,serverVersion:d.version}},idempotencyKey:i.idempotencyKey},{status:409})}}if(!Er(i.slug))return f(e,{success:!1,error:{code:"PUB002",message:"Slug can only contain lowercase letters, numbers, and hyphens"},idempotencyKey:i.idempotencyKey},{status:400});if(i.dryRun){let d=await D().getArticle(i.slug),b=[];return d||b.push("Article with this slug does not exist"),f(e,{success:!0,warnings:b,idempotencyKey:i.idempotencyKey},{status:200})}let l=await D().removeArticle(i.slug,i.idempotencyKey),p=O(),m=N(n.rateLimitResult),P={"X-Bloggy-Version":`platform/${p.version}`,"X-Idempotency-Key":i.idempotencyKey,...m},h=l.success?200:l.error?.code==="PUB007"?404:400;return f(e,l,{status:h,headers:P})}catch(t){return console.error("Unpublish endpoint error:",t),f(e,{success:false,error:{code:"PUB007",message:"Internal server error during unpublishing"},idempotencyKey:""},{status:500})}}function _r(e){let t=[];if(!e||typeof e!="object")return t.push("Request body must be a valid object"),t;let r=e;return (!r.slug||typeof r.slug!="string")&&t.push("Missing required field: slug"),(!r.idempotencyKey||typeof r.idempotencyKey!="string")&&t.push("Missing required field: idempotencyKey"),r.slug&&typeof r.slug=="string"&&!r.slug.trim()&&t.push("Slug cannot be empty"),t}function Er(e){return !e||typeof e!="string"?false:/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)&&e.length>=1&&e.length<=100}async function Br(e){try{let t=await B(e);if(!t.authenticated){let m=await k(e),P={success:!1,versions:{bloggy:{name:"unknown",version:"unknown",major:0,minor:0,patch:0},platform:{name:"unknown",version:"unknown",major:0,minor:0,patch:0}},compatibility:{compatible:!1,errorMessage:m.error?.error?.message??"Authentication required"}};return f(e,P,{status:401})}let r=t.token??"anonymous",n=await I(r);if(!n.allowed){let m=n.errorResponse.error?.details?.rateLimit,P=m&&typeof m=="object"&&"limit"in m&&"remaining"in m&&"reset"in m&&"count"in m&&"success"in m?m:{limit:10,remaining:0,reset:Date.now()+6e4,count:10,success:!1},h=N(P),u={success:!1,versions:{bloggy:{name:"unknown",version:"unknown",major:0,minor:0,patch:0},platform:{name:"unknown",version:"unknown",major:0,minor:0,patch:0}},compatibility:{compatible:!1,errorMessage:n.errorResponse.error?.message??"Rate limit exceeded"}};return f(e,u,{status:429,headers:h})}let s=O(),i=e.headers.get("X-Bloggy-Version"),o={name:"unknown",version:"unknown",major:0,minor:0,patch:0};if(i)try{if(/^\d+\.\d+\.\d+/.test(i)){let m=i.split("."),P=parseInt(m[0]??"0",10),h=parseInt(m[1]??"0",10),u=parseInt(m[2]?.split("-")[0]??"0",10);o={name:"bloggy",version:i,major:P,minor:h,patch:u};}else {let m=M(i);m?.bloggyVersion&&(o=m.bloggyVersion);}}catch(m){console.warn("Failed to parse X-Bloggy-Version header:",m);}let a={compatible:!0};o.version!=="unknown"&&(a=Ze(o,s));let c={success:!0,versions:{bloggy:o,platform:s},compatibility:a},l=N(n.rateLimitResult),p={"X-Bloggy-Version":`platform/${s.version}`,"Cache-Control":"public, max-age=300, stale-while-revalidate=60",...l};return f(e,c,{status:200,headers:p})}catch(t){console.error("Version endpoint error:",t);let r={success:false,versions:{bloggy:{name:"unknown",version:"unknown",major:0,minor:0,patch:0},platform:{name:"unknown",version:"unknown",major:0,minor:0,patch:0}},compatibility:{compatible:false,errorMessage:"Internal server error while checking version compatibility"},error:t instanceof Error?t.message:"Unknown error"};return f(e,r,{status:500})}}async function kr(e,{params:t}){try{let{slug:r}=await t,n=await B(e);if(!n.authenticated){let d=await k(e);return NextResponse.json(d.error,{status:401})}let s=n.token??"anonymous",i=await I(s);if(!i.allowed){let d=i.errorResponse.error?.details?.rateLimit||{limit:10,remaining:0,reset:Date.now()+6e4,count:10,success:!1},b=N(d);return f(e,i.errorResponse,{status:429,headers:b})}if(!r||!Ie(r))return f(e,{exists:!1,error:{code:"PUB002",message:"Invalid slug format. Must be lowercase letters, numbers, and hyphens only."}},{status:400});let o=e.headers.get("X-Bloggy-Version");if(o){let d=M(o);if(d?.platformVersion){let b=O();if(d.platformVersion.major!==b.major)return f(e,{exists:!1,error:{code:"PUB009",message:"Major version incompatibility. Please upgrade your blog platform package.",details:{clientVersion:d.platformVersion.version,serverVersion:b.version}}},{status:409})}}let l=await D().getArticle(r)!==null,p={exists:l,...l&&{message:"Slug is already in use. Please choose another (e.g., append '-v2')."}},m=O(),P=N(i.rateLimitResult),h={"X-Bloggy-Version":`platform/${m.version}`,...P},u=e.headers.get("X-Idempotency-Key");return u&&(h["X-Idempotency-Key"]=u,console.log(`Slug check for idempotency: ${u}, exists: ${l}`)),f(e,p,{status:200,headers:h})}catch(r){return console.error("Slug existence check error:",r instanceof Error?r.message:String(r)),f(e,{exists:false,error:{code:"PUB007",message:"Internal server error during slug check"}},{status:500})}}async function Dr(e){return ee(e,["GET"])}var Oi=q.version;
30
- export{oe as ApiKeyAuth,Fe as BlogArticlePage,He as BlogHomePage,pt as Button,K as Card,J as CardContent,_t as CardDescription,Et as CardFooter,Ae as CardHeader,ve as CardTitle,_e as DrizzleStorage,G as EnvAuth,ce as InMemoryStorage,Y as NoAuth,Oi as PACKAGE_VERSION,ne as Pagination,ge as PaginationContent,re as PaginationEllipsis,E as PaginationItem,$ as PaginationLink,he as PaginationNext,fe as PaginationPrevious,de as ShadcnPagination,W as StructuredDataError,ae as UninitializedAuth,Le as autoConfigureRateLimit,S as bpArticles,H as bpOperations,te as buttonVariants,ze as checkRateLimit,x as cn,ue as configureRateLimit,hr as createBlogSitemapRoute,br as createDynamicBlogSitemap,We as createRateLimitErrorResponse,X as createStructuredDataScript,I as enforceRateLimit,St as extractKeywordsFromArticle,Te as extractTokenFromHeader,Vt as generateArticleMetadata,ie as generateArticleStructuredData,De as generateAuthorStructuredData,Tt as generateBlogHomeMetadata,Se as generateBlogHomeStructuredData,Ee as generateBlogSitemapEntries,Me as generateBreadcrumbStructuredData,U as generateCanonicalUrl,sr as generateCanonicalUrlFromSlug,Pe as generateCompleteArticleStructuredData,ye as generateOrganizationStructuredData,Pt as generatePaginationMetadata,cr as generateSiteMetadata,dr as generateSitemap,gr as generateSitemapIndex,xe as generateWebSiteStructuredData,Ce as getAuthConfig,ar as getBaseUrl,ir as getDrizzleAdapterSql,N as getRateLimitHeaders,D as getStorage,me as initBlogPlatform,Yt as initBlogPlatformDev,Jt as initBlogPlatformOnce,Qt as initBlogPlatformProd,Ht as initEnvAuth,or as isValidCanonicalUrl,mr as metadataToHtml,j as normalizeDomain,Je as normalizeSlug,Tr as publishHandler,Rt as safeGenerateArticleStructuredData,le as setAuthConfig,Oe as setStorage,Ft as shouldSkipAuth,Ye as sitemapToXml,kr as slugExistsHandler,Dr as slugExistsOptionsHandler,Ue as structuredDataToJsonLd,Lr as unpublishHandler,lr as updateArticleCanonicalUrl,xt as usePagination,pr as validateMetadata,fr as validateSitemap,$e as validateStructuredData,Br as versionHandler};//# sourceMappingURL=index.mjs.map
24
+ );`}}function F(e,t=true){let r=e.trim();return r=r.replace(/\/+$/,""),/^https?:\/\//.exec(r)||(r=`${t?"https":"http"}://${r}`),t&&r.startsWith("http://")&&(r=r.replace("http://","https://")),r}function Ze(e){let t=e.trim();if(!t)throw new Error("Slug cannot be empty");if(!/^[a-z0-9-]+$/.test(t))throw new Error("Slug can only contain lowercase letters, numbers, and hyphens");let n=t.replace(/-+/g,"-").replace(/^-+|-+$/g,"");if(!n)throw new Error("Slug cannot consist only of hyphens");return n}function V(e,t={}){let{forceHttps:r=true,removeTrailingSlash:n=true,domain:o=e.site.domain,pathPrefix:i="/blog"}=t;if(!o)throw new Error("Domain is required for canonical URL generation");if(!e.slug)throw new Error("Article slug is required for canonical URL generation");let s=F(o,r),a=Ze(e.slug),c=i.replace(/^(?!\/)/,"/").replace(/\/+$/,""),l=`${s}${c}/${a}`;return n&&(l=l.replace(/\/+$/,"")),l}function mr(e,t,r={}){return V({slug:t,site:e},r)}function pr(e){try{let t=new URL(e);return !(!["http:","https:"].includes(t.protocol)||!t.hostname||t.hostname.length===0||/^https?:\/\/\//.exec(e)&&!/^https?:\/\/[^\/]/.exec(e)||e.includes(" "))}catch{return false}}function dr(e){try{let t=new URL(e);return `${t.protocol}//${t.host}`}catch{throw new Error("Invalid canonical URL provided")}}function gr(e,t={}){let r=V(e,t);return {...e,meta:{...e.meta,canonicalUrl:r}}}function fr(e,t={},r){let n=r?.path??"/blog",i=`https://${t.canonical?.domain??e.domain}${n}`,s=r?.title?`${r.title} | ${e.name}`:e.name,a=r?.description??e.description,c=t.openGraph?.siteName??e.name,l=[{name:"description",content:a},{name:"author",content:c}];r?.pageNumber&&r.pageNumber>1&&l.push({name:"page",content:r.pageNumber.toString()}),t.meta?.robots&&l.push({name:"robots",content:t.meta.robots}),t.meta?.viewport&&l.push({name:"viewport",content:t.meta.viewport}),t.meta?.themeColor&&l.push({name:"theme-color",content:t.meta.themeColor}),t.meta?.applicationName&&l.push({name:"application-name",content:t.meta.applicationName});let p=[{property:"og:title",content:s},{property:"og:description",content:a},{property:"og:url",content:i},{property:"og:site_name",content:c},{property:"og:locale",content:t.openGraph?.locale??e.locale},{property:"og:type",content:t.openGraph?.type??"website"}];t.openGraph?.defaultImage&&p.push({property:"og:image",content:t.openGraph.defaultImage},{property:"og:image:alt",content:`${c} - ${e.tagline}`});let u=hr(null,{site:t.twitter?.site,creator:t.twitter?.creator,cardType:t.twitter?.cardType??"summary"},{title:s,description:a,image:t.openGraph?.defaultImage});return {meta:l,openGraph:p,twitter:u,links:[{rel:"canonical",href:i}],title:s,description:a,canonicalUrl:i}}function hr(e,t,r){let n=r?.title??e?.meta.title??e?.title??"",o=r?.description??e?.meta.description??e?.excerpt??"",i=r?.image??e?.meta.ogImage??e?.featuredImage,s=[{name:"twitter:card",content:t.cardType},{name:"twitter:title",content:n},{name:"twitter:description",content:o}];return t.site&&s.push({name:"twitter:site",content:t.site}),t.creator&&s.push({name:"twitter:creator",content:t.creator}),i&&(s.push({name:"twitter:image",content:i}),e?.featuredImageAlt),s}function br(e){let t=[];return t.push(`<title>${T(e.title)}</title>`),e.meta.forEach(r=>{let n=[];r.name&&n.push(`name="${T(r.name)}"`),r.property&&n.push(`property="${T(r.property)}"`),r.httpEquiv&&n.push(`http-equiv="${T(r.httpEquiv)}"`),n.push(`content="${T(r.content)}"`),t.push(`<meta ${n.join(" ")} />`);}),e.openGraph.forEach(r=>{t.push(`<meta property="${T(r.property)}" content="${T(r.content)}" />`);}),e.twitter.forEach(r=>{t.push(`<meta name="${T(r.name)}" content="${T(r.content)}" />`);}),e.links.forEach(r=>{let n=[];n.push(`rel="${T(r.rel)}"`),n.push(`href="${T(r.href)}"`),r.type&&n.push(`type="${T(r.type)}"`),r.title&&n.push(`title="${T(r.title)}"`),t.push(`<link ${n.join(" ")} />`);}),t.join(`
25
+ `)}function T(e){let t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;"};return e.replace(/[&<>"']/g,r=>t[r]??r)}function yr(e){let t=[],r=[];return e.title?e.title.length>60?r.push("Title longer than 60 characters may be truncated in search results"):e.title.length<30&&r.push("Title shorter than 30 characters may not be descriptive enough"):t.push("Title is required"),e.description?e.description.length>160?r.push("Meta description longer than 160 characters may be truncated"):e.description.length<120&&r.push("Meta description shorter than 120 characters may not be descriptive enough"):t.push("Meta description is required"),e.canonicalUrl?e.canonicalUrl.startsWith("https://")||r.push("Canonical URL should use HTTPS for better SEO"):t.push("Canonical URL is required"),e.openGraph.find(i=>i.property==="og:image")||r.push("OpenGraph image missing - social media sharing will not show image preview"),e.twitter.find(i=>i.name==="twitter:card")||r.push("Twitter Card type missing - Twitter sharing may not display properly"),{valid:t.length===0,errors:t,warnings:r}}async function Ie(e,t,r=[],n={}){let{includeAuthorPages:o=true,includePaginationPages:i=true,articlesPerPage:s=10,maxEntries:a=5e4,changeFrequency:c={},priority:l={}}=n,p=[],u=F(n.canonical?.domain??e.domain,n.canonical?.forceHttps??true),P=n.canonical?.pathPrefix??"/blog";if(p.push({url:`${u}${P}`,lastModified:q(t),changeFrequency:c.homePage??"daily",priority:l.homePage??1}),t.forEach(h=>{if(p.length>=a)return;let m=V(h,n.canonical);p.push({url:m,lastModified:h.updatedAt,changeFrequency:c.articles??"monthly",priority:l.articles??.8});}),o&&r.forEach(h=>{if(p.length>=a)return;let m=`${u}${P}/authors/${h.slug}`,d=t.filter(C=>C.author?.id===h.id),b=q(d);p.push({url:m,lastModified:b,changeFrequency:c.authorPages??"weekly",priority:l.authorPages??.6});}),i&&t.length>s){let h=Math.ceil(t.length/s);for(let m=2;m<=h&&!(p.length>=a);m++)p.push({url:`${u}${P}?page=${m}`,lastModified:q(t),changeFrequency:c.paginationPages??"daily",priority:l.paginationPages??.5});}return p}function xr(e,t,r=[],n={}){let{includeAuthorPages:o=true,includePaginationPages:i=true,articlesPerPage:s=10,maxEntries:a=5e4,changeFrequency:c={},priority:l={}}=n,p=[],u=F(n.canonical?.domain??e.domain,n.canonical?.forceHttps??true),P=n.canonical?.pathPrefix??"/blog",h=new Date().toISOString(),m=1;if(m+=t.length,o&&(m+=r.length),i&&t.length>s){let b=Math.ceil(t.length/s);m+=b-1;}let d=m>a;if(p.push({loc:`${u}${P}`,lastmod:q(t),changefreq:c.homePage??"daily",priority:l.homePage??1}),t.forEach(b=>{if(p.length>=a)return;let C=V(b,n.canonical);p.push({loc:C,lastmod:b.updatedAt,changefreq:c.articles??"monthly",priority:l.articles??.8});}),o&&r.forEach(b=>{if(p.length>=a)return;let C=`${u}${P}/authors/${b.slug}`,lt=t.filter(ut=>ut.author?.id===b.id),ct=q(lt);p.push({loc:C,lastmod:ct,changefreq:c.authorPages??"weekly",priority:l.authorPages??.6});}),i&&t.length>s){let b=Math.ceil(t.length/s);for(let C=2;C<=b&&!(p.length>=a);C++)p.push({loc:`${u}${P}?page=${C}`,lastmod:q(t),changefreq:c.paginationPages??"daily",priority:l.paginationPages??.5});}return {entries:p,totalEntries:p.length,truncated:d,generatedAt:h,baseUrl:u}}function et(e){let t='<?xml version="1.0" encoding="UTF-8"?>',r='<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',n="</urlset>",o=e.entries.map(i=>{let s=[];return s.push(" <url>"),s.push(` <loc>${te(i.loc)}</loc>`),i.lastmod&&s.push(` <lastmod>${te(i.lastmod)}</lastmod>`),i.changefreq&&s.push(` <changefreq>${te(i.changefreq)}</changefreq>`),i.priority!==void 0&&s.push(` <priority>${i.priority.toFixed(1)}</priority>`),s.push(" </url>"),s.join(`
26
+ `)});return [t,r,...o,n].join(`
27
+ `)}function Pr(e,t){let r='<?xml version="1.0" encoding="UTF-8"?>',n='<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',o="</sitemapindex>",i=e.map(s=>{let a=[];return a.push(" <sitemap>"),a.push(` <loc>${te(s.url)}</loc>`),s.lastmod&&a.push(` <lastmod>${te(s.lastmod)}</lastmod>`),a.push(" </sitemap>"),a.join(`
28
+ `)});return [r,n,...i,o].join(`
29
+ `)}function Sr(e){let t=[],r=[];e.entries.length===0?t.push("Sitemap must contain at least one URL"):e.entries.length>5e4&&t.push("Sitemap contains more than 50,000 URLs (Google limit)"),e.truncated&&r.push("Sitemap was truncated due to size limits"),e.entries.forEach((o,i)=>{try{new URL(o.loc);}catch{t.push(`Invalid URL at entry ${i+1}: ${o.loc}`);}o.priority!==void 0&&(o.priority<0||o.priority>1)&&t.push(`Invalid priority at entry ${i+1}: must be between 0.0 and 1.0`),o.lastmod&&!vr(o.lastmod)&&t.push(`Invalid lastmod date at entry ${i+1}: ${o.lastmod}`),o.loc.length>2048&&r.push(`URL at entry ${i+1} exceeds 2048 character limit`);});let n=new Map;return e.entries.forEach(o=>{let i=n.get(o.loc)??0;n.set(o.loc,i+1);}),n.forEach((o,i)=>{o>1&&t.push(`Duplicate URL found: ${i} (appears ${o} times)`);}),{valid:t.length===0,errors:t,warnings:r}}function q(e){return e.length===0?new Date().toISOString():e.reduce((r,n)=>{let o=new Date(n.updatedAt);return o>r?o:r},new Date(e[0].updatedAt)).toISOString()}function Rr(e,t,r=[],n={}){return async function(){let s=(await Ie(e,t,r,n)).map(l=>({loc:l.url,lastmod:typeof l.lastModified=="string"?l.lastModified:l.lastModified?.toISOString(),changefreq:l.changeFrequency,priority:l.priority})),a={entries:s,totalEntries:s.length,generatedAt:new Date().toISOString(),baseUrl:F(n.canonical?.domain??e.domain,n.canonical?.forceHttps??true)},c=et(a);return new Response(c,{headers:{"Content-Type":"application/xml","Cache-Control":"public, max-age=3600, s-maxage=3600"}})}}function Ar(e){return async function(){let r=await e.getSite(),n=await e.getArticles(),o=e.getAuthors?await e.getAuthors():[];return Ie(r,n,o,e.options)}}function te(e){let t={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;"};return e.replace(/[&<>"']/g,r=>t[r]??r)}function vr(e){try{let t=new Date(e),r=t.toISOString(),n=e.endsWith("Z")&&!e.includes(".")?e.replace("Z",".000Z"):e;return r===n&&!isNaN(t.getTime())}catch{return false}}var z={name:"@xexr/blog-platform",version:"1.0.2"};function tt(e){let r=e.replace(/^v/,"").split(".");if(r.length<3)throw new Error(`Invalid version format: ${e}`);let n=parseInt(r[0]??"0",10),o=parseInt(r[1]??"0",10),i=parseInt(r[2]?.split("-")[0]??"0",10);if(isNaN(n)||isNaN(o)||isNaN(i))throw new Error(`Invalid version format: ${e}`);return {major:n,minor:o,patch:i}}function O(){let e=tt(z.version);return {name:z.name,version:z.version,...e}}function $(e){try{let t=e.split(" "),r={};for(let n of t){let[o,i]=n.split("/");if(!o||!i)continue;let s=tt(i),a={name:o,version:i,...s};o==="bloggy"?r.bloggyVersion=a:o==="platform"&&(r.platformVersion=a);}return r}catch{return null}}function rt(e,t){try{return e.major!==t.major?{compatible:!1,errorCode:"PUB009",errorMessage:`Major version incompatibility: ${e.name} ${e.version} is not compatible with ${t.name} ${t.version}. Please upgrade.`}:e.minor!==t.minor?{compatible:!0,errorCode:"PUB010",warning:`Minor version difference: ${e.name} ${e.version} with ${t.name} ${t.version}. Some features may not be available.`}:{compatible:!0}}catch(r){return {compatible:false,errorMessage:`Failed to check version compatibility: ${r instanceof Error?r.message:"Unknown error"}`}}}var nt={enableCSP:true,cspDirectives:{"default-src":"'self'","script-src":"'self' 'unsafe-inline'","style-src":"'self' 'unsafe-inline'","img-src":"'self' data: https:","font-src":"'self' https:","connect-src":"'self'","media-src":"'self'","object-src":"'none'","base-uri":"'self'","form-action":"'self'","frame-ancestors":"'none'","upgrade-insecure-requests":""},enableFrameOptions:true,frameOptions:"DENY",enableContentTypeOptions:true,enableXSSProtection:true,enableReferrerPolicy:true,referrerPolicy:"strict-origin-when-cross-origin",enableHSTS:true,hstsMaxAge:31536e3,hstsIncludeSubdomains:true,enablePermissionsPolicy:true,permissionsPolicyDirectives:{camera:"()",microphone:"()",geolocation:"()",payment:"()",usb:"()",accelerometer:"()",gyroscope:"()",magnetometer:"()"}};function Nr(){let e=process.env.BLOG_PLATFORM_DISABLE_CSP==="true",t=process.env.BLOG_PLATFORM_FRAME_OPTIONS,r=process.env.BLOG_PLATFORM_DISABLE_HSTS==="true";return {...nt,enableCSP:!e,frameOptions:t??nt.frameOptions,enableHSTS:!r}}function Tr(e){return Object.entries(e).map(([t,r])=>r?`${t} ${r}`:t).join("; ")}function Cr(e){return Object.entries(e).map(([t,r])=>`${t}=${r}`).join(", ")}function Or(e,t={}){let r={...Nr(),...t},n={};if(r.enableCSP){let o={...r.cspDirectives,...t.cspDirectives??{}};n["Content-Security-Policy"]=Tr(o);}if(r.enableFrameOptions&&(n["X-Frame-Options"]=r.frameOptions),r.enableContentTypeOptions&&(n["X-Content-Type-Options"]="nosniff"),r.enableXSSProtection&&(n["X-XSS-Protection"]="1; mode=block"),r.enableReferrerPolicy&&(n["Referrer-Policy"]=r.referrerPolicy),r.enableHSTS&&Lr(e)){let o=[`max-age=${r.hstsMaxAge}`,r.hstsIncludeSubdomains?"includeSubDomains":""].filter(Boolean).join("; ");n["Strict-Transport-Security"]=o;}if(r.enablePermissionsPolicy){let o={...r.permissionsPolicyDirectives,...t.permissionsPolicyDirectives??{}};n["Permissions-Policy"]=Cr(o);}return n}function Lr(e){return !!(e.url.startsWith("https://")||e.headers.get("x-forwarded-proto")==="https"||e.headers.get("cf-visitor")?.includes('"scheme":"https"'))}function ge(e,t={}){return Or(e,{...t,cspDirectives:{...{"default-src":"'none'","frame-ancestors":"'none'","base-uri":"'none'"},...t.cspDirectives??{}}})}var it={allowedOrigins:["http://localhost:3000","https://localhost:3000","http://127.0.0.1:3000","https://127.0.0.1:3000"],allowWildcard:false,allowCredentials:false,maxAge:86400,securityConfig:{}};function ot(){let e=process.env.BLOG_PLATFORM_ALLOWED_ORIGINS,t=process.env.BLOG_PLATFORM_ALLOW_WILDCARD==="true",r=process.env.BLOG_PLATFORM_ALLOW_CREDENTIALS==="true";return {...it,allowedOrigins:e?e.split(",").map(n=>n.trim()):it.allowedOrigins,allowWildcard:t,allowCredentials:r}}function st(e,t){return e?t.allowWildcard?true:t.allowedOrigins.includes(e):false}function at(e,t){let r=e.headers.get("origin"),n={};return t.allowWildcard?n["Access-Control-Allow-Origin"]="*":r&&st(r,t)&&(n["Access-Control-Allow-Origin"]=r),t.allowCredentials&&!t.allowWildcard&&(n["Access-Control-Allow-Credentials"]="true"),t.allowWildcard||(n.Vary="Origin"),n}function _r(e,t,r,n){return {...at(e,t),"Access-Control-Allow-Methods":r.join(", "),"Access-Control-Allow-Headers":n.join(", "),"Access-Control-Max-Age":t.maxAge.toString()}}var Br=["Content-Type","X-Bloggy-Version","X-Idempotency-Key","Authorization","X-Requested-With"];function f(e,t,r={}){let{status:n=200,headers:o={},corsConfig:i={}}=r,s={...ot(),...i},a=at(e,s),c=ge(e,s.securityConfig),l={"Content-Type":"application/json",...a,...c,...o};return NextResponse.json(t,{status:n,headers:l})}function re(e,t,r={}){let{allowedHeaders:n=Br,corsConfig:o={}}=r,i={...ot(),...o},s=e.headers.get("origin");if(s&&!i.allowWildcard&&!st(s,i)){let l=ge(e,i.securityConfig);return new NextResponse(null,{status:403,headers:{"Content-Type":"text/plain",...l}})}let a=_r(e,i,[...t,"OPTIONS"],n),c=ge(e,i.securityConfig);return new NextResponse(null,{status:200,headers:{...a,...c}})}async function Er(e){try{let t=await E(e);if(!t.authenticated){let d=await M(e);return f(e,d.error,{status:401})}let r=t.token??"anonymous",n=await I(r);if(!n.allowed){let d=n.errorResponse.error?.details?.rateLimit,b=d&&typeof d=="object"&&"limit"in d&&"remaining"in d&&"reset"in d&&"count"in d&&"success"in d?d:{limit:10,remaining:0,reset:Date.now()+6e4,count:10,success:!1},C=N(b);return f(e,n.errorResponse,{status:429,headers:C})}if(!e.headers.get("content-type")?.includes("application/json"))return f(e,{success:!1,error:{code:"PUB001",message:"Content-Type must be application/json"},idempotencyKey:""},{status:400});let i;try{i=await e.json();}catch{return f(e,{success:!1,error:{code:"PUB001",message:"Invalid JSON in request body"},idempotencyKey:""},{status:400})}let s=Ir(i);if(s.length>0)return f(e,{success:!1,error:{code:"PUB001",message:"Missing required fields",details:{errors:s}},idempotencyKey:i.idempotencyKey??""},{status:400});let a=e.headers.get("X-Bloggy-Version");if(a){let d=$(a);if(d?.platformVersion){let b=O();if(d.platformVersion.major!==b.major)return f(e,{success:!1,error:{code:"PUB009",message:"Major version incompatibility. Please upgrade your blog platform package.",details:{clientVersion:d.platformVersion.version,serverVersion:b.version}},idempotencyKey:i.idempotencyKey},{status:409})}}if(i.dryRun){let d=[];return i.article.wordCount<50&&d.push("Article has fewer than 50 words, which may affect SEO"),(!i.article.excerpt||i.article.excerpt.length<120)&&d.push("Article excerpt is shorter than recommended 120 characters"),i.article.meta.keywords.length||d.push("No SEO keywords provided"),f(e,{success:!0,warnings:d,idempotencyKey:i.idempotencyKey},{status:200})}let c={...i.article,slug:i.slug??i.article.slug,meta:{...i.article.meta,description:i.metaDescription??i.article.meta.description}};if(!Me(c.slug))return f(e,{success:!1,error:{code:"PUB002",message:"Slug can only contain lowercase letters, numbers, and hyphens"},idempotencyKey:i.idempotencyKey},{status:400});let p=await D().saveArticle(c,i.idempotencyKey),u=O(),P=N(n.rateLimitResult),h={"X-Bloggy-Version":`platform/${u.version}`,"X-Idempotency-Key":i.idempotencyKey,...P};p.success&&(h.Location=p.url??`/${c.slug}`);let m=p.success?201:p.error?.code==="PUB003"?409:400;return f(e,p,{status:m,headers:h})}catch(t){return console.error("Publish endpoint error:",t),f(e,{success:false,error:{code:"PUB007",message:"Internal server error during publishing"},idempotencyKey:""},{status:500})}}function Ir(e){let t=[];if(!e||typeof e!="object")return t.push("Request body must be a valid object"),t;let r=e;if((!r.article||typeof r.article!="object")&&t.push("Missing required field: article"),(!r.idempotencyKey||typeof r.idempotencyKey!="string")&&t.push("Missing required field: idempotencyKey"),r.article&&typeof r.article=="object"){let n=r.article,o=["id","slug","title","content","publishedAt","site"];for(let i of o)n[i]||t.push(`Missing required article field: ${i}`);if(n.site&&typeof n.site=="object"){let i=n.site,s=["id","name","domain"];for(let a of s)i[a]||t.push(`Missing required site field: ${a}`);}if(n.meta&&typeof n.meta=="object"){let i=n.meta;Array.isArray(i.keywords)||t.push("Article meta.keywords must be an array");}}return t}function Me(e){return !e||typeof e!="string"?false:/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)&&e.length>=1&&e.length<=100}async function Mr(e){try{let t=await E(e);if(!t.authenticated){let m=await M(e);return NextResponse.json(m.error,{status:401})}let r=t.token??"anonymous",n=await I(r);if(!n.allowed){let m=n.errorResponse.error?.details?.rateLimit,d=m&&typeof m=="object"&&"limit"in m&&"remaining"in m&&"reset"in m&&"count"in m&&"success"in m?m:{limit:10,remaining:0,reset:Date.now()+6e4,count:10,success:!1},b=N(d);return f(e,n.errorResponse,{status:429,headers:b})}if(!e.headers.get("content-type")?.includes("application/json"))return f(e,{success:!1,error:{code:"PUB001",message:"Content-Type must be application/json"},idempotencyKey:""},{status:400});let i;try{i=await e.json();}catch{return f(e,{success:!1,error:{code:"PUB001",message:"Invalid JSON in request body"},idempotencyKey:""},{status:400})}let s=Dr(i);if(s.length>0)return f(e,{success:!1,error:{code:"PUB001",message:"Missing required fields",details:{errors:s}},idempotencyKey:i.idempotencyKey??""},{status:400});let a=e.headers.get("X-Bloggy-Version");if(a){let m=$(a);if(m?.platformVersion){let d=O();if(m.platformVersion.major!==d.major)return f(e,{success:!1,error:{code:"PUB009",message:"Major version incompatibility. Please upgrade your blog platform package.",details:{clientVersion:m.platformVersion.version,serverVersion:d.version}},idempotencyKey:i.idempotencyKey},{status:409})}}if(!$r(i.slug))return f(e,{success:!1,error:{code:"PUB002",message:"Slug can only contain lowercase letters, numbers, and hyphens"},idempotencyKey:i.idempotencyKey},{status:400});if(i.dryRun){let d=await D().getArticle(i.slug),b=[];return d||b.push("Article with this slug does not exist"),f(e,{success:!0,warnings:b,idempotencyKey:i.idempotencyKey},{status:200})}let l=await D().removeArticle(i.slug,i.idempotencyKey),p=O(),u=N(n.rateLimitResult),P={"X-Bloggy-Version":`platform/${p.version}`,"X-Idempotency-Key":i.idempotencyKey,...u},h=l.success?200:l.error?.code==="PUB007"?404:400;return f(e,l,{status:h,headers:P})}catch(t){return console.error("Unpublish endpoint error:",t),f(e,{success:false,error:{code:"PUB007",message:"Internal server error during unpublishing"},idempotencyKey:""},{status:500})}}function Dr(e){let t=[];if(!e||typeof e!="object")return t.push("Request body must be a valid object"),t;let r=e;return (!r.slug||typeof r.slug!="string")&&t.push("Missing required field: slug"),(!r.idempotencyKey||typeof r.idempotencyKey!="string")&&t.push("Missing required field: idempotencyKey"),r.slug&&typeof r.slug=="string"&&!r.slug.trim()&&t.push("Slug cannot be empty"),t}function $r(e){return !e||typeof e!="string"?false:/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)&&e.length>=1&&e.length<=100}async function Ur(e){try{let t=await E(e);if(!t.authenticated){let u=await M(e),P={success:!1,versions:{bloggy:{name:"unknown",version:"unknown",major:0,minor:0,patch:0},platform:{name:"unknown",version:"unknown",major:0,minor:0,patch:0}},compatibility:{compatible:!1,errorMessage:u.error?.error?.message??"Authentication required"}};return f(e,P,{status:401})}let r=t.token??"anonymous",n=await I(r);if(!n.allowed){let u=n.errorResponse.error?.details?.rateLimit,P=u&&typeof u=="object"&&"limit"in u&&"remaining"in u&&"reset"in u&&"count"in u&&"success"in u?u:{limit:10,remaining:0,reset:Date.now()+6e4,count:10,success:!1},h=N(P),m={success:!1,versions:{bloggy:{name:"unknown",version:"unknown",major:0,minor:0,patch:0},platform:{name:"unknown",version:"unknown",major:0,minor:0,patch:0}},compatibility:{compatible:!1,errorMessage:n.errorResponse.error?.message??"Rate limit exceeded"}};return f(e,m,{status:429,headers:h})}let o=O(),i=e.headers.get("X-Bloggy-Version"),s={name:"unknown",version:"unknown",major:0,minor:0,patch:0};if(i)try{if(/^\d+\.\d+\.\d+/.test(i)){let u=i.split("."),P=parseInt(u[0]??"0",10),h=parseInt(u[1]??"0",10),m=parseInt(u[2]?.split("-")[0]??"0",10);s={name:"bloggy",version:i,major:P,minor:h,patch:m};}else {let u=$(i);u?.bloggyVersion&&(s=u.bloggyVersion);}}catch(u){console.warn("Failed to parse X-Bloggy-Version header:",u);}let a={compatible:!0};s.version!=="unknown"&&(a=rt(s,o));let c={success:!0,versions:{bloggy:s,platform:o},compatibility:a},l=N(n.rateLimitResult),p={"X-Bloggy-Version":`platform/${o.version}`,"Cache-Control":"public, max-age=300, stale-while-revalidate=60",...l};return f(e,c,{status:200,headers:p})}catch(t){console.error("Version endpoint error:",t);let r={success:false,versions:{bloggy:{name:"unknown",version:"unknown",major:0,minor:0,patch:0},platform:{name:"unknown",version:"unknown",major:0,minor:0,patch:0}},compatibility:{compatible:false,errorMessage:"Internal server error while checking version compatibility"},error:t instanceof Error?t.message:"Unknown error"};return f(e,r,{status:500})}}async function Gr(e,{params:t}){try{let{slug:r}=await t,n=await E(e);if(!n.authenticated){let d=await M(e);return NextResponse.json(d.error,{status:401})}let o=n.token??"anonymous",i=await I(o);if(!i.allowed){let d=i.errorResponse.error?.details?.rateLimit||{limit:10,remaining:0,reset:Date.now()+6e4,count:10,success:!1},b=N(d);return f(e,i.errorResponse,{status:429,headers:b})}if(!r||!Me(r))return f(e,{exists:!1,error:{code:"PUB002",message:"Invalid slug format. Must be lowercase letters, numbers, and hyphens only."}},{status:400});let s=e.headers.get("X-Bloggy-Version");if(s){let d=$(s);if(d?.platformVersion){let b=O();if(d.platformVersion.major!==b.major)return f(e,{exists:!1,error:{code:"PUB009",message:"Major version incompatibility. Please upgrade your blog platform package.",details:{clientVersion:d.platformVersion.version,serverVersion:b.version}}},{status:409})}}let l=await D().getArticle(r)!==null,p={exists:l,...l&&{message:"Slug is already in use. Please choose another (e.g., append '-v2')."}},u=O(),P=N(i.rateLimitResult),h={"X-Bloggy-Version":`platform/${u.version}`,...P},m=e.headers.get("X-Idempotency-Key");return m&&(h["X-Idempotency-Key"]=m,console.log(`Slug check for idempotency: ${m}, exists: ${l}`)),f(e,p,{status:200,headers:h})}catch(r){return console.error("Slug existence check error:",r instanceof Error?r.message:String(r)),f(e,{exists:false,error:{code:"PUB007",message:"Internal server error during slug check"}},{status:500})}}async function Hr(e){return re(e,["GET"])}var Hi=z.version;
30
+ export{le as ApiKeyAuth,We as BlogArticlePage,Fe as BlogHomePage,ft as Button,Y as Card,Q as CardContent,kt as CardDescription,Mt as CardFooter,we as CardHeader,Ne as CardTitle,Ee as DrizzleStorage,H as EnvAuth,me as InMemoryStorage,Z as NoAuth,Hi as PACKAGE_VERSION,oe as Pagination,he as PaginationContent,ie as PaginationEllipsis,B as PaginationItem,U as PaginationLink,ye as PaginationNext,be as PaginationPrevious,fe as ShadcnPagination,X as StructuredDataError,ce as UninitializedAuth,Be as autoConfigureRateLimit,S as bpArticles,j as bpOperations,J as buildBlogPath,ne as buttonVariants,Ke as checkRateLimit,x as cn,pe as configureRateLimit,Rr as createBlogSitemapRoute,Ar as createDynamicBlogSitemap,Je as createRateLimitErrorResponse,K as createStructuredDataScript,I as enforceRateLimit,vt as extractKeywordsFromArticle,Oe as extractTokenFromHeader,zt as generateArticleMetadata,se as generateArticleStructuredData,$e as generateAuthorStructuredData,_t as generateBlogHomeMetadata,Ae as generateBlogHomeStructuredData,Ie as generateBlogSitemapEntries,Ue as generateBreadcrumbStructuredData,V as generateCanonicalUrl,mr as generateCanonicalUrlFromSlug,Re as generateCompleteArticleStructuredData,Pe as generateOrganizationStructuredData,At as generatePaginationMetadata,fr as generateSiteMetadata,xr as generateSitemap,Pr as generateSitemapIndex,Se as generateWebSiteStructuredData,Le as getAuthConfig,dr as getBaseUrl,ur as getDrizzleAdapterSql,Nt as getPathPrefixFromBlogUrl,N as getRateLimitHeaders,D as getStorage,de as initBlogPlatform,nr as initBlogPlatformDev,rr as initBlogPlatformOnce,ir as initBlogPlatformProd,Xt as initEnvAuth,pr as isValidCanonicalUrl,br as metadataToHtml,k as normalizeBlogBasePath,F as normalizeDomain,Ze as normalizeSlug,Er as publishHandler,wt as safeGenerateArticleStructuredData,ue as setAuthConfig,_e as setStorage,Jt as shouldSkipAuth,et as sitemapToXml,Gr as slugExistsHandler,Hr as slugExistsOptionsHandler,Ge as structuredDataToJsonLd,Mr as unpublishHandler,gr as updateArticleCanonicalUrl,Rt as usePagination,yr as validateMetadata,Sr as validateSitemap,Ve as validateStructuredData,Ur as versionHandler};//# sourceMappingURL=index.mjs.map
31
31
  //# sourceMappingURL=index.mjs.map