@mandujs/core 0.11.0 → 0.12.0

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.
@@ -0,0 +1,169 @@
1
+ /**
2
+ * File Loader - 단일 파일 로더
3
+ *
4
+ * JSON, YAML, TOML 파일을 로드하고 파싱
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * file({ path: 'data/settings.json' })
9
+ * file({ path: 'config/app.yaml' })
10
+ * ```
11
+ */
12
+
13
+ import type { Loader, FileLoaderOptions } from "./types";
14
+ import type { LoaderContext } from "../types";
15
+ import { LoaderError, ParseError } from "../types";
16
+ import { generateFileDigest } from "../digest";
17
+ import { inferParser } from "./types";
18
+ import * as fs from "fs";
19
+ import * as path from "path";
20
+
21
+ /**
22
+ * JSON 파싱
23
+ */
24
+ function parseJson(content: string, filePath: string): unknown {
25
+ try {
26
+ return JSON.parse(content);
27
+ } catch (error) {
28
+ throw new ParseError(
29
+ `Failed to parse JSON: ${error instanceof Error ? error.message : error}`,
30
+ undefined,
31
+ filePath
32
+ );
33
+ }
34
+ }
35
+
36
+ /**
37
+ * YAML 파싱 (동적 임포트)
38
+ */
39
+ async function parseYaml(content: string, filePath: string): Promise<unknown> {
40
+ try {
41
+ // yaml 패키지 동적 로드
42
+ const yaml = await import("yaml").catch(() => null);
43
+
44
+ if (!yaml) {
45
+ throw new Error("yaml package not installed. Run: pnpm add yaml");
46
+ }
47
+
48
+ return yaml.parse(content);
49
+ } catch (error) {
50
+ if (error instanceof Error && error.message.includes("not installed")) {
51
+ throw error;
52
+ }
53
+ throw new ParseError(
54
+ `Failed to parse YAML: ${error instanceof Error ? error.message : error}`,
55
+ undefined,
56
+ filePath
57
+ );
58
+ }
59
+ }
60
+
61
+ /**
62
+ * TOML 파싱 (동적 임포트)
63
+ */
64
+ async function parseToml(content: string, filePath: string): Promise<unknown> {
65
+ try {
66
+ // @iarna/toml 또는 toml 패키지 동적 로드
67
+ const toml = await import("@iarna/toml").catch(() =>
68
+ import("toml").catch(() => null)
69
+ );
70
+
71
+ if (!toml) {
72
+ throw new Error("toml package not installed. Run: pnpm add @iarna/toml");
73
+ }
74
+
75
+ return toml.parse(content);
76
+ } catch (error) {
77
+ if (error instanceof Error && error.message.includes("not installed")) {
78
+ throw error;
79
+ }
80
+ throw new ParseError(
81
+ `Failed to parse TOML: ${error instanceof Error ? error.message : error}`,
82
+ undefined,
83
+ filePath
84
+ );
85
+ }
86
+ }
87
+
88
+ /**
89
+ * File Loader 팩토리
90
+ */
91
+ export function file(options: FileLoaderOptions): Loader {
92
+ const { path: filePath, parser: explicitParser } = options;
93
+
94
+ return {
95
+ name: "file",
96
+
97
+ async load(context: LoaderContext): Promise<void> {
98
+ const { store, config, logger, parseData, generateDigest } = context;
99
+
100
+ // 절대 경로 계산
101
+ const absolutePath = path.isAbsolute(filePath)
102
+ ? filePath
103
+ : path.join(config.root, filePath);
104
+
105
+ // 파일 존재 확인
106
+ if (!fs.existsSync(absolutePath)) {
107
+ throw new LoaderError(
108
+ `File not found: ${absolutePath}`,
109
+ context.collection
110
+ );
111
+ }
112
+
113
+ // 파일 읽기
114
+ const content = fs.readFileSync(absolutePath, "utf-8");
115
+
116
+ // 다이제스트 생성
117
+ const digest = generateFileDigest(content);
118
+
119
+ // 기존 엔트리와 비교
120
+ const existingEntry = store.get("_single");
121
+ if (existingEntry?.digest === digest) {
122
+ logger.debug("File unchanged, skipping parse");
123
+ return;
124
+ }
125
+
126
+ // 파서 결정
127
+ const parserType = explicitParser ?? inferParser(absolutePath);
128
+
129
+ if (!parserType || parserType === "markdown") {
130
+ throw new LoaderError(
131
+ `Cannot determine parser for file: ${absolutePath}. Use .json, .yaml, .yml, or .toml extension, or specify parser option.`,
132
+ context.collection
133
+ );
134
+ }
135
+
136
+ // 파싱
137
+ let rawData: unknown;
138
+
139
+ switch (parserType) {
140
+ case "json":
141
+ rawData = parseJson(content, absolutePath);
142
+ break;
143
+ case "yaml":
144
+ rawData = await parseYaml(content, absolutePath);
145
+ break;
146
+ case "toml":
147
+ rawData = await parseToml(content, absolutePath);
148
+ break;
149
+ }
150
+
151
+ // 스키마 검증
152
+ const data = await parseData({
153
+ id: "_single",
154
+ data: rawData,
155
+ filePath: absolutePath,
156
+ });
157
+
158
+ // 저장
159
+ store.set({
160
+ id: "_single",
161
+ data: data as Record<string, unknown>,
162
+ filePath: absolutePath,
163
+ digest,
164
+ });
165
+
166
+ logger.info(`Loaded file: ${filePath}`);
167
+ },
168
+ };
169
+ }
@@ -0,0 +1,252 @@
1
+ /**
2
+ * Glob Loader - 패턴 매칭 파일 로더
3
+ *
4
+ * Glob 패턴으로 여러 파일을 로드 (Markdown, JSON 등)
5
+ *
6
+ * @example
7
+ * ```ts
8
+ * glob({ pattern: 'content/posts/**\/*.md' })
9
+ * glob({ pattern: ['content/blog/**\/*.md', 'content/news/**\/*.md'] })
10
+ * ```
11
+ */
12
+
13
+ import type { Loader, GlobLoaderOptions, ParsedMarkdown } from "./types";
14
+ import type { LoaderContext, DataEntry } from "../types";
15
+ import { LoaderError, ParseError } from "../types";
16
+ import { generateFileDigest, combineDigests } from "../digest";
17
+ import { inferParser, MARKDOWN_EXTENSIONS } from "./types";
18
+ import * as fs from "fs";
19
+ import * as path from "path";
20
+
21
+ // fast-glob 동적 임포트
22
+ async function fastGlob(patterns: string[], options: { onlyFiles: boolean; absolute: boolean }): Promise<string[]> {
23
+ const fg = await import("fast-glob");
24
+ return fg.glob(patterns, options);
25
+ }
26
+
27
+ /**
28
+ * 프론트매터 파싱 (---로 구분된 YAML)
29
+ */
30
+ async function parseFrontmatter(
31
+ content: string,
32
+ filePath: string
33
+ ): Promise<ParsedMarkdown> {
34
+ const frontmatterRegex = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
35
+ const match = content.match(frontmatterRegex);
36
+
37
+ if (!match) {
38
+ // 프론트매터 없음
39
+ return {
40
+ data: {},
41
+ body: content.trim(),
42
+ };
43
+ }
44
+
45
+ const [, rawFrontmatter, body] = match;
46
+
47
+ try {
48
+ // yaml 동적 로드
49
+ const yaml = await import("yaml").catch(() => null);
50
+
51
+ if (!yaml) {
52
+ // yaml 없으면 빈 데이터 반환
53
+ console.warn(
54
+ `[GlobLoader] yaml package not installed, frontmatter ignored for ${filePath}`
55
+ );
56
+ return {
57
+ data: {},
58
+ body: body.trim(),
59
+ rawFrontmatter,
60
+ };
61
+ }
62
+
63
+ const data = yaml.parse(rawFrontmatter) || {};
64
+
65
+ return {
66
+ data: typeof data === "object" ? data : {},
67
+ body: body.trim(),
68
+ rawFrontmatter,
69
+ };
70
+ } catch (error) {
71
+ throw new ParseError(
72
+ `Failed to parse frontmatter: ${error instanceof Error ? error.message : error}`,
73
+ undefined,
74
+ filePath
75
+ );
76
+ }
77
+ }
78
+
79
+ /**
80
+ * 파일 경로에서 ID 생성 (기본)
81
+ */
82
+ function defaultGenerateId(params: { filePath: string; base: string }): string {
83
+ const { filePath, base } = params;
84
+
85
+ // base 기준 상대 경로
86
+ const relativePath = path.relative(base, filePath);
87
+
88
+ // 확장자 제거, 경로 구분자를 슬래시로 통일
89
+ const withoutExt = relativePath.replace(/\.[^.]+$/, "");
90
+ const normalized = withoutExt.replace(/\\/g, "/");
91
+
92
+ // index 파일은 상위 폴더명 사용
93
+ if (normalized.endsWith("/index")) {
94
+ return normalized.slice(0, -6) || "index";
95
+ }
96
+
97
+ return normalized;
98
+ }
99
+
100
+ /**
101
+ * Glob Loader 팩토리
102
+ */
103
+ export function glob(options: GlobLoaderOptions): Loader {
104
+ const { pattern, base, generateId = defaultGenerateId } = options;
105
+
106
+ return {
107
+ name: "glob",
108
+
109
+ async load(context: LoaderContext): Promise<void> {
110
+ const { store, config, logger, parseData, renderMarkdown, watcher } = context;
111
+
112
+ // 기본 디렉토리
113
+ const baseDir = base
114
+ ? path.isAbsolute(base)
115
+ ? base
116
+ : path.join(config.root, base)
117
+ : config.root;
118
+
119
+ // 패턴 배열로 통일
120
+ const patterns = Array.isArray(pattern) ? pattern : [pattern];
121
+
122
+ // 절대 패턴으로 변환
123
+ const absolutePatterns = patterns.map((p) =>
124
+ path.isAbsolute(p) ? p : path.join(config.root, p)
125
+ );
126
+
127
+ // 파일 검색
128
+ const filePaths = await fastGlob(absolutePatterns, {
129
+ onlyFiles: true,
130
+ absolute: true,
131
+ });
132
+
133
+ if (filePaths.length === 0) {
134
+ logger.warn(`No files matched pattern: ${patterns.join(", ")}`);
135
+ return;
136
+ }
137
+
138
+ // 파일 감시 추가 (dev 모드)
139
+ if (watcher) {
140
+ watcher.add(absolutePatterns);
141
+ }
142
+
143
+ // 기존 엔트리 ID 수집 (삭제 감지용)
144
+ const existingIds = new Set(store.keys());
145
+ const processedIds = new Set<string>();
146
+
147
+ // 병렬 처리
148
+ await Promise.all(
149
+ filePaths.map(async (filePath) => {
150
+ const id = generateId({ filePath, base: baseDir });
151
+ processedIds.add(id);
152
+
153
+ try {
154
+ await processFile(context, filePath, id, baseDir);
155
+ } catch (error) {
156
+ logger.error(
157
+ `Failed to process ${filePath}: ${error instanceof Error ? error.message : error}`
158
+ );
159
+ }
160
+ })
161
+ );
162
+
163
+ // 삭제된 파일 처리
164
+ for (const id of existingIds) {
165
+ if (!processedIds.has(id)) {
166
+ store.delete(id);
167
+ logger.debug(`Removed deleted entry: ${id}`);
168
+ }
169
+ }
170
+
171
+ logger.info(`Processed ${processedIds.size} files`);
172
+ },
173
+ };
174
+ }
175
+
176
+ /**
177
+ * 단일 파일 처리
178
+ */
179
+ async function processFile(
180
+ context: LoaderContext,
181
+ filePath: string,
182
+ id: string,
183
+ baseDir: string
184
+ ): Promise<void> {
185
+ const { store, parseData, renderMarkdown, logger } = context;
186
+
187
+ // 파일 읽기
188
+ const content = fs.readFileSync(filePath, "utf-8");
189
+ const fileDigest = generateFileDigest(content);
190
+
191
+ // 기존 엔트리와 비교
192
+ const existingEntry = store.get(id);
193
+ if (existingEntry?.digest === fileDigest) {
194
+ logger.debug(`Unchanged: ${id}`);
195
+ return;
196
+ }
197
+
198
+ // 파서 타입 결정
199
+ const parserType = inferParser(filePath);
200
+
201
+ let entry: DataEntry;
202
+
203
+ if (parserType === "markdown") {
204
+ // Markdown 파일 처리
205
+ const parsed = await parseFrontmatter(content, filePath);
206
+
207
+ // 프론트매터 검증
208
+ const data = await parseData({
209
+ id,
210
+ data: parsed.data,
211
+ filePath,
212
+ });
213
+
214
+ // 다이제스트 (프론트매터 + 본문)
215
+ const digest = combineDigests([
216
+ fileDigest,
217
+ context.generateDigest(parsed.data),
218
+ ]);
219
+
220
+ entry = {
221
+ id,
222
+ data: data as Record<string, unknown>,
223
+ filePath,
224
+ body: parsed.body,
225
+ digest,
226
+ };
227
+
228
+ // Markdown 렌더링 (옵션)
229
+ if (renderMarkdown) {
230
+ entry.rendered = await renderMarkdown(parsed.body);
231
+ }
232
+ } else if (parserType === "json") {
233
+ // JSON 파일
234
+ const rawData = JSON.parse(content);
235
+ const data = await parseData({ id, data: rawData, filePath });
236
+
237
+ entry = {
238
+ id,
239
+ data: data as Record<string, unknown>,
240
+ filePath,
241
+ digest: fileDigest,
242
+ };
243
+ } else {
244
+ // 지원하지 않는 파일 타입
245
+ logger.warn(`Unsupported file type: ${filePath}`);
246
+ return;
247
+ }
248
+
249
+ // 저장
250
+ store.set(entry);
251
+ logger.debug(`Processed: ${id}`);
252
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Content Loaders - 빌트인 로더 모음
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * import { file, glob, api } from '@mandujs/core/content';
7
+ *
8
+ * export default defineContentConfig({
9
+ * collections: {
10
+ * settings: { loader: file({ path: 'data/settings.json' }) },
11
+ * posts: { loader: glob({ pattern: 'content/posts/**\/*.md' }) },
12
+ * products: { loader: api({ url: 'https://api.example.com/products' }) },
13
+ * },
14
+ * });
15
+ * ```
16
+ */
17
+
18
+ export { file } from "./file";
19
+ export { glob } from "./glob";
20
+ export { api } from "./api";
21
+
22
+ // 타입 재export
23
+ export type {
24
+ Loader,
25
+ FileLoaderOptions,
26
+ GlobLoaderOptions,
27
+ ApiLoaderOptions,
28
+ PaginationConfig,
29
+ ParsedMarkdown,
30
+ LoaderEntry,
31
+ LoaderFactory,
32
+ } from "./types";
33
+
34
+ export { inferParser, FILE_PARSERS, MARKDOWN_EXTENSIONS } from "./types";
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Loader Types - 로더 공통 인터페이스
3
+ *
4
+ * 모든 로더가 구현해야 하는 인터페이스와 유틸리티 타입
5
+ */
6
+
7
+ import type { ZodSchema } from "zod";
8
+ import type { LoaderContext, DataEntry, RenderedContent } from "../types";
9
+
10
+ /**
11
+ * 로더 인터페이스
12
+ */
13
+ export interface Loader {
14
+ /** 로더 이름 (디버깅용) */
15
+ name: string;
16
+ /** 콘텐츠 로드 함수 */
17
+ load: (context: LoaderContext) => Promise<void>;
18
+ /** 기본 스키마 (컬렉션 설정보다 우선순위 낮음) */
19
+ schema?: ZodSchema | (() => ZodSchema | Promise<ZodSchema>);
20
+ }
21
+
22
+ /**
23
+ * File Loader 옵션
24
+ */
25
+ export interface FileLoaderOptions {
26
+ /** 파일 경로 (프로젝트 루트 기준) */
27
+ path: string;
28
+ /** 파서 타입 (자동 감지됨) */
29
+ parser?: "json" | "yaml" | "toml";
30
+ }
31
+
32
+ /**
33
+ * Glob Loader 옵션
34
+ */
35
+ export interface GlobLoaderOptions {
36
+ /** Glob 패턴 */
37
+ pattern: string | string[];
38
+ /** 기본 디렉토리 */
39
+ base?: string;
40
+ /** ID 생성 함수 */
41
+ generateId?: (params: { filePath: string; base: string }) => string;
42
+ }
43
+
44
+ /**
45
+ * API Loader 옵션
46
+ */
47
+ export interface ApiLoaderOptions {
48
+ /** API URL */
49
+ url: string | (() => string | Promise<string>);
50
+ /** HTTP 메서드 */
51
+ method?: "GET" | "POST";
52
+ /** 요청 헤더 */
53
+ headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>);
54
+ /** 요청 바디 (POST) */
55
+ body?: unknown | (() => unknown | Promise<unknown>);
56
+ /** 응답 변환 */
57
+ transform?: (response: unknown) => unknown[] | Promise<unknown[]>;
58
+ /** 캐시 TTL (초) */
59
+ cacheTTL?: number;
60
+ /** 페이지네이션 설정 */
61
+ pagination?: PaginationConfig;
62
+ }
63
+
64
+ /**
65
+ * 페이지네이션 설정
66
+ */
67
+ export interface PaginationConfig {
68
+ /** 다음 페이지 URL 추출 */
69
+ getNextUrl?: (response: unknown, currentUrl: string) => string | null;
70
+ /** 총 페이지 수 추출 */
71
+ getTotalPages?: (response: unknown) => number;
72
+ /** 페이지 크기 */
73
+ pageSize?: number;
74
+ }
75
+
76
+ /**
77
+ * Markdown 프론트매터 파싱 결과
78
+ */
79
+ export interface ParsedMarkdown {
80
+ /** 프론트매터 데이터 */
81
+ data: Record<string, unknown>;
82
+ /** Markdown 본문 */
83
+ body: string;
84
+ /** 원본 프론트매터 문자열 */
85
+ rawFrontmatter?: string;
86
+ }
87
+
88
+ /**
89
+ * 로더 결과 엔트리 (store.set 전)
90
+ */
91
+ export interface LoaderEntry<T = Record<string, unknown>> {
92
+ /** 고유 ID */
93
+ id: string;
94
+ /** 데이터 */
95
+ data: T;
96
+ /** 파일 경로 (파일 기반) */
97
+ filePath?: string;
98
+ /** 본문 (Markdown 등) */
99
+ body?: string;
100
+ /** 다이제스트 */
101
+ digest?: string;
102
+ /** 렌더링된 콘텐츠 */
103
+ rendered?: RenderedContent;
104
+ }
105
+
106
+ /**
107
+ * 로더 팩토리 함수 타입
108
+ */
109
+ export type LoaderFactory<TOptions> = (options: TOptions) => Loader;
110
+
111
+ /**
112
+ * 지원 파일 확장자별 파서
113
+ */
114
+ export const FILE_PARSERS = {
115
+ ".json": "json",
116
+ ".yaml": "yaml",
117
+ ".yml": "yaml",
118
+ ".toml": "toml",
119
+ } as const;
120
+
121
+ /**
122
+ * Markdown 파일 확장자
123
+ */
124
+ export const MARKDOWN_EXTENSIONS = new Set([".md", ".mdx", ".markdown"]);
125
+
126
+ /**
127
+ * 파일 확장자로 파서 타입 추론
128
+ */
129
+ export function inferParser(filePath: string): "json" | "yaml" | "toml" | "markdown" | null {
130
+ const ext = filePath.toLowerCase().slice(filePath.lastIndexOf("."));
131
+
132
+ if (MARKDOWN_EXTENSIONS.has(ext)) {
133
+ return "markdown";
134
+ }
135
+
136
+ return FILE_PARSERS[ext as keyof typeof FILE_PARSERS] ?? null;
137
+ }