@xexr/blog-platform 1.0.3 → 1.0.5
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/app/blog/[slug]/page.tsx +87 -26
- package/dist/index.d.mts +8 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +8 -8
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +8 -8
- package/dist/index.mjs.map +1 -1
- package/package.json +9 -8
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
'use strict';var te=require('next/link'),qe=require('next/image'),clsx=require('clsx'),tailwindMerge=require('tailwind-merge'),lucideReact=require('lucide-react'),reactSlot=require('@radix-ui/react-slot'),classVarianceAuthority=require('class-variance-authority'),jsxRuntime=require('react/jsx-runtime'),dateFns=require('date-fns'),rsc=require('next-mdx-remote-client/rsc'),Xe=require('react'),Oe=require('@radix-ui/react-separator'),Wt=require('remark-gfm'),Xt=require('remark-toc'),Kt=require('rehype-slug'),ratelimit=require('@upstash/ratelimit'),redis=require('@upstash/redis'),drizzleOrm=require('drizzle-orm'),sqliteCore=require('drizzle-orm/sqlite-core'),server=require('next/server');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var te__default=/*#__PURE__*/_interopDefault(te);var qe__default=/*#__PURE__*/_interopDefault(qe);var Xe__namespace=/*#__PURE__*/_interopNamespace(Xe);var Oe__namespace=/*#__PURE__*/_interopNamespace(Oe);var Wt__default=/*#__PURE__*/_interopDefault(Wt);var Xt__default=/*#__PURE__*/_interopDefault(Xt);var Kt__default=/*#__PURE__*/_interopDefault(Kt);function v(...e){return tailwindMerge.twMerge(clsx.clsx(e))}var se=classVarianceAuthority.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 yt({className:e,variant:t,size:r,asChild:n=false,...i}){return jsxRuntime.jsx(n?reactSlot.Slot:"button",{"data-slot":"button",className:v(se({variant:t,size:r,className:e})),...i})}function xe({className:e,...t}){return jsxRuntime.jsx("nav",{role:"navigation","aria-label":"pagination","data-slot":"pagination",className:v("mx-auto flex w-full justify-center",e),...t})}function ye({className:e,...t}){return jsxRuntime.jsx("ul",{"data-slot":"pagination-content",className:v("flex flex-row items-center gap-1",e),...t})}function B({...e}){return jsxRuntime.jsx("li",{"data-slot":"pagination-item",...e})}function U({className:e,isActive:t,size:r="icon",...n}){return jsxRuntime.jsx("a",{"aria-current":t?"page":void 0,"data-slot":"pagination-link","data-active":t,className:v(se({variant:t?"outline":"ghost",size:r}),e),...n})}function Pe({className:e,...t}){return jsxRuntime.jsxs(U,{"aria-label":"Go to previous page",size:"default",className:v("gap-1 px-2.5 sm:pl-2.5",e),...t,children:[jsxRuntime.jsx(lucideReact.ChevronLeftIcon,{}),jsxRuntime.jsx("span",{className:"hidden sm:block",children:"Previous"})]})}function ve({className:e,...t}){return jsxRuntime.jsxs(U,{"aria-label":"Go to next page",size:"default",className:v("gap-1 px-2.5 sm:pr-2.5",e),...t,children:[jsxRuntime.jsx("span",{className:"hidden sm:block",children:"Next"}),jsxRuntime.jsx(lucideReact.ChevronRightIcon,{})]})}function ae({className:e,...t}){return jsxRuntime.jsxs("span",{"aria-hidden":true,"data-slot":"pagination-ellipsis",className:v("flex size-9 items-center justify-center",e),...t,children:[jsxRuntime.jsx(lucideReact.MoreHorizontalIcon,{className:"size-4"}),jsxRuntime.jsx("span",{className:"sr-only",children:"More pages"})]})}function le({currentPage:e,totalPages:t,baseUrl:r,className:n,maxVisiblePages:i=5,showPrevNext:o=true,showFirstLast:s=true}){if(t<=1)return null;let a=()=>{let m=Math.floor(i/2),g=Math.max(1,e-m),x=Math.min(t,g+i-1);return x-g+1<i&&(g=Math.max(1,x-i+1)),{start:g,end:x}},{start:c,end:l}=a(),d=Array.from({length:l-c+1},(m,g)=>c+g),p=m=>m===1?r:`${r}?page=${m}`,P=e>1,f=e<t;return jsxRuntime.jsxs(xe,{className:n,children:[jsxRuntime.jsxs(ye,{children:[s&&e>2&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(B,{children:jsxRuntime.jsx(U,{href:p(1),"aria-label":"Go to first page",children:jsxRuntime.jsx(lucideReact.ChevronsLeft,{className:"h-4 w-4"})})}),c>2&&jsxRuntime.jsx(B,{children:jsxRuntime.jsx(ae,{})})]}),o&&jsxRuntime.jsx(B,{children:P?jsxRuntime.jsx(Pe,{href:p(e-1)}):jsxRuntime.jsx("span",{className:"flex h-9 items-center justify-center gap-1 px-2.5 text-muted-foreground sm:pl-2.5",children:jsxRuntime.jsx("span",{className:"hidden sm:block",children:"Previous"})})}),d.map(m=>jsxRuntime.jsx(B,{children:jsxRuntime.jsx(U,{href:p(m),isActive:m===e,children:m})},m)),o&&jsxRuntime.jsx(B,{children:f?jsxRuntime.jsx(ve,{href:p(e+1)}):jsxRuntime.jsx("span",{className:"flex h-9 items-center justify-center gap-1 px-2.5 text-muted-foreground sm:pr-2.5",children:jsxRuntime.jsx("span",{className:"hidden sm:block",children:"Next"})})}),s&&e<t-1&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[l<t-1&&jsxRuntime.jsx(B,{children:jsxRuntime.jsx(ae,{})}),jsxRuntime.jsx(B,{children:jsxRuntime.jsx(U,{href:p(t),"aria-label":"Go to last page",children:jsxRuntime.jsx(lucideReact.ChevronsRight,{className:"h-4 w-4"})})})]})]}),jsxRuntime.jsxs("div",{className:"sr-only","aria-live":"polite",children:["Page ",e," of ",t]})]})}function Nt(e,t=10){let r=e.page,n=Array.isArray(r)?r[0]:r,i=Math.max(1,parseInt(n??"1",10)),o=(i-1)*t;return {currentPage:i,itemsPerPage:t,offset:o,calculateTotalPages:a=>Math.ceil(a/t)}}function Tt(e,t,r,n){let i=n?`${n}${e===1?r:`${r}?page=${e}`}`:void 0,o=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:{...i&&{canonical:i}},other:{...o&&{prev:o},...s&&{next:s}}}}function ce(e,t={}){let{customDomain:r,pathPrefix:n="/blog",language:i,isAccessibleForFree:o=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?Ve(e.author,{customDomain:r,pathPrefix:n}):void 0,d=Re(e.site,{customDomain:r,pathPrefix:n}),P=`PT${Math.max(1,Math.ceil(e.readingSeconds/60))}M`,f={"@context":"https://schema.org","@type":"BlogPosting","@id":`${c}#article`,headline:e.title,description:e.excerpt,datePublished:e.publishedAt,dateModified:e.updatedAt,author:l,publisher:d,mainEntityOfPage:{"@type":"WebPage","@id":c},wordCount:e.wordCount,timeRequired:P,isAccessibleForFree:o};return s&&(e.featuredImage&&(f.image=e.featuredImage),e.meta.keywords.length>0&&(f.keywords=[...e.meta.keywords]),(i??e.site.locale)&&(f.inLanguage=i??e.site.locale),e.site.toneAdjectives.length>0&&(f.about=e.site.toneAdjectives.map(m=>({"@type":"Thing",name:m}))),e.site.toneAdjectives.length>0&&(f.genre=[...e.site.toneAdjectives])),f}function Ve(e,t={}){let{customDomain:r,pathPrefix:n="/blog"}=t,i={"@context":"https://schema.org","@type":"Person","@id":`#author-${e.id}`,name:e.name,identifier:e.id};if(e.bio&&(i.description=e.bio),e.slug?.trim()){let o=r?`https://${r}${n}/authors/${e.slug}`:`${n}/authors/${e.slug}`;i.url=o;}return e.isGuest&&(i.additionalType="GuestAuthor"),e.toneAdjectives&&e.toneAdjectives.length>0&&(i.knowsAbout=[...e.toneAdjectives]),i}function Re(e,t={}){let{customDomain:r,pathPrefix:n="/blog"}=t,o=`https://${r??e.domain}${n}`,s={"@context":"https://schema.org","@type":"Organization","@id":`${o}#organization`,name:e.name,url:o};return e.description?.trim()&&(s.description=e.description),e.tagline?.trim()&&(s.description=s.description?`${s.description}. ${e.tagline}`:e.tagline),s}function Ae(e,t={}){let{customDomain:r,pathPrefix:n="/blog",language:i,includeSearchAction:o=true}=t,a=`https://${r??e.domain}${n}`,c=Re(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),(i??e.locale)&&(l.inLanguage=i??e.locale),o&&(l.potentialAction={"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:`${a}?search={search_term_string}`},"query-input":"required name=search_term_string"}),l}function He(e,t={}){let{customDomain:r}=t;return {"@context":"https://schema.org","@type":"BreadcrumbList",itemListElement:e.map((n,i)=>({"@type":"ListItem",position:i+1,name:n.name,item:r&&!n.url.startsWith("http")?`https://${r}${n.url}`:n.url}))}}function we(e,t={}){let r=[];r.push(ce(e,t)),r.push(Ae(e.site,t));let n=t.pathPrefix??"/blog",i=[{name:"Home",url:"/"},{name:e.site.name,url:n},{name:e.title,url:`${n}/${e.slug}`}];return r.push(He(i,t)),r}function Ne(e,t=[],r={}){let n=[];if(n.push(Ae(e,r)),t.length>0){let i=t.slice(0,5).map(o=>ce(o,r));n.push(...i);}return n}function Ge(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 je(e){return JSON.stringify(e,null,0)}function J(e){return {type:"application/ld+json",dangerouslySetInnerHTML:{__html:je(e)}}}function Ct(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 K=class extends Error{constructor(r,n,i){super(r);this.code=n;this.details=i;this.name="StructuredDataError";}code;details};function Lt(e,t={}){try{let r=ce(e,t),n=Ge(r);return n.isValid?{schema:r}:{error:new K("Generated schema validation failed","VALIDATION_FAILED",n.errors)}}catch(r){return {error:new K("Failed to generate structured data","GENERATION_FAILED",r)}}}function I(e="/blog"){let t=e.trim();return !t||t==="/"?"":t.replace(/^(?!\/)/,"/").replace(/\/+$/,"")}function V(e,t){let r=I(e),n=t?.replace(/^\/+/,"").replace(/\/+$/,"");return n?`${r}/${n}`.replace(/\/+/g,"/"):r||"/"}function Ot(e){let t=new URL(e);return I(t.pathname)}var ue={accentColor:"hsl(var(--primary))",accentHoverColor:"hsl(var(--primary))",accentBackgroundColor:"hsl(var(--primary) / 0.08)",accentBorderColor:"hsl(var(--primary) / 0.25)"};function Y(e={}){return {"--blog-accent":e.accentColor??ue.accentColor,"--blog-accent-hover":e.accentHoverColor??ue.accentHoverColor,"--blog-accent-bg":e.accentBackgroundColor??ue.accentBackgroundColor,"--blog-accent-border":e.accentBorderColor??ue.accentBorderColor}}function Te(e,t){let r=new Date(e),n=new Date(t);return {publishedDateLabel:dateFns.format(r,"d MMMM yyyy"),publishedRelativeLabel:dateFns.formatDistanceToNow(r,{addSuffix:true}),updatedDateLabel:dateFns.format(n,"d MMMM yyyy"),isUpdated:n.getTime()!==r.getTime()}}function Ce(e){let t=[],r=false;for(let n of e.split(`
|
|
2
|
-
`)){if(/^\s*```/.test(n)){r=!r;continue}if(r)continue;let i=/^(#{2,3})\s+(.+?)\s*#*\s*$/.exec(n);if(!i?.[1]||!i[2])continue;let o=Bt(i[2]);o&&t.push({id:kt(o),text:o,level:i[1].length});}return t}function Bt(e){return e.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/[*_`~]/g,"").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim()}function kt(e){return e.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-")}function We({articles:e,siteName:t,siteTagline:r,className:n,site:i,includeStructuredData:o=false,basePath:s="/blog",pagination:a,theme:c}){let l=I(s)||"/";return jsxRuntime.jsxs("div",{style:Y(c),className:v("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&&jsxRuntime.jsxs("header",{className:"blog-header mb-8 text-center sm:mb-12 lg:mb-16",children:[jsxRuntime.jsx("h1",{className:"blog-title mb-2 bg-linear-to-r from-[var(--blog-accent-hover)] to-[var(--blog-accent)] bg-clip-text text-3xl font-semibold tracking-tight text-balance text-transparent sm:text-4xl lg:text-5xl",children:t}),r&&jsxRuntime.jsx("p",{className:"blog-tagline text-muted-foreground text-base sm:text-lg",children:r})]}),jsxRuntime.jsxs("main",{className:"articles-list",children:[e.length===0?jsxRuntime.jsxs("div",{className:"no-articles text-muted-foreground py-16 text-center sm:py-24 lg:py-32",children:[jsxRuntime.jsx("h2",{className:"mb-3 text-xl font-light sm:mb-4 sm:text-2xl lg:text-3xl",children:"No articles yet"}),jsxRuntime.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."})]}):jsxRuntime.jsx("div",{className:"space-y-0",children:e.map(d=>jsxRuntime.jsx(Dt,{article:d,basePath:l},d.id))}),a&&a.totalPages>1&&jsxRuntime.jsx("div",{className:"pagination-wrapper mt-12",children:jsxRuntime.jsx(le,{currentPage:a.currentPage,totalPages:a.totalPages,baseUrl:a.baseUrl??l,className:"justify-center"})})]}),o&&i&&(()=>{let d=J(Ne(i,e.slice(0,5),{pathPrefix:l}));return jsxRuntime.jsx("script",{type:d.type,dangerouslySetInnerHTML:d.dangerouslySetInnerHTML})})()]})}function Mt(e){return `${Math.ceil(e/60)} min read`}function Dt({article:e,basePath:t}){let r=V(t,e.slug),n=dateFns.formatDistanceToNow(new Date(e.publishedAt),{addSuffix:true}),i=Mt(e.readingSeconds),o=e.featuredImage;return jsxRuntime.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:jsxRuntime.jsxs(te__default.default,{href:r,className:"focus-visible:ring-ring block rounded-2xl hover:no-underline focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none","aria-label":`Read article: ${e.title}`,children:[jsxRuntime.jsxs("div",{className:"space-y-4 lg:hidden",children:[o&&jsxRuntime.jsx("div",{className:"relative aspect-[16/10] w-full overflow-hidden rounded-2xl",children:jsxRuntime.jsx(qe__default.default,{src:o,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"})}),jsxRuntime.jsxs("div",{className:"space-y-3",children:[jsxRuntime.jsx("h2",{className:"group-hover:text-[var(--blog-accent)] text-lg leading-tight font-bold text-balance transition-colors sm:text-xl md:text-2xl",children:e.title}),jsxRuntime.jsxs("div",{className:"text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1 text-sm",children:[e.author&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("span",{className:"font-medium",children:e.author.name}),jsxRuntime.jsx("span",{className:"text-border",children:"\u2022"})]}),jsxRuntime.jsx("time",{dateTime:e.publishedAt,className:"font-medium","aria-label":`Published ${n}`,children:n}),jsxRuntime.jsx("span",{className:"text-border",children:"\u2022"}),jsxRuntime.jsx("span",{className:"font-medium",children:i})]}),e.excerpt&&jsxRuntime.jsx("p",{className:"text-muted-foreground line-clamp-3 text-sm leading-relaxed sm:text-base",children:e.excerpt})]})]}),jsxRuntime.jsxs("div",{className:"hidden items-start gap-6 lg:flex xl:gap-8",children:[o&&jsxRuntime.jsx("div",{className:"relative aspect-[16/10] w-64 shrink-0 overflow-hidden rounded-2xl xl:w-72",children:jsxRuntime.jsx(qe__default.default,{src:o,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"})}),jsxRuntime.jsxs("div",{className:"flex min-h-[180px] flex-1 flex-col justify-between space-y-4 xl:min-h-[200px]",children:[jsxRuntime.jsxs("div",{className:"space-y-4",children:[jsxRuntime.jsx("h2",{className:"group-hover:text-[var(--blog-accent)] text-2xl leading-tight font-bold text-balance transition-colors xl:text-3xl",children:e.title}),e.excerpt&&jsxRuntime.jsx("p",{className:"text-muted-foreground line-clamp-3 text-base leading-relaxed xl:text-lg",children:e.excerpt})]}),jsxRuntime.jsxs("div",{className:"text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1 text-sm",children:[e.author&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("span",{className:"font-medium",children:e.author.name}),jsxRuntime.jsx("span",{className:"text-border",children:"\u2022"})]}),jsxRuntime.jsx("time",{dateTime:e.publishedAt,className:"font-medium","aria-label":`Published ${n}`,children:n}),jsxRuntime.jsx("span",{className:"text-border",children:"\u2022"}),jsxRuntime.jsx("span",{className:"font-medium",children:i})]})]})]})]})})}function $t(e,t,r,n,i="/blog"){let o=e?`${e} - Blog`:"Blog",s=n&&n.currentPage>1?`${o} - Page ${n.currentPage}`:o,a=t??"Read our latest articles and insights.",c=I(i)||"/",l=r?`${r}${n&&n.currentPage>1?`${c}?page=${n.currentPage}`:c}`:void 0,d=n&&n.currentPage>1&&r?`${r}${n.currentPage===2?c:`${c}?page=${n.currentPage-1}`}`:void 0,p=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:{...d&&{prev:d},...p&&{next:p}}}}var Vt=classVarianceAuthority.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 Le({className:e,variant:t,...r}){return jsxRuntime.jsx("div",{className:v(Vt({variant:t}),e),...r})}function Q({className:e,...t}){return jsxRuntime.jsx("div",{"data-slot":"card",className:v("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Gt({className:e,...t}){return jsxRuntime.jsx("div",{"data-slot":"card-header",className:v("@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 jt({className:e,...t}){return jsxRuntime.jsx("div",{"data-slot":"card-title",className:v("leading-none font-semibold",e),...t})}function Ft({className:e,...t}){return jsxRuntime.jsx("div",{"data-slot":"card-description",className:v("text-muted-foreground text-sm",e),...t})}function Z({className:e,...t}){return jsxRuntime.jsx("div",{"data-slot":"card-content",className:v("px-6",e),...t})}function qt({className:e,...t}){return jsxRuntime.jsx("div",{"data-slot":"card-footer",className:v("flex items-center px-6 [.border-t]:pt-6",e),...t})}var ee=Xe__namespace.forwardRef(({className:e,orientation:t="horizontal",decorative:r=true,...n},i)=>jsxRuntime.jsx(Oe__namespace.Root,{ref:i,decorative:r,orientation:t,className:v("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...n}));ee.displayName=Oe__namespace.Root.displayName;var Ke={mdxOptions:{remarkPlugins:[Xt__default.default,Wt__default.default],rehypePlugins:[Kt__default.default]}};function rr(e){return `${Math.ceil(e/60)} min read`}function Ye({article:e,className:t,navigation:r,basePath:n="/blog",theme:i,postArticleCta:o,relatedArticles:s=[],showShareLinks:a=true}){let c=I(n)||"/",l=Te(e.publishedAt,e.updatedAt),d=rr(e.readingSeconds),p=Ce(e.content),P=e.meta.canonicalUrl??V(c,e.slug),f=e.featuredImage;return jsxRuntime.jsxs("article",{style:Y(i),className:v("article-page mx-auto max-w-6xl 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&&jsxRuntime.jsx("header",{className:"mx-auto mb-8 max-w-4xl sm:mb-12 lg:mb-16",children:jsxRuntime.jsxs(te__default.default,{href:r.backToHome.url,className:"text-muted-foreground hover:text-[var(--blog-accent)] 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:[jsxRuntime.jsx(lucideReact.ArrowLeft,{className:"h-4 w-4 transition-transform group-hover:-translate-x-1 sm:h-5 sm:w-5","aria-hidden":"true"}),jsxRuntime.jsxs("span",{className:"text-sm font-medium sm:text-base",children:[jsxRuntime.jsx("span",{className:"hidden sm:inline",children:r.backToHome.label??"Back to all articles"}),jsxRuntime.jsx("span",{className:"sm:hidden",children:"Back"})]})]})}),jsxRuntime.jsxs("header",{className:"article-header mx-auto mb-6 max-w-4xl space-y-4 text-center sm:mb-8 sm:space-y-6 lg:mb-12 lg:space-y-8",children:[jsxRuntime.jsx("h1",{className:"article-title text-foreground px-4 text-2xl leading-tight font-light tracking-tight text-balance sm:px-0 sm:text-3xl md:text-4xl lg:text-5xl xl:text-6xl",children:e.title}),e.excerpt&&jsxRuntime.jsx("p",{className:"article-excerpt text-muted-foreground mx-auto mt-6 max-w-xs px-4 text-base leading-relaxed text-balance 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}),jsxRuntime.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&&jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx("span",{className:"sr-only",children:"Author"}),jsxRuntime.jsx("span",{className:"font-medium",children:e.author.name}),e.author.isGuest&&jsxRuntime.jsx(Le,{variant:"outline",className:"text-xs",children:"Guest Author"})]}),jsxRuntime.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-3 gap-y-1",children:[jsxRuntime.jsxs("time",{dateTime:e.publishedAt,className:"font-medium","aria-label":`Published ${l.publishedDateLabel}`,children:["Published ",l.publishedDateLabel]}),jsxRuntime.jsx("span",{className:"text-border",children:"\u2022"}),jsxRuntime.jsx("span",{className:"font-medium",children:l.publishedRelativeLabel}),jsxRuntime.jsx("span",{className:"text-border",children:"\u2022"}),jsxRuntime.jsx("span",{className:"font-medium",children:d})]}),l.isUpdated&&jsxRuntime.jsxs("time",{dateTime:e.updatedAt,className:"text-xs",children:["Updated ",l.updatedDateLabel]}),jsxRuntime.jsx("div",{className:"bg-border h-px w-6 sm:w-8","aria-hidden":"true"}),jsxRuntime.jsxs("span",{className:"text-xs tracking-wider uppercase sm:text-sm",role:"text",children:["From ",e.site.name]})]})]}),f&&jsxRuntime.jsx("div",{className:"article-featured-image mx-auto my-8 aspect-[16/9] w-full max-w-4xl overflow-hidden rounded-2xl sm:my-12 lg:my-16",children:jsxRuntime.jsx(qe__default.default,{src:f,alt:e.featuredImageAlt??`Featured image for ${e.title}`,className:"h-full w-full object-cover",width:800,height:450,priority:true})}),jsxRuntime.jsxs("div",{className:"article-content mx-auto grid max-w-6xl grid-cols-1 gap-8 lg:grid-cols-[minmax(0,1fr)_14rem] lg:gap-12",children:[jsxRuntime.jsxs("div",{className:"min-w-0",children:[jsxRuntime.jsx(Je,{items:p,variant:"mobile"}),jsxRuntime.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-headings:text-balance prose-headings:text-[var(--blog-accent)] 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-p:text-pretty prose-img:mx-auto prose-img:rounded-2xl prose-a:text-[var(--blog-accent)] prose-a:transition-colors hover:prose-a:text-[var(--blog-accent-hover)] max-w-none",children:jsxRuntime.jsx(rsc.MDXRemote,{source:e.content,options:Ke})})]}),jsxRuntime.jsx(Je,{items:p,variant:"desktop"})]}),e.author?.bio&&jsxRuntime.jsxs("div",{className:"author-bio mx-auto mt-12 max-w-4xl",children:[jsxRuntime.jsx(ee,{className:"mb-8"}),jsxRuntime.jsx(Q,{className:"border-[var(--blog-accent-border)] bg-[var(--blog-accent-bg)]",children:jsxRuntime.jsxs(Z,{className:"flex flex-col gap-4 p-5 sm:flex-row sm:items-start sm:p-6",children:[jsxRuntime.jsx("div",{className:"flex size-12 shrink-0 items-center justify-center rounded-full bg-[var(--blog-accent)] text-lg font-semibold text-white","aria-hidden":"true",children:e.author.name.slice(0,1)}),jsxRuntime.jsxs("div",{className:"min-w-0 space-y-2",children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("p",{className:"text-muted-foreground text-sm font-medium",children:"Written by"}),jsxRuntime.jsxs("h2",{className:"text-foreground flex flex-wrap items-center gap-2 text-xl font-semibold",children:[e.author.name,e.author.isGuest&&jsxRuntime.jsx(Le,{variant:"outline",className:"text-xs",children:"Guest Author"})]})]}),jsxRuntime.jsx("p",{className:"text-muted-foreground leading-relaxed",children:e.author.bio})]})]})})]}),((o??false)||a||s.length>0)&&jsxRuntime.jsxs("div",{className:"mx-auto mt-12 max-w-4xl space-y-8",children:[jsxRuntime.jsx(ee,{}),o&&jsxRuntime.jsx(nr,{cta:o}),a&&jsxRuntime.jsx(or,{title:e.title,url:P}),s.length>0&&jsxRuntime.jsx(ir,{articles:s.slice(0,3),basePath:c})]}),(!!r?.previousArticle||!!r?.nextArticle)&&jsxRuntime.jsxs("nav",{className:"article-nav mx-auto mt-12 max-w-4xl",children:[jsxRuntime.jsx(ee,{className:"mb-8"}),jsxRuntime.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2",children:[r?.previousArticle&&jsxRuntime.jsx(Q,{className:"group hover:border-[var(--blog-accent-border)] hover:bg-[var(--blog-accent-bg)] cursor-pointer transition-colors",children:jsxRuntime.jsx(te__default.default,{href:r.previousArticle.url,className:"block",children:jsxRuntime.jsxs(Z,{className:"p-4",children:[jsxRuntime.jsx("div",{className:"text-muted-foreground mb-2 text-sm font-medium",children:"\u2190 Previous Article"}),jsxRuntime.jsx("div",{className:"text-foreground group-hover:text-[var(--blog-accent)] transition-colors",children:r.previousArticle.title})]})})}),r?.nextArticle&&jsxRuntime.jsx(Q,{className:v("group hover:border-[var(--blog-accent-border)] hover:bg-[var(--blog-accent-bg)] cursor-pointer transition-colors",!r?.previousArticle&&"md:col-start-2"),children:jsxRuntime.jsx(te__default.default,{href:r.nextArticle.url,className:"block",children:jsxRuntime.jsxs(Z,{className:"p-4 md:text-right",children:[jsxRuntime.jsx("div",{className:"text-muted-foreground mb-2 text-sm font-medium",children:"Next Article \u2192"}),jsxRuntime.jsx("div",{className:"text-foreground group-hover:text-[var(--blog-accent)] transition-colors",children:r.nextArticle.title})]})})})]})]}),(()=>{let m=J(we(e,{pathPrefix:c}));return jsxRuntime.jsx("script",{type:m.type,dangerouslySetInnerHTML:m.dangerouslySetInnerHTML})})()]})}function Je({items:e,variant:t}){if(e.length===0)return null;let r=jsxRuntime.jsx("ul",{className:"space-y-2 text-sm",children:e.map(n=>jsxRuntime.jsx("li",{className:n.level===3?"pl-4":void 0,children:jsxRuntime.jsx("a",{href:`#${n.id}`,className:"text-muted-foreground hover:text-[var(--blog-accent)] block leading-snug transition-colors",children:n.text})},n.id))});return t==="mobile"?jsxRuntime.jsxs("nav",{"aria-label":"Table of contents",className:"mb-8 rounded-2xl border border-[var(--blog-accent-border)] bg-[var(--blog-accent-bg)] p-4 lg:hidden",children:[jsxRuntime.jsx("p",{className:"text-foreground mb-3 text-sm font-semibold",children:"On this page"}),r]}):jsxRuntime.jsx("aside",{className:"hidden lg:block",children:jsxRuntime.jsxs("nav",{"aria-label":"Table of contents",className:"sticky top-24 max-h-[calc(100vh-8rem)] overflow-y-auto border-l border-border pl-5",children:[jsxRuntime.jsx("p",{className:"text-muted-foreground mb-3 text-xs font-semibold tracking-wider uppercase",children:"On this page"}),r]})})}function nr({cta:e}){return jsxRuntime.jsx("div",{className:"rounded-2xl border border-[var(--blog-accent-border)] bg-[var(--blog-accent-bg)] p-5 sm:p-6",children:jsxRuntime.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between",children:[jsxRuntime.jsxs("div",{className:"space-y-1",children:[jsxRuntime.jsx("h2",{className:"text-foreground text-xl font-semibold",children:e.title}),e.description&&jsxRuntime.jsx("p",{className:"text-muted-foreground leading-relaxed",children:e.description})]}),jsxRuntime.jsxs(te__default.default,{href:e.href,className:"inline-flex shrink-0 items-center justify-center gap-2 rounded-full bg-[var(--blog-accent)] px-4 py-2 text-sm font-semibold text-white transition-opacity hover:opacity-90",children:[e.label,jsxRuntime.jsx(lucideReact.ArrowUpRight,{className:"size-4","aria-hidden":"true"})]})]})})}function or({title:e,url:t}){let r=encodeURIComponent(e),n=encodeURIComponent(t);return jsxRuntime.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[jsxRuntime.jsxs("span",{className:"text-muted-foreground inline-flex items-center gap-2 text-sm font-medium",children:[jsxRuntime.jsx(lucideReact.Share2,{className:"size-4","aria-hidden":"true"}),"Share"]}),jsxRuntime.jsx("a",{href:`https://x.com/intent/tweet?text=${r}&url=${n}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted-foreground hover:border-[var(--blog-accent-border)] hover:text-[var(--blog-accent)] rounded-full border border-border px-3 py-1.5 text-sm transition-colors",children:"X"}),jsxRuntime.jsx("a",{href:`https://www.linkedin.com/sharing/share-offsite/?url=${n}`,target:"_blank",rel:"noopener noreferrer",className:"text-muted-foreground hover:border-[var(--blog-accent-border)] hover:text-[var(--blog-accent)] rounded-full border border-border px-3 py-1.5 text-sm transition-colors",children:"LinkedIn"}),jsxRuntime.jsxs("a",{href:`mailto:?subject=${r}&body=${n}`,className:"text-muted-foreground hover:border-[var(--blog-accent-border)] hover:text-[var(--blog-accent)] inline-flex items-center gap-1.5 rounded-full border border-border px-3 py-1.5 text-sm transition-colors",children:[jsxRuntime.jsx(lucideReact.Mail,{className:"size-3.5","aria-hidden":"true"}),"Email"]})]})}function ir({articles:e,basePath:t}){return jsxRuntime.jsxs("section",{className:"space-y-4","aria-labelledby":"related-articles-title",children:[jsxRuntime.jsx("h2",{id:"related-articles-title",className:"text-xl font-semibold",children:"You might also like"}),jsxRuntime.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:e.map(r=>jsxRuntime.jsxs(te__default.default,{href:V(t,r.slug),className:"group rounded-2xl border border-border p-4 transition-colors hover:border-[var(--blog-accent-border)] hover:bg-[var(--blog-accent-bg)] hover:no-underline",children:[jsxRuntime.jsx("h3",{className:"text-foreground group-hover:text-[var(--blog-accent)] line-clamp-3 font-semibold transition-colors",children:r.title}),r.excerpt&&jsxRuntime.jsx("p",{className:"text-muted-foreground mt-2 line-clamp-3 text-sm leading-relaxed",children:r.excerpt})]},r.id))})]})}function sr(e,t="/blog"){let r=e.meta.title??e.title,n=e.meta.description??e.excerpt,i=e.meta.canonicalUrl??`${e.site.domain}${V(t,e.slug)}`,o=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:i,images:o?[{url:o,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:o?[o]:void 0},alternates:{canonical:i}}}function _e(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 o=/^Token\s+(.+)$/i.exec(t);return o?.[1]?o[1]:null}var me=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=>_e(t);hashToken(t){return t.substring(0,8)+"..."}},j=class extends me{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(i=>i.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);}},re=class{async validateToken(){return {valid:true,context:{development:true}}}extractToken(){return "development-mode"}},de=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 ar(){return globalThis.__BLOG_PLATFORM_AUTH_CONFIG__??=new de,globalThis.__BLOG_PLATFORM_AUTH_CONFIG__}function pe(e){globalThis.__BLOG_PLATFORM_AUTH_CONFIG__=e;}function Be(){return globalThis.__BLOG_PLATFORM_AUTH_CONFIG__??ar()}function lr(e){pe(new j(e));}async function k(e){let t=Be(),r=t.extractToken?t.extractToken(e):_e(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 cr(e,t=""){let n=Be().errorMessages??{},i,o;switch(e.errorCode){case "missing":i=n.missing??"Authentication token is required",o="PUB005";break;case "expired":i=n.expired??"Authentication token has expired",o="PUB005";break;default:i=n.invalid??"Invalid authentication credentials",o="PUB005";break}return {success:false,error:{code:o,message:i,details:{authError:e.errorCode??"invalid"}},idempotencyKey:t}}async function M(e){let t=await k(e);return t.authenticated?{authenticated:true,context:t.result.context}:{authenticated:false,error:cr(t.result)}}function ur(){let e=process.env.SKIP_BLOG_PLATFORM_AUTH;return e==="true"||e==="1"||process.env.NODE_ENV==="test"}var ge=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 o={success:false,error:{code:"PUB003",message:"This URL is already in use. Please choose another."},idempotencyKey:r};return await this.storeOperationResult(r,o),o}this.articles.set(t.slug,t);let i={success:true,url:`/${t.slug}`,platformPostId:t.id,publishedAt:t.publishedAt,idempotencyKey:r};return await this.storeOperationResult(r,i),i}async getArticle(t){return this.articles.get(t)??null}async listArticles(t={}){let{limit:r=10,offset:n=0,sortBy:i="publishedAt",order:o="desc"}=t,s=Array.from(this.articles.values());return s.sort((c,l)=>{let d=new Date(c[i]).getTime(),p=new Date(l[i]).getTime();return o==="desc"?p-d:d-p}),{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 o={success:false,error:{code:"PUB007",message:"Article not found"},idempotencyKey:r};return await this.storeOperationResult(r,o),o}this.articles.delete(t);let i={success:true,idempotencyKey:r};return await this.storeOperationResult(r,i),i}async checkIdempotency(t){return this.operations.get(t)??null}async storeOperationResult(t,r){this.operations.set(t,r);}};function mr(){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 dr(){let e=globalThis;e.__BLOG_PLATFORM_STORAGE__||(mr(),e.__BLOG_PLATFORM_STORAGE__=new ge);let t=e.__BLOG_PLATFORM_STORAGE__;if(!t)throw new Error("Blog platform storage not initialized");return t}function D(){return dr()}function ke(e){let t=globalThis;t.__BLOG_PLATFORM_STORAGE__=e;}function gr(){return globalThis.__BLOG_PLATFORM_RATE_LIMITER__??null}function fr(e){let t=globalThis;t.__BLOG_PLATFORM_RATE_LIMITER__=e;}function fe(e){let{redisUrl:t,redisToken:r,requestsPerMinute:n=5,keyPrefix:i="blog-platform-ratelimit",analytics:o=true}=e,s=new redis.Redis({url:t,token:r}),a=new ratelimit.Ratelimit({redis:s,analytics:o,prefix:i,limiter:ratelimit.Ratelimit.slidingWindow(n,"1m")});fr(a);}function Ee(){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}fe({redisUrl:e,redisToken:t}),console.log("Blog platform: Rate limiting configured (5 requests per minute per token)");}async function Ze(e){let t=gr();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 et(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 E(e,t=""){let r=await Ze(e);return r.success?{allowed:true,rateLimitResult:r}:{allowed:false,errorResponse:et(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 he(e){let{auth:t,storage:r,rateLimit:n,autoRateLimit:i=true}=e;if(!t)throw new Error(`Blog platform initialization failed: 'auth' is required.
|
|
1
|
+
'use strict';var ne=require('next/link'),Xe=require('next/image'),clsx=require('clsx'),tailwindMerge=require('tailwind-merge'),lucideReact=require('lucide-react'),reactSlot=require('@radix-ui/react-slot'),classVarianceAuthority=require('class-variance-authority'),jsxRuntime=require('react/jsx-runtime'),dateFns=require('date-fns'),rsc=require('next-mdx-remote-client/rsc'),Qe=require('react'),_e=require('@radix-ui/react-separator'),er=require('remark-gfm'),tr=require('remark-toc'),rr=require('rehype-slug'),ratelimit=require('@upstash/ratelimit'),redis=require('@upstash/redis'),drizzleOrm=require('drizzle-orm'),sqliteCore=require('drizzle-orm/sqlite-core'),server=require('next/server');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var ne__default=/*#__PURE__*/_interopDefault(ne);var Xe__default=/*#__PURE__*/_interopDefault(Xe);var Qe__namespace=/*#__PURE__*/_interopNamespace(Qe);var _e__namespace=/*#__PURE__*/_interopNamespace(_e);var er__default=/*#__PURE__*/_interopDefault(er);var tr__default=/*#__PURE__*/_interopDefault(tr);var rr__default=/*#__PURE__*/_interopDefault(rr);function y(...e){return tailwindMerge.twMerge(clsx.clsx(e))}var le=classVarianceAuthority.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 Rt({className:e,variant:t,size:r,asChild:n=false,...i}){return jsxRuntime.jsx(n?reactSlot.Slot:"button",{"data-slot":"button",className:y(le({variant:t,size:r,className:e})),...i})}function ye({className:e,...t}){return jsxRuntime.jsx("nav",{role:"navigation","aria-label":"pagination","data-slot":"pagination",className:y("mx-auto flex w-full justify-center",e),...t})}function Pe({className:e,...t}){return jsxRuntime.jsx("ul",{"data-slot":"pagination-content",className:y("flex flex-row items-center gap-1",e),...t})}function B({...e}){return jsxRuntime.jsx("li",{"data-slot":"pagination-item",...e})}function U({className:e,isActive:t,size:r="icon",...n}){return jsxRuntime.jsx("a",{"aria-current":t?"page":void 0,"data-slot":"pagination-link","data-active":t,className:y(le({variant:t?"outline":"ghost",size:r}),e),...n})}function ve({className:e,...t}){return jsxRuntime.jsxs(U,{"aria-label":"Go to previous page",size:"default",className:y("gap-1 px-2.5 sm:pl-2.5",e),...t,children:[jsxRuntime.jsx(lucideReact.ChevronLeftIcon,{}),jsxRuntime.jsx("span",{className:"hidden sm:block",children:"Previous"})]})}function Ae({className:e,...t}){return jsxRuntime.jsxs(U,{"aria-label":"Go to next page",size:"default",className:y("gap-1 px-2.5 sm:pr-2.5",e),...t,children:[jsxRuntime.jsx("span",{className:"hidden sm:block",children:"Next"}),jsxRuntime.jsx(lucideReact.ChevronRightIcon,{})]})}function ce({className:e,...t}){return jsxRuntime.jsxs("span",{"aria-hidden":true,"data-slot":"pagination-ellipsis",className:y("flex size-9 items-center justify-center",e),...t,children:[jsxRuntime.jsx(lucideReact.MoreHorizontalIcon,{className:"size-4"}),jsxRuntime.jsx("span",{className:"sr-only",children:"More pages"})]})}function ue({currentPage:e,totalPages:t,baseUrl:r,className:n,maxVisiblePages:i=5,showPrevNext:o=true,showFirstLast:s=true}){if(t<=1)return null;let a=()=>{let m=Math.floor(i/2),g=Math.max(1,e-m),x=Math.min(t,g+i-1);return x-g+1<i&&(g=Math.max(1,x-i+1)),{start:g,end:x}},{start:u,end:l}=a(),d=Array.from({length:l-u+1},(m,g)=>u+g),p=m=>m===1?r:`${r}?page=${m}`,v=e>1,h=e<t;return jsxRuntime.jsxs(ye,{className:n,children:[jsxRuntime.jsxs(Pe,{children:[s&&e>2&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx(B,{children:jsxRuntime.jsx(U,{href:p(1),"aria-label":"Go to first page",children:jsxRuntime.jsx(lucideReact.ChevronsLeft,{className:"h-4 w-4"})})}),u>2&&jsxRuntime.jsx(B,{children:jsxRuntime.jsx(ce,{})})]}),o&&jsxRuntime.jsx(B,{children:v?jsxRuntime.jsx(ve,{href:p(e-1)}):jsxRuntime.jsx("span",{className:"flex h-9 items-center justify-center gap-1 px-2.5 text-muted-foreground sm:pl-2.5",children:jsxRuntime.jsx("span",{className:"hidden sm:block",children:"Previous"})})}),d.map(m=>jsxRuntime.jsx(B,{children:jsxRuntime.jsx(U,{href:p(m),isActive:m===e,children:m})},m)),o&&jsxRuntime.jsx(B,{children:h?jsxRuntime.jsx(Ae,{href:p(e+1)}):jsxRuntime.jsx("span",{className:"flex h-9 items-center justify-center gap-1 px-2.5 text-muted-foreground sm:pr-2.5",children:jsxRuntime.jsx("span",{className:"hidden sm:block",children:"Next"})})}),s&&e<t-1&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[l<t-1&&jsxRuntime.jsx(B,{children:jsxRuntime.jsx(ce,{})}),jsxRuntime.jsx(B,{children:jsxRuntime.jsx(U,{href:p(t),"aria-label":"Go to last page",children:jsxRuntime.jsx(lucideReact.ChevronsRight,{className:"h-4 w-4"})})})]})]}),jsxRuntime.jsxs("div",{className:"sr-only","aria-live":"polite",children:["Page ",e," of ",t]})]})}function _t(e,t=10){let r=e.page,n=Array.isArray(r)?r[0]:r,i=Math.max(1,parseInt(n??"1",10)),o=(i-1)*t;return {currentPage:i,itemsPerPage:t,offset:o,calculateTotalPages:a=>Math.ceil(a/t)}}function Bt(e,t,r,n){let i=n?`${n}${e===1?r:`${r}?page=${e}`}`:void 0,o=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:{...i&&{canonical:i}},other:{...o&&{prev:o},...s&&{next:s}}}}function me(e,t={}){let{customDomain:r,pathPrefix:n="/blog",language:i,isAccessibleForFree:o=true,includeOptionalProperties:s=true}=t,a=r??e.site.domain,u=r?`https://${a}${n}/${e.slug}`:e.meta.canonicalUrl??`https://${a}${n}/${e.slug}`,l=e.author?Ge(e.author,{customDomain:r,pathPrefix:n}):void 0,d=Re(e.site,{customDomain:r,pathPrefix:n}),v=`PT${Math.max(1,Math.ceil(e.readingSeconds/60))}M`,h={"@context":"https://schema.org","@type":"BlogPosting","@id":`${u}#article`,headline:e.title,description:e.excerpt,datePublished:e.publishedAt,dateModified:e.updatedAt,author:l,publisher:d,mainEntityOfPage:{"@type":"WebPage","@id":u},wordCount:e.wordCount,timeRequired:v,isAccessibleForFree:o};return s&&(e.featuredImage&&(h.image=e.featuredImage),e.meta.keywords.length>0&&(h.keywords=[...e.meta.keywords]),(i??e.site.locale)&&(h.inLanguage=i??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 Ge(e,t={}){let{customDomain:r,pathPrefix:n="/blog"}=t,i={"@context":"https://schema.org","@type":"Person","@id":`#author-${e.id}`,name:e.name,identifier:e.id};if(e.bio&&(i.description=e.bio),e.slug?.trim()){let o=r?`https://${r}${n}/authors/${e.slug}`:`${n}/authors/${e.slug}`;i.url=o;}return e.isGuest&&(i.additionalType="GuestAuthor"),e.toneAdjectives&&e.toneAdjectives.length>0&&(i.knowsAbout=[...e.toneAdjectives]),i}function Re(e,t={}){let{customDomain:r,pathPrefix:n="/blog"}=t,o=`https://${r??e.domain}${n}`,s={"@context":"https://schema.org","@type":"Organization","@id":`${o}#organization`,name:e.name,url:o};return e.description?.trim()&&(s.description=e.description),e.tagline?.trim()&&(s.description=s.description?`${s.description}. ${e.tagline}`:e.tagline),s}function we(e,t={}){let{customDomain:r,pathPrefix:n="/blog",language:i,includeSearchAction:o=true}=t,a=`https://${r??e.domain}${n}`,u=Re(e,t),l={"@context":"https://schema.org","@type":"WebSite","@id":`${a}#website`,name:e.name,url:a,publisher:u};return e.description?.trim()&&(l.description=e.description),(i??e.locale)&&(l.inLanguage=i??e.locale),o&&(l.potentialAction={"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:`${a}?search={search_term_string}`},"query-input":"required name=search_term_string"}),l}function je(e,t={}){let{customDomain:r}=t;return {"@context":"https://schema.org","@type":"BreadcrumbList",itemListElement:e.map((n,i)=>({"@type":"ListItem",position:i+1,name:n.name,item:r&&!n.url.startsWith("http")?`https://${r}${n.url}`:n.url}))}}function Ne(e,t={}){let r=[];r.push(me(e,t)),r.push(we(e.site,t));let n=t.pathPrefix??"/blog",i=[{name:"Home",url:"/"},{name:e.site.name,url:n},{name:e.title,url:`${n}/${e.slug}`}];return r.push(je(i,t)),r}function Te(e,t=[],r={}){let n=[];if(n.push(we(e,r)),t.length>0){let i=t.slice(0,5).map(o=>me(o,r));n.push(...i);}return n}function Fe(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 qe(e){return JSON.stringify(e,null,0)}function Q(e){return {type:"application/ld+json",dangerouslySetInnerHTML:{__html:qe(e)}}}function It(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 Y=class extends Error{constructor(r,n,i){super(r);this.code=n;this.details=i;this.name="StructuredDataError";}code;details};function kt(e,t={}){try{let r=me(e,t),n=Fe(r);return n.isValid?{schema:r}:{error:new Y("Generated schema validation failed","VALIDATION_FAILED",n.errors)}}catch(r){return {error:new Y("Failed to generate structured data","GENERATION_FAILED",r)}}}function E(e="/blog"){let t=e.trim();return !t||t==="/"?"":t.replace(/^(?!\/)/,"/").replace(/\/+$/,"")}function H(e,t){let r=E(e),n=t?.replace(/^\/+/,"").replace(/\/+$/,"");return n?`${r}/${n}`.replace(/\/+/g,"/"):r||"/"}function Et(e){let t=new URL(e);return E(t.pathname)}var j={accentColor:"hsl(var(--primary))",accentHoverColor:"hsl(var(--primary))",textAccentColor:"hsl(var(--primary))",textAccentHoverColor:"hsl(var(--primary))",accentBackgroundColor:"hsl(var(--primary) / 0.08)",accentBorderColor:"hsl(var(--primary) / 0.25)"};function Z(e={}){return {"--blog-accent":e.accentColor??j.accentColor,"--blog-accent-hover":e.accentHoverColor??j.accentHoverColor,"--blog-text-accent":e.textAccentColor??e.accentColor??j.textAccentColor,"--blog-text-accent-hover":e.textAccentHoverColor??e.accentHoverColor??j.textAccentHoverColor,"--blog-accent-bg":e.accentBackgroundColor??j.accentBackgroundColor,"--blog-accent-border":e.accentBorderColor??j.accentBorderColor}}function Ce(e,t){let r=new Date(e),n=new Date(t);return {publishedDateLabel:dateFns.format(r,"d MMMM yyyy"),publishedRelativeLabel:dateFns.formatDistanceToNow(r,{addSuffix:true}),updatedDateLabel:dateFns.format(n,"d MMMM yyyy"),isUpdated:n.getTime()!==r.getTime()}}function Le(e){let t=[],r=false;for(let n of e.split(`
|
|
2
|
+
`)){if(/^\s*```/.test(n)){r=!r;continue}if(r)continue;let i=/^(#{2,3})\s+(.+?)\s*#*\s*$/.exec(n);if(!i?.[1]||!i[2])continue;let o=Dt(i[2]);o&&t.push({id:$t(o),text:o,level:i[1].length});}return t}function Dt(e){return e.replace(/\[([^\]]+)\]\([^)]+\)/g,"$1").replace(/[*_`~]/g,"").replace(/<[^>]+>/g,"").replace(/\s+/g," ").trim()}function $t(e){return e.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").replace(/-+/g,"-")}function Ke({articles:e,siteName:t,siteTagline:r,className:n,site:i,includeStructuredData:o=false,basePath:s="/blog",pagination:a,theme:u}){let l=E(s)||"/";return jsxRuntime.jsxs("div",{style:Z(u),className:y("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&&jsxRuntime.jsxs("header",{className:"blog-header mb-8 text-center sm:mb-12 lg:mb-16",children:[jsxRuntime.jsx("h1",{className:"blog-title mb-2 bg-linear-to-r from-[var(--blog-accent-hover)] to-[var(--blog-accent)] bg-clip-text text-3xl font-semibold tracking-tight text-balance text-transparent sm:text-4xl lg:text-5xl",children:t}),r&&jsxRuntime.jsx("p",{className:"blog-tagline text-muted-foreground text-base sm:text-lg",children:r})]}),jsxRuntime.jsxs("main",{className:"articles-list",children:[e.length===0?jsxRuntime.jsxs("div",{className:"no-articles text-muted-foreground py-16 text-center sm:py-24 lg:py-32",children:[jsxRuntime.jsx("h2",{className:"mb-3 text-xl font-light sm:mb-4 sm:text-2xl lg:text-3xl",children:"No articles yet"}),jsxRuntime.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."})]}):jsxRuntime.jsx("div",{className:"space-y-0",children:e.map(d=>jsxRuntime.jsx(Gt,{article:d,basePath:l},d.id))}),a&&a.totalPages>1&&jsxRuntime.jsx("div",{className:"pagination-wrapper mt-12",children:jsxRuntime.jsx(ue,{currentPage:a.currentPage,totalPages:a.totalPages,baseUrl:a.baseUrl??l,className:"justify-center"})})]}),o&&i&&(()=>{let d=Q(Te(i,e.slice(0,5),{pathPrefix:l}));return jsxRuntime.jsx("script",{type:d.type,dangerouslySetInnerHTML:d.dangerouslySetInnerHTML})})()]})}function Vt(e){return `${Math.ceil(e/60)} min read`}function Gt({article:e,basePath:t}){let r=H(t,e.slug),n=dateFns.formatDistanceToNow(new Date(e.publishedAt),{addSuffix:true}),i=Vt(e.readingSeconds),o=e.featuredImage;return jsxRuntime.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:jsxRuntime.jsxs(ne__default.default,{href:r,className:"focus-visible:ring-ring block rounded-2xl hover:no-underline focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none","aria-label":`Read article: ${e.title}`,children:[jsxRuntime.jsxs("div",{className:"space-y-4 lg:hidden",children:[o&&jsxRuntime.jsx("div",{className:"relative aspect-[16/10] w-full overflow-hidden rounded-2xl",children:jsxRuntime.jsx(Xe__default.default,{src:o,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"})}),jsxRuntime.jsxs("div",{className:"space-y-3",children:[jsxRuntime.jsx("h2",{className:"group-hover:text-[var(--blog-accent)] text-lg leading-tight font-bold text-balance transition-colors sm:text-xl md:text-2xl",children:e.title}),jsxRuntime.jsxs("div",{className:"text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1 text-sm",children:[e.author&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("span",{className:"font-medium",children:e.author.name}),jsxRuntime.jsx("span",{className:"text-border",children:"\u2022"})]}),jsxRuntime.jsx("time",{dateTime:e.publishedAt,className:"font-medium","aria-label":`Published ${n}`,children:n}),jsxRuntime.jsx("span",{className:"text-border",children:"\u2022"}),jsxRuntime.jsx("span",{className:"font-medium",children:i})]}),e.excerpt&&jsxRuntime.jsx("p",{className:"text-muted-foreground line-clamp-3 text-sm leading-relaxed sm:text-base",children:e.excerpt})]})]}),jsxRuntime.jsxs("div",{className:"hidden items-start gap-6 lg:flex xl:gap-8",children:[o&&jsxRuntime.jsx("div",{className:"relative aspect-[16/10] w-64 shrink-0 overflow-hidden rounded-2xl xl:w-72",children:jsxRuntime.jsx(Xe__default.default,{src:o,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"})}),jsxRuntime.jsxs("div",{className:"flex min-h-[180px] flex-1 flex-col justify-between space-y-4 xl:min-h-[200px]",children:[jsxRuntime.jsxs("div",{className:"space-y-4",children:[jsxRuntime.jsx("h2",{className:"group-hover:text-[var(--blog-accent)] text-2xl leading-tight font-bold text-balance transition-colors xl:text-3xl",children:e.title}),e.excerpt&&jsxRuntime.jsx("p",{className:"text-muted-foreground line-clamp-3 text-base leading-relaxed xl:text-lg",children:e.excerpt})]}),jsxRuntime.jsxs("div",{className:"text-muted-foreground flex flex-wrap items-center gap-x-3 gap-y-1 text-sm",children:[e.author&&jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("span",{className:"font-medium",children:e.author.name}),jsxRuntime.jsx("span",{className:"text-border",children:"\u2022"})]}),jsxRuntime.jsx("time",{dateTime:e.publishedAt,className:"font-medium","aria-label":`Published ${n}`,children:n}),jsxRuntime.jsx("span",{className:"text-border",children:"\u2022"}),jsxRuntime.jsx("span",{className:"font-medium",children:i})]})]})]})]})})}function jt(e,t,r,n,i="/blog"){let o=e?`${e} - Blog`:"Blog",s=n&&n.currentPage>1?`${o} - Page ${n.currentPage}`:o,a=t??"Read our latest articles and insights.",u=E(i)||"/",l=r?`${r}${n&&n.currentPage>1?`${u}?page=${n.currentPage}`:u}`:void 0,d=n&&n.currentPage>1&&r?`${r}${n.currentPage===2?u:`${u}?page=${n.currentPage-1}`}`:void 0,p=n&&n.currentPage<n.totalPages&&r?`${r}${u}?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:{...d&&{prev:d},...p&&{next:p}}}}var qt=classVarianceAuthority.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 Oe({className:e,variant:t,...r}){return jsxRuntime.jsx("div",{className:y(qt({variant:t}),e),...r})}function ee({className:e,...t}){return jsxRuntime.jsx("div",{"data-slot":"card",className:y("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",e),...t})}function Xt({className:e,...t}){return jsxRuntime.jsx("div",{"data-slot":"card-header",className:y("@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 Wt({className:e,...t}){return jsxRuntime.jsx("div",{"data-slot":"card-title",className:y("leading-none font-semibold",e),...t})}function Kt({className:e,...t}){return jsxRuntime.jsx("div",{"data-slot":"card-description",className:y("text-muted-foreground text-sm",e),...t})}function te({className:e,...t}){return jsxRuntime.jsx("div",{"data-slot":"card-content",className:y("px-6",e),...t})}function Jt({className:e,...t}){return jsxRuntime.jsx("div",{"data-slot":"card-footer",className:y("flex items-center px-6 [.border-t]:pt-6",e),...t})}function Ye({alt:e="",className:t,src:r,...n}){if(typeof r!="string"||r.length===0)return jsxRuntime.jsx("img",{alt:e,className:t,...n});let i=`blog-image-preview-${Yt(r)}`;return jsxRuntime.jsxs(jsxRuntime.Fragment,{children:[jsxRuntime.jsx("a",{href:`#${i}`,className:"group mx-auto block cursor-zoom-in rounded-2xl focus-visible:ring-2 focus-visible:ring-[var(--blog-text-accent)] focus-visible:ring-offset-2 focus-visible:outline-none","aria-label":e?`Expand image: ${e}`:"Expand article image",children:jsxRuntime.jsx("img",{src:r,alt:e,className:y("mx-auto rounded-2xl border border-[var(--blog-accent-border)] shadow-[0_18px_60px_rgb(168_85_247_/_0.12)] transition-opacity group-hover:opacity-95",t),...n})}),jsxRuntime.jsxs("div",{id:i,className:"invisible fixed inset-0 z-50 flex opacity-0 transition-opacity target:visible target:opacity-100",role:"dialog","aria-modal":"true","aria-label":e?`Image preview: ${e}`:"Image preview",children:[jsxRuntime.jsx("a",{href:"#article-content",className:"absolute inset-0 bg-black/85 backdrop-blur-sm","aria-label":"Close image preview"}),jsxRuntime.jsx("div",{className:"pointer-events-none relative z-10 flex min-h-screen w-full items-center justify-center p-4 sm:p-6",children:jsxRuntime.jsx("img",{src:r,alt:e,className:"pointer-events-auto max-h-[88vh] max-w-[94vw] rounded-3xl object-contain shadow-2xl"})}),jsxRuntime.jsx("a",{href:"#article-content",className:"absolute top-4 right-4 z-20 inline-flex size-10 items-center justify-center rounded-full border border-white/20 bg-black/50 text-xl leading-none text-white no-underline transition-colors hover:bg-white/10 focus-visible:ring-2 focus-visible:ring-white focus-visible:outline-none","aria-label":"Close image preview",children:"\xD7"})]})]})}function Yt(e){let t=0;for(let r=0;r<e.length;r+=1)t=(t<<5)-t+e.charCodeAt(r),t|=0;return Math.abs(t).toString(36)}var re=Qe__namespace.forwardRef(({className:e,orientation:t="horizontal",decorative:r=true,...n},i)=>jsxRuntime.jsx(_e__namespace.Root,{ref:i,decorative:r,orientation:t,className:y("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...n}));re.displayName=_e__namespace.Root.displayName;var Ze={mdxOptions:{remarkPlugins:[tr__default.default,er__default.default],rehypePlugins:[rr__default.default]}};function lr(e){return `${Math.ceil(e/60)} min read`}function rt({article:e,className:t,navigation:r,basePath:n="/blog",theme:i,postArticleCta:o,relatedArticles:s=[],showShareLinks:a=true}){let u=E(n)||"/",l=Ce(e.publishedAt,e.updatedAt),d=lr(e.readingSeconds),p=Le(e.content),v=e.meta.canonicalUrl??H(u,e.slug),h=e.featuredImage;return jsxRuntime.jsxs("article",{style:Z(i),className:y("article-page mx-auto max-w-6xl 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&&jsxRuntime.jsx("header",{className:"mx-auto mb-8 max-w-4xl sm:mb-12 lg:mb-16",children:jsxRuntime.jsxs(ne__default.default,{href:r.backToHome.url,className:"text-muted-foreground hover:text-[var(--blog-accent)] 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:[jsxRuntime.jsx(lucideReact.ArrowLeft,{className:"h-4 w-4 transition-transform group-hover:-translate-x-1 sm:h-5 sm:w-5","aria-hidden":"true"}),jsxRuntime.jsxs("span",{className:"text-sm font-medium sm:text-base",children:[jsxRuntime.jsx("span",{className:"hidden sm:inline",children:r.backToHome.label??"Back to all articles"}),jsxRuntime.jsx("span",{className:"sm:hidden",children:"Back"})]})]})}),jsxRuntime.jsxs("header",{className:"article-header mx-auto mb-6 max-w-4xl space-y-4 text-center sm:mb-8 sm:space-y-6 lg:mb-12 lg:space-y-8",children:[jsxRuntime.jsx("h1",{className:"article-title bg-linear-to-br from-[var(--blog-accent-hover)] via-[var(--blog-text-accent)] to-fuchsia-200 bg-clip-text px-4 text-2xl leading-tight font-light tracking-tight text-balance text-transparent sm:px-0 sm:text-3xl md:text-4xl lg:text-5xl xl:text-6xl",children:e.title}),e.excerpt&&jsxRuntime.jsx("p",{className:"article-excerpt text-muted-foreground mx-auto mt-6 max-w-[42rem] px-4 text-lg leading-relaxed text-balance sm:mt-8 sm:max-w-[46rem] sm:px-0 sm:text-xl md:max-w-[52rem] md:text-2xl lg:max-w-4xl lg:text-2xl",children:e.excerpt}),jsxRuntime.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&&jsxRuntime.jsxs("div",{className:"flex items-center gap-2",children:[jsxRuntime.jsx("span",{className:"sr-only",children:"Author"}),jsxRuntime.jsx("span",{className:"font-medium",children:e.author.name}),e.author.isGuest&&jsxRuntime.jsx(Oe,{variant:"outline",className:"text-xs",children:"Guest Author"})]}),jsxRuntime.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-3 gap-y-1",children:[jsxRuntime.jsxs("time",{dateTime:e.publishedAt,className:"font-medium","aria-label":`Published ${l.publishedDateLabel}`,children:["Published ",l.publishedDateLabel]}),jsxRuntime.jsx("span",{className:"text-border",children:"\u2022"}),jsxRuntime.jsx("span",{className:"font-medium",children:l.publishedRelativeLabel}),jsxRuntime.jsx("span",{className:"text-border",children:"\u2022"}),jsxRuntime.jsx("span",{className:"font-medium",children:d})]}),l.isUpdated&&jsxRuntime.jsxs("time",{dateTime:e.updatedAt,className:"text-xs",children:["Updated ",l.updatedDateLabel]}),jsxRuntime.jsx("div",{className:"bg-border h-px w-6 sm:w-8","aria-hidden":"true"}),jsxRuntime.jsxs("span",{className:"text-xs tracking-wider uppercase sm:text-sm",role:"text",children:["From ",e.site.name]})]})]}),h&&jsxRuntime.jsx("div",{className:"article-featured-image mx-auto my-8 aspect-[16/9] w-full max-w-4xl overflow-hidden rounded-3xl border border-[var(--blog-accent-border)] shadow-[0_24px_80px_rgb(168_85_247_/_0.14)] sm:my-12 lg:my-16",children:jsxRuntime.jsx(Xe__default.default,{src:h,alt:e.featuredImageAlt??`Featured image for ${e.title}`,className:"h-full w-full object-cover",width:800,height:450,priority:true})}),jsxRuntime.jsxs("div",{id:"article-content",className:"article-content mx-auto grid max-w-6xl grid-cols-1 gap-8 lg:grid-cols-[minmax(0,1fr)_14rem] lg:gap-12",children:[jsxRuntime.jsxs("div",{className:"min-w-0",children:[jsxRuntime.jsx(et,{items:p,variant:"mobile"}),jsxRuntime.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-headings:text-balance prose-headings:text-[var(--blog-text-accent)] 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-p:text-pretty prose-a:text-[var(--blog-text-accent)] prose-a:transition-colors hover:prose-a:text-[var(--blog-text-accent-hover)] max-w-none",children:jsxRuntime.jsx(rsc.MDXRemote,{source:e.content,options:Ze,components:{img:Ye}})})]}),jsxRuntime.jsx(et,{items:p,variant:"desktop"})]}),e.author?.bio&&jsxRuntime.jsxs("div",{className:"author-bio mx-auto mt-12 max-w-4xl",children:[jsxRuntime.jsx(re,{className:"mb-8"}),jsxRuntime.jsx(ee,{className:"border-[var(--blog-accent-border)] bg-[var(--blog-accent-bg)]",children:jsxRuntime.jsxs(te,{className:"flex flex-col gap-4 p-5 sm:flex-row sm:items-start sm:p-6",children:[jsxRuntime.jsx("div",{className:"flex size-12 shrink-0 items-center justify-center rounded-full bg-[var(--blog-accent)] text-lg font-semibold text-white","aria-hidden":"true",children:e.author.name.slice(0,1)}),jsxRuntime.jsxs("div",{className:"min-w-0 space-y-2",children:[jsxRuntime.jsxs("div",{children:[jsxRuntime.jsx("p",{className:"text-muted-foreground text-sm font-medium",children:"Written by"}),jsxRuntime.jsxs("h2",{className:"text-foreground flex flex-wrap items-center gap-2 text-xl font-semibold",children:[e.author.name,e.author.isGuest&&jsxRuntime.jsx(Oe,{variant:"outline",className:"text-xs",children:"Guest Author"})]})]}),jsxRuntime.jsx("p",{className:"text-muted-foreground leading-relaxed",children:e.author.bio})]})]})})]}),((o??false)||a||s.length>0)&&jsxRuntime.jsxs("div",{className:"mx-auto mt-12 max-w-4xl space-y-8",children:[jsxRuntime.jsx(re,{}),o&&jsxRuntime.jsx(cr,{cta:o}),a&&jsxRuntime.jsx(ur,{title:e.title,url:v}),s.length>0&&jsxRuntime.jsx(mr,{articles:s.slice(0,3),basePath:u})]}),(!!r?.previousArticle||!!r?.nextArticle)&&jsxRuntime.jsxs("nav",{className:"article-nav mx-auto mt-12 max-w-4xl",children:[jsxRuntime.jsx(re,{className:"mb-8"}),jsxRuntime.jsxs("div",{className:"grid grid-cols-1 gap-4 md:grid-cols-2",children:[r?.previousArticle&&jsxRuntime.jsx(ee,{className:"group hover:border-[var(--blog-accent-border)] hover:bg-[var(--blog-accent-bg)] cursor-pointer transition-colors",children:jsxRuntime.jsxs(ne__default.default,{href:r.previousArticle.url,className:"block",children:[r.previousArticle.featuredImage&&jsxRuntime.jsx(Be,{src:r.previousArticle.featuredImage,alt:r.previousArticle.featuredImageAlt??`Featured image for ${r.previousArticle.title}`}),jsxRuntime.jsxs(te,{className:"p-4",children:[jsxRuntime.jsx("div",{className:"text-muted-foreground mb-2 text-sm font-medium",children:"\u2190 Previous Article"}),jsxRuntime.jsx("div",{className:"text-foreground group-hover:text-[var(--blog-text-accent)] transition-colors",children:r.previousArticle.title})]})]})}),r?.nextArticle&&jsxRuntime.jsx(ee,{className:y("group hover:border-[var(--blog-accent-border)] hover:bg-[var(--blog-accent-bg)] cursor-pointer transition-colors",!r?.previousArticle&&"md:col-start-2"),children:jsxRuntime.jsxs(ne__default.default,{href:r.nextArticle.url,className:"block",children:[r.nextArticle.featuredImage&&jsxRuntime.jsx(Be,{src:r.nextArticle.featuredImage,alt:r.nextArticle.featuredImageAlt??`Featured image for ${r.nextArticle.title}`}),jsxRuntime.jsxs(te,{className:"p-4 md:text-right",children:[jsxRuntime.jsx("div",{className:"text-muted-foreground mb-2 text-sm font-medium",children:"Next Article \u2192"}),jsxRuntime.jsx("div",{className:"text-foreground group-hover:text-[var(--blog-text-accent)] transition-colors",children:r.nextArticle.title})]})]})})]})]}),(()=>{let m=Q(Ne(e,{pathPrefix:u}));return jsxRuntime.jsx("script",{type:m.type,dangerouslySetInnerHTML:m.dangerouslySetInnerHTML})})()]})}function et({items:e,variant:t}){if(e.length===0)return null;let r=jsxRuntime.jsx("ul",{className:"space-y-2 text-sm",children:e.map(n=>jsxRuntime.jsx("li",{className:n.level===3?"pl-4":void 0,children:jsxRuntime.jsx("a",{href:`#${n.id}`,className:"text-muted-foreground hover:text-[var(--blog-text-accent)] block leading-snug transition-colors",children:n.text})},n.id))});return t==="mobile"?jsxRuntime.jsxs("nav",{"aria-label":"Table of contents",className:"mb-8 rounded-2xl border border-[var(--blog-accent-border)] bg-[var(--blog-accent-bg)] p-4 lg:hidden",children:[jsxRuntime.jsx("p",{className:"text-foreground mb-3 text-sm font-semibold",children:"On this page"}),r]}):jsxRuntime.jsx("aside",{className:"hidden lg:block",children:jsxRuntime.jsxs("nav",{"aria-label":"Table of contents",className:"sticky top-24 max-h-[calc(100vh-8rem)] overflow-y-auto border-l border-border pl-5",children:[jsxRuntime.jsx("p",{className:"text-muted-foreground mb-3 text-xs font-semibold tracking-wider uppercase",children:"On this page"}),r]})})}function cr({cta:e}){return jsxRuntime.jsx("div",{className:"rounded-2xl border border-[var(--blog-accent-border)] bg-[var(--blog-accent-bg)] p-5 sm:p-6",children:jsxRuntime.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between",children:[jsxRuntime.jsxs("div",{className:"space-y-1",children:[jsxRuntime.jsx("h2",{className:"text-foreground text-xl font-semibold",children:e.title}),e.description&&jsxRuntime.jsx("p",{className:"text-muted-foreground leading-relaxed",children:e.description})]}),jsxRuntime.jsxs(ne__default.default,{href:e.href,className:"inline-flex shrink-0 items-center justify-center gap-2 rounded-full bg-[var(--blog-accent)] px-4 py-2 text-sm font-semibold text-white transition-opacity hover:opacity-90",children:[e.label,jsxRuntime.jsx(lucideReact.ArrowUpRight,{className:"size-4","aria-hidden":"true"})]})]})})}function ur({title:e,url:t}){let r=encodeURIComponent(e),n=encodeURIComponent(t);return jsxRuntime.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-2 sm:gap-3",children:[jsxRuntime.jsxs("span",{className:"text-muted-foreground inline-flex basis-full items-center justify-center gap-2 text-sm font-medium sm:basis-auto",children:[jsxRuntime.jsx(lucideReact.Share2,{className:"size-4","aria-hidden":"true"}),"Share"]}),jsxRuntime.jsx("a",{href:`https://x.com/intent/tweet?text=${r}&url=${n}`,target:"_blank",rel:"noopener noreferrer","aria-label":"Share on X",className:"text-muted-foreground hover:border-[var(--blog-accent-border)] hover:bg-[var(--blog-accent-bg)] hover:text-foreground inline-flex size-9 items-center justify-center rounded-full border border-border grayscale transition-colors",children:jsxRuntime.jsx("span",{className:"text-sm font-semibold","aria-hidden":"true",children:"X"})}),jsxRuntime.jsx("a",{href:`https://www.linkedin.com/sharing/share-offsite/?url=${n}`,target:"_blank",rel:"noopener noreferrer","aria-label":"Share on LinkedIn",className:"text-muted-foreground hover:border-[var(--blog-accent-border)] hover:bg-[var(--blog-accent-bg)] hover:text-foreground inline-flex size-9 items-center justify-center rounded-full border border-border grayscale transition-colors",children:jsxRuntime.jsx("span",{className:"text-sm font-bold","aria-hidden":"true",children:"in"})}),jsxRuntime.jsx("a",{href:`mailto:?subject=${r}&body=${n}`,"aria-label":"Share by email",className:"text-muted-foreground hover:border-[var(--blog-accent-border)] hover:bg-[var(--blog-accent-bg)] hover:text-foreground inline-flex size-9 items-center justify-center rounded-full border border-border grayscale transition-colors",children:jsxRuntime.jsx(lucideReact.Mail,{className:"size-4","aria-hidden":"true"})})]})}function mr({articles:e,basePath:t}){return jsxRuntime.jsxs("section",{className:"space-y-4","aria-labelledby":"related-articles-title",children:[jsxRuntime.jsx("h2",{id:"related-articles-title",className:"text-xl font-semibold",children:"You might also like"}),jsxRuntime.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:e.map(r=>jsxRuntime.jsxs(ne__default.default,{href:H(t,r.slug),className:"group overflow-hidden rounded-2xl border border-border transition-colors hover:border-[var(--blog-accent-border)] hover:bg-[var(--blog-accent-bg)] hover:no-underline",children:[r.featuredImage&&jsxRuntime.jsx(Be,{src:r.featuredImage,alt:r.featuredImageAlt??`Featured image for ${r.title}`}),jsxRuntime.jsxs("div",{className:"p-4",children:[jsxRuntime.jsx("h3",{className:"text-foreground group-hover:text-[var(--blog-text-accent)] line-clamp-3 font-semibold transition-colors",children:r.title}),r.excerpt&&jsxRuntime.jsx("p",{className:"text-muted-foreground mt-2 line-clamp-3 text-sm leading-relaxed",children:r.excerpt})]})]},r.id))})]})}function Be({src:e,alt:t}){return jsxRuntime.jsx("div",{className:"aspect-[16/9] overflow-hidden border-b border-border bg-[var(--blog-accent-bg)]",children:jsxRuntime.jsx(Xe__default.default,{src:e,alt:t,width:480,height:270,className:"h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"})})}function dr(e,t="/blog"){let r=e.meta.title??e.title,n=e.meta.description??e.excerpt,i=e.meta.canonicalUrl??`${e.site.domain}${H(t,e.slug)}`,o=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:i,images:o?[{url:o,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:o?[o]:void 0},alternates:{canonical:i}}}function Ie(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 o=/^Token\s+(.+)$/i.exec(t);return o?.[1]?o[1]:null}var de=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=>Ie(t);hashToken(t){return t.substring(0,8)+"..."}},q=class extends de{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(i=>i.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);}},oe=class{async validateToken(){return {valid:true,context:{development:true}}}extractToken(){return "development-mode"}},pe=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 pr(){return globalThis.__BLOG_PLATFORM_AUTH_CONFIG__??=new pe,globalThis.__BLOG_PLATFORM_AUTH_CONFIG__}function ge(e){globalThis.__BLOG_PLATFORM_AUTH_CONFIG__=e;}function ke(){return globalThis.__BLOG_PLATFORM_AUTH_CONFIG__??pr()}function gr(e){ge(new q(e));}async function I(e){let t=ke(),r=t.extractToken?t.extractToken(e):Ie(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 fr(e,t=""){let n=ke().errorMessages??{},i,o;switch(e.errorCode){case "missing":i=n.missing??"Authentication token is required",o="PUB005";break;case "expired":i=n.expired??"Authentication token has expired",o="PUB005";break;default:i=n.invalid??"Invalid authentication credentials",o="PUB005";break}return {success:false,error:{code:o,message:i,details:{authError:e.errorCode??"invalid"}},idempotencyKey:t}}async function M(e){let t=await I(e);return t.authenticated?{authenticated:true,context:t.result.context}:{authenticated:false,error:fr(t.result)}}function hr(){let e=process.env.SKIP_BLOG_PLATFORM_AUTH;return e==="true"||e==="1"||process.env.NODE_ENV==="test"}var fe=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 o={success:false,error:{code:"PUB003",message:"This URL is already in use. Please choose another."},idempotencyKey:r};return await this.storeOperationResult(r,o),o}this.articles.set(t.slug,t);let i={success:true,url:`/${t.slug}`,platformPostId:t.id,publishedAt:t.publishedAt,idempotencyKey:r};return await this.storeOperationResult(r,i),i}async getArticle(t){return this.articles.get(t)??null}async listArticles(t={}){let{limit:r=10,offset:n=0,sortBy:i="publishedAt",order:o="desc"}=t,s=Array.from(this.articles.values());return s.sort((u,l)=>{let d=new Date(u[i]).getTime(),p=new Date(l[i]).getTime();return o==="desc"?p-d:d-p}),{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 o={success:false,error:{code:"PUB007",message:"Article not found"},idempotencyKey:r};return await this.storeOperationResult(r,o),o}this.articles.delete(t);let i={success:true,idempotencyKey:r};return await this.storeOperationResult(r,i),i}async checkIdempotency(t){return this.operations.get(t)??null}async storeOperationResult(t,r){this.operations.set(t,r);}};function br(){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 xr(){let e=globalThis;e.__BLOG_PLATFORM_STORAGE__||(br(),e.__BLOG_PLATFORM_STORAGE__=new fe);let t=e.__BLOG_PLATFORM_STORAGE__;if(!t)throw new Error("Blog platform storage not initialized");return t}function D(){return xr()}function Ee(e){let t=globalThis;t.__BLOG_PLATFORM_STORAGE__=e;}function Pr(){return globalThis.__BLOG_PLATFORM_RATE_LIMITER__??null}function vr(e){let t=globalThis;t.__BLOG_PLATFORM_RATE_LIMITER__=e;}function he(e){let{redisUrl:t,redisToken:r,requestsPerMinute:n=5,keyPrefix:i="blog-platform-ratelimit",analytics:o=true}=e,s=new redis.Redis({url:t,token:r}),a=new ratelimit.Ratelimit({redis:s,analytics:o,prefix:i,limiter:ratelimit.Ratelimit.slidingWindow(n,"1m")});vr(a);}function Me(){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}he({redisUrl:e,redisToken:t}),console.log("Blog platform: Rate limiting configured (5 requests per minute per token)");}async function ot(e){let t=Pr();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 it(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 k(e,t=""){let r=await ot(e);return r.success?{allowed:true,rateLimitResult:r}:{allowed:false,errorResponse:it(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 be(e){let{auth:t,storage:r,rateLimit:n,autoRateLimit:i=true}=e;if(!t)throw new Error(`Blog platform initialization failed: 'auth' is required.
|
|
3
3
|
Example: initBlogPlatform({ auth: new EnvAuth() })
|
|
4
|
-
See https://github.com/xexr/blog-platform#authentication for more details.`);console.log("Blog platform: Setting up authentication"),
|
|
4
|
+
See https://github.com/xexr/blog-platform#authentication for more details.`);console.log("Blog platform: Setting up authentication"),ge(t),n?(console.log("Blog platform: Using custom rate limiting configuration"),he(n)):i?(console.log("Blog platform: Auto-configuring rate limiting from environment"),Me()):console.log("Blog platform: Rate limiting disabled"),r?(console.log("Blog platform: Using custom storage provider"),Ee(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 Ar(e){if(globalThis.__BLOG_PLATFORM_INITIALISED__){console.log("Blog platform: Already initialized, skipping");return}console.log("Blog platform: Initializing blog platform once"),be(e);}function Sr(){be({auth:new oe,autoRateLimit:false}),console.log("Blog platform: Development mode enabled (no auth, in-memory storage, no rate limiting)");}function Rr(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.`);be({auth:new q(t),autoRateLimit:true}),console.log("Blog platform: Production mode enabled (environment-based auth, rate limiting)");}var A=sqliteCore.sqliteTable("bp_articles",{id:sqliteCore.text("id").primaryKey(),slug:sqliteCore.text("slug").notNull(),title:sqliteCore.text("title").notNull(),excerpt:sqliteCore.text("excerpt").notNull(),content:sqliteCore.text("content").notNull(),readingSeconds:sqliteCore.integer("reading_seconds").notNull(),wordCount:sqliteCore.integer("word_count").notNull(),publishedAt:sqliteCore.text("published_at").notNull(),updatedAt:sqliteCore.text("updated_at").notNull(),featuredImage:sqliteCore.text("featured_image"),featuredImageAlt:sqliteCore.text("featured_image_alt"),authorJson:sqliteCore.text("author_json"),siteJson:sqliteCore.text("site_json").notNull(),metaJson:sqliteCore.text("meta_json").notNull(),version:sqliteCore.integer("version").notNull()},e=>({slugUniqueIdx:sqliteCore.uniqueIndex("bp_articles_slug_unique").on(e.slug)})),z=sqliteCore.sqliteTable("bp_operations",{key:sqliteCore.text("key").primaryKey(),resultJson:sqliteCore.text("result_json").notNull(),createdAt:sqliteCore.integer("created_at",{mode:"timestamp_ms"}).notNull(),expiresAt:sqliteCore.integer("expires_at",{mode:"timestamp_ms"})});function Lr(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 st(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 De=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:A.id}).from(A).where(drizzleOrm.eq(A.id,t.id)).limit(1)).length!==0)return n}else return n;let i=await this.db.select().from(A).where(drizzleOrm.eq(A.slug,t.slug)).limit(1),o=i[0];if(o&&o.id!==t.id){let u={success:false,error:{code:"PUB003",message:"This URL is already in use. Please choose another."},idempotencyKey:r};return await this.storeOperationResult(r,u),u}let s=Lr(t);i.length===0?await this.db.insert(A).values(s).run():await this.db.update(A).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(drizzleOrm.and(drizzleOrm.eq(A.id,s.id),drizzleOrm.eq(A.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(A).where(drizzleOrm.eq(A.slug,t)).limit(1);return r[0]?st(r[0]):null}async listArticles(t={}){let{limit:r=10,offset:n=0,sortBy:i="publishedAt",order:o="desc"}=t,s=i==="publishedAt"?A.publishedAt:A.updatedAt,a=o==="desc"?drizzleOrm.desc(s):s,u=await this.db.select().from(A).orderBy(a).limit(r).offset(n),l=await this.db.select({c:drizzleOrm.sql`count(*)`}).from(A),d=Number(l?.[0]?.c??0);return {articles:u.map(st),total:d}}async removeArticle(t,r){let n=await this.checkIdempotency(r);if(n)if(n.success){if(!((await this.db.select({id:A.id}).from(A).where(drizzleOrm.eq(A.slug,t)).limit(1)).length>0))return n}else return n;if(!(await this.db.select().from(A).where(drizzleOrm.eq(A.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(A).where(drizzleOrm.eq(A.slug,t)).run();let o={success:true,idempotencyKey:r};return await this.storeOperationResult(r,o),o}async checkIdempotency(t){let r=await this.db.select().from(z).where(drizzleOrm.eq(z.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(),i=this.options.operationTtlMs?n+this.options.operationTtlMs:null;await this.db.delete(z).where(drizzleOrm.eq(z.key,t)).run(),await this.db.insert(z).values({key:t,resultJson:JSON.stringify(r),createdAt:new Date(n),expiresAt:i?new Date(i):null}).run();}};function Or(){return {createArticles:`CREATE TABLE IF NOT EXISTS bp_articles (
|
|
5
5
|
id TEXT PRIMARY KEY,
|
|
6
6
|
slug TEXT NOT NULL UNIQUE,
|
|
7
7
|
title TEXT NOT NULL,
|
|
@@ -22,11 +22,11 @@ See https://github.com/xexr/blog-platform#authentication for more details.`);con
|
|
|
22
22
|
result_json TEXT NOT NULL,
|
|
23
23
|
created_at INTEGER NOT NULL,
|
|
24
24
|
expires_at INTEGER
|
|
25
|
-
);`}}function
|
|
26
|
-
`)}function T(e){let t={"&":"&","<":"<",">":">",'"':""","'":"'"};return e.replace(/[&<>"']/g,r=>t[r]??r)}function
|
|
25
|
+
);`}}function X(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 lt(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 G(e,t={}){let{forceHttps:r=true,removeTrailingSlash:n=true,domain:i=e.site.domain,pathPrefix:o="/blog"}=t;if(!i)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=X(i,r),a=lt(e.slug),u=o.replace(/^(?!\/)/,"/").replace(/\/+$/,""),l=`${s}${u}/${a}`;return n&&(l=l.replace(/\/+$/,"")),l}function _r(e,t,r={}){return G({slug:t,site:e},r)}function Br(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 Ir(e){try{let t=new URL(e);return `${t.protocol}//${t.host}`}catch{throw new Error("Invalid canonical URL provided")}}function kr(e,t={}){let r=G(e,t);return {...e,meta:{...e.meta,canonicalUrl:r}}}function Er(e,t={},r){let n=r?.path??"/blog",o=`https://${t.canonical?.domain??e.domain}${n}`,s=r?.title?`${r.title} | ${e.name}`:e.name,a=r?.description??e.description,u=t.openGraph?.siteName??e.name,l=[{name:"description",content:a},{name:"author",content:u}];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 d=[{property:"og:title",content:s},{property:"og:description",content:a},{property:"og:url",content:o},{property:"og:site_name",content:u},{property:"og:locale",content:t.openGraph?.locale??e.locale},{property:"og:type",content:t.openGraph?.type??"website"}];t.openGraph?.defaultImage&&d.push({property:"og:image",content:t.openGraph.defaultImage},{property:"og:image:alt",content:`${u} - ${e.tagline}`});let p=Mr(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:d,twitter:p,links:[{rel:"canonical",href:o}],title:s,description:a,canonicalUrl:o}}function Mr(e,t,r){let n=r?.title??e?.meta.title??e?.title??"",i=r?.description??e?.meta.description??e?.excerpt??"",o=r?.image??e?.meta.ogImage??e?.featuredImage,s=[{name:"twitter:card",content:t.cardType},{name:"twitter:title",content:n},{name:"twitter:description",content:i}];return t.site&&s.push({name:"twitter:site",content:t.site}),t.creator&&s.push({name:"twitter:creator",content:t.creator}),o&&(s.push({name:"twitter:image",content:o}),e?.featuredImageAlt),s}function Dr(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(`
|
|
26
|
+
`)}function T(e){let t={"&":"&","<":"<",">":">",'"':""","'":"'"};return e.replace(/[&<>"']/g,r=>t[r]??r)}function $r(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(o=>o.property==="og:image")||r.push("OpenGraph image missing - social media sharing will not show image preview"),e.twitter.find(o=>o.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 $e(e,t,r=[],n={}){let{includeAuthorPages:i=true,includePaginationPages:o=true,articlesPerPage:s=10,maxEntries:a=5e4,changeFrequency:u={},priority:l={}}=n,d=[],p=X(n.canonical?.domain??e.domain,n.canonical?.forceHttps??true),v=n.canonical?.pathPrefix??"/blog";if(d.push({url:`${p}${v}`,lastModified:W(t),changeFrequency:u.homePage??"daily",priority:l.homePage??1}),t.forEach(h=>{if(d.length>=a)return;let m=G(h,n.canonical);d.push({url:m,lastModified:h.updatedAt,changeFrequency:u.articles??"monthly",priority:l.articles??.8});}),i&&r.forEach(h=>{if(d.length>=a)return;let m=`${p}${v}/authors/${h.slug}`,g=t.filter(C=>C.author?.id===h.id),x=W(g);d.push({url:m,lastModified:x,changeFrequency:u.authorPages??"weekly",priority:l.authorPages??.6});}),o&&t.length>s){let h=Math.ceil(t.length/s);for(let m=2;m<=h&&!(d.length>=a);m++)d.push({url:`${p}${v}?page=${m}`,lastModified:W(t),changeFrequency:u.paginationPages??"daily",priority:l.paginationPages??.5});}return d}function Ur(e,t,r=[],n={}){let{includeAuthorPages:i=true,includePaginationPages:o=true,articlesPerPage:s=10,maxEntries:a=5e4,changeFrequency:u={},priority:l={}}=n,d=[],p=X(n.canonical?.domain??e.domain,n.canonical?.forceHttps??true),v=n.canonical?.pathPrefix??"/blog",h=new Date().toISOString(),m=1;if(m+=t.length,i&&(m+=r.length),o&&t.length>s){let x=Math.ceil(t.length/s);m+=x-1;}let g=m>a;if(d.push({loc:`${p}${v}`,lastmod:W(t),changefreq:u.homePage??"daily",priority:l.homePage??1}),t.forEach(x=>{if(d.length>=a)return;let C=G(x,n.canonical);d.push({loc:C,lastmod:x.updatedAt,changefreq:u.articles??"monthly",priority:l.articles??.8});}),i&&r.forEach(x=>{if(d.length>=a)return;let C=`${p}${v}/authors/${x.slug}`,bt=t.filter(yt=>yt.author?.id===x.id),xt=W(bt);d.push({loc:C,lastmod:xt,changefreq:u.authorPages??"weekly",priority:l.authorPages??.6});}),o&&t.length>s){let x=Math.ceil(t.length/s);for(let C=2;C<=x&&!(d.length>=a);C++)d.push({loc:`${p}${v}?page=${C}`,lastmod:W(t),changefreq:u.paginationPages??"daily",priority:l.paginationPages??.5});}return {entries:d,totalEntries:d.length,truncated:g,generatedAt:h,baseUrl:p}}function ct(e){let t='<?xml version="1.0" encoding="UTF-8"?>',r='<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',n="</urlset>",i=e.entries.map(o=>{let s=[];return s.push(" <url>"),s.push(` <loc>${se(o.loc)}</loc>`),o.lastmod&&s.push(` <lastmod>${se(o.lastmod)}</lastmod>`),o.changefreq&&s.push(` <changefreq>${se(o.changefreq)}</changefreq>`),o.priority!==void 0&&s.push(` <priority>${o.priority.toFixed(1)}</priority>`),s.push(" </url>"),s.join(`
|
|
27
27
|
`)});return [t,r,...i,n].join(`
|
|
28
|
-
`)}function
|
|
28
|
+
`)}function Hr(e,t){let r='<?xml version="1.0" encoding="UTF-8"?>',n='<sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',i="</sitemapindex>",o=e.map(s=>{let a=[];return a.push(" <sitemap>"),a.push(` <loc>${se(s.url)}</loc>`),s.lastmod&&a.push(` <lastmod>${se(s.lastmod)}</lastmod>`),a.push(" </sitemap>"),a.join(`
|
|
29
29
|
`)});return [r,n,...o,i].join(`
|
|
30
|
-
`)}function Ir(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((i,o)=>{try{new URL(i.loc);}catch{t.push(`Invalid URL at entry ${o+1}: ${i.loc}`);}i.priority!==void 0&&(i.priority<0||i.priority>1)&&t.push(`Invalid priority at entry ${o+1}: must be between 0.0 and 1.0`),i.lastmod&&!$r(i.lastmod)&&t.push(`Invalid lastmod date at entry ${o+1}: ${i.lastmod}`),i.loc.length>2048&&r.push(`URL at entry ${o+1} exceeds 2048 character limit`);});let n=new Map;return e.entries.forEach(i=>{let o=n.get(i.loc)??0;n.set(i.loc,o+1);}),n.forEach((i,o)=>{i>1&&t.push(`Duplicate URL found: ${o} (appears ${i} times)`);}),{valid:t.length===0,errors:t,warnings:r}}function z(e){return e.length===0?new Date().toISOString():e.reduce((r,n)=>{let i=new Date(n.updatedAt);return i>r?i:r},new Date(e[0].updatedAt)).toISOString()}function Mr(e,t,r=[],n={}){return async function(){let s=(await Me(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:q(n.canonical?.domain??e.domain,n.canonical?.forceHttps??true)},c=ot(a);return new Response(c,{headers:{"Content-Type":"application/xml","Cache-Control":"public, max-age=3600, s-maxage=3600"}})}}function Dr(e){return async function(){let r=await e.getSite(),n=await e.getArticles(),i=e.getAuthors?await e.getAuthors():[];return Me(r,n,i,e.options)}}function oe(e){let t={"&":"&","<":"<",">":">",'"':""","'":"'"};return e.replace(/[&<>"']/g,r=>t[r]??r)}function $r(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 W={name:"@xexr/blog-platform",version:"1.0.3"};function it(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),i=parseInt(r[1]??"0",10),o=parseInt(r[2]?.split("-")[0]??"0",10);if(isNaN(n)||isNaN(i)||isNaN(o))throw new Error(`Invalid version format: ${e}`);return {major:n,minor:i,patch:o}}function L(){let e=it(W.version);return {name:W.name,version:W.version,...e}}function $(e){try{let t=e.split(" "),r={};for(let n of t){let[i,o]=n.split("/");if(!i||!o)continue;let s=it(o),a={name:i,version:o,...s};i==="bloggy"?r.bloggyVersion=a:i==="platform"&&(r.platformVersion=a);}return r}catch{return null}}function st(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 at={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 Vr(){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 {...at,enableCSP:!e,frameOptions:t??at.frameOptions,enableHSTS:!r}}function Hr(e){return Object.entries(e).map(([t,r])=>r?`${t} ${r}`:t).join("; ")}function Gr(e){return Object.entries(e).map(([t,r])=>`${t}=${r}`).join(", ")}function jr(e,t={}){let r={...Vr(),...t},n={};if(r.enableCSP){let i={...r.cspDirectives,...t.cspDirectives??{}};n["Content-Security-Policy"]=Hr(i);}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&&Fr(e)){let i=[`max-age=${r.hstsMaxAge}`,r.hstsIncludeSubdomains?"includeSubDomains":""].filter(Boolean).join("; ");n["Strict-Transport-Security"]=i;}if(r.enablePermissionsPolicy){let i={...r.permissionsPolicyDirectives,...t.permissionsPolicyDirectives??{}};n["Permissions-Policy"]=Gr(i);}return n}function Fr(e){return !!(e.url.startsWith("https://")||e.headers.get("x-forwarded-proto")==="https"||e.headers.get("cf-visitor")?.includes('"scheme":"https"'))}function be(e,t={}){return jr(e,{...t,cspDirectives:{...{"default-src":"'none'","frame-ancestors":"'none'","base-uri":"'none'"},...t.cspDirectives??{}}})}var lt={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 ct(){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 {...lt,allowedOrigins:e?e.split(",").map(n=>n.trim()):lt.allowedOrigins,allowWildcard:t,allowCredentials:r}}function ut(e,t){return e?t.allowWildcard?true:t.allowedOrigins.includes(e):false}function mt(e,t){let r=e.headers.get("origin"),n={};return t.allowWildcard?n["Access-Control-Allow-Origin"]="*":r&&ut(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 qr(e,t,r,n){return {...mt(e,t),"Access-Control-Allow-Methods":r.join(", "),"Access-Control-Allow-Headers":n.join(", "),"Access-Control-Max-Age":t.maxAge.toString()}}var zr=["Content-Type","X-Bloggy-Version","X-Idempotency-Key","Authorization","X-Requested-With"];function b(e,t,r={}){let{status:n=200,headers:i={},corsConfig:o={}}=r,s={...ct(),...o},a=mt(e,s),c=be(e,s.securityConfig),l={"Content-Type":"application/json",...a,...c,...i};return server.NextResponse.json(t,{status:n,headers:l})}function ie(e,t,r={}){let{allowedHeaders:n=zr,corsConfig:i={}}=r,o={...ct(),...i},s=e.headers.get("origin");if(s&&!o.allowWildcard&&!ut(s,o)){let l=be(e,o.securityConfig);return new server.NextResponse(null,{status:403,headers:{"Content-Type":"text/plain",...l}})}let a=qr(e,o,[...t,"OPTIONS"],n),c=be(e,o.securityConfig);return new server.NextResponse(null,{status:200,headers:{...a,...c}})}async function Wr(e){try{let t=await k(e);if(!t.authenticated){let g=await M(e);return b(e,g.error,{status:401})}let r=t.token??"anonymous",n=await E(r);if(!n.allowed){let g=n.errorResponse.error?.details?.rateLimit,x=g&&typeof g=="object"&&"limit"in g&&"remaining"in g&&"reset"in g&&"count"in g&&"success"in g?g:{limit:10,remaining:0,reset:Date.now()+6e4,count:10,success:!1},C=N(x);return b(e,n.errorResponse,{status:429,headers:C})}if(!e.headers.get("content-type")?.includes("application/json"))return b(e,{success:!1,error:{code:"PUB001",message:"Content-Type must be application/json"},idempotencyKey:""},{status:400});let o;try{o=await e.json();}catch{return b(e,{success:!1,error:{code:"PUB001",message:"Invalid JSON in request body"},idempotencyKey:""},{status:400})}let s=Xr(o);if(s.length>0)return b(e,{success:!1,error:{code:"PUB001",message:"Missing required fields",details:{errors:s}},idempotencyKey:o.idempotencyKey??""},{status:400});let a=e.headers.get("X-Bloggy-Version");if(a){let g=$(a);if(g?.platformVersion){let x=L();if(g.platformVersion.major!==x.major)return b(e,{success:!1,error:{code:"PUB009",message:"Major version incompatibility. Please upgrade your blog platform package.",details:{clientVersion:g.platformVersion.version,serverVersion:x.version}},idempotencyKey:o.idempotencyKey},{status:409})}}if(o.dryRun){let g=[];return o.article.wordCount<50&&g.push("Article has fewer than 50 words, which may affect SEO"),(!o.article.excerpt||o.article.excerpt.length<120)&&g.push("Article excerpt is shorter than recommended 120 characters"),o.article.meta.keywords.length||g.push("No SEO keywords provided"),b(e,{success:!0,warnings:g,idempotencyKey:o.idempotencyKey},{status:200})}let c={...o.article,slug:o.slug??o.article.slug,meta:{...o.article.meta,description:o.metaDescription??o.article.meta.description}};if(!$e(c.slug))return b(e,{success:!1,error:{code:"PUB002",message:"Slug can only contain lowercase letters, numbers, and hyphens"},idempotencyKey:o.idempotencyKey},{status:400});let d=await D().saveArticle(c,o.idempotencyKey),p=L(),P=N(n.rateLimitResult),f={"X-Bloggy-Version":`platform/${p.version}`,"X-Idempotency-Key":o.idempotencyKey,...P};d.success&&(f.Location=d.url??`/${c.slug}`);let m=d.success?201:d.error?.code==="PUB003"?409:400;return b(e,d,{status:m,headers:f})}catch(t){return console.error("Publish endpoint error:",t),b(e,{success:false,error:{code:"PUB007",message:"Internal server error during publishing"},idempotencyKey:""},{status:500})}}function Xr(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,i=["id","slug","title","content","publishedAt","site"];for(let o of i)n[o]||t.push(`Missing required article field: ${o}`);if(n.site&&typeof n.site=="object"){let o=n.site,s=["id","name","domain"];for(let a of s)o[a]||t.push(`Missing required site field: ${a}`);}if(n.meta&&typeof n.meta=="object"){let o=n.meta;Array.isArray(o.keywords)||t.push("Article meta.keywords must be an array");}}return t}function $e(e){return !e||typeof e!="string"?false:/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)&&e.length>=1&&e.length<=100}async function Jr(e){try{let t=await k(e);if(!t.authenticated){let m=await M(e);return server.NextResponse.json(m.error,{status:401})}let r=t.token??"anonymous",n=await E(r);if(!n.allowed){let m=n.errorResponse.error?.details?.rateLimit,g=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},x=N(g);return b(e,n.errorResponse,{status:429,headers:x})}if(!e.headers.get("content-type")?.includes("application/json"))return b(e,{success:!1,error:{code:"PUB001",message:"Content-Type must be application/json"},idempotencyKey:""},{status:400});let o;try{o=await e.json();}catch{return b(e,{success:!1,error:{code:"PUB001",message:"Invalid JSON in request body"},idempotencyKey:""},{status:400})}let s=Yr(o);if(s.length>0)return b(e,{success:!1,error:{code:"PUB001",message:"Missing required fields",details:{errors:s}},idempotencyKey:o.idempotencyKey??""},{status:400});let a=e.headers.get("X-Bloggy-Version");if(a){let m=$(a);if(m?.platformVersion){let g=L();if(m.platformVersion.major!==g.major)return b(e,{success:!1,error:{code:"PUB009",message:"Major version incompatibility. Please upgrade your blog platform package.",details:{clientVersion:m.platformVersion.version,serverVersion:g.version}},idempotencyKey:o.idempotencyKey},{status:409})}}if(!Qr(o.slug))return b(e,{success:!1,error:{code:"PUB002",message:"Slug can only contain lowercase letters, numbers, and hyphens"},idempotencyKey:o.idempotencyKey},{status:400});if(o.dryRun){let g=await D().getArticle(o.slug),x=[];return g||x.push("Article with this slug does not exist"),b(e,{success:!0,warnings:x,idempotencyKey:o.idempotencyKey},{status:200})}let l=await D().removeArticle(o.slug,o.idempotencyKey),d=L(),p=N(n.rateLimitResult),P={"X-Bloggy-Version":`platform/${d.version}`,"X-Idempotency-Key":o.idempotencyKey,...p},f=l.success?200:l.error?.code==="PUB007"?404:400;return b(e,l,{status:f,headers:P})}catch(t){return console.error("Unpublish endpoint error:",t),b(e,{success:false,error:{code:"PUB007",message:"Internal server error during unpublishing"},idempotencyKey:""},{status:500})}}function Yr(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 Qr(e){return !e||typeof e!="string"?false:/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)&&e.length>=1&&e.length<=100}async function Zr(e){try{let t=await k(e);if(!t.authenticated){let p=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:p.error?.error?.message??"Authentication required"}};return b(e,P,{status:401})}let r=t.token??"anonymous",n=await E(r);if(!n.allowed){let p=n.errorResponse.error?.details?.rateLimit,P=p&&typeof p=="object"&&"limit"in p&&"remaining"in p&&"reset"in p&&"count"in p&&"success"in p?p:{limit:10,remaining:0,reset:Date.now()+6e4,count:10,success:!1},f=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 b(e,m,{status:429,headers:f})}let i=L(),o=e.headers.get("X-Bloggy-Version"),s={name:"unknown",version:"unknown",major:0,minor:0,patch:0};if(o)try{if(/^\d+\.\d+\.\d+/.test(o)){let p=o.split("."),P=parseInt(p[0]??"0",10),f=parseInt(p[1]??"0",10),m=parseInt(p[2]?.split("-")[0]??"0",10);s={name:"bloggy",version:o,major:P,minor:f,patch:m};}else {let p=$(o);p?.bloggyVersion&&(s=p.bloggyVersion);}}catch(p){console.warn("Failed to parse X-Bloggy-Version header:",p);}let a={compatible:!0};s.version!=="unknown"&&(a=st(s,i));let c={success:!0,versions:{bloggy:s,platform:i},compatibility:a},l=N(n.rateLimitResult),d={"X-Bloggy-Version":`platform/${i.version}`,"Cache-Control":"public, max-age=300, stale-while-revalidate=60",...l};return b(e,c,{status:200,headers:d})}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 b(e,r,{status:500})}}async function tn(e,{params:t}){try{let{slug:r}=await t,n=await k(e);if(!n.authenticated){let g=await M(e);return server.NextResponse.json(g.error,{status:401})}let i=n.token??"anonymous",o=await E(i);if(!o.allowed){let g=o.errorResponse.error?.details?.rateLimit||{limit:10,remaining:0,reset:Date.now()+6e4,count:10,success:!1},x=N(g);return b(e,o.errorResponse,{status:429,headers:x})}if(!r||!$e(r))return b(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 g=$(s);if(g?.platformVersion){let x=L();if(g.platformVersion.major!==x.major)return b(e,{exists:!1,error:{code:"PUB009",message:"Major version incompatibility. Please upgrade your blog platform package.",details:{clientVersion:g.platformVersion.version,serverVersion:x.version}}},{status:409})}}let l=await D().getArticle(r)!==null,d={exists:l,...l&&{message:"Slug is already in use. Please choose another (e.g., append '-v2')."}},p=L(),P=N(o.rateLimitResult),f={"X-Bloggy-Version":`platform/${p.version}`,...P},m=e.headers.get("X-Idempotency-Key");return m&&(f["X-Idempotency-Key"]=m,console.log(`Slug check for idempotency: ${m}, exists: ${l}`)),b(e,d,{status:200,headers:f})}catch(r){return console.error("Slug existence check error:",r instanceof Error?r.message:String(r)),b(e,{exists:false,error:{code:"PUB007",message:"Internal server error during slug check"}},{status:500})}}async function rn(e){return ie(e,["GET"])}var ai=W.version;
|
|
31
|
-
exports.ApiKeyAuth=
|
|
30
|
+
`)}function Vr(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((i,o)=>{try{new URL(i.loc);}catch{t.push(`Invalid URL at entry ${o+1}: ${i.loc}`);}i.priority!==void 0&&(i.priority<0||i.priority>1)&&t.push(`Invalid priority at entry ${o+1}: must be between 0.0 and 1.0`),i.lastmod&&!Fr(i.lastmod)&&t.push(`Invalid lastmod date at entry ${o+1}: ${i.lastmod}`),i.loc.length>2048&&r.push(`URL at entry ${o+1} exceeds 2048 character limit`);});let n=new Map;return e.entries.forEach(i=>{let o=n.get(i.loc)??0;n.set(i.loc,o+1);}),n.forEach((i,o)=>{i>1&&t.push(`Duplicate URL found: ${o} (appears ${i} times)`);}),{valid:t.length===0,errors:t,warnings:r}}function W(e){return e.length===0?new Date().toISOString():e.reduce((r,n)=>{let i=new Date(n.updatedAt);return i>r?i:r},new Date(e[0].updatedAt)).toISOString()}function Gr(e,t,r=[],n={}){return async function(){let s=(await $e(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:X(n.canonical?.domain??e.domain,n.canonical?.forceHttps??true)},u=ct(a);return new Response(u,{headers:{"Content-Type":"application/xml","Cache-Control":"public, max-age=3600, s-maxage=3600"}})}}function jr(e){return async function(){let r=await e.getSite(),n=await e.getArticles(),i=e.getAuthors?await e.getAuthors():[];return $e(r,n,i,e.options)}}function se(e){let t={"&":"&","<":"<",">":">",'"':""","'":"'"};return e.replace(/[&<>"']/g,r=>t[r]??r)}function Fr(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 K={name:"@xexr/blog-platform",version:"1.0.5"};function ut(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),i=parseInt(r[1]??"0",10),o=parseInt(r[2]?.split("-")[0]??"0",10);if(isNaN(n)||isNaN(i)||isNaN(o))throw new Error(`Invalid version format: ${e}`);return {major:n,minor:i,patch:o}}function L(){let e=ut(K.version);return {name:K.name,version:K.version,...e}}function $(e){try{let t=e.split(" "),r={};for(let n of t){let[i,o]=n.split("/");if(!i||!o)continue;let s=ut(o),a={name:i,version:o,...s};i==="bloggy"?r.bloggyVersion=a:i==="platform"&&(r.platformVersion=a);}return r}catch{return null}}function mt(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 dt={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 zr(){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 {...dt,enableCSP:!e,frameOptions:t??dt.frameOptions,enableHSTS:!r}}function Xr(e){return Object.entries(e).map(([t,r])=>r?`${t} ${r}`:t).join("; ")}function Wr(e){return Object.entries(e).map(([t,r])=>`${t}=${r}`).join(", ")}function Kr(e,t={}){let r={...zr(),...t},n={};if(r.enableCSP){let i={...r.cspDirectives,...t.cspDirectives??{}};n["Content-Security-Policy"]=Xr(i);}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&&Jr(e)){let i=[`max-age=${r.hstsMaxAge}`,r.hstsIncludeSubdomains?"includeSubDomains":""].filter(Boolean).join("; ");n["Strict-Transport-Security"]=i;}if(r.enablePermissionsPolicy){let i={...r.permissionsPolicyDirectives,...t.permissionsPolicyDirectives??{}};n["Permissions-Policy"]=Wr(i);}return n}function Jr(e){return !!(e.url.startsWith("https://")||e.headers.get("x-forwarded-proto")==="https"||e.headers.get("cf-visitor")?.includes('"scheme":"https"'))}function xe(e,t={}){return Kr(e,{...t,cspDirectives:{...{"default-src":"'none'","frame-ancestors":"'none'","base-uri":"'none'"},...t.cspDirectives??{}}})}var pt={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 gt(){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 {...pt,allowedOrigins:e?e.split(",").map(n=>n.trim()):pt.allowedOrigins,allowWildcard:t,allowCredentials:r}}function ft(e,t){return e?t.allowWildcard?true:t.allowedOrigins.includes(e):false}function ht(e,t){let r=e.headers.get("origin"),n={};return t.allowWildcard?n["Access-Control-Allow-Origin"]="*":r&&ft(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 Yr(e,t,r,n){return {...ht(e,t),"Access-Control-Allow-Methods":r.join(", "),"Access-Control-Allow-Headers":n.join(", "),"Access-Control-Max-Age":t.maxAge.toString()}}var Qr=["Content-Type","X-Bloggy-Version","X-Idempotency-Key","Authorization","X-Requested-With"];function b(e,t,r={}){let{status:n=200,headers:i={},corsConfig:o={}}=r,s={...gt(),...o},a=ht(e,s),u=xe(e,s.securityConfig),l={"Content-Type":"application/json",...a,...u,...i};return server.NextResponse.json(t,{status:n,headers:l})}function ae(e,t,r={}){let{allowedHeaders:n=Qr,corsConfig:i={}}=r,o={...gt(),...i},s=e.headers.get("origin");if(s&&!o.allowWildcard&&!ft(s,o)){let l=xe(e,o.securityConfig);return new server.NextResponse(null,{status:403,headers:{"Content-Type":"text/plain",...l}})}let a=Yr(e,o,[...t,"OPTIONS"],n),u=xe(e,o.securityConfig);return new server.NextResponse(null,{status:200,headers:{...a,...u}})}async function Zr(e){try{let t=await I(e);if(!t.authenticated){let g=await M(e);return b(e,g.error,{status:401})}let r=t.token??"anonymous",n=await k(r);if(!n.allowed){let g=n.errorResponse.error?.details?.rateLimit,x=g&&typeof g=="object"&&"limit"in g&&"remaining"in g&&"reset"in g&&"count"in g&&"success"in g?g:{limit:10,remaining:0,reset:Date.now()+6e4,count:10,success:!1},C=N(x);return b(e,n.errorResponse,{status:429,headers:C})}if(!e.headers.get("content-type")?.includes("application/json"))return b(e,{success:!1,error:{code:"PUB001",message:"Content-Type must be application/json"},idempotencyKey:""},{status:400});let o;try{o=await e.json();}catch{return b(e,{success:!1,error:{code:"PUB001",message:"Invalid JSON in request body"},idempotencyKey:""},{status:400})}let s=en(o);if(s.length>0)return b(e,{success:!1,error:{code:"PUB001",message:"Missing required fields",details:{errors:s}},idempotencyKey:o.idempotencyKey??""},{status:400});let a=e.headers.get("X-Bloggy-Version");if(a){let g=$(a);if(g?.platformVersion){let x=L();if(g.platformVersion.major!==x.major)return b(e,{success:!1,error:{code:"PUB009",message:"Major version incompatibility. Please upgrade your blog platform package.",details:{clientVersion:g.platformVersion.version,serverVersion:x.version}},idempotencyKey:o.idempotencyKey},{status:409})}}if(o.dryRun){let g=[];return o.article.wordCount<50&&g.push("Article has fewer than 50 words, which may affect SEO"),(!o.article.excerpt||o.article.excerpt.length<120)&&g.push("Article excerpt is shorter than recommended 120 characters"),o.article.meta.keywords.length||g.push("No SEO keywords provided"),b(e,{success:!0,warnings:g,idempotencyKey:o.idempotencyKey},{status:200})}let u={...o.article,slug:o.slug??o.article.slug,meta:{...o.article.meta,description:o.metaDescription??o.article.meta.description}};if(!He(u.slug))return b(e,{success:!1,error:{code:"PUB002",message:"Slug can only contain lowercase letters, numbers, and hyphens"},idempotencyKey:o.idempotencyKey},{status:400});let d=await D().saveArticle(u,o.idempotencyKey),p=L(),v=N(n.rateLimitResult),h={"X-Bloggy-Version":`platform/${p.version}`,"X-Idempotency-Key":o.idempotencyKey,...v};d.success&&(h.Location=d.url??`/${u.slug}`);let m=d.success?201:d.error?.code==="PUB003"?409:400;return b(e,d,{status:m,headers:h})}catch(t){return console.error("Publish endpoint error:",t),b(e,{success:false,error:{code:"PUB007",message:"Internal server error during publishing"},idempotencyKey:""},{status:500})}}function en(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,i=["id","slug","title","content","publishedAt","site"];for(let o of i)n[o]||t.push(`Missing required article field: ${o}`);if(n.site&&typeof n.site=="object"){let o=n.site,s=["id","name","domain"];for(let a of s)o[a]||t.push(`Missing required site field: ${a}`);}if(n.meta&&typeof n.meta=="object"){let o=n.meta;Array.isArray(o.keywords)||t.push("Article meta.keywords must be an array");}}return t}function He(e){return !e||typeof e!="string"?false:/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)&&e.length>=1&&e.length<=100}async function rn(e){try{let t=await I(e);if(!t.authenticated){let m=await M(e);return server.NextResponse.json(m.error,{status:401})}let r=t.token??"anonymous",n=await k(r);if(!n.allowed){let m=n.errorResponse.error?.details?.rateLimit,g=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},x=N(g);return b(e,n.errorResponse,{status:429,headers:x})}if(!e.headers.get("content-type")?.includes("application/json"))return b(e,{success:!1,error:{code:"PUB001",message:"Content-Type must be application/json"},idempotencyKey:""},{status:400});let o;try{o=await e.json();}catch{return b(e,{success:!1,error:{code:"PUB001",message:"Invalid JSON in request body"},idempotencyKey:""},{status:400})}let s=nn(o);if(s.length>0)return b(e,{success:!1,error:{code:"PUB001",message:"Missing required fields",details:{errors:s}},idempotencyKey:o.idempotencyKey??""},{status:400});let a=e.headers.get("X-Bloggy-Version");if(a){let m=$(a);if(m?.platformVersion){let g=L();if(m.platformVersion.major!==g.major)return b(e,{success:!1,error:{code:"PUB009",message:"Major version incompatibility. Please upgrade your blog platform package.",details:{clientVersion:m.platformVersion.version,serverVersion:g.version}},idempotencyKey:o.idempotencyKey},{status:409})}}if(!on(o.slug))return b(e,{success:!1,error:{code:"PUB002",message:"Slug can only contain lowercase letters, numbers, and hyphens"},idempotencyKey:o.idempotencyKey},{status:400});if(o.dryRun){let g=await D().getArticle(o.slug),x=[];return g||x.push("Article with this slug does not exist"),b(e,{success:!0,warnings:x,idempotencyKey:o.idempotencyKey},{status:200})}let l=await D().removeArticle(o.slug,o.idempotencyKey),d=L(),p=N(n.rateLimitResult),v={"X-Bloggy-Version":`platform/${d.version}`,"X-Idempotency-Key":o.idempotencyKey,...p},h=l.success?200:l.error?.code==="PUB007"?404:400;return b(e,l,{status:h,headers:v})}catch(t){return console.error("Unpublish endpoint error:",t),b(e,{success:false,error:{code:"PUB007",message:"Internal server error during unpublishing"},idempotencyKey:""},{status:500})}}function nn(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 on(e){return !e||typeof e!="string"?false:/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(e)&&e.length>=1&&e.length<=100}async function sn(e){try{let t=await I(e);if(!t.authenticated){let p=await M(e),v={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:p.error?.error?.message??"Authentication required"}};return b(e,v,{status:401})}let r=t.token??"anonymous",n=await k(r);if(!n.allowed){let p=n.errorResponse.error?.details?.rateLimit,v=p&&typeof p=="object"&&"limit"in p&&"remaining"in p&&"reset"in p&&"count"in p&&"success"in p?p:{limit:10,remaining:0,reset:Date.now()+6e4,count:10,success:!1},h=N(v),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 b(e,m,{status:429,headers:h})}let i=L(),o=e.headers.get("X-Bloggy-Version"),s={name:"unknown",version:"unknown",major:0,minor:0,patch:0};if(o)try{if(/^\d+\.\d+\.\d+/.test(o)){let p=o.split("."),v=parseInt(p[0]??"0",10),h=parseInt(p[1]??"0",10),m=parseInt(p[2]?.split("-")[0]??"0",10);s={name:"bloggy",version:o,major:v,minor:h,patch:m};}else {let p=$(o);p?.bloggyVersion&&(s=p.bloggyVersion);}}catch(p){console.warn("Failed to parse X-Bloggy-Version header:",p);}let a={compatible:!0};s.version!=="unknown"&&(a=mt(s,i));let u={success:!0,versions:{bloggy:s,platform:i},compatibility:a},l=N(n.rateLimitResult),d={"X-Bloggy-Version":`platform/${i.version}`,"Cache-Control":"public, max-age=300, stale-while-revalidate=60",...l};return b(e,u,{status:200,headers:d})}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 b(e,r,{status:500})}}async function ln(e,{params:t}){try{let{slug:r}=await t,n=await I(e);if(!n.authenticated){let g=await M(e);return server.NextResponse.json(g.error,{status:401})}let i=n.token??"anonymous",o=await k(i);if(!o.allowed){let g=o.errorResponse.error?.details?.rateLimit||{limit:10,remaining:0,reset:Date.now()+6e4,count:10,success:!1},x=N(g);return b(e,o.errorResponse,{status:429,headers:x})}if(!r||!He(r))return b(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 g=$(s);if(g?.platformVersion){let x=L();if(g.platformVersion.major!==x.major)return b(e,{exists:!1,error:{code:"PUB009",message:"Major version incompatibility. Please upgrade your blog platform package.",details:{clientVersion:g.platformVersion.version,serverVersion:x.version}}},{status:409})}}let l=await D().getArticle(r)!==null,d={exists:l,...l&&{message:"Slug is already in use. Please choose another (e.g., append '-v2')."}},p=L(),v=N(o.rateLimitResult),h={"X-Bloggy-Version":`platform/${p.version}`,...v},m=e.headers.get("X-Idempotency-Key");return m&&(h["X-Idempotency-Key"]=m,console.log(`Slug check for idempotency: ${m}, exists: ${l}`)),b(e,d,{status:200,headers:h})}catch(r){return console.error("Slug existence check error:",r instanceof Error?r.message:String(r)),b(e,{exists:false,error:{code:"PUB007",message:"Internal server error during slug check"}},{status:500})}}async function cn(e){return ae(e,["GET"])}var bi=K.version;
|
|
31
|
+
exports.ApiKeyAuth=de;exports.BlogArticlePage=rt;exports.BlogHomePage=Ke;exports.Button=Rt;exports.Card=ee;exports.CardContent=te;exports.CardDescription=Kt;exports.CardFooter=Jt;exports.CardHeader=Xt;exports.CardTitle=Wt;exports.DrizzleStorage=De;exports.EnvAuth=q;exports.InMemoryStorage=fe;exports.NoAuth=oe;exports.PACKAGE_VERSION=bi;exports.Pagination=ue;exports.PaginationContent=Pe;exports.PaginationEllipsis=ce;exports.PaginationItem=B;exports.PaginationLink=U;exports.PaginationNext=Ae;exports.PaginationPrevious=ve;exports.ShadcnPagination=ye;exports.StructuredDataError=Y;exports.UninitializedAuth=pe;exports.autoConfigureRateLimit=Me;exports.bpArticles=A;exports.bpOperations=z;exports.buildBlogPath=H;exports.buttonVariants=le;exports.checkRateLimit=ot;exports.cn=y;exports.configureRateLimit=he;exports.createBlogSitemapRoute=Gr;exports.createDynamicBlogSitemap=jr;exports.createRateLimitErrorResponse=it;exports.createStructuredDataScript=Q;exports.enforceRateLimit=k;exports.extractKeywordsFromArticle=It;exports.extractTableOfContents=Le;exports.extractTokenFromHeader=Ie;exports.formatArticleDateMeta=Ce;exports.generateArticleMetadata=dr;exports.generateArticleStructuredData=me;exports.generateAuthorStructuredData=Ge;exports.generateBlogHomeMetadata=jt;exports.generateBlogHomeStructuredData=Te;exports.generateBlogSitemapEntries=$e;exports.generateBreadcrumbStructuredData=je;exports.generateCanonicalUrl=G;exports.generateCanonicalUrlFromSlug=_r;exports.generateCompleteArticleStructuredData=Ne;exports.generateOrganizationStructuredData=Re;exports.generatePaginationMetadata=Bt;exports.generateSiteMetadata=Er;exports.generateSitemap=Ur;exports.generateSitemapIndex=Hr;exports.generateWebSiteStructuredData=we;exports.getAuthConfig=ke;exports.getBaseUrl=Ir;exports.getBlogThemeStyle=Z;exports.getDrizzleAdapterSql=Or;exports.getPathPrefixFromBlogUrl=Et;exports.getRateLimitHeaders=N;exports.getStorage=D;exports.initBlogPlatform=be;exports.initBlogPlatformDev=Sr;exports.initBlogPlatformOnce=Ar;exports.initBlogPlatformProd=Rr;exports.initEnvAuth=gr;exports.isValidCanonicalUrl=Br;exports.metadataToHtml=Dr;exports.normalizeBlogBasePath=E;exports.normalizeDomain=X;exports.normalizeSlug=lt;exports.publishHandler=Zr;exports.safeGenerateArticleStructuredData=kt;exports.setAuthConfig=ge;exports.setStorage=Ee;exports.shouldSkipAuth=hr;exports.sitemapToXml=ct;exports.slugExistsHandler=ln;exports.slugExistsOptionsHandler=cn;exports.structuredDataToJsonLd=qe;exports.unpublishHandler=rn;exports.updateArticleCanonicalUrl=kr;exports.usePagination=_t;exports.validateMetadata=$r;exports.validateSitemap=Vr;exports.validateStructuredData=Fe;exports.versionHandler=sn;//# sourceMappingURL=index.js.map
|
|
32
32
|
//# sourceMappingURL=index.js.map
|