cms-renderer 0.2.6 → 0.2.9
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/lib/block-renderer.d.ts +7 -2
- package/dist/lib/block-renderer.js +7 -2
- package/dist/lib/block-renderer.js.map +1 -1
- package/dist/lib/block-toolbar.js +9 -61
- package/dist/lib/block-toolbar.js.map +1 -1
- package/dist/lib/cms-api.d.ts +7 -5
- package/dist/lib/cms-api.js +9 -5
- package/dist/lib/cms-api.js.map +1 -1
- package/dist/lib/renderer.d.ts +4 -7
- package/dist/lib/renderer.js +34 -9
- package/dist/lib/renderer.js.map +1 -1
- package/dist/lib/schema.d.ts +6 -3
- package/dist/lib/schema.js +34 -8
- package/dist/lib/schema.js.map +1 -1
- package/dist/lib/types.d.ts +21 -1
- package/package.json +2 -5
- package/dist/lib/data-utils.d.ts +0 -218
- package/dist/lib/data-utils.js +0 -250
- package/dist/lib/data-utils.js.map +0 -1
package/dist/lib/data-utils.d.ts
DELETED
|
@@ -1,218 +0,0 @@
|
|
|
1
|
-
import { Result } from './result.js';
|
|
2
|
-
import { BlockData } from './types.js';
|
|
3
|
-
import '@repo/cms-schema/blocks';
|
|
4
|
-
import 'react';
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* Data Fetching Utilities
|
|
8
|
-
*
|
|
9
|
-
* Three implementations showing the progression from naive to production-ready:
|
|
10
|
-
* - v1 (Naive): Direct await, crashes on any error
|
|
11
|
-
* - v2 (Defensive): Try-catch with null fallback
|
|
12
|
-
* - v3 (Robust): Result type, retry logic, timeout support
|
|
13
|
-
*
|
|
14
|
-
* The robust version (v3) is exported as the default `fetchPage`.
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
/**
|
|
18
|
-
* Page structure returned by the tRPC API.
|
|
19
|
-
*/
|
|
20
|
-
interface Page {
|
|
21
|
-
slug: string;
|
|
22
|
-
title: string;
|
|
23
|
-
blocks: BlockData[];
|
|
24
|
-
}
|
|
25
|
-
/**
|
|
26
|
-
* Error codes for data fetching failures.
|
|
27
|
-
*/
|
|
28
|
-
declare const FetchErrorCode: {
|
|
29
|
-
readonly INVALID_SLUG: "INVALID_SLUG";
|
|
30
|
-
readonly NOT_FOUND: "NOT_FOUND";
|
|
31
|
-
readonly NETWORK_ERROR: "NETWORK_ERROR";
|
|
32
|
-
readonly TIMEOUT: "TIMEOUT";
|
|
33
|
-
readonly PARSE_ERROR: "PARSE_ERROR";
|
|
34
|
-
readonly SERVER_ERROR: "SERVER_ERROR";
|
|
35
|
-
readonly RETRY_EXHAUSTED: "RETRY_EXHAUSTED";
|
|
36
|
-
};
|
|
37
|
-
type FetchErrorCode = (typeof FetchErrorCode)[keyof typeof FetchErrorCode];
|
|
38
|
-
/**
|
|
39
|
-
* Structured error for data fetching failures.
|
|
40
|
-
*/
|
|
41
|
-
interface FetchError {
|
|
42
|
-
code: FetchErrorCode;
|
|
43
|
-
message: string;
|
|
44
|
-
cause?: Error;
|
|
45
|
-
retryCount?: number;
|
|
46
|
-
}
|
|
47
|
-
/**
|
|
48
|
-
* Options for robust data fetching.
|
|
49
|
-
*/
|
|
50
|
-
interface FetchOptions {
|
|
51
|
-
/**
|
|
52
|
-
* Timeout in milliseconds.
|
|
53
|
-
* @default 10000 (10 seconds)
|
|
54
|
-
*/
|
|
55
|
-
timeout?: number;
|
|
56
|
-
/**
|
|
57
|
-
* Number of retry attempts for transient failures.
|
|
58
|
-
* @default 3
|
|
59
|
-
*/
|
|
60
|
-
retries?: number;
|
|
61
|
-
/**
|
|
62
|
-
* Base delay between retries in milliseconds.
|
|
63
|
-
* Uses exponential backoff: delay * 2^attempt
|
|
64
|
-
* @default 1000 (1 second)
|
|
65
|
-
*/
|
|
66
|
-
retryDelay?: number;
|
|
67
|
-
/**
|
|
68
|
-
* AbortSignal for cancellation support.
|
|
69
|
-
*/
|
|
70
|
-
signal?: AbortSignal;
|
|
71
|
-
}
|
|
72
|
-
/**
|
|
73
|
-
* Naive data fetcher - crashes on any error.
|
|
74
|
-
*
|
|
75
|
-
* DO NOT USE IN PRODUCTION. This is for demonstration only.
|
|
76
|
-
*
|
|
77
|
-
* Problems:
|
|
78
|
-
* - No input validation
|
|
79
|
-
* - No error handling
|
|
80
|
-
* - Will crash the entire app on network failure
|
|
81
|
-
* - No timeout protection
|
|
82
|
-
* - No retry logic for transient failures
|
|
83
|
-
*
|
|
84
|
-
* @example
|
|
85
|
-
* ```ts
|
|
86
|
-
* // This throws if slug is invalid or network fails
|
|
87
|
-
* const page = await fetchPageV1('demo');
|
|
88
|
-
* ```
|
|
89
|
-
*/
|
|
90
|
-
declare function fetchPageV1(slug: string): Promise<Page>;
|
|
91
|
-
/**
|
|
92
|
-
* Defensive data fetcher - catches errors but loses context.
|
|
93
|
-
*
|
|
94
|
-
* Better than v1 but still problematic:
|
|
95
|
-
* - Returns null on any error (loses error details)
|
|
96
|
-
* - Caller can't distinguish between 404 and network failure
|
|
97
|
-
* - No retry logic for transient failures
|
|
98
|
-
* - No timeout protection
|
|
99
|
-
*
|
|
100
|
-
* @example
|
|
101
|
-
* ```ts
|
|
102
|
-
* const page = await fetchPageV2(slug);
|
|
103
|
-
* if (!page) {
|
|
104
|
-
* // What went wrong? 404? Network? Timeout? We don't know.
|
|
105
|
-
* return <NotFound />;
|
|
106
|
-
* }
|
|
107
|
-
* ```
|
|
108
|
-
*/
|
|
109
|
-
declare function fetchPageV2(slug: string): Promise<Page | null>;
|
|
110
|
-
/**
|
|
111
|
-
* Robust data fetcher - production-ready with full error context.
|
|
112
|
-
*
|
|
113
|
-
* Features:
|
|
114
|
-
* - Input validation with specific error codes
|
|
115
|
-
* - Result type for explicit error handling
|
|
116
|
-
* - Automatic retry with exponential backoff
|
|
117
|
-
* - Timeout support via AbortController
|
|
118
|
-
* - Distinguishes between error types (404 vs network vs timeout)
|
|
119
|
-
* - Preserves error context for debugging
|
|
120
|
-
*
|
|
121
|
-
* @param slug - Page slug to fetch
|
|
122
|
-
* @param options - Fetch options (timeout, retries, etc.)
|
|
123
|
-
* @returns Result containing the page data or a structured error
|
|
124
|
-
*
|
|
125
|
-
* @example
|
|
126
|
-
* ```ts
|
|
127
|
-
* const result = await fetchPageV3('demo', {
|
|
128
|
-
* timeout: 5000,
|
|
129
|
-
* retries: 3,
|
|
130
|
-
* });
|
|
131
|
-
*
|
|
132
|
-
* if (!result.ok) {
|
|
133
|
-
* switch (result.error.code) {
|
|
134
|
-
* case 'NOT_FOUND':
|
|
135
|
-
* return <NotFoundPage slug={slug} />;
|
|
136
|
-
* case 'TIMEOUT':
|
|
137
|
-
* return <TimeoutError onRetry={handleRetry} />;
|
|
138
|
-
* case 'NETWORK_ERROR':
|
|
139
|
-
* return <NetworkError message={result.error.message} />;
|
|
140
|
-
* case 'RETRY_EXHAUSTED':
|
|
141
|
-
* return <RetryExhausted attempts={result.error.retryCount} />;
|
|
142
|
-
* default:
|
|
143
|
-
* return <GenericError />;
|
|
144
|
-
* }
|
|
145
|
-
* }
|
|
146
|
-
*
|
|
147
|
-
* return <PageRenderer page={result.value} />;
|
|
148
|
-
* ```
|
|
149
|
-
*/
|
|
150
|
-
declare function fetchPageV3(slug: string, options?: FetchOptions): Promise<Result<Page, FetchError>>;
|
|
151
|
-
/**
|
|
152
|
-
* Production-ready page fetcher.
|
|
153
|
-
*
|
|
154
|
-
* This is an alias for `fetchPageV3` - the robust implementation
|
|
155
|
-
* with validation, retry logic, and Result-based error handling.
|
|
156
|
-
*
|
|
157
|
-
* @example
|
|
158
|
-
* ```ts
|
|
159
|
-
* import { fetchPage } from '@/lib/data-utils';
|
|
160
|
-
*
|
|
161
|
-
* const result = await fetchPage('demo');
|
|
162
|
-
* if (!result.ok) {
|
|
163
|
-
* // Handle error with full context
|
|
164
|
-
* console.error(`[${result.error.code}] ${result.error.message}`);
|
|
165
|
-
* return null;
|
|
166
|
-
* }
|
|
167
|
-
* return result.value;
|
|
168
|
-
* ```
|
|
169
|
-
*/
|
|
170
|
-
declare const fetchPage: typeof fetchPageV3;
|
|
171
|
-
/**
|
|
172
|
-
* Validates a page slug format.
|
|
173
|
-
*
|
|
174
|
-
* @param slug - Slug to validate
|
|
175
|
-
* @returns true if slug is valid format
|
|
176
|
-
*/
|
|
177
|
-
declare function isValidSlug(slug: string): boolean;
|
|
178
|
-
/**
|
|
179
|
-
* Normalizes a slug (lowercase, trim, replace spaces with hyphens).
|
|
180
|
-
*
|
|
181
|
-
* @param input - Raw input to normalize
|
|
182
|
-
* @returns Normalized slug
|
|
183
|
-
*/
|
|
184
|
-
declare function normalizeSlug(input: string): string;
|
|
185
|
-
/**
|
|
186
|
-
* Prefetches multiple pages in parallel with Result types.
|
|
187
|
-
*
|
|
188
|
-
* @param slugs - Array of page slugs to fetch
|
|
189
|
-
* @param options - Fetch options applied to all requests
|
|
190
|
-
* @returns Array of Results for each page
|
|
191
|
-
*
|
|
192
|
-
* @example
|
|
193
|
-
* ```ts
|
|
194
|
-
* const results = await prefetchPages(['home', 'about', 'blog']);
|
|
195
|
-
* const errors = results.filter(r => !r.ok);
|
|
196
|
-
* if (errors.length > 0) {
|
|
197
|
-
* console.warn(`${errors.length} pages failed to load`);
|
|
198
|
-
* }
|
|
199
|
-
* ```
|
|
200
|
-
*/
|
|
201
|
-
declare function prefetchPages(slugs: string[], options?: FetchOptions): Promise<Result<Page, FetchError>[]>;
|
|
202
|
-
/**
|
|
203
|
-
* Fetches a page with stale-while-revalidate semantics.
|
|
204
|
-
* Returns cached data immediately if available, then updates in background.
|
|
205
|
-
*
|
|
206
|
-
* @param slug - Page slug to fetch
|
|
207
|
-
* @param cache - Cache storage (e.g., Map, localStorage wrapper)
|
|
208
|
-
* @param options - Fetch options
|
|
209
|
-
* @returns Cached data or fresh fetch result
|
|
210
|
-
*/
|
|
211
|
-
declare function fetchPageWithSWR(slug: string, cache: Map<string, {
|
|
212
|
-
data: Page;
|
|
213
|
-
timestamp: number;
|
|
214
|
-
}>, options?: FetchOptions & {
|
|
215
|
-
maxAge?: number;
|
|
216
|
-
}): Promise<Result<Page, FetchError>>;
|
|
217
|
-
|
|
218
|
-
export { type FetchError, FetchErrorCode, type FetchOptions, type Page, fetchPage, fetchPageV1, fetchPageV2, fetchPageV3, fetchPageWithSWR, isValidSlug, normalizeSlug, prefetchPages };
|
package/dist/lib/data-utils.js
DELETED
|
@@ -1,250 +0,0 @@
|
|
|
1
|
-
// lib/result.ts
|
|
2
|
-
function ok(value) {
|
|
3
|
-
return { ok: true, value };
|
|
4
|
-
}
|
|
5
|
-
function err(error) {
|
|
6
|
-
return { ok: false, error };
|
|
7
|
-
}
|
|
8
|
-
|
|
9
|
-
// lib/data-utils.ts
|
|
10
|
-
var FetchErrorCode = {
|
|
11
|
-
INVALID_SLUG: "INVALID_SLUG",
|
|
12
|
-
NOT_FOUND: "NOT_FOUND",
|
|
13
|
-
NETWORK_ERROR: "NETWORK_ERROR",
|
|
14
|
-
TIMEOUT: "TIMEOUT",
|
|
15
|
-
PARSE_ERROR: "PARSE_ERROR",
|
|
16
|
-
SERVER_ERROR: "SERVER_ERROR",
|
|
17
|
-
RETRY_EXHAUSTED: "RETRY_EXHAUSTED"
|
|
18
|
-
};
|
|
19
|
-
var DEFAULT_TIMEOUT = 1e4;
|
|
20
|
-
var DEFAULT_RETRIES = 3;
|
|
21
|
-
var DEFAULT_RETRY_DELAY = 1e3;
|
|
22
|
-
var TRANSIENT_STATUS_CODES = [408, 429, 500, 502, 503, 504];
|
|
23
|
-
var mockPages = {
|
|
24
|
-
demo: {
|
|
25
|
-
slug: "demo",
|
|
26
|
-
title: "Demo Page",
|
|
27
|
-
blocks: [
|
|
28
|
-
{
|
|
29
|
-
id: "mock-header-1",
|
|
30
|
-
type: "header",
|
|
31
|
-
content: {
|
|
32
|
-
headline: "Welcome",
|
|
33
|
-
alignment: "center"
|
|
34
|
-
}
|
|
35
|
-
},
|
|
36
|
-
{
|
|
37
|
-
id: "mock-article-1",
|
|
38
|
-
type: "article",
|
|
39
|
-
content: {
|
|
40
|
-
headline: "Getting Started",
|
|
41
|
-
body: "## Introduction\n\nThis is a demo article."
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
]
|
|
45
|
-
},
|
|
46
|
-
about: {
|
|
47
|
-
slug: "about",
|
|
48
|
-
title: "About Us",
|
|
49
|
-
blocks: [
|
|
50
|
-
{
|
|
51
|
-
id: "mock-header-2",
|
|
52
|
-
type: "header",
|
|
53
|
-
content: {
|
|
54
|
-
headline: "About Our Company",
|
|
55
|
-
alignment: "left"
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
]
|
|
59
|
-
}
|
|
60
|
-
};
|
|
61
|
-
function createFetchError(code, message, options = {}) {
|
|
62
|
-
return { code, message, ...options };
|
|
63
|
-
}
|
|
64
|
-
function delay(ms) {
|
|
65
|
-
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
66
|
-
}
|
|
67
|
-
function exponentialBackoff(baseDelay, attempt) {
|
|
68
|
-
const jitter = Math.random() * 100;
|
|
69
|
-
return baseDelay * 2 ** attempt + jitter;
|
|
70
|
-
}
|
|
71
|
-
function isTransientError(error) {
|
|
72
|
-
if (error instanceof Error) {
|
|
73
|
-
if (error.name === "TypeError" && error.message.includes("fetch")) {
|
|
74
|
-
return true;
|
|
75
|
-
}
|
|
76
|
-
for (const code of TRANSIENT_STATUS_CODES) {
|
|
77
|
-
if (error.message.includes(String(code))) {
|
|
78
|
-
return true;
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
return false;
|
|
83
|
-
}
|
|
84
|
-
async function simulateFetch(slug, signal) {
|
|
85
|
-
await delay(50 + Math.random() * 100);
|
|
86
|
-
if (signal?.aborted) {
|
|
87
|
-
throw new Error("Request aborted");
|
|
88
|
-
}
|
|
89
|
-
const page = mockPages[slug];
|
|
90
|
-
if (!page) {
|
|
91
|
-
const error = new Error(`Page not found: ${slug}`);
|
|
92
|
-
error.name = "NotFoundError";
|
|
93
|
-
throw error;
|
|
94
|
-
}
|
|
95
|
-
return page;
|
|
96
|
-
}
|
|
97
|
-
async function fetchPageV1(slug) {
|
|
98
|
-
return simulateFetch(slug);
|
|
99
|
-
}
|
|
100
|
-
async function fetchPageV2(slug) {
|
|
101
|
-
try {
|
|
102
|
-
if (!slug || typeof slug !== "string") {
|
|
103
|
-
return null;
|
|
104
|
-
}
|
|
105
|
-
return await simulateFetch(slug);
|
|
106
|
-
} catch {
|
|
107
|
-
return null;
|
|
108
|
-
}
|
|
109
|
-
}
|
|
110
|
-
async function fetchPageV3(slug, options = {}) {
|
|
111
|
-
const {
|
|
112
|
-
timeout = DEFAULT_TIMEOUT,
|
|
113
|
-
retries = DEFAULT_RETRIES,
|
|
114
|
-
retryDelay = DEFAULT_RETRY_DELAY,
|
|
115
|
-
signal: externalSignal
|
|
116
|
-
} = options;
|
|
117
|
-
if (slug === null || slug === void 0) {
|
|
118
|
-
return err(
|
|
119
|
-
createFetchError(
|
|
120
|
-
FetchErrorCode.INVALID_SLUG,
|
|
121
|
-
`Slug must be a string, received ${slug === null ? "null" : "undefined"}`
|
|
122
|
-
)
|
|
123
|
-
);
|
|
124
|
-
}
|
|
125
|
-
if (typeof slug !== "string") {
|
|
126
|
-
return err(
|
|
127
|
-
createFetchError(
|
|
128
|
-
FetchErrorCode.INVALID_SLUG,
|
|
129
|
-
`Slug must be a string, received ${typeof slug}`
|
|
130
|
-
)
|
|
131
|
-
);
|
|
132
|
-
}
|
|
133
|
-
const trimmedSlug = slug.trim();
|
|
134
|
-
if (trimmedSlug.length === 0) {
|
|
135
|
-
return err(createFetchError(FetchErrorCode.INVALID_SLUG, "Slug cannot be empty"));
|
|
136
|
-
}
|
|
137
|
-
const controller = new AbortController();
|
|
138
|
-
const { signal } = controller;
|
|
139
|
-
if (externalSignal) {
|
|
140
|
-
externalSignal.addEventListener("abort", () => controller.abort());
|
|
141
|
-
}
|
|
142
|
-
const timeoutId = setTimeout(() => controller.abort(), timeout);
|
|
143
|
-
let lastError;
|
|
144
|
-
let attempt = 0;
|
|
145
|
-
try {
|
|
146
|
-
while (attempt <= retries) {
|
|
147
|
-
try {
|
|
148
|
-
const page = await simulateFetch(trimmedSlug, signal);
|
|
149
|
-
clearTimeout(timeoutId);
|
|
150
|
-
return ok(page);
|
|
151
|
-
} catch (error) {
|
|
152
|
-
lastError = error instanceof Error ? error : new Error(String(error));
|
|
153
|
-
if (signal.aborted) {
|
|
154
|
-
clearTimeout(timeoutId);
|
|
155
|
-
return err(
|
|
156
|
-
createFetchError(FetchErrorCode.TIMEOUT, `Request timed out after ${timeout}ms`, {
|
|
157
|
-
cause: lastError
|
|
158
|
-
})
|
|
159
|
-
);
|
|
160
|
-
}
|
|
161
|
-
if (lastError.name === "NotFoundError") {
|
|
162
|
-
clearTimeout(timeoutId);
|
|
163
|
-
return err(
|
|
164
|
-
createFetchError(FetchErrorCode.NOT_FOUND, `Page "${trimmedSlug}" not found`, {
|
|
165
|
-
cause: lastError
|
|
166
|
-
})
|
|
167
|
-
);
|
|
168
|
-
}
|
|
169
|
-
if (attempt < retries && isTransientError(lastError)) {
|
|
170
|
-
attempt++;
|
|
171
|
-
const backoff = exponentialBackoff(retryDelay, attempt);
|
|
172
|
-
if (process.env.NODE_ENV === "development") {
|
|
173
|
-
console.warn(
|
|
174
|
-
`[fetchPageV3] Retry ${attempt}/${retries} for "${trimmedSlug}" after ${Math.round(backoff)}ms`
|
|
175
|
-
);
|
|
176
|
-
}
|
|
177
|
-
await delay(backoff);
|
|
178
|
-
continue;
|
|
179
|
-
}
|
|
180
|
-
break;
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
clearTimeout(timeoutId);
|
|
184
|
-
if (attempt >= retries) {
|
|
185
|
-
return err(
|
|
186
|
-
createFetchError(FetchErrorCode.RETRY_EXHAUSTED, `Failed after ${retries} retry attempts`, {
|
|
187
|
-
cause: lastError,
|
|
188
|
-
retryCount: attempt
|
|
189
|
-
})
|
|
190
|
-
);
|
|
191
|
-
}
|
|
192
|
-
return err(
|
|
193
|
-
createFetchError(
|
|
194
|
-
FetchErrorCode.NETWORK_ERROR,
|
|
195
|
-
lastError?.message ?? "Unknown network error",
|
|
196
|
-
{ cause: lastError }
|
|
197
|
-
)
|
|
198
|
-
);
|
|
199
|
-
} catch (error) {
|
|
200
|
-
clearTimeout(timeoutId);
|
|
201
|
-
const cause = error instanceof Error ? error : new Error(String(error));
|
|
202
|
-
return err(
|
|
203
|
-
createFetchError(FetchErrorCode.SERVER_ERROR, `Unexpected error: ${cause.message}`, { cause })
|
|
204
|
-
);
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
var fetchPage = fetchPageV3;
|
|
208
|
-
function isValidSlug(slug) {
|
|
209
|
-
return /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug);
|
|
210
|
-
}
|
|
211
|
-
function normalizeSlug(input) {
|
|
212
|
-
return input.toLowerCase().trim().replace(/\s+/g, "-").replace(/[^a-z0-9-]/g, "").replace(/-+/g, "-").replace(/^-|-$/g, "");
|
|
213
|
-
}
|
|
214
|
-
async function prefetchPages(slugs, options) {
|
|
215
|
-
return Promise.all(slugs.map((slug) => fetchPageV3(slug, options)));
|
|
216
|
-
}
|
|
217
|
-
async function fetchPageWithSWR(slug, cache, options = {}) {
|
|
218
|
-
const { maxAge = 6e4 } = options;
|
|
219
|
-
const cached = cache.get(slug);
|
|
220
|
-
const now = Date.now();
|
|
221
|
-
if (cached && now - cached.timestamp < maxAge) {
|
|
222
|
-
return ok(cached.data);
|
|
223
|
-
}
|
|
224
|
-
const result = await fetchPageV3(slug, options);
|
|
225
|
-
if (result.ok) {
|
|
226
|
-
cache.set(slug, { data: result.value, timestamp: now });
|
|
227
|
-
}
|
|
228
|
-
if (!result.ok && cached) {
|
|
229
|
-
if (process.env.NODE_ENV === "development") {
|
|
230
|
-
console.warn(
|
|
231
|
-
`[fetchPageWithSWR] Returning stale cache for "${slug}" after fetch failure:`,
|
|
232
|
-
result.error.message
|
|
233
|
-
);
|
|
234
|
-
}
|
|
235
|
-
return ok(cached.data);
|
|
236
|
-
}
|
|
237
|
-
return result;
|
|
238
|
-
}
|
|
239
|
-
export {
|
|
240
|
-
FetchErrorCode,
|
|
241
|
-
fetchPage,
|
|
242
|
-
fetchPageV1,
|
|
243
|
-
fetchPageV2,
|
|
244
|
-
fetchPageV3,
|
|
245
|
-
fetchPageWithSWR,
|
|
246
|
-
isValidSlug,
|
|
247
|
-
normalizeSlug,
|
|
248
|
-
prefetchPages
|
|
249
|
-
};
|
|
250
|
-
//# sourceMappingURL=data-utils.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../lib/result.ts","../../lib/data-utils.ts"],"sourcesContent":["/**\n * Result Type Utilities\n *\n * Go-style error handling with discriminated union types.\n * Provides type-safe success/error handling without exceptions.\n *\n * @example\n * ```ts\n * const [err, data] = await handle(async () => {\n * const response = await fetch(url);\n * if (!response.ok) throw new Error(`HTTP ${response.status}`);\n * return response.json();\n * });\n *\n * if (err) {\n * console.error('Failed:', err.message);\n * return { error: err.message };\n * }\n * return { data };\n * ```\n */\n\n// -----------------------------------------------------------------------------\n// Result Type\n// -----------------------------------------------------------------------------\n\n/**\n * A discriminated union representing either success or failure.\n *\n * @template T - The success value type\n * @template E - The error type (defaults to Error)\n *\n * @example\n * ```ts\n * function divide(a: number, b: number): Result<number, string> {\n * if (b === 0) return err('Division by zero');\n * return ok(a / b);\n * }\n *\n * const result = divide(10, 2);\n * if (isOk(result)) {\n * console.log('Result:', result.value); // 5\n * } else {\n * console.error('Error:', result.error);\n * }\n * ```\n */\nexport type Result<T, E = Error> = { ok: true; value: T } | { ok: false; error: E };\n\n// -----------------------------------------------------------------------------\n// Constructors\n// -----------------------------------------------------------------------------\n\n/**\n * Creates a success Result.\n *\n * @param value - The success value\n * @returns A success Result containing the value\n *\n * @example\n * ```ts\n * const result = ok(42);\n * // { ok: true, value: 42 }\n * ```\n */\nexport function ok<T>(value: T): Result<T, never> {\n return { ok: true, value };\n}\n\n/**\n * Creates a failure Result.\n *\n * @param error - The error value\n * @returns A failure Result containing the error\n *\n * @example\n * ```ts\n * const result = err(new Error('Something went wrong'));\n * // { ok: false, error: Error('Something went wrong') }\n * ```\n */\nexport function err<E>(error: E): Result<never, E> {\n return { ok: false, error };\n}\n\n// -----------------------------------------------------------------------------\n// Type Guards\n// -----------------------------------------------------------------------------\n\n/**\n * Type guard to check if a Result is successful.\n *\n * @param result - The Result to check\n * @returns true if the Result is a success\n *\n * @example\n * ```ts\n * const result = fetchData();\n * if (isOk(result)) {\n * // TypeScript knows result.value exists here\n * console.log(result.value);\n * }\n * ```\n */\nexport function isOk<T, E>(result: Result<T, E>): result is { ok: true; value: T } {\n return result.ok === true;\n}\n\n/**\n * Type guard to check if a Result is a failure.\n *\n * @param result - The Result to check\n * @returns true if the Result is a failure\n *\n * @example\n * ```ts\n * const result = fetchData();\n * if (isErr(result)) {\n * // TypeScript knows result.error exists here\n * console.error(result.error);\n * }\n * ```\n */\nexport function isErr<T, E>(result: Result<T, E>): result is { ok: false; error: E } {\n return result.ok === false;\n}\n\n// -----------------------------------------------------------------------------\n// Extractors\n// -----------------------------------------------------------------------------\n\n/**\n * Extracts the value from a Result, throwing if it's an error.\n *\n * @param result - The Result to unwrap\n * @returns The success value\n * @throws The error if Result is a failure\n *\n * @example\n * ```ts\n * const result = ok(42);\n * const value = unwrap(result); // 42\n *\n * const errorResult = err(new Error('fail'));\n * const value2 = unwrap(errorResult); // throws Error('fail')\n * ```\n */\nexport function unwrap<T, E>(result: Result<T, E>): T {\n if (isOk(result)) {\n return result.value;\n }\n throw result.error;\n}\n\n/**\n * Extracts the value from a Result, returning a default on error.\n *\n * @param result - The Result to unwrap\n * @param defaultValue - The value to return if Result is an error\n * @returns The success value or the default value\n *\n * @example\n * ```ts\n * const result = err(new Error('fail'));\n * const value = unwrapOr(result, 0); // 0\n *\n * const okResult = ok(42);\n * const value2 = unwrapOr(okResult, 0); // 42\n * ```\n */\nexport function unwrapOr<T, E>(result: Result<T, E>, defaultValue: T): T {\n if (isOk(result)) {\n return result.value;\n }\n return defaultValue;\n}\n\n/**\n * Extracts the value from a Result, computing a default on error.\n *\n * @param result - The Result to unwrap\n * @param fn - Function to compute the default value from the error\n * @returns The success value or the computed default\n *\n * @example\n * ```ts\n * const result = err(new Error('not found'));\n * const value = unwrapOrElse(result, (e) => {\n * console.error('Error:', e.message);\n * return [];\n * });\n * ```\n */\nexport function unwrapOrElse<T, E>(result: Result<T, E>, fn: (error: E) => T): T {\n if (isOk(result)) {\n return result.value;\n }\n return fn(result.error);\n}\n\n// -----------------------------------------------------------------------------\n// Transformers\n// -----------------------------------------------------------------------------\n\n/**\n * Maps a successful Result's value.\n *\n * @param result - The Result to map\n * @param fn - Function to transform the value\n * @returns A new Result with the transformed value, or the original error\n *\n * @example\n * ```ts\n * const result = ok(5);\n * const doubled = map(result, (n) => n * 2); // ok(10)\n *\n * const errorResult = err('fail');\n * const still = map(errorResult, (n) => n * 2); // err('fail')\n * ```\n */\nexport function map<T, U, E>(result: Result<T, E>, fn: (value: T) => U): Result<U, E> {\n if (isOk(result)) {\n return ok(fn(result.value));\n }\n return result;\n}\n\n/**\n * Maps a failed Result's error.\n *\n * @param result - The Result to map\n * @param fn - Function to transform the error\n * @returns A new Result with the transformed error, or the original value\n *\n * @example\n * ```ts\n * const result = err('not found');\n * const mapped = mapErr(result, (e) => new Error(e)); // err(Error('not found'))\n * ```\n */\nexport function mapErr<T, E, F>(result: Result<T, E>, fn: (error: E) => F): Result<T, F> {\n if (isErr(result)) {\n return err(fn(result.error));\n }\n return result;\n}\n\n/**\n * Chains Result-returning operations.\n *\n * @param result - The Result to chain from\n * @param fn - Function that returns a new Result\n * @returns The chained Result\n *\n * @example\n * ```ts\n * function parse(input: string): Result<number, string> {\n * const n = parseInt(input, 10);\n * return isNaN(n) ? err('not a number') : ok(n);\n * }\n *\n * function double(n: number): Result<number, string> {\n * return ok(n * 2);\n * }\n *\n * const result = flatMap(parse('5'), double); // ok(10)\n * const fail = flatMap(parse('abc'), double); // err('not a number')\n * ```\n */\nexport function flatMap<T, U, E>(\n result: Result<T, E>,\n fn: (value: T) => Result<U, E>\n): Result<U, E> {\n if (isOk(result)) {\n return fn(result.value);\n }\n return result;\n}\n\n// -----------------------------------------------------------------------------\n// Async Helpers\n// -----------------------------------------------------------------------------\n\n/**\n * Wraps a Promise in a Result type.\n *\n * @param promise - The Promise to wrap\n * @returns A Promise that resolves to a Result\n *\n * @example\n * ```ts\n * const result = await fromPromise(fetch('/api/data'));\n * if (isErr(result)) {\n * console.error('Fetch failed:', result.error);\n * return;\n * }\n * const response = result.value;\n * ```\n */\nexport async function fromPromise<T>(promise: Promise<T>): Promise<Result<T, Error>> {\n try {\n const value = await promise;\n return ok(value);\n } catch (error) {\n return err(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\n/**\n * Wraps a throwing function in a Result type.\n *\n * @param fn - The function to wrap\n * @returns A Result containing the return value or the thrown error\n *\n * @example\n * ```ts\n * const result = tryCatch(() => JSON.parse(input));\n * if (isErr(result)) {\n * console.error('Invalid JSON:', result.error);\n * return null;\n * }\n * return result.value;\n * ```\n */\nexport function tryCatch<T>(fn: () => T): Result<T, Error> {\n try {\n return ok(fn());\n } catch (error) {\n return err(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\n/**\n * Wraps an async function in a Result type.\n *\n * @param fn - The async function to wrap\n * @returns A Promise that resolves to a Result\n *\n * @example\n * ```ts\n * const result = await tryCatchAsync(async () => {\n * const response = await fetch('/api/data');\n * if (!response.ok) throw new Error(`HTTP ${response.status}`);\n * return response.json();\n * });\n * ```\n */\nexport async function tryCatchAsync<T>(fn: () => Promise<T>): Promise<Result<T, Error>> {\n try {\n const value = await fn();\n return ok(value);\n } catch (error) {\n return err(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\n// -----------------------------------------------------------------------------\n// Tuple Helpers (Go-style)\n// -----------------------------------------------------------------------------\n\n/**\n * Go-style tuple for error handling: [error, value]\n *\n * @example\n * ```ts\n * const [err, data] = await handle(fetchData);\n * if (err) {\n * console.error(err);\n * return;\n * }\n * console.log(data);\n * ```\n */\nexport type GoTuple<T, E = Error> = [E, undefined] | [undefined, T];\n\n/**\n * Converts a Result to a Go-style tuple.\n *\n * @param result - The Result to convert\n * @returns A tuple of [error, value]\n *\n * @example\n * ```ts\n * const result = await fetchData();\n * const [err, data] = toTuple(result);\n * ```\n */\nexport function toTuple<T, E>(result: Result<T, E>): GoTuple<T, E> {\n if (isOk(result)) {\n return [undefined, result.value];\n }\n return [result.error, undefined];\n}\n\n/**\n * Wraps an async function and returns a Go-style tuple.\n *\n * @param fn - The async function to wrap\n * @returns A Promise that resolves to [error, value] tuple\n *\n * @example\n * ```ts\n * const [err, data] = await handle(async () => {\n * const res = await fetch('/api/users');\n * if (!res.ok) throw new Error(`HTTP ${res.status}`);\n * return res.json();\n * });\n *\n * if (err) {\n * console.error('Failed to fetch users:', err.message);\n * return [];\n * }\n * return data;\n * ```\n */\nexport async function handle<T>(fn: () => Promise<T>): Promise<GoTuple<T, Error>> {\n try {\n const value = await fn();\n return [undefined, value];\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n return [err, undefined];\n }\n}\n\n/**\n * Wraps a synchronous function and returns a Go-style tuple.\n *\n * @param fn - The function to wrap\n * @returns A tuple of [error, value]\n *\n * @example\n * ```ts\n * const [err, parsed] = handleSync(() => JSON.parse(input));\n * if (err) {\n * console.error('Invalid JSON:', err.message);\n * return null;\n * }\n * return parsed;\n * ```\n */\nexport function handleSync<T>(fn: () => T): GoTuple<T, Error> {\n try {\n const value = fn();\n return [undefined, value];\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n return [err, undefined];\n }\n}\n","/**\n * Data Fetching Utilities\n *\n * Three implementations showing the progression from naive to production-ready:\n * - v1 (Naive): Direct await, crashes on any error\n * - v2 (Defensive): Try-catch with null fallback\n * - v3 (Robust): Result type, retry logic, timeout support\n *\n * The robust version (v3) is exported as the default `fetchPage`.\n */\n\nimport { err, ok, type Result } from './result';\nimport type { BlockData } from './types';\n\n// -----------------------------------------------------------------------------\n// Types\n// -----------------------------------------------------------------------------\n\n/**\n * Page structure returned by the tRPC API.\n */\nexport interface Page {\n slug: string;\n title: string;\n blocks: BlockData[];\n}\n\n/**\n * Error codes for data fetching failures.\n */\nexport const FetchErrorCode = {\n INVALID_SLUG: 'INVALID_SLUG',\n NOT_FOUND: 'NOT_FOUND',\n NETWORK_ERROR: 'NETWORK_ERROR',\n TIMEOUT: 'TIMEOUT',\n PARSE_ERROR: 'PARSE_ERROR',\n SERVER_ERROR: 'SERVER_ERROR',\n RETRY_EXHAUSTED: 'RETRY_EXHAUSTED',\n} as const;\n\nexport type FetchErrorCode = (typeof FetchErrorCode)[keyof typeof FetchErrorCode];\n\n/**\n * Structured error for data fetching failures.\n */\nexport interface FetchError {\n code: FetchErrorCode;\n message: string;\n cause?: Error;\n retryCount?: number;\n}\n\n/**\n * Options for robust data fetching.\n */\nexport interface FetchOptions {\n /**\n * Timeout in milliseconds.\n * @default 10000 (10 seconds)\n */\n timeout?: number;\n\n /**\n * Number of retry attempts for transient failures.\n * @default 3\n */\n retries?: number;\n\n /**\n * Base delay between retries in milliseconds.\n * Uses exponential backoff: delay * 2^attempt\n * @default 1000 (1 second)\n */\n retryDelay?: number;\n\n /**\n * AbortSignal for cancellation support.\n */\n signal?: AbortSignal;\n}\n\n// -----------------------------------------------------------------------------\n// Constants\n// -----------------------------------------------------------------------------\n\nconst DEFAULT_TIMEOUT = 10_000; // 10 seconds\nconst DEFAULT_RETRIES = 3;\nconst DEFAULT_RETRY_DELAY = 1_000; // 1 second\n\n/**\n * HTTP status codes that indicate transient failures (should retry).\n */\nconst TRANSIENT_STATUS_CODES = [408, 429, 500, 502, 503, 504] as const;\n\n// -----------------------------------------------------------------------------\n// Mock Data Store (for demonstration)\n// -----------------------------------------------------------------------------\n\n/**\n * Simulated data store.\n * In production, this would be replaced with actual tRPC/API calls.\n */\nconst mockPages: Record<string, Page> = {\n demo: {\n slug: 'demo',\n title: 'Demo Page',\n blocks: [\n {\n id: 'mock-header-1',\n type: 'header',\n content: {\n headline: 'Welcome',\n alignment: 'center',\n },\n },\n {\n id: 'mock-article-1',\n type: 'article',\n content: {\n headline: 'Getting Started',\n body: '## Introduction\\n\\nThis is a demo article.',\n },\n },\n ],\n },\n about: {\n slug: 'about',\n title: 'About Us',\n blocks: [\n {\n id: 'mock-header-2',\n type: 'header',\n content: {\n headline: 'About Our Company',\n alignment: 'left',\n },\n },\n ],\n },\n};\n\n// -----------------------------------------------------------------------------\n// Helper Functions\n// -----------------------------------------------------------------------------\n\n/**\n * Creates a FetchError with the given code and message.\n */\nfunction createFetchError(\n code: FetchErrorCode,\n message: string,\n options: { cause?: Error; retryCount?: number } = {}\n): FetchError {\n return { code, message, ...options };\n}\n\n/**\n * Delays execution for the specified duration.\n */\nfunction delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Calculates exponential backoff delay.\n */\nfunction exponentialBackoff(baseDelay: number, attempt: number): number {\n // Add jitter to prevent thundering herd\n const jitter = Math.random() * 100;\n return baseDelay * 2 ** attempt + jitter;\n}\n\n/**\n * Checks if an error represents a transient failure that should be retried.\n */\nfunction isTransientError(error: unknown): boolean {\n if (error instanceof Error) {\n // Network errors\n if (error.name === 'TypeError' && error.message.includes('fetch')) {\n return true;\n }\n // Check for HTTP status codes in error message\n for (const code of TRANSIENT_STATUS_CODES) {\n if (error.message.includes(String(code))) {\n return true;\n }\n }\n }\n return false;\n}\n\n/**\n * Simulates a network request with configurable behavior.\n * In production, this would be an actual fetch/tRPC call.\n */\nasync function simulateFetch(slug: string, signal?: AbortSignal): Promise<Page> {\n // Simulate network latency\n await delay(50 + Math.random() * 100);\n\n // Check for cancellation\n if (signal?.aborted) {\n throw new Error('Request aborted');\n }\n\n const page = mockPages[slug];\n if (!page) {\n const error = new Error(`Page not found: ${slug}`);\n error.name = 'NotFoundError';\n throw error;\n }\n\n return page;\n}\n\n// -----------------------------------------------------------------------------\n// V1: Naive Implementation\n// -----------------------------------------------------------------------------\n\n/**\n * Naive data fetcher - crashes on any error.\n *\n * DO NOT USE IN PRODUCTION. This is for demonstration only.\n *\n * Problems:\n * - No input validation\n * - No error handling\n * - Will crash the entire app on network failure\n * - No timeout protection\n * - No retry logic for transient failures\n *\n * @example\n * ```ts\n * // This throws if slug is invalid or network fails\n * const page = await fetchPageV1('demo');\n * ```\n */\nexport async function fetchPageV1(slug: string): Promise<Page> {\n // Direct await - any error crashes the caller\n return simulateFetch(slug);\n}\n\n// -----------------------------------------------------------------------------\n// V2: Defensive Implementation\n// -----------------------------------------------------------------------------\n\n/**\n * Defensive data fetcher - catches errors but loses context.\n *\n * Better than v1 but still problematic:\n * - Returns null on any error (loses error details)\n * - Caller can't distinguish between 404 and network failure\n * - No retry logic for transient failures\n * - No timeout protection\n *\n * @example\n * ```ts\n * const page = await fetchPageV2(slug);\n * if (!page) {\n * // What went wrong? 404? Network? Timeout? We don't know.\n * return <NotFound />;\n * }\n * ```\n */\nexport async function fetchPageV2(slug: string): Promise<Page | null> {\n try {\n // Basic validation\n if (!slug || typeof slug !== 'string') {\n return null;\n }\n\n return await simulateFetch(slug);\n } catch {\n // All errors become null - we lose valuable context\n return null;\n }\n}\n\n// -----------------------------------------------------------------------------\n// V3: Robust Implementation\n// -----------------------------------------------------------------------------\n\n/**\n * Robust data fetcher - production-ready with full error context.\n *\n * Features:\n * - Input validation with specific error codes\n * - Result type for explicit error handling\n * - Automatic retry with exponential backoff\n * - Timeout support via AbortController\n * - Distinguishes between error types (404 vs network vs timeout)\n * - Preserves error context for debugging\n *\n * @param slug - Page slug to fetch\n * @param options - Fetch options (timeout, retries, etc.)\n * @returns Result containing the page data or a structured error\n *\n * @example\n * ```ts\n * const result = await fetchPageV3('demo', {\n * timeout: 5000,\n * retries: 3,\n * });\n *\n * if (!result.ok) {\n * switch (result.error.code) {\n * case 'NOT_FOUND':\n * return <NotFoundPage slug={slug} />;\n * case 'TIMEOUT':\n * return <TimeoutError onRetry={handleRetry} />;\n * case 'NETWORK_ERROR':\n * return <NetworkError message={result.error.message} />;\n * case 'RETRY_EXHAUSTED':\n * return <RetryExhausted attempts={result.error.retryCount} />;\n * default:\n * return <GenericError />;\n * }\n * }\n *\n * return <PageRenderer page={result.value} />;\n * ```\n */\nexport async function fetchPageV3(\n slug: string,\n options: FetchOptions = {}\n): Promise<Result<Page, FetchError>> {\n const {\n timeout = DEFAULT_TIMEOUT,\n retries = DEFAULT_RETRIES,\n retryDelay = DEFAULT_RETRY_DELAY,\n signal: externalSignal,\n } = options;\n\n // 1. Validate input\n if (slug === null || slug === undefined) {\n return err(\n createFetchError(\n FetchErrorCode.INVALID_SLUG,\n `Slug must be a string, received ${slug === null ? 'null' : 'undefined'}`\n )\n );\n }\n\n if (typeof slug !== 'string') {\n return err(\n createFetchError(\n FetchErrorCode.INVALID_SLUG,\n `Slug must be a string, received ${typeof slug}`\n )\n );\n }\n\n const trimmedSlug = slug.trim();\n if (trimmedSlug.length === 0) {\n return err(createFetchError(FetchErrorCode.INVALID_SLUG, 'Slug cannot be empty'));\n }\n\n // 2. Create abort controller for timeout\n const controller = new AbortController();\n const { signal } = controller;\n\n // Link external signal if provided\n if (externalSignal) {\n externalSignal.addEventListener('abort', () => controller.abort());\n }\n\n // 3. Set up timeout\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n // 4. Attempt fetch with retry logic\n let lastError: Error | undefined;\n let attempt = 0;\n\n try {\n while (attempt <= retries) {\n try {\n const page = await simulateFetch(trimmedSlug, signal);\n clearTimeout(timeoutId);\n return ok(page);\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n\n // Check for abort/timeout\n if (signal.aborted) {\n clearTimeout(timeoutId);\n return err(\n createFetchError(FetchErrorCode.TIMEOUT, `Request timed out after ${timeout}ms`, {\n cause: lastError,\n })\n );\n }\n\n // Check for 404 (not retryable)\n if (lastError.name === 'NotFoundError') {\n clearTimeout(timeoutId);\n return err(\n createFetchError(FetchErrorCode.NOT_FOUND, `Page \"${trimmedSlug}\" not found`, {\n cause: lastError,\n })\n );\n }\n\n // Check if we should retry\n if (attempt < retries && isTransientError(lastError)) {\n attempt++;\n const backoff = exponentialBackoff(retryDelay, attempt);\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `[fetchPageV3] Retry ${attempt}/${retries} for \"${trimmedSlug}\" after ${Math.round(backoff)}ms`\n );\n }\n await delay(backoff);\n continue;\n }\n\n // No more retries or non-transient error\n break;\n }\n }\n\n // 5. All retries exhausted\n clearTimeout(timeoutId);\n\n if (attempt >= retries) {\n return err(\n createFetchError(FetchErrorCode.RETRY_EXHAUSTED, `Failed after ${retries} retry attempts`, {\n cause: lastError,\n retryCount: attempt,\n })\n );\n }\n\n // Non-retryable error\n return err(\n createFetchError(\n FetchErrorCode.NETWORK_ERROR,\n lastError?.message ?? 'Unknown network error',\n { cause: lastError }\n )\n );\n } catch (error) {\n clearTimeout(timeoutId);\n const cause = error instanceof Error ? error : new Error(String(error));\n return err(\n createFetchError(FetchErrorCode.SERVER_ERROR, `Unexpected error: ${cause.message}`, { cause })\n );\n }\n}\n\n// -----------------------------------------------------------------------------\n// Default Export\n// -----------------------------------------------------------------------------\n\n/**\n * Production-ready page fetcher.\n *\n * This is an alias for `fetchPageV3` - the robust implementation\n * with validation, retry logic, and Result-based error handling.\n *\n * @example\n * ```ts\n * import { fetchPage } from '@/lib/data-utils';\n *\n * const result = await fetchPage('demo');\n * if (!result.ok) {\n * // Handle error with full context\n * console.error(`[${result.error.code}] ${result.error.message}`);\n * return null;\n * }\n * return result.value;\n * ```\n */\nexport const fetchPage = fetchPageV3;\n\n// -----------------------------------------------------------------------------\n// Utility Functions\n// -----------------------------------------------------------------------------\n\n/**\n * Validates a page slug format.\n *\n * @param slug - Slug to validate\n * @returns true if slug is valid format\n */\nexport function isValidSlug(slug: string): boolean {\n // Slugs should be lowercase, alphanumeric with hyphens\n return /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug);\n}\n\n/**\n * Normalizes a slug (lowercase, trim, replace spaces with hyphens).\n *\n * @param input - Raw input to normalize\n * @returns Normalized slug\n */\nexport function normalizeSlug(input: string): string {\n return input\n .toLowerCase()\n .trim()\n .replace(/\\s+/g, '-')\n .replace(/[^a-z0-9-]/g, '')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '');\n}\n\n/**\n * Prefetches multiple pages in parallel with Result types.\n *\n * @param slugs - Array of page slugs to fetch\n * @param options - Fetch options applied to all requests\n * @returns Array of Results for each page\n *\n * @example\n * ```ts\n * const results = await prefetchPages(['home', 'about', 'blog']);\n * const errors = results.filter(r => !r.ok);\n * if (errors.length > 0) {\n * console.warn(`${errors.length} pages failed to load`);\n * }\n * ```\n */\nexport async function prefetchPages(\n slugs: string[],\n options?: FetchOptions\n): Promise<Result<Page, FetchError>[]> {\n return Promise.all(slugs.map((slug) => fetchPageV3(slug, options)));\n}\n\n/**\n * Fetches a page with stale-while-revalidate semantics.\n * Returns cached data immediately if available, then updates in background.\n *\n * @param slug - Page slug to fetch\n * @param cache - Cache storage (e.g., Map, localStorage wrapper)\n * @param options - Fetch options\n * @returns Cached data or fresh fetch result\n */\nexport async function fetchPageWithSWR(\n slug: string,\n cache: Map<string, { data: Page; timestamp: number }>,\n options: FetchOptions & { maxAge?: number } = {}\n): Promise<Result<Page, FetchError>> {\n const { maxAge = 60_000 } = options; // 1 minute default\n\n const cached = cache.get(slug);\n const now = Date.now();\n\n // Return fresh cache immediately\n if (cached && now - cached.timestamp < maxAge) {\n return ok(cached.data);\n }\n\n // Fetch fresh data\n const result = await fetchPageV3(slug, options);\n\n // Update cache on success\n if (result.ok) {\n cache.set(slug, { data: result.value, timestamp: now });\n }\n\n // If fetch failed but we have stale cache, return it with warning\n if (!result.ok && cached) {\n if (process.env.NODE_ENV === 'development') {\n console.warn(\n `[fetchPageWithSWR] Returning stale cache for \"${slug}\" after fetch failure:`,\n result.error.message\n );\n }\n return ok(cached.data);\n }\n\n return result;\n}\n"],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