@ingram-tech/nk-blog 0.1.4 → 0.1.6
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/render.d.ts +12 -0
- package/dist/render.d.ts.map +1 -1
- package/dist/render.js +12 -0
- package/dist/render.js.map +1 -1
- package/package.json +9 -6
- package/src/blog.ts +170 -0
- package/src/contract.ts +97 -0
- package/src/date.ts +22 -0
- package/src/http.ts +16 -0
- package/src/index.ts +40 -0
- package/src/keys.ts +12 -0
- package/src/limited-mdx.ts +267 -0
- package/src/reading-time.ts +21 -0
- package/src/render.tsx +94 -0
- package/src/rss.ts +71 -0
- package/src/schema.ts +68 -0
- package/src/seo.ts +69 -0
- package/src/server.ts +22 -0
- package/src/sources/fs.ts +59 -0
- package/src/sources/github.ts +112 -0
- package/src/sources/publish.ts +103 -0
- package/src/types.ts +34 -0
- package/src/unstyled/callout.tsx +18 -0
- package/src/unstyled/figure.tsx +30 -0
- package/src/unstyled/index.ts +24 -0
- package/src/unstyled/newsletter-subscribe.tsx +23 -0
- package/src/unstyled/tweet.tsx +12 -0
- package/src/unstyled/youtube.tsx +24 -0
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import type { BlogSource, RawPostFile } from "../blog.js";
|
|
3
|
+
import { assertResponseOk } from "../http.js";
|
|
4
|
+
import { keys } from "../keys.js";
|
|
5
|
+
|
|
6
|
+
export interface GitHubRepoConfig {
|
|
7
|
+
owner: string;
|
|
8
|
+
repo: string;
|
|
9
|
+
/** Branch, tag, or commit; defaults to the repo's default branch. */
|
|
10
|
+
ref?: string;
|
|
11
|
+
/** Content directory inside the repo, e.g. "content/blog". */
|
|
12
|
+
dir: string;
|
|
13
|
+
/** Falls back to the GITHUB_TOKEN env var. */
|
|
14
|
+
token?: string;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const API = "https://api.github.com";
|
|
18
|
+
|
|
19
|
+
export function githubHeaders(token: string | undefined): Record<string, string> {
|
|
20
|
+
const resolved = token ?? keys().GITHUB_TOKEN;
|
|
21
|
+
return {
|
|
22
|
+
accept: "application/vnd.github+json",
|
|
23
|
+
"x-github-api-version": "2022-11-28",
|
|
24
|
+
"user-agent": "nk-blog",
|
|
25
|
+
...(resolved ? { authorization: `Bearer ${resolved}` } : {}),
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const treeSchema = z.object({
|
|
30
|
+
truncated: z.boolean(),
|
|
31
|
+
tree: z.array(
|
|
32
|
+
z.object({
|
|
33
|
+
path: z.string(),
|
|
34
|
+
type: z.string(),
|
|
35
|
+
sha: z.string(),
|
|
36
|
+
}),
|
|
37
|
+
),
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const blobSchema = z.object({
|
|
41
|
+
content: z.string(),
|
|
42
|
+
encoding: z.literal("base64"),
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Read a repo's posts over the GitHub API — the admin publisher's read path
|
|
47
|
+
* (list a target's real posts; reconcile instead of blind-append). One Trees
|
|
48
|
+
* call for the listing, then batched blob fetches: never per-file `contents`
|
|
49
|
+
* round-trips.
|
|
50
|
+
*/
|
|
51
|
+
export function githubSource(config: GitHubRepoConfig): BlogSource {
|
|
52
|
+
return {
|
|
53
|
+
async load(): Promise<RawPostFile[]> {
|
|
54
|
+
const headers = githubHeaders(config.token);
|
|
55
|
+
const base = `${API}/repos/${config.owner}/${config.repo}`;
|
|
56
|
+
const ref = config.ref ?? "HEAD";
|
|
57
|
+
|
|
58
|
+
const treeResponse = await fetch(
|
|
59
|
+
`${base}/git/trees/${encodeURIComponent(ref)}?recursive=1`,
|
|
60
|
+
{ headers },
|
|
61
|
+
);
|
|
62
|
+
await assertResponseOk(
|
|
63
|
+
treeResponse,
|
|
64
|
+
`nk-blog: listing ${config.owner}/${config.repo}@${ref}`,
|
|
65
|
+
);
|
|
66
|
+
const { tree, truncated } = treeSchema.parse(await treeResponse.json());
|
|
67
|
+
if (truncated) {
|
|
68
|
+
throw new Error(
|
|
69
|
+
`nk-blog: git tree for ${config.owner}/${config.repo} is truncated; narrow \`dir\``,
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const prefix = `${config.dir.replace(/\/$/, "")}/`;
|
|
74
|
+
const files = tree.filter(
|
|
75
|
+
(entry) =>
|
|
76
|
+
entry.type === "blob" &&
|
|
77
|
+
entry.path.startsWith(prefix) &&
|
|
78
|
+
/\.mdx?$/.test(entry.path),
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
// Bounded concurrency: an unbounded Promise.all over every post blob
|
|
82
|
+
// hammers the API and trips secondary rate limits on large blogs.
|
|
83
|
+
const CONCURRENCY = 8;
|
|
84
|
+
const results: { name: string; content: string }[] = [];
|
|
85
|
+
for (let i = 0; i < files.length; i += CONCURRENCY) {
|
|
86
|
+
const chunk = await Promise.all(
|
|
87
|
+
files.slice(i, i + CONCURRENCY).map(async (entry) => {
|
|
88
|
+
const blobResponse = await fetch(
|
|
89
|
+
`${base}/git/blobs/${entry.sha}`,
|
|
90
|
+
{
|
|
91
|
+
headers,
|
|
92
|
+
},
|
|
93
|
+
);
|
|
94
|
+
await assertResponseOk(
|
|
95
|
+
blobResponse,
|
|
96
|
+
`nk-blog: reading ${entry.path}`,
|
|
97
|
+
);
|
|
98
|
+
const blob = blobSchema.parse(await blobResponse.json());
|
|
99
|
+
return {
|
|
100
|
+
name: entry.path.slice(prefix.length),
|
|
101
|
+
content: Buffer.from(blob.content, "base64").toString(
|
|
102
|
+
"utf8",
|
|
103
|
+
),
|
|
104
|
+
};
|
|
105
|
+
}),
|
|
106
|
+
);
|
|
107
|
+
results.push(...chunk);
|
|
108
|
+
}
|
|
109
|
+
return results;
|
|
110
|
+
},
|
|
111
|
+
};
|
|
112
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import matter from "gray-matter";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import {
|
|
4
|
+
blogFrontmatterSchema,
|
|
5
|
+
type BlogFrontmatterInput,
|
|
6
|
+
slugPattern,
|
|
7
|
+
} from "../schema.js";
|
|
8
|
+
import type { PostFormat } from "../types.js";
|
|
9
|
+
import { assertResponseOk } from "../http.js";
|
|
10
|
+
import { githubHeaders, type GitHubRepoConfig } from "./github.js";
|
|
11
|
+
|
|
12
|
+
const API = "https://api.github.com";
|
|
13
|
+
|
|
14
|
+
/** Canonical on-disk form of a post: YAML frontmatter + body, one trailing \n. */
|
|
15
|
+
export function serializePost(frontmatter: BlogFrontmatterInput, body: string): string {
|
|
16
|
+
// Validate before serializing so admin can never commit a file the sites'
|
|
17
|
+
// readers would reject at build time.
|
|
18
|
+
blogFrontmatterSchema.parse(frontmatter);
|
|
19
|
+
return `${matter.stringify(`\n${body.trim()}\n`, frontmatter).trim()}\n`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface PublishPostInput {
|
|
23
|
+
slug: string;
|
|
24
|
+
frontmatter: BlogFrontmatterInput;
|
|
25
|
+
body: string;
|
|
26
|
+
/** Admin's automated path emits "md" (data, never code) — the default. */
|
|
27
|
+
format?: PostFormat;
|
|
28
|
+
message?: string;
|
|
29
|
+
/** Commit to this branch (e.g. for a draft/preview PR) instead of the ref. */
|
|
30
|
+
branch?: string;
|
|
31
|
+
/** Update an existing post instead of failing the slug-collision check. */
|
|
32
|
+
overwrite?: boolean;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const putResponseSchema = z.object({
|
|
36
|
+
content: z.object({ path: z.string(), sha: z.string() }),
|
|
37
|
+
commit: z.object({ sha: z.string(), html_url: z.string().optional() }),
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
export type PublishedPost = z.infer<typeof putResponseSchema>;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Publish a post by committing one content file to the target repo — the
|
|
44
|
+
* entire replacement for admin's buildPostsJson/buildMdx machinery.
|
|
45
|
+
*/
|
|
46
|
+
export async function publishPost(
|
|
47
|
+
target: GitHubRepoConfig,
|
|
48
|
+
input: PublishPostInput,
|
|
49
|
+
): Promise<PublishedPost> {
|
|
50
|
+
if (!slugPattern.test(input.slug)) {
|
|
51
|
+
// The slug lands in a repo file path — anything looser is a traversal
|
|
52
|
+
// vector (`../.github/workflows/x`) and breaks routes/RSS URLs anyway.
|
|
53
|
+
throw new Error(`nk-blog: invalid slug "${input.slug}"`);
|
|
54
|
+
}
|
|
55
|
+
const frontmatterSlug = input.frontmatter.slug;
|
|
56
|
+
if (frontmatterSlug !== undefined && frontmatterSlug !== input.slug) {
|
|
57
|
+
// The reader routes by the frontmatter override, so a mismatch defeats
|
|
58
|
+
// the filename-based collision check below and can break the target
|
|
59
|
+
// site's build with a duplicate-slug error.
|
|
60
|
+
throw new Error(
|
|
61
|
+
`nk-blog: frontmatter slug "${frontmatterSlug}" does not match publish slug "${input.slug}"`,
|
|
62
|
+
);
|
|
63
|
+
}
|
|
64
|
+
const headers = githubHeaders(target.token);
|
|
65
|
+
const base = `${API}/repos/${target.owner}/${target.repo}`;
|
|
66
|
+
const filePath = `${target.dir.replace(/\/$/, "")}/${input.slug}.${
|
|
67
|
+
input.format ?? "md"
|
|
68
|
+
}`;
|
|
69
|
+
const branch = input.branch ?? target.ref;
|
|
70
|
+
const refQuery = branch ? `?ref=${encodeURIComponent(branch)}` : "";
|
|
71
|
+
|
|
72
|
+
// Slug-collision check (and the sha needed when overwriting).
|
|
73
|
+
const existing = await fetch(`${base}/contents/${filePath}${refQuery}`, {
|
|
74
|
+
headers,
|
|
75
|
+
});
|
|
76
|
+
let existingSha: string | undefined;
|
|
77
|
+
if (existing.ok) {
|
|
78
|
+
if (!input.overwrite) {
|
|
79
|
+
throw new Error(
|
|
80
|
+
`nk-blog: ${filePath} already exists in ${target.owner}/${target.repo}`,
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
existingSha = z.object({ sha: z.string() }).parse(await existing.json()).sha;
|
|
84
|
+
} else if (existing.status !== 404) {
|
|
85
|
+
await assertResponseOk(existing, `nk-blog: checking ${filePath}`);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const response = await fetch(`${base}/contents/${filePath}`, {
|
|
89
|
+
method: "PUT",
|
|
90
|
+
headers: { ...headers, "content-type": "application/json" },
|
|
91
|
+
body: JSON.stringify({
|
|
92
|
+
message: input.message ?? `content: publish ${input.slug}`,
|
|
93
|
+
content: Buffer.from(
|
|
94
|
+
serializePost(input.frontmatter, input.body),
|
|
95
|
+
"utf8",
|
|
96
|
+
).toString("base64"),
|
|
97
|
+
...(branch ? { branch } : {}),
|
|
98
|
+
...(existingSha ? { sha: existingSha } : {}),
|
|
99
|
+
}),
|
|
100
|
+
});
|
|
101
|
+
await assertResponseOk(response, `nk-blog: publishing ${filePath}`);
|
|
102
|
+
return putResponseSchema.parse(await response.json());
|
|
103
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
export type PostFormat = "md" | "mdx";
|
|
2
|
+
|
|
3
|
+
/** Everything a listing page needs — no body. */
|
|
4
|
+
export interface BlogPostPreview {
|
|
5
|
+
slug: string;
|
|
6
|
+
title: string;
|
|
7
|
+
seoTitle?: string;
|
|
8
|
+
description: string;
|
|
9
|
+
/** ISO 8601. */
|
|
10
|
+
date: string;
|
|
11
|
+
/** ISO 8601; set when the post declares an `updated` date. */
|
|
12
|
+
updated?: string;
|
|
13
|
+
authors: string[];
|
|
14
|
+
/** First author — convenience for single-byline layouts. */
|
|
15
|
+
author: string;
|
|
16
|
+
category?: string;
|
|
17
|
+
tags: string[];
|
|
18
|
+
image?: string;
|
|
19
|
+
draft: boolean;
|
|
20
|
+
featured: boolean;
|
|
21
|
+
/** Reserved for i18n'd blogs; not interpreted by the reader yet. */
|
|
22
|
+
lang?: string;
|
|
23
|
+
/** Reserved canonical-URL override for syndicated posts. */
|
|
24
|
+
canonical?: string;
|
|
25
|
+
format: PostFormat;
|
|
26
|
+
readingTimeMinutes: number;
|
|
27
|
+
/** e.g. "5 min read" — derived from the body, never authored. */
|
|
28
|
+
readTime: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A full post: the preview fields plus the body (frontmatter stripped). */
|
|
32
|
+
export interface BlogPost extends BlogPostPreview {
|
|
33
|
+
content: string;
|
|
34
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { CalloutProps } from "../contract.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Unstyled default. Semantic structure only — style it from the site via the
|
|
5
|
+
* data attributes, or replace it wholesale. No visual props beyond className,
|
|
6
|
+
* ever (the bright line that keeps "unstyled" from eroding into a theme).
|
|
7
|
+
*/
|
|
8
|
+
export const Callout: React.FC<CalloutProps> = ({
|
|
9
|
+
variant = "note",
|
|
10
|
+
title,
|
|
11
|
+
className,
|
|
12
|
+
children,
|
|
13
|
+
}) => (
|
|
14
|
+
<aside data-callout={variant} className={className}>
|
|
15
|
+
{title ? <p data-callout-title>{title}</p> : null}
|
|
16
|
+
<div data-callout-body>{children}</div>
|
|
17
|
+
</aside>
|
|
18
|
+
);
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { FigureProps } from "../contract.js";
|
|
2
|
+
|
|
3
|
+
const toDimension = (value: number | string | undefined): number | undefined =>
|
|
4
|
+
typeof value === "string" ? Number(value) : value;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Unstyled captioned image: correct semantics (figure/figcaption), lazy
|
|
8
|
+
* loading, and explicit dimensions when given (CLS). Sites wanting
|
|
9
|
+
* next/image replace this wholesale.
|
|
10
|
+
*/
|
|
11
|
+
export const Figure: React.FC<FigureProps> = ({
|
|
12
|
+
src,
|
|
13
|
+
alt,
|
|
14
|
+
caption,
|
|
15
|
+
width,
|
|
16
|
+
height,
|
|
17
|
+
className,
|
|
18
|
+
}) => (
|
|
19
|
+
<figure className={className}>
|
|
20
|
+
<img
|
|
21
|
+
src={src}
|
|
22
|
+
alt={alt}
|
|
23
|
+
width={toDimension(width)}
|
|
24
|
+
height={toDimension(height)}
|
|
25
|
+
loading="lazy"
|
|
26
|
+
decoding="async"
|
|
27
|
+
/>
|
|
28
|
+
{caption ? <figcaption>{caption}</figcaption> : null}
|
|
29
|
+
</figure>
|
|
30
|
+
);
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { defineBlogComponents } from "../contract.js";
|
|
2
|
+
import { Callout } from "./callout.js";
|
|
3
|
+
import { Figure } from "./figure.js";
|
|
4
|
+
import { NewsletterSubscribe } from "./newsletter-subscribe.js";
|
|
5
|
+
import { Tweet } from "./tweet.js";
|
|
6
|
+
import { YouTube } from "./youtube.js";
|
|
7
|
+
|
|
8
|
+
export { Callout, Figure, NewsletterSubscribe, Tweet, YouTube };
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The complete default registry. A site's whole obligation is:
|
|
12
|
+
*
|
|
13
|
+
* export const blogComponents = defineBlogComponents({
|
|
14
|
+
* ...unstyled,
|
|
15
|
+
* Callout: BrandCallout, // replaced wholesale where the brand cares
|
|
16
|
+
* });
|
|
17
|
+
*/
|
|
18
|
+
export const unstyled = defineBlogComponents({
|
|
19
|
+
Callout,
|
|
20
|
+
Figure,
|
|
21
|
+
YouTube,
|
|
22
|
+
Tweet,
|
|
23
|
+
NewsletterSubscribe,
|
|
24
|
+
});
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { NewsletterSubscribeProps } from "../contract.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Plain HTML form POSTing to the injected endpoint — works with zero client
|
|
5
|
+
* JS. The package never bakes in a newsletter backend.
|
|
6
|
+
*/
|
|
7
|
+
export const NewsletterSubscribe: React.FC<NewsletterSubscribeProps> = ({
|
|
8
|
+
action,
|
|
9
|
+
placeholder,
|
|
10
|
+
buttonLabel,
|
|
11
|
+
className,
|
|
12
|
+
}) => (
|
|
13
|
+
<form action={action} method="post" className={className}>
|
|
14
|
+
<input
|
|
15
|
+
type="email"
|
|
16
|
+
name="email"
|
|
17
|
+
required
|
|
18
|
+
placeholder={placeholder ?? "you@example.com"}
|
|
19
|
+
aria-label="Email address"
|
|
20
|
+
/>
|
|
21
|
+
<button type="submit">{buttonLabel ?? "Subscribe"}</button>
|
|
22
|
+
</form>
|
|
23
|
+
);
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { TweetProps } from "../contract.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Zero-JS default: the standard `twitter-tweet` blockquote, progressively
|
|
5
|
+
* enhanced if the site loads the platform widget script — otherwise it
|
|
6
|
+
* degrades to a plain link. No data fetching in the package.
|
|
7
|
+
*/
|
|
8
|
+
export const Tweet: React.FC<TweetProps> = ({ id, className }) => (
|
|
9
|
+
<blockquote className={["twitter-tweet", className].filter(Boolean).join(" ")}>
|
|
10
|
+
<a href={`https://twitter.com/i/status/${encodeURIComponent(id)}`}>View post</a>
|
|
11
|
+
</blockquote>
|
|
12
|
+
);
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { YouTubeProps } from "../contract.js";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Privacy-enhanced (youtube-nocookie), lazy-loaded embed with a stable 16:9
|
|
5
|
+
* box (CLS). The inline aspect-ratio is behavior, not styling.
|
|
6
|
+
*/
|
|
7
|
+
export const YouTube: React.FC<YouTubeProps> = ({ id, title, start, className }) => {
|
|
8
|
+
const startSeconds = typeof start === "string" ? Number(start) : start;
|
|
9
|
+
const src = `https://www.youtube-nocookie.com/embed/${encodeURIComponent(id)}${
|
|
10
|
+
startSeconds ? `?start=${startSeconds}` : ""
|
|
11
|
+
}`;
|
|
12
|
+
return (
|
|
13
|
+
<iframe
|
|
14
|
+
src={src}
|
|
15
|
+
title={title ?? "YouTube video"}
|
|
16
|
+
loading="lazy"
|
|
17
|
+
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
|
|
18
|
+
allowFullScreen
|
|
19
|
+
referrerPolicy="strict-origin-when-cross-origin"
|
|
20
|
+
className={className}
|
|
21
|
+
style={{ aspectRatio: "16 / 9", width: "100%", border: 0 }}
|
|
22
|
+
/>
|
|
23
|
+
);
|
|
24
|
+
};
|