@stacksjs/cms 0.75.674 → 0.75.683
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/blog.d.ts +5 -4
- package/dist/blog.js +2 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -1
- package/dist/markdown.d.ts +26 -0
- package/dist/markdown.js +1 -0
- package/package.json +9 -9
package/dist/blog.d.ts
CHANGED
|
@@ -27,10 +27,11 @@ export declare function loadPosts(options?: BlogDirOptions): PostMeta[];
|
|
|
27
27
|
/** One published post with its body, or null for a draft, an unsafe slug or no such file. */
|
|
28
28
|
export declare function loadPost(slug: unknown, options?: BlogDirOptions): Post | null;
|
|
29
29
|
/**
|
|
30
|
-
* A post body as HTML:
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
* figure and grid
|
|
30
|
+
* A post body as HTML: `renderSafeMarkdown` (HTML in the post shows as text,
|
|
31
|
+
* unsafe links are dropped), then `renderPostHtml`, which turns a lone image
|
|
32
|
+
* into a captioned figure, consecutive images into a grid and a bare video
|
|
33
|
+
* link into an embed. Pair it with `articleHead()` for the figure and grid
|
|
34
|
+
* styles.
|
|
34
35
|
*/
|
|
35
36
|
export declare function renderPostBody(markdown: string, options?: { publicDir?: string }): string;
|
|
36
37
|
/** "October 11, 2026". A post date is a calendar day, so it is read as UTC. */
|
package/dist/blog.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{existsSync,readdirSync,readFileSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{renderPostHtml}from"./article";export function blogContentDir(){return join(process.cwd(),"content/blog")}const SLUG=/^[A-Za-z0-9][\w-]{0,199}$/;const USERNAME=/^[a-z0-9][a-z0-9_-]{0,99}$/;export function isPostSlug(slug){return SLUG.test(slug)}export function parseFrontmatter(markdown){const match=markdown.replace(/\r\n/g,`
|
|
1
|
+
import{existsSync,readdirSync,readFileSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{renderPostHtml}from"./article";import{renderSafeMarkdown}from"./markdown";export function blogContentDir(){return join(process.cwd(),"content/blog")}const SLUG=/^[A-Za-z0-9][\w-]{0,199}$/;const USERNAME=/^[a-z0-9][a-z0-9_-]{0,99}$/;export function isPostSlug(slug){return SLUG.test(slug)}export function parseFrontmatter(markdown){const match=markdown.replace(/\r\n/g,`
|
|
2
2
|
`).match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!match)return{data:{},body:markdown};const data={};for(const line of(match[1]??"").split(`
|
|
3
|
-
`)){const colon=line.indexOf(":");if(colon===-1)continue;const key=line.slice(0,colon).trim();let value=line.slice(colon+1).trim();if(value.startsWith('"')&&value.endsWith('"')||value.startsWith("'")&&value.endsWith("'"))value=value.slice(1,-1);if(key)data[key]=value}return{data,body:match[2]??""}}export function isPublished(data){return!!data.title&&!!data.date&&data.draft!=="true"}export function readingMinutes(markdown){const words=markdown.replace(/```[\s\S]*?```/g," ").replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").split(/\s+/).filter((word)=>/[\p{L}\p{N}]/u.test(word)).length;return Math.max(1,Math.round(words/230))}export function authorsOf(data){const usernames=(data.authors??"").replace(/^\[|\]$/g,"").split(",").map((name)=>name.trim().replace(/^["']|["']$/g,"").toLowerCase()).filter((name)=>USERNAME.test(name));if(usernames.length>0){return[...new Set(usernames)].map((username)=>({username,name:data[`author.${username}.name`]??"",avatar:data[`author.${username}.avatar`]??"",bio:data[`author.${username}.bio`]??""}))}const username=(data.authorUsername??"").toLowerCase();if(!data.author&&!username)return[];return[{username:USERNAME.test(username)?username:"",name:data.author??"",avatar:data.authorAvatar??"",bio:data.authorBio??""}]}function toPost(slug,markdown){const{data,body}=parseFrontmatter(markdown);if(!isPublished(data))return null;return{slug,title:data.title,date:data.date,description:data.description??"",author:data.author??"",authors:authorsOf(data),image:data.image??"",imageAlt:data.imageAlt??"",featured:data.featured==="true",minutes:readingMinutes(body),frontmatter:data,body}}export function sortPosts(posts){return[...posts].sort((a,b)=>{if(a.featured!==b.featured)return a.featured?-1:1;return b.date.localeCompare(a.date)})}export function loadPosts(options={}){const dir=options.dir??blogContentDir();if(!existsSync(dir))return[];const posts=[];for(const file of readdirSync(dir)){const slug=file.replace(/\.md$/,"");if(!file.endsWith(".md")||!SLUG.test(slug))continue;const post=toPost(slug,readFileSync(join(dir,file),"utf8"));if(post){const{body,...meta}=post;posts.push(meta)}}return sortPosts(posts)}export function loadPost(slug,options={}){const name=String(slug??"");if(!SLUG.test(name))return null;const file=join(options.dir??blogContentDir(),`${name}.md`);if(!existsSync(file))return null;return toPost(name,readFileSync(file,"utf8"))}export function renderPostBody(markdown,options={}){return renderPostHtml(
|
|
3
|
+
`)){const colon=line.indexOf(":");if(colon===-1)continue;const key=line.slice(0,colon).trim();let value=line.slice(colon+1).trim();if(value.startsWith('"')&&value.endsWith('"')||value.startsWith("'")&&value.endsWith("'"))value=value.slice(1,-1);if(key)data[key]=value}return{data,body:match[2]??""}}export function isPublished(data){return!!data.title&&!!data.date&&data.draft!=="true"}export function readingMinutes(markdown){const words=markdown.replace(/```[\s\S]*?```/g," ").replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").split(/\s+/).filter((word)=>/[\p{L}\p{N}]/u.test(word)).length;return Math.max(1,Math.round(words/230))}export function authorsOf(data){const usernames=(data.authors??"").replace(/^\[|\]$/g,"").split(",").map((name)=>name.trim().replace(/^["']|["']$/g,"").toLowerCase()).filter((name)=>USERNAME.test(name));if(usernames.length>0){return[...new Set(usernames)].map((username)=>({username,name:data[`author.${username}.name`]??"",avatar:data[`author.${username}.avatar`]??"",bio:data[`author.${username}.bio`]??""}))}const username=(data.authorUsername??"").toLowerCase();if(!data.author&&!username)return[];return[{username:USERNAME.test(username)?username:"",name:data.author??"",avatar:data.authorAvatar??"",bio:data.authorBio??""}]}function toPost(slug,markdown){const{data,body}=parseFrontmatter(markdown);if(!isPublished(data))return null;return{slug,title:data.title,date:data.date,description:data.description??"",author:data.author??"",authors:authorsOf(data),image:data.image??"",imageAlt:data.imageAlt??"",featured:data.featured==="true",minutes:readingMinutes(body),frontmatter:data,body}}export function sortPosts(posts){return[...posts].sort((a,b)=>{if(a.featured!==b.featured)return a.featured?-1:1;return b.date.localeCompare(a.date)})}export function loadPosts(options={}){const dir=options.dir??blogContentDir();if(!existsSync(dir))return[];const posts=[];for(const file of readdirSync(dir)){const slug=file.replace(/\.md$/,"");if(!file.endsWith(".md")||!SLUG.test(slug))continue;const post=toPost(slug,readFileSync(join(dir,file),"utf8"));if(post){const{body,...meta}=post;posts.push(meta)}}return sortPosts(posts)}export function loadPost(slug,options={}){const name=String(slug??"");if(!SLUG.test(name))return null;const file=join(options.dir??blogContentDir(),`${name}.md`);if(!existsSync(file))return null;return toPost(name,readFileSync(file,"utf8"))}export function renderPostBody(markdown,options={}){return renderPostHtml(renderSafeMarkdown(markdown,{headingIds:false}),{publicDir:options.publicDir??join(process.cwd(),"public")})}export function formatPostDate(date,locale="en-US"){const parsed=new Date(`${date}T00:00:00Z`);if(Number.isNaN(parsed.getTime()))return date;return parsed.toLocaleDateString(locale,{month:"long",day:"numeric",year:"numeric",timeZone:"UTC"})}export function initialsOf(name){const parts=name.trim().split(/\s+/).filter(Boolean);return((parts[0]?.[0]??"")+(parts.length>1?parts.at(-1)[0]:"")).toUpperCase()}export function joinNames(names){if(names.length<=1)return names[0]??"";return`${names.slice(0,-1).join(", ")} and ${names.at(-1)}`}export function createAuthorResolver(options={}){const ttl=options.ttlMs??10*60*1000;const cache=new Map;async function profileOf(username){if(!options.lookup||!username||!USERNAME.test(username))return null;const cached=cache.get(username);if(cached&&Date.now()-cached.at<ttl)return cached.profile;let profile=null;try{profile=await options.lookup(username)??null}catch{profile=null}if(ttl>0)cache.set(username,{at:Date.now(),profile});return profile}const one=async(ref)=>{const profile=await profileOf(ref.username);const name=String(profile?.name||ref.name||ref.username||options.fallbackName||process.env.APP_NAME||"Blog");return{name,initials:String(profile?.initials||initialsOf(name)),avatar:String(profile?.avatar||ref.avatar||""),bio:String(ref.bio||profile?.bio||""),url:String(profile?.url||"")}};const resolve=async(post)=>{const refs=post.authors.length>0?post.authors:[{username:"",name:"",avatar:"",bio:""}];return Promise.all(refs.map(one))};resolve.one=one;resolve.clear=()=>cache.clear();return resolve}export function bylineOf(authors){return authors.map((author,index)=>({...author,joiner:index===0?"":index===authors.length-1?" and ":", ",avatarStyle:author.avatar?`background-image:url(${JSON.stringify(author.avatar)})`:""}))}
|
package/dist/index.d.ts
CHANGED
|
@@ -9,6 +9,7 @@ export type { MenuTreeItem } from './menus/index';
|
|
|
9
9
|
export type { EditablePageDocument } from './pages/document';
|
|
10
10
|
export type { SavedPageDocument, SavePageDocumentInput } from './pages/document';
|
|
11
11
|
export type { PublishedPage } from './public/resolve';
|
|
12
|
+
export type { SafeMarkdownOptions } from './markdown';
|
|
12
13
|
export declare const cms: CmsNamespace;
|
|
13
14
|
export declare interface CmsNamespace {
|
|
14
15
|
posts: PostsModule
|
|
@@ -41,6 +42,7 @@ export { publishDuePages } from './publish/index';
|
|
|
41
42
|
export { cmsNotFoundFallback, cmsPageFallback } from './public/fallback';
|
|
42
43
|
export { renderCmsPage } from './public/render';
|
|
43
44
|
export { normalizePath, resolvePublishedPage } from './public/resolve';
|
|
45
|
+
export { renderSafeMarkdown, safeUrl } from './markdown';
|
|
44
46
|
export { sanitizeRichText } from './public/sanitize';
|
|
45
47
|
export { recordSlugChangeRedirects, resolveRedirect } from './redirects/index';
|
|
46
48
|
export { fetchRevisions, restoreRevision, storeRevision } from './revisions/index';
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import*as authors from"./authors";import*as postCategories from"./categorizables";import*as comments from"./commentables";import*as pages from"./pages";import*as posts from"./posts";import*as tags from"./taggables";export const cms={posts,postCategories,tags,comments,authors,pages};export default cms;export{authors,postCategories as categorizable,comments,pages,posts,tags};export{defaultBlocks,registerDefaultBlocks}from"./blocks/defaults";export{allBlocks,defineBlock,getBlock,parseStoredBlocks,registerBlocks,validateBlocks}from"./blocks/registry";export{fetchMenuTree}from"./menus";export{createPageDocument,fetchPageDocument,PageDocumentError,updatePageDocument}from"./pages/document";export{publishDuePages}from"./publish";export{cmsNotFoundFallback,cmsPageFallback}from"./public/fallback";export{renderCmsPage}from"./public/render";export{normalizePath,resolvePublishedPage}from"./public/resolve";export{sanitizeRichText}from"./public/sanitize";export{recordSlugChangeRedirects,resolveRedirect}from"./redirects";export{fetchRevisions,restoreRevision,storeRevision}from"./revisions";
|
|
1
|
+
import*as authors from"./authors";import*as postCategories from"./categorizables";import*as comments from"./commentables";import*as pages from"./pages";import*as posts from"./posts";import*as tags from"./taggables";export const cms={posts,postCategories,tags,comments,authors,pages};export default cms;export{authors,postCategories as categorizable,comments,pages,posts,tags};export{defaultBlocks,registerDefaultBlocks}from"./blocks/defaults";export{allBlocks,defineBlock,getBlock,parseStoredBlocks,registerBlocks,validateBlocks}from"./blocks/registry";export{fetchMenuTree}from"./menus";export{createPageDocument,fetchPageDocument,PageDocumentError,updatePageDocument}from"./pages/document";export{publishDuePages}from"./publish";export{cmsNotFoundFallback,cmsPageFallback}from"./public/fallback";export{renderCmsPage}from"./public/render";export{normalizePath,resolvePublishedPage}from"./public/resolve";export{renderSafeMarkdown,safeUrl}from"./markdown";export{sanitizeRichText}from"./public/sanitize";export{recordSlugChangeRedirects,resolveRedirect}from"./redirects";export{fetchRevisions,restoreRevision,storeRevision}from"./revisions";
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `url` when a reader can follow it safely, otherwise `null`. Relative paths,
|
|
3
|
+
* anchors and the allowed schemes pass. Anything with control characters,
|
|
4
|
+
* whitespace or a backslash is refused rather than guessing how a browser
|
|
5
|
+
* would read it.
|
|
6
|
+
*/
|
|
7
|
+
export declare function safeUrl(url: string, kind?: 'link' | 'image'): string | null;
|
|
8
|
+
/**
|
|
9
|
+
* Render `markdown` (GitHub-flavoured: tables, task lists, strikethrough,
|
|
10
|
+
* autolinks) to HTML with raw HTML escaped and unsafe URLs removed.
|
|
11
|
+
*/
|
|
12
|
+
export declare function renderSafeMarkdown(markdown: string, options?: SafeMarkdownOptions): string;
|
|
13
|
+
/**
|
|
14
|
+
* Markdown to HTML for content the reader's browser should not trust, such as
|
|
15
|
+
* blog posts.
|
|
16
|
+
*
|
|
17
|
+
* A post is written in Markdown, not HTML: any HTML in it is shown as the text
|
|
18
|
+
* it is, so a stray `<script>` or `onerror=` reads as characters on the page.
|
|
19
|
+
* Links and images may only point where a link should (http, https, a relative
|
|
20
|
+
* path or an anchor; links may also be mailto). Code in backticks or fences
|
|
21
|
+
* keeps showing `<` as `<`.
|
|
22
|
+
*/
|
|
23
|
+
/** Options for {@link renderSafeMarkdown}. */
|
|
24
|
+
export declare interface SafeMarkdownOptions {
|
|
25
|
+
headingIds?: boolean
|
|
26
|
+
}
|
package/dist/markdown.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const LINK_SCHEMES=["http","https","mailto"];const IMAGE_SCHEMES=["http","https"];function decodeEntities(value){return value.replace(/&#x([\da-f]+);?/gi,(_,hex)=>String.fromCodePoint(Number.parseInt(hex,16))).replace(/&#(\d+);?/g,(_,dec)=>String.fromCodePoint(Number(dec))).replace(/"/g,'"').replace(/'|'/g,"'").replace(/</g,"<").replace(/>/g,">").replace(/&/g,"&")}export function safeUrl(url,kind="link"){const value=url.trim();if(!value||/[\u0000- \u007F-\u009F\\]/.test(value))return null;const scheme=/^([^/?#]*):/.exec(value)?.[1];if(scheme===undefined)return value;return(kind==="image"?IMAGE_SCHEMES:LINK_SCHEMES).includes(scheme.toLowerCase())?value:null}function filterUrls(html){return html.replace(/<(a|img)\b([^>]*)>/g,(_tag,name,attributes)=>{const kept=attributes.replace(/\s([\w:-]+)="([^"]*)"/g,(attribute,key,encoded)=>(key==="href"||key==="src")&&safeUrl(decodeEntities(encoded),name==="img"?"image":"link")===null?"":attribute);return`<${name}${kept}>`})}export function renderSafeMarkdown(markdown,options={}){const html=Bun.markdown.html(markdown,{tables:true,strikethrough:true,tasklists:true,autolinks:true,headings:options.headingIds===false?undefined:{ids:true},noHtmlBlocks:true,noHtmlSpans:true});return filterUrls(html)}
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/cms",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.683",
|
|
6
6
|
"description": "Stacks cms utilities.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -58,14 +58,14 @@
|
|
|
58
58
|
"prepublishOnly": "bun run build"
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
|
-
"@stacksjs/database": "0.75.
|
|
62
|
-
"@stacksjs/error-handling": "0.75.
|
|
63
|
-
"@stacksjs/orm": "0.75.
|
|
64
|
-
"@stacksjs/path": "0.75.
|
|
65
|
-
"@stacksjs/sites": "0.75.
|
|
66
|
-
"@stacksjs/slug": "0.75.
|
|
67
|
-
"@stacksjs/stx": "^0.2.
|
|
68
|
-
"@stacksjs/validation": "0.75.
|
|
61
|
+
"@stacksjs/database": "0.75.683",
|
|
62
|
+
"@stacksjs/error-handling": "0.75.683",
|
|
63
|
+
"@stacksjs/orm": "0.75.683",
|
|
64
|
+
"@stacksjs/path": "0.75.683",
|
|
65
|
+
"@stacksjs/sites": "0.75.683",
|
|
66
|
+
"@stacksjs/slug": "0.75.683",
|
|
67
|
+
"@stacksjs/stx": "^0.2.934",
|
|
68
|
+
"@stacksjs/validation": "0.75.683",
|
|
69
69
|
"ts-medium-editor": "^0.2.0",
|
|
70
70
|
"ts-slug": "^0.2.1",
|
|
71
71
|
"ts-spreadsheets": "^0.2.5"
|