feat: scaffold Journal layer with configurable post route and git-install check
- journal module registers the Journal pages at journal.routes paths - typed anonymous-GET client, html gate, SSR x-forwarded-for forwarding - fixture API, built-server SSR smoke and git-tag install check
This commit is contained in:
150
app/utils/client.ts
Normal file
150
app/utils/client.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
// Typed client for the anonymous GET routes of the Journal API. It wraps an
|
||||
// injected fetcher, so the Nuxt composable decides the base URL and headers
|
||||
// and `node --test` can drive it with a stub. It never calls a write route.
|
||||
|
||||
import type {
|
||||
JournalAuthor,
|
||||
JournalCategory,
|
||||
JournalItem,
|
||||
JournalPage,
|
||||
JournalPost,
|
||||
JournalPostDetail,
|
||||
JournalTag,
|
||||
} from './types.ts'
|
||||
|
||||
/** The Journal API's per_page ceiling. */
|
||||
export const JOURNAL_MAX_PER_PAGE = 30
|
||||
|
||||
/** The Journal API's per_page default. */
|
||||
export const JOURNAL_DEFAULT_PER_PAGE = 9
|
||||
|
||||
/** Issues one GET for `path` (e.g. "/posts") with `query`, resolving the parsed JSON. */
|
||||
export type JournalFetcher = (path: string, query?: Record<string, string | number>) => Promise<unknown>
|
||||
|
||||
export interface PostListOptions {
|
||||
page?: number
|
||||
perPage?: number
|
||||
/** "<column> <asc|desc>", passed through verbatim. */
|
||||
sort?: string
|
||||
/** Category slug or id; the API includes nested children. */
|
||||
category?: string
|
||||
tag?: string
|
||||
search?: string
|
||||
}
|
||||
|
||||
export interface AuthorPostListOptions {
|
||||
page?: number
|
||||
perPage?: number
|
||||
sort?: string
|
||||
}
|
||||
|
||||
/** Clamps a per_page value to 1..30 like the API does; non-numeric gives the default 9. */
|
||||
export function clampPerPage(value: unknown): number {
|
||||
const n = typeof value === 'number' ? value : typeof value === 'string' && value.trim() !== '' ? Number(value) : NaN
|
||||
if (!Number.isFinite(n)) return JOURNAL_DEFAULT_PER_PAGE
|
||||
const i = Math.trunc(n)
|
||||
if (i < 1) return 1
|
||||
if (i > JOURNAL_MAX_PER_PAGE) return JOURNAL_MAX_PER_PAGE
|
||||
return i
|
||||
}
|
||||
|
||||
/** Query for GET /posts: per_page always clamped, other keys only when set. */
|
||||
export function buildPostListQuery(opts: PostListOptions = {}): Record<string, string | number> {
|
||||
const q: Record<string, string | number> = { per_page: clampPerPage(opts.perPage) }
|
||||
if (opts.page !== undefined && Number.isInteger(opts.page) && opts.page > 0) q.page = opts.page
|
||||
if (opts.sort) q.sort = opts.sort
|
||||
if (opts.category) q.category = opts.category
|
||||
if (opts.tag) q.tag = opts.tag
|
||||
if (opts.search) q.search = opts.search
|
||||
return q
|
||||
}
|
||||
|
||||
/** Encodes each "/"-separated segment of a slug (post slugs may contain "/"). */
|
||||
export function encodeSlugPath(slug: string): string {
|
||||
return String(slug)
|
||||
.split('/')
|
||||
.map((part) => encodeURIComponent(part))
|
||||
.join('/')
|
||||
}
|
||||
|
||||
/** Depth-first flattening of the categories tree, parents before children. */
|
||||
export function flattenCategories(tree: readonly JournalCategory[] | null | undefined): JournalCategory[] {
|
||||
const out: JournalCategory[] = []
|
||||
const walk = (nodes: readonly JournalCategory[] | null | undefined): void => {
|
||||
for (const node of nodes ?? []) {
|
||||
out.push(node)
|
||||
walk(node.children)
|
||||
}
|
||||
}
|
||||
walk(tree)
|
||||
return out
|
||||
}
|
||||
|
||||
/** True for a fetch error that carries HTTP status 404 (ofetch, h3 or plain). */
|
||||
export function isNotFound(err: unknown): boolean {
|
||||
if (!err || typeof err !== 'object') return false
|
||||
const e = err as { status?: unknown; statusCode?: unknown; response?: { status?: unknown } }
|
||||
return e.status === 404 || e.statusCode === 404 || e.response?.status === 404
|
||||
}
|
||||
|
||||
export interface JournalClient {
|
||||
getPost(slug: string): Promise<JournalPostDetail | null>
|
||||
listPosts(opts?: PostListOptions): Promise<JournalPage<JournalPost>>
|
||||
listCategories(): Promise<JournalCategory[]>
|
||||
findCategory(slug: string): Promise<JournalCategory | null>
|
||||
listTags(): Promise<JournalTag[]>
|
||||
getAuthor(slug: string): Promise<JournalAuthor | null>
|
||||
listAuthorPosts(slug: string, opts?: AuthorPostListOptions): Promise<JournalPage<JournalPost> | null>
|
||||
}
|
||||
|
||||
export function createJournalClient(fetcher: JournalFetcher): JournalClient {
|
||||
const orNull = async <T>(p: Promise<T>): Promise<T | null> => {
|
||||
try {
|
||||
return await p
|
||||
} catch (err) {
|
||||
if (isNotFound(err)) return null
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
const listCategories = async (): Promise<JournalCategory[]> => {
|
||||
// include_empty=1 always (D-24): an empty category still has a page.
|
||||
const res = (await fetcher('/categories', { include_empty: 1 })) as JournalItem<JournalCategory[]>
|
||||
return Array.isArray(res?.data) ? res.data : []
|
||||
}
|
||||
|
||||
return {
|
||||
async getPost(slug) {
|
||||
const res = (await orNull(fetcher(`/posts/${encodeSlugPath(slug)}`))) as JournalItem<JournalPostDetail> | null
|
||||
return res?.data ?? null
|
||||
},
|
||||
|
||||
async listPosts(opts = {}) {
|
||||
return (await fetcher('/posts', buildPostListQuery(opts))) as JournalPage<JournalPost>
|
||||
},
|
||||
|
||||
listCategories,
|
||||
|
||||
async findCategory(slug) {
|
||||
const rows = flattenCategories(await listCategories())
|
||||
return rows.find((c) => c.slug === slug) ?? null
|
||||
},
|
||||
|
||||
async listTags() {
|
||||
const res = (await fetcher('/tags')) as JournalItem<JournalTag[]>
|
||||
return Array.isArray(res?.data) ? res.data : []
|
||||
},
|
||||
|
||||
async getAuthor(slug) {
|
||||
const res = (await orNull(fetcher(`/authors/${encodeURIComponent(slug)}`))) as JournalItem<JournalAuthor> | null
|
||||
return res?.data ?? null
|
||||
},
|
||||
|
||||
async listAuthorPosts(slug, opts = {}) {
|
||||
const q: Record<string, string | number> = { per_page: clampPerPage(opts.perPage) }
|
||||
if (opts.page !== undefined && Number.isInteger(opts.page) && opts.page > 0) q.page = opts.page
|
||||
if (opts.sort) q.sort = opts.sort
|
||||
return (await orNull(fetcher(`/authors/${encodeURIComponent(slug)}/posts`, q))) as JournalPage<JournalPost> | null
|
||||
},
|
||||
}
|
||||
}
|
||||
23
app/utils/htmlGate.ts
Normal file
23
app/utils/htmlGate.ts
Normal file
@@ -0,0 +1,23 @@
|
||||
// HTML gate for every v-html sink (post body, category content, author bio).
|
||||
// The three patterns are the verbatim regex sources of the Journal plugin's
|
||||
// FormatHTML / CheckHTML gate (classes/format_html.go), with the i flag for
|
||||
// Go's (?i). Imported content bypasses the Go gate, so the layer checks again.
|
||||
|
||||
export const UNSAFE_TAG = /<(?:script|iframe|object|embed)\b/i
|
||||
export const EVENT_HANDLER = /\son[a-z]+\s*=/i
|
||||
export const DANGEROUS_URL = /(?:javascript|vbscript|data):/i
|
||||
|
||||
/** True when `html` matches none of the three Journal patterns. */
|
||||
export function isSafeJournalHtml(html: string | null | undefined): boolean {
|
||||
if (!html) return true
|
||||
return !(UNSAFE_TAG.test(html) || EVENT_HANDLER.test(html) || DANGEROUS_URL.test(html))
|
||||
}
|
||||
|
||||
/**
|
||||
* Gate result for a v-html sink: `html` is the input when safe and "" when
|
||||
* not, so the unsafe value never reaches the DOM. Null input is safe and "".
|
||||
*/
|
||||
export function gateJournalHtml(html: string | null | undefined): { safe: boolean; html: string } {
|
||||
if (!html) return { safe: true, html: '' }
|
||||
return isSafeJournalHtml(html) ? { safe: true, html } : { safe: false, html: '' }
|
||||
}
|
||||
78
app/utils/routes.ts
Normal file
78
app/utils/routes.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
// Journal route configuration: defaults, stable route names, validation and
|
||||
// path filling. Pure TypeScript, so `node --test` and the layer module both
|
||||
// import it directly.
|
||||
|
||||
import type { JournalRoutes } from './types.ts'
|
||||
|
||||
/** Neutral default paths. An app moves or disables any of them in journal.routes. */
|
||||
export const DEFAULT_JOURNAL_ROUTES: Readonly<JournalRoutes> = Object.freeze({
|
||||
index: '/blog',
|
||||
post: '/blog/:slug',
|
||||
category: '/blog/category/:category',
|
||||
tag: '/blog/tag/:tag',
|
||||
author: '/blog/author/:author',
|
||||
})
|
||||
|
||||
/** Route names stay stable whatever the paths are, so links never hard-code a path. */
|
||||
export const JOURNAL_ROUTE_NAMES: Readonly<Record<keyof JournalRoutes, string>> = Object.freeze({
|
||||
index: 'journal-index',
|
||||
post: 'journal-post',
|
||||
category: 'journal-category',
|
||||
tag: 'journal-tag',
|
||||
author: 'journal-author',
|
||||
})
|
||||
|
||||
/** The route param each path must carry. */
|
||||
const REQUIRED_PARAM: Readonly<Record<keyof JournalRoutes, string | null>> = {
|
||||
index: null,
|
||||
post: 'slug',
|
||||
category: 'category',
|
||||
tag: 'tag',
|
||||
author: 'author',
|
||||
}
|
||||
|
||||
const ROUTE_KEYS = Object.keys(DEFAULT_JOURNAL_ROUTES) as Array<keyof JournalRoutes>
|
||||
|
||||
/**
|
||||
* Merges `input` over the defaults and validates every value: each is `false`
|
||||
* or a string starting with "/", and post, category, tag and author carry
|
||||
* their `:slug`, `:category`, `:tag` or `:author` param. Throws an Error that
|
||||
* names `journal.routes.<key>` otherwise.
|
||||
*/
|
||||
export function normalizeJournalRoutes(input?: Partial<Record<string, unknown>> | null): JournalRoutes {
|
||||
const out = { ...DEFAULT_JOURNAL_ROUTES } as JournalRoutes
|
||||
for (const key of ROUTE_KEYS) {
|
||||
const raw = input && Object.prototype.hasOwnProperty.call(input, key) ? input[key] : undefined
|
||||
if (raw === undefined || raw === null) continue
|
||||
if (raw === false) {
|
||||
out[key] = false
|
||||
continue
|
||||
}
|
||||
if (typeof raw !== 'string' || !raw.startsWith('/')) {
|
||||
throw new Error(`journal.routes.${key} must be false or a path starting with "/", got ${JSON.stringify(raw)}`)
|
||||
}
|
||||
const param = REQUIRED_PARAM[key]
|
||||
if (param && !new RegExp(`:${param}(?![A-Za-z0-9_])`).test(raw)) {
|
||||
throw new Error(`journal.routes.${key} must contain the :${param} param, got "${raw}"`)
|
||||
}
|
||||
out[key] = raw
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/**
|
||||
* Fills the `:name` params of a route pattern, encoding each value per path
|
||||
* segment (a "/" inside a value stays a separator). A custom matcher such as
|
||||
* `:slug(.*)` and a trailing modifier are dropped with the param. Unknown
|
||||
* params become empty.
|
||||
*/
|
||||
export function fillJournalPath(pattern: string, params: Record<string, string | number>): string {
|
||||
return pattern.replace(/:([A-Za-z_][A-Za-z0-9_]*)(\([^)]*\))?[?*+]?/g, (_m, name: string) => {
|
||||
const value = params[name]
|
||||
if (value === undefined || value === null) return ''
|
||||
return String(value)
|
||||
.split('/')
|
||||
.map((part) => encodeURIComponent(part))
|
||||
.join('/')
|
||||
})
|
||||
}
|
||||
143
app/utils/types.ts
Normal file
143
app/utils/types.ts
Normal file
@@ -0,0 +1,143 @@
|
||||
// Wire types of the anonymous Journal API (/_journal/api/v1). Field names
|
||||
// mirror the Go serializers exactly (snake_case); a field is nullable where
|
||||
// Go can emit null. Types only, so `node --test` can import any util.
|
||||
|
||||
/** The author object embedded in a post row. `null` when the post has none. */
|
||||
export interface JournalAuthorRef {
|
||||
id: number
|
||||
first_name: string
|
||||
last_name: string
|
||||
login: string
|
||||
}
|
||||
|
||||
/** A category or tag reference embedded in a post row. */
|
||||
export interface JournalTermRef {
|
||||
id: number
|
||||
name: string
|
||||
slug: string
|
||||
}
|
||||
|
||||
export interface JournalFeaturedImage {
|
||||
id: number
|
||||
url: string
|
||||
file_name: string
|
||||
file_size: number
|
||||
}
|
||||
|
||||
/** One post row, as GET /posts and GET /authors/{author}/posts list it. */
|
||||
export interface JournalPost {
|
||||
id: number
|
||||
title: string
|
||||
slug: string
|
||||
excerpt: string | null
|
||||
content: string | null
|
||||
content_html: string | null
|
||||
reading_time: number
|
||||
published: boolean
|
||||
/** UTC, "2006-01-02T15:04:05+00:00". */
|
||||
published_at: string | null
|
||||
is_pinned: boolean
|
||||
metadata: unknown
|
||||
sources: unknown
|
||||
author: JournalAuthorRef | null
|
||||
categories: JournalTermRef[]
|
||||
tags: JournalTermRef[]
|
||||
featured_images: JournalFeaturedImage[]
|
||||
featured_image_url: string | null
|
||||
translations: unknown
|
||||
created_at: string | null
|
||||
updated_at: string | null
|
||||
}
|
||||
|
||||
/** previous_post / next_post on GET /posts/{slug}. */
|
||||
export interface JournalPostSibling {
|
||||
id: number
|
||||
title: string
|
||||
slug: string
|
||||
}
|
||||
|
||||
/** GET /posts/{slug} data: the post plus its neighbours and related posts. */
|
||||
export interface JournalPostDetail extends JournalPost {
|
||||
previous_post: JournalPostSibling | null
|
||||
next_post: JournalPostSibling | null
|
||||
/** Latest 3 in the same categories; empty when the post has no category. */
|
||||
related_posts: JournalPost[]
|
||||
}
|
||||
|
||||
/** One node of the GET /categories tree. */
|
||||
export interface JournalCategory {
|
||||
id: number
|
||||
name: string
|
||||
slug: string
|
||||
description: string | null
|
||||
/** Rich HTML body of the category page, stored as is; null when unset. */
|
||||
content: string | null
|
||||
parent_id: number | null
|
||||
nest_depth: number | null
|
||||
post_count: number
|
||||
children?: JournalCategory[]
|
||||
}
|
||||
|
||||
export interface JournalTag {
|
||||
id: number
|
||||
name: string
|
||||
slug: string
|
||||
post_count: number
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /authors/{author} data. `slug` is the canonical identifier: the author
|
||||
* slug when set, otherwise the login. Missing names are "".
|
||||
*/
|
||||
export interface JournalAuthor {
|
||||
id: number
|
||||
slug: string
|
||||
first_name: string
|
||||
last_name: string
|
||||
}
|
||||
|
||||
export interface JournalPageMeta {
|
||||
current_page: number
|
||||
last_page: number
|
||||
per_page: number
|
||||
total: number
|
||||
}
|
||||
|
||||
/** The paginated envelope of GET /posts and GET /authors/{author}/posts. */
|
||||
export interface JournalPage<T> {
|
||||
data: T[]
|
||||
meta: JournalPageMeta
|
||||
}
|
||||
|
||||
/** The single-object envelope ({ data }) of show and list endpoints. */
|
||||
export interface JournalItem<T> {
|
||||
data: T
|
||||
}
|
||||
|
||||
/** Route paths per Journal view; `false` disables the view. */
|
||||
export interface JournalRoutes {
|
||||
index: string | false
|
||||
post: string | false
|
||||
category: string | false
|
||||
tag: string | false
|
||||
author: string | false
|
||||
}
|
||||
|
||||
export interface JournalPerPage {
|
||||
index: number
|
||||
category: number
|
||||
tag: number
|
||||
author: number
|
||||
}
|
||||
|
||||
/** Options of the `journal` config key in nuxt.config. */
|
||||
export interface JournalModuleOptions {
|
||||
routes: JournalRoutes
|
||||
perPage: JournalPerPage
|
||||
/** "<column> <asc|desc>", column one of published_at, created_at, updated_at, title, id. */
|
||||
sort: string
|
||||
/** How many related posts a post page shows. */
|
||||
relatedCount: number
|
||||
/** Whether /rss.xml is served and linked. */
|
||||
rss: boolean
|
||||
}
|
||||
29
app/utils/view.ts
Normal file
29
app/utils/view.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
// View shaping for SSR payloads. Pages run API rows through these in
|
||||
// useAsyncData's transform, so the serialized payload carries only what the
|
||||
// page renders: no raw `content` source, no `translations`, and never an HTML
|
||||
// body that failed the Journal gate.
|
||||
|
||||
import { gateJournalHtml } from './htmlGate.ts'
|
||||
import type { JournalPost, JournalPostDetail } from './types.ts'
|
||||
|
||||
/** A post row as a list or card renders it: without body, source or translations. */
|
||||
export function toListPost(post: JournalPost): JournalPost {
|
||||
return { ...post, content: null, content_html: null, translations: null }
|
||||
}
|
||||
|
||||
/** A post page's data: the gated body, with `content_blocked` set when the gate refused it. */
|
||||
export interface JournalPostView extends JournalPostDetail {
|
||||
content_blocked: boolean
|
||||
}
|
||||
|
||||
export function toPostView(post: JournalPostDetail): JournalPostView {
|
||||
const gated = gateJournalHtml(post.content_html)
|
||||
return {
|
||||
...post,
|
||||
content: null,
|
||||
translations: null,
|
||||
content_html: gated.html,
|
||||
content_blocked: !gated.safe,
|
||||
related_posts: (post.related_posts ?? []).map(toListPost),
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user