-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpost-repository.ts
More file actions
375 lines (302 loc) · 9.51 KB
/
Copy pathpost-repository.ts
File metadata and controls
375 lines (302 loc) · 9.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
import fs from 'fs';
import path from 'path';
import type { FeedData, Feed, FeedFrontmatter } from '@/blog/model/types';
import { FeedFrontmatterSchema } from '@/blog/model/frontmatter-schema';
import {
filterListedPosts,
isListedPost,
type PublicationQueryOptions,
} from './policy';
const postsDirectory = path.join(process.cwd(), 'posts');
const isProduction = process.env.NODE_ENV === 'production';
const shouldLogContentIssues = process.env.NODE_ENV !== 'test';
// Cache for folder path lookups by slug
const slugToFolderCache = new Map<string, string>();
let cachedSortedFeedData: FeedData[] | null = null;
function normalizeSlug(slug: string): string {
try {
return decodeURIComponent(slug);
} catch {
return slug;
}
}
function logContentIssue(message: string): void {
if (!shouldLogContentIssues) {
return;
}
console.warn(`[post-repository] ${message}`);
}
export type FeedQueryOptions = PublicationQueryOptions;
// TOC item type
export interface TocItem {
id: string;
text: string;
level: number;
children?: TocItem[];
}
// Safe file system utilities
function safeReadFile(filePath: string): string | null {
try {
return fs.readFileSync(filePath, 'utf8');
} catch {
logContentIssue('Failed to read a content file.');
return null;
}
}
function safeReaddir(dirPath: string): string[] | null {
try {
return fs.readdirSync(dirPath);
} catch {
logContentIssue('Failed to read a content directory.');
return null;
}
}
function safeExists(p: string): boolean {
try {
return fs.existsSync(p);
} catch {
logContentIssue('Failed to check content path existence.');
return false;
}
}
function isDirectory(p: string): boolean {
try {
return fs.statSync(p).isDirectory();
} catch {
return false;
}
}
// Recursively find all post folders (folders with index.mdx + meta.json)
function findAllPostFolders(dir: string, relativePath: string = ''): string[] {
const folders: string[] = [];
const items = safeReaddir(dir);
if (!items) return folders;
for (const item of items) {
const fullPath = path.join(dir, item);
if (!isDirectory(fullPath)) continue;
const currentRelPath = relativePath ? `${relativePath}/${item}` : item;
const hasIndex = safeExists(path.join(fullPath, 'index.mdx'));
const hasMeta = safeExists(path.join(fullPath, 'meta.json'));
if (hasIndex && hasMeta) {
folders.push(currentRelPath);
}
// Recursively search subdirectories (for series folders)
const subFolders = findAllPostFolders(fullPath, currentRelPath);
folders.push(...subFolders);
}
return folders;
}
// Validate frontmatter
function validateFeedFrontmatter(
data: unknown,
folderPath: string
): FeedFrontmatter | null {
const result = FeedFrontmatterSchema.safeParse(data);
if (!result.success) {
logContentIssue(`Invalid frontmatter for ${folderPath}.`);
return null;
}
return result.data;
}
const PROSE_CHARACTERS_PER_MINUTE = 700;
const TABLE_READING_WEIGHT = 0.35;
const FENCED_CODE_BLOCK_REGEX = /```[\s\S]*?```/g;
const DETAILS_BLOCK_REGEX = /<details[\s\S]*?<\/details>/gi;
const IMAGE_LINK_REGEX = /!\[.*?\]\(.*?\)/g;
const MARKDOWN_LINK_REGEX = /\[(.*?)\]\(.*?\)/g;
const HTML_TAG_REGEX = /<\/?[^>]+>/g;
const MARKDOWN_DECORATION_REGEX = /[#*_`]/g;
const LEADING_MARKER_REGEX = /^\s*[>\-+]\s?/gm;
const TABLE_DELIMITER_REGEX = /^\|?[\s:-|]+\|?$/;
function normalizeReadableLine(line: string): string {
return line
.replace(HTML_TAG_REGEX, ' ')
.replace(MARKDOWN_DECORATION_REGEX, ' ')
.replace(LEADING_MARKER_REGEX, '')
.replace(/\s+/g, ' ')
.trim();
}
function weightedReadingLength(content: string): number {
const withoutHiddenContent = content
.replace(DETAILS_BLOCK_REGEX, ' ')
.replace(FENCED_CODE_BLOCK_REGEX, ' ')
.replace(IMAGE_LINK_REGEX, ' ')
.replace(MARKDOWN_LINK_REGEX, '$1');
const lines = withoutHiddenContent.split('\n');
let proseLength = 0;
let tableLength = 0;
for (const rawLine of lines) {
const line = rawLine.trim();
if (!line) {
continue;
}
if (line.startsWith('|')) {
if (TABLE_DELIMITER_REGEX.test(line)) {
continue;
}
const normalizedTableLine = normalizeReadableLine(
line.replace(/\|/g, ' ')
);
tableLength += normalizedTableLine.length;
continue;
}
proseLength += normalizeReadableLine(line).length;
}
return proseLength + Math.ceil(tableLength * TABLE_READING_WEIGHT);
}
// Calculate reading time from MDX content
export function calculateReadingTime(content: string): number {
const length = weightedReadingLength(content);
return Math.max(1, Math.ceil(length / PROSE_CHARACTERS_PER_MINUTE));
}
const CONTENT_IMAGE_SOURCE_REGEX =
/!\[[^\]]*]\(([^)\s]+(?:\s+"[^"]*")?)\)|<(?:img|Image)\b[^>]*?\bsrc=["']([^"']+)["'][^>]*?>/g;
function normalizeImageSource(source: string): string {
const trimmedSource = source.trim();
if (
trimmedSource.startsWith('<') &&
trimmedSource.endsWith('>') &&
trimmedSource.length > 2
) {
return trimmedSource.slice(1, -1);
}
const [urlToken] = trimmedSource.split(/\s+/);
return urlToken;
}
function extractFirstImageSource(content: string): string | undefined {
const matches = content.matchAll(CONTENT_IMAGE_SOURCE_REGEX);
for (const match of matches) {
const candidateSource = match[1] ?? match[2];
if (candidateSource) {
return normalizeImageSource(candidateSource);
}
}
return undefined;
}
// Load metadata from JSON file (folder path relative to posts/)
function loadMetadata(folderPath: string): FeedFrontmatter | null {
const metaPath = path.join(postsDirectory, folderPath, 'meta.json');
const metaContents = safeReadFile(metaPath);
if (!metaContents) {
logContentIssue(`Metadata file missing for ${folderPath}.`);
return null;
}
try {
const data = JSON.parse(metaContents);
const metadata = validateFeedFrontmatter(data, folderPath);
if (!metadata) {
return null;
}
const needsMdxRead = !metadata.readingTime || !metadata.image;
if (needsMdxRead) {
const mdxPath = path.join(postsDirectory, folderPath, 'index.mdx');
const mdxContents = safeReadFile(mdxPath);
if (mdxContents) {
if (!metadata.readingTime) {
metadata.readingTime = calculateReadingTime(mdxContents);
}
if (!metadata.image) {
metadata.image = extractFirstImageSource(mdxContents);
}
}
}
// Cache the slug -> folder path mapping
slugToFolderCache.set(metadata.slug, folderPath);
return metadata;
} catch {
logContentIssue(`Failed to parse metadata for ${folderPath}.`);
return null;
}
}
// Get folder path from slug (using cache or scanning)
export function getFolderSlug(slug: string): string | null {
const normalizedSlug = normalizeSlug(slug);
// Check cache first
if (slugToFolderCache.has(normalizedSlug)) {
return slugToFolderCache.get(normalizedSlug)!;
}
// Populate slug cache by loading full feed index first
getSortedFeedData({ includePrivate: true });
if (slugToFolderCache.has(normalizedSlug)) {
return slugToFolderCache.get(normalizedSlug)!;
}
if (isProduction) {
return null;
}
// If not cached, scan all folders to build cache
const allFolders = findAllPostFolders(postsDirectory);
for (const folderPath of allFolders) {
const metadata = loadMetadata(folderPath);
if (metadata?.slug === normalizedSlug) {
return folderPath;
}
}
return null;
}
// Get all feed slugs for static generation
export function getAllFeedSlugs(options: FeedQueryOptions = {}) {
return getSortedFeedData(options).map((feed) => ({ slug: feed.slug }));
}
// Get sorted feed data for listing pages
export function getSortedFeedData(options: FeedQueryOptions = {}): FeedData[] {
if (isProduction && cachedSortedFeedData) {
return filterListedPosts(cachedSortedFeedData, options);
}
if (!safeExists(postsDirectory)) {
logContentIssue('Posts directory does not exist.');
return [];
}
const allFolders = findAllPostFolders(postsDirectory);
const allFeedData = allFolders
.map((folderPath) => {
const metadata = loadMetadata(folderPath);
if (!metadata) {
logContentIssue(`Failed to load metadata for ${folderPath}.`);
return null;
}
return metadata as FeedData; // slug is already included in FeedFrontmatter
})
.filter((feed): feed is FeedData => feed !== null);
// Sort by date (newest first)
const sortedFeedData = allFeedData.sort((a, b) => {
if (a.date < b.date) {
return 1;
} else {
return -1;
}
});
if (isProduction) {
cachedSortedFeedData = sortedFeedData;
}
return filterListedPosts(sortedFeedData, options);
}
// Get single feed data with MDX component
export async function getFeedData(
slug: string,
options: FeedQueryOptions = {}
): Promise<Feed | null> {
const folderPath = getFolderSlug(slug);
if (!folderPath) {
logContentIssue(`Could not find folder for slug ${slug}.`);
return null;
}
const metadata = loadMetadata(folderPath);
if (!metadata) {
logContentIssue(`Failed to load metadata for ${folderPath}.`);
return null;
}
if (!isListedPost(metadata, options)) {
return null;
}
try {
// Dynamic import of MDX file using folder path
const mdxModule = await import(`@/../posts/${folderPath}/index.mdx`);
return {
...metadata,
Content: mdxModule.default,
} as Feed;
} catch {
logContentIssue(`Failed to load MDX content for ${folderPath}.`);
return null;
}
}