cms-renderer 0.1.3 → 0.1.4

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.
@@ -1,7 +1,284 @@
1
- import {
2
- BlockRenderer,
3
- walkReactNode
4
- } from "../chunk-6QR5B5KQ.js";
1
+ // lib/block-renderer.tsx
2
+ import React from "react";
3
+ import { BlockToolbar } from "./block-toolbar.js";
4
+ import { jsx, jsxs } from "react/jsx-runtime";
5
+ function walkReactNode(node, visitors, ctx = {}) {
6
+ const path = ctx.path ?? [];
7
+ if (node == null || typeof node === "boolean") return node;
8
+ if (typeof node === "string" || typeof node === "number") {
9
+ const value = String(node);
10
+ return visitors.onText ? visitors.onText({ value, path, parentType: ctx.parentType, key: ctx.key }) : node;
11
+ }
12
+ if (Array.isArray(node)) {
13
+ return node.map((child, i) => {
14
+ const childKey = child?.key ?? null;
15
+ const result = walkReactNode(child, visitors, {
16
+ path: [...path, i],
17
+ parentType: ctx.parentType,
18
+ key: childKey
19
+ });
20
+ if (React.isValidElement(result) && result.key == null) {
21
+ return React.cloneElement(result, { key: childKey ?? `arr-${path.join("-")}-${i}` });
22
+ }
23
+ return result;
24
+ });
25
+ }
26
+ if (React.isValidElement(node)) {
27
+ const el = node;
28
+ const elProps = el.props;
29
+ const hasChildren = elProps && "children" in elProps;
30
+ const nextChildren = hasChildren ? React.Children.map(elProps.children, (child, i) => {
31
+ const childKey = child?.key ?? null;
32
+ const result = walkReactNode(child, visitors, {
33
+ path: [...path, "children", i],
34
+ parentType: el.type,
35
+ key: childKey
36
+ });
37
+ if (React.isValidElement(result) && result.key == null) {
38
+ return React.cloneElement(result, { key: childKey ?? `child-${path.join("-")}-${i}` });
39
+ }
40
+ return result;
41
+ }) : elProps?.children;
42
+ const cloned = hasChildren ? React.cloneElement(el, void 0, nextChildren) : el;
43
+ return visitors.onElement ? visitors.onElement({ element: cloned, path }) : cloned;
44
+ }
45
+ return node;
46
+ }
47
+ function extractContentValues(content, basePath = []) {
48
+ const map = /* @__PURE__ */ new Map();
49
+ function walk(obj, path) {
50
+ if (typeof obj === "string" && obj.trim() !== "") {
51
+ const contentPath = path.join(".");
52
+ const existing = map.get(obj) || [];
53
+ existing.push({ contentPath, value: obj });
54
+ map.set(obj, existing);
55
+ } else if (Array.isArray(obj)) {
56
+ for (let index = 0; index < obj.length; index++) {
57
+ walk(obj[index], [...path, String(index)]);
58
+ }
59
+ } else if (obj && typeof obj === "object") {
60
+ for (const [key, value] of Object.entries(obj)) {
61
+ walk(value, [...path, key]);
62
+ }
63
+ }
64
+ }
65
+ walk(content, basePath);
66
+ return map;
67
+ }
68
+ function renderToWalkableTree(node, keyPrefix = "") {
69
+ if (node == null || typeof node === "boolean") return node;
70
+ if (typeof node === "string" || typeof node === "number") return node;
71
+ if (Array.isArray(node)) {
72
+ return node.map((child, i) => {
73
+ const result = renderToWalkableTree(child, `${keyPrefix}${i}-`);
74
+ if (React.isValidElement(result) && result.key == null) {
75
+ const existingKey = child?.key;
76
+ return React.cloneElement(result, { key: existingKey ?? `${keyPrefix}${i}` });
77
+ }
78
+ return result;
79
+ });
80
+ }
81
+ if (React.isValidElement(node)) {
82
+ const el = node;
83
+ const elProps = el.props;
84
+ if (typeof el.type === "function") {
85
+ try {
86
+ const rendered = el.type(el.props);
87
+ return renderToWalkableTree(rendered, keyPrefix);
88
+ } catch {
89
+ return node;
90
+ }
91
+ }
92
+ if (elProps && "children" in elProps) {
93
+ const newChildren = renderToWalkableTree(elProps.children, keyPrefix);
94
+ return React.cloneElement(el, void 0, newChildren);
95
+ }
96
+ return node;
97
+ }
98
+ return node;
99
+ }
100
+ function BlockRenderer({ block, registry, disableEditable }) {
101
+ const Component = registry[block.type];
102
+ if (!Component) {
103
+ if (process.env.NODE_ENV === "development") {
104
+ console.warn(`[BlockRenderer] Unknown block type: ${block.type}`);
105
+ }
106
+ return null;
107
+ }
108
+ const component = /* @__PURE__ */ jsx(Component, { content: block.content });
109
+ if (disableEditable) {
110
+ return component;
111
+ }
112
+ const renderedTree = renderToWalkableTree(component);
113
+ const contentValueMap = extractContentValues(block.content);
114
+ const usedPaths = /* @__PURE__ */ new Set();
115
+ let isRoot = true;
116
+ const wrappedComponent = walkReactNode(renderedTree, {
117
+ onText: ({ value, key, path }) => {
118
+ const matches = contentValueMap.get(value);
119
+ if (!matches || matches.length === 0) {
120
+ return value;
121
+ }
122
+ const match = matches.find((m) => !usedPaths.has(m.contentPath)) ?? matches[0];
123
+ if (!match) return value;
124
+ usedPaths.add(match.contentPath);
125
+ const spanKey = key ?? `${block.id}-${match.contentPath}-${path.join("-")}`;
126
+ return /* @__PURE__ */ jsx(
127
+ "span",
128
+ {
129
+ "data-cms-editable": true,
130
+ "data-block-id": block.id,
131
+ "data-block-type": block.type,
132
+ "data-content-path": match.contentPath,
133
+ children: value
134
+ },
135
+ spanKey
136
+ );
137
+ },
138
+ onElement: ({ element, path }) => {
139
+ if (isRoot && path.length === 0) {
140
+ isRoot = false;
141
+ const elProps = element.props;
142
+ const existingChildren = elProps?.children;
143
+ return React.cloneElement(
144
+ element,
145
+ {
146
+ "data-cms-block": true,
147
+ "data-block-id": block.id,
148
+ "data-block-type": block.type
149
+ },
150
+ existingChildren,
151
+ /* @__PURE__ */ jsx(BlockToolbar, { blockId: block.id }, "cms-toolbar")
152
+ );
153
+ }
154
+ return element;
155
+ }
156
+ });
157
+ return /* @__PURE__ */ jsxs("div", { style: { display: "contents" }, children: [
158
+ /* @__PURE__ */ jsx("style", { children: `
159
+ [data-cms-block] {
160
+ position: relative;
161
+ }
162
+ [data-cms-block]:hover {
163
+ outline: 2px solid #3b82f6;
164
+ outline-offset: 4px;
165
+ }
166
+ [data-cms-editable] {
167
+ cursor: pointer;
168
+ border-radius: 2px;
169
+ }
170
+ [data-cms-editable]:hover {
171
+ outline: 2px solid #3b82f6;
172
+ outline-offset: 2px;
173
+ }
174
+ .cms-block-toolbar {
175
+ position: absolute;
176
+ bottom: -16px;
177
+ left: 50%;
178
+ transform: translateX(-50%);
179
+ display: flex;
180
+ gap: 4px;
181
+ background: #1f2937;
182
+ border-radius: 6px;
183
+ padding: 4px;
184
+ box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
185
+ opacity: 0;
186
+ pointer-events: none;
187
+ transition: opacity 0.15s ease;
188
+ z-index: 1000;
189
+ }
190
+ [data-cms-block]:hover .cms-block-toolbar {
191
+ opacity: 1;
192
+ pointer-events: auto;
193
+ }
194
+ .cms-block-toolbar button {
195
+ display: flex;
196
+ align-items: center;
197
+ justify-content: center;
198
+ width: 28px;
199
+ height: 28px;
200
+ border: none;
201
+ background: transparent;
202
+ color: #9ca3af;
203
+ border-radius: 4px;
204
+ cursor: pointer;
205
+ transition: background 0.15s ease, color 0.15s ease;
206
+ }
207
+ .cms-block-toolbar button:hover {
208
+ background: #374151;
209
+ color: #fff;
210
+ }
211
+ .cms-block-toolbar button.delete:hover {
212
+ background: #dc2626;
213
+ color: #fff;
214
+ }
215
+ .cms-block-toolbar button:disabled {
216
+ opacity: 0.4;
217
+ cursor: not-allowed;
218
+ }
219
+ .cms-block-toolbar button:disabled:hover {
220
+ background: transparent;
221
+ color: #9ca3af;
222
+ }
223
+ .cms-block-toolbar svg {
224
+ width: 16px;
225
+ height: 16px;
226
+ }
227
+ ` }),
228
+ /* @__PURE__ */ jsx(
229
+ "script",
230
+ {
231
+ dangerouslySetInnerHTML: {
232
+ __html: `
233
+ (function() {
234
+ if (window.__cmsEditableInitialized) return;
235
+ window.__cmsEditableInitialized = true;
236
+
237
+ document.addEventListener('click', function(e) {
238
+ // Ignore toolbar clicks
239
+ if (e.target.closest('.cms-block-toolbar')) {
240
+ return;
241
+ }
242
+
243
+ // Check for editable text click first (more specific)
244
+ var editableTarget = e.target.closest('[data-cms-editable]');
245
+ if (editableTarget) {
246
+ var message = {
247
+ type: 'cms-editable-click',
248
+ blockId: editableTarget.getAttribute('data-block-id'),
249
+ blockType: editableTarget.getAttribute('data-block-type'),
250
+ contentPath: editableTarget.getAttribute('data-content-path')
251
+ };
252
+
253
+ if (window.parent && window.parent !== window) {
254
+ window.parent.postMessage(message, '*');
255
+ }
256
+ return;
257
+ }
258
+
259
+ // Check for block-level click
260
+ var blockTarget = e.target.closest('[data-cms-block]');
261
+ if (blockTarget) {
262
+ var message = {
263
+ type: 'cms-editable-click',
264
+ blockId: blockTarget.getAttribute('data-block-id'),
265
+ blockType: blockTarget.getAttribute('data-block-type'),
266
+ contentPath: null
267
+ };
268
+
269
+ if (window.parent && window.parent !== window) {
270
+ window.parent.postMessage(message, '*');
271
+ }
272
+ }
273
+ });
274
+ })();
275
+ `
276
+ }
277
+ }
278
+ ),
279
+ wrappedComponent
280
+ ] }, block.id);
281
+ }
5
282
  export {
6
283
  BlockRenderer,
7
284
  walkReactNode
@@ -1 +1 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
1
+ {"version":3,"sources":["../../lib/block-renderer.tsx"],"sourcesContent":["/**\n * Block Renderer Component\n *\n * Dispatches block data to the appropriate component using the ComponentMap pattern.\n * This is the main entry point for rendering blocks from the CMS.\n */\n\nimport React from 'react';\nimport { BlockToolbar } from './block-toolbar';\nimport type { BlockComponentRegistry, BlockData } from './types';\n\ntype TextInfo = {\n value: string;\n path: Array<string | number>;\n parentType?: React.ElementType;\n key?: React.Key | null;\n};\n\ntype ElementInfo = {\n element: React.ReactElement;\n path: Array<string | number>;\n};\n\ntype WalkVisitors = {\n /**\n * Called for every string/number child encountered.\n * Return:\n * - same string (or modified)\n * - a ReactNode (e.g. wrap in <span/>)\n */\n onText?: (info: TextInfo) => React.ReactNode;\n\n /**\n * Called for every ReactElement encountered (after children are processed).\n * Return:\n * - same element\n * - a cloned/modified element\n */\n onElement?: (info: ElementInfo) => React.ReactElement;\n};\n\n/**\n * Recursively maps a ReactNode tree, allowing transformations of text nodes and/or elements.\n * SSR-safe: does not touch DOM APIs.\n */\nexport function walkReactNode(\n node: React.ReactNode,\n visitors: WalkVisitors,\n ctx: {\n path?: Array<string | number>;\n parentType?: React.ElementType;\n key?: React.Key | null;\n } = {}\n): React.ReactNode {\n const path = ctx.path ?? [];\n\n // Fast-path primitives\n if (node == null || typeof node === 'boolean') return node;\n\n if (typeof node === 'string' || typeof node === 'number') {\n const value = String(node);\n return visitors.onText\n ? visitors.onText({ value, path, parentType: ctx.parentType, key: ctx.key })\n : node;\n }\n\n // Arrays\n if (Array.isArray(node)) {\n return node.map((child, i) => {\n // biome-ignore lint/suspicious/noExplicitAny: React child key access\n const childKey = (child as any)?.key ?? null;\n const result = walkReactNode(child, visitors, {\n path: [...path, i],\n parentType: ctx.parentType,\n key: childKey,\n });\n // Ensure array children have keys\n if (React.isValidElement(result) && result.key == null) {\n return React.cloneElement(result, { key: childKey ?? `arr-${path.join('-')}-${i}` });\n }\n return result;\n });\n }\n\n // ReactElement (including Fragment)\n if (React.isValidElement(node)) {\n // biome-ignore lint/suspicious/noExplicitAny: React element props access\n const el = node as React.ReactElement<any>;\n const elProps = el.props as Record<string, unknown> | null;\n\n // Recurse into children (if any)\n const hasChildren = elProps && 'children' in elProps;\n const nextChildren = hasChildren\n ? React.Children.map(elProps.children as React.ReactNode, (child, i) => {\n // biome-ignore lint/suspicious/noExplicitAny: React child key access\n const childKey = (child as any)?.key ?? null;\n const result = walkReactNode(child, visitors, {\n path: [...path, 'children', i],\n parentType: el.type as React.ElementType,\n key: childKey,\n });\n // Ensure children have keys\n if (React.isValidElement(result) && result.key == null) {\n return React.cloneElement(result, { key: childKey ?? `child-${path.join('-')}-${i}` });\n }\n return result;\n })\n : (elProps?.children as React.ReactNode);\n\n // Only clone if children changed (or if you want to force a clone)\n const cloned = hasChildren\n ? React.cloneElement(el, undefined, nextChildren as React.ReactNode)\n : el;\n\n return visitors.onElement ? visitors.onElement({ element: cloned, path }) : cloned;\n }\n\n // Functions, symbols, portals, etc. are rare here; return as-is\n return node;\n}\n\n// -----------------------------------------------------------------------------\n// Content Value Extraction\n// -----------------------------------------------------------------------------\n\ntype ContentMatch = {\n contentPath: string;\n value: string;\n};\n\n/**\n * Extracts all string values from a content object with their paths.\n * Returns a Map where keys are string values and values are arrays of content paths.\n */\nfunction extractContentValues(\n content: Record<string, unknown>,\n basePath: string[] = []\n): Map<string, ContentMatch[]> {\n const map = new Map<string, ContentMatch[]>();\n\n function walk(obj: unknown, path: string[]) {\n if (typeof obj === 'string' && obj.trim() !== '') {\n const contentPath = path.join('.');\n const existing = map.get(obj) || [];\n existing.push({ contentPath, value: obj });\n map.set(obj, existing);\n } else if (Array.isArray(obj)) {\n for (let index = 0; index < obj.length; index++) {\n walk(obj[index], [...path, String(index)]);\n }\n } else if (obj && typeof obj === 'object') {\n for (const [key, value] of Object.entries(obj)) {\n walk(value, [...path, key]);\n }\n }\n }\n\n walk(content, basePath);\n return map;\n}\n\n// -----------------------------------------------------------------------------\n// Props\n// -----------------------------------------------------------------------------\n\ninterface BlockRendererProps {\n /**\n * The block data to render.\n * Must have a `type` field that maps to a registered component.\n */\n block: BlockData;\n registry: Partial<BlockComponentRegistry>;\n /**\n * If true, renders the component without any tree walking or editable wrappers.\n */\n disableEditable?: boolean;\n}\n\n// -----------------------------------------------------------------------------\n// Component\n// -----------------------------------------------------------------------------\n\n/**\n * Recursively renders a React node, invoking function components to get their output.\n * This allows us to walk the full rendered tree, not just the element wrappers.\n */\nfunction renderToWalkableTree(node: React.ReactNode, keyPrefix = ''): React.ReactNode {\n if (node == null || typeof node === 'boolean') return node;\n if (typeof node === 'string' || typeof node === 'number') return node;\n\n if (Array.isArray(node)) {\n return node.map((child, i) => {\n const result = renderToWalkableTree(child, `${keyPrefix}${i}-`);\n // Ensure array children have keys\n if (React.isValidElement(result) && result.key == null) {\n // biome-ignore lint/suspicious/noExplicitAny: Adding key to element\n const existingKey = (child as any)?.key;\n return React.cloneElement(result, { key: existingKey ?? `${keyPrefix}${i}` });\n }\n return result;\n });\n }\n\n if (React.isValidElement(node)) {\n // biome-ignore lint/suspicious/noExplicitAny: React element props access\n const el = node as React.ReactElement<any>;\n const elProps = el.props as Record<string, unknown> | null;\n\n // If it's a function component, invoke it to get the rendered output\n if (typeof el.type === 'function') {\n try {\n // biome-ignore lint/complexity/noBannedTypes: Need to invoke React function component\n const rendered = (el.type as Function)(el.props);\n return renderToWalkableTree(rendered, keyPrefix);\n } catch {\n // If component throws (e.g., uses hooks), return as-is\n return node;\n }\n }\n\n // For host elements (div, span, etc.), recurse into children\n if (elProps && 'children' in elProps) {\n const newChildren = renderToWalkableTree(elProps.children as React.ReactNode, keyPrefix);\n return React.cloneElement(el, undefined, newChildren);\n }\n\n return node;\n }\n\n return node;\n}\n\n/**\n * Renders a single block by dispatching to the appropriate component.\n *\n * Uses the ComponentMap pattern: the block's `type` field determines which\n * component renders the block's `content`.\n *\n * Internally, it:\n * 1. Renders the component tree by invoking function components\n * 2. Extracts all string values from block.content\n * 3. Walks the rendered tree and wraps matching text nodes with spans\n */\nexport function BlockRenderer({ block, registry, disableEditable }: BlockRendererProps) {\n const Component = registry[block.type];\n\n if (!Component) {\n // Log warning in development, render nothing in production\n if (process.env.NODE_ENV === 'development') {\n console.warn(`[BlockRenderer] Unknown block type: ${block.type}`);\n }\n return null;\n }\n\n // biome-ignore lint/suspicious/noExplicitAny: Type safety ensured by BlockData discriminated union\n const component = <Component content={block.content as any} />;\n\n if (disableEditable) {\n return component;\n }\n\n // Render the component tree to get the actual DOM structure with all children\n const renderedTree = renderToWalkableTree(component);\n\n // Extract all string values from content with their paths\n const contentValueMap = extractContentValues(block.content as Record<string, unknown>);\n\n // Track which content paths have been used to handle duplicates\n const usedPaths = new Set<string>();\n\n // Track if we've processed the root element\n let isRoot = true;\n\n // Walk the tree: wrap matching text nodes and add attributes to root element\n const wrappedComponent = walkReactNode(renderedTree, {\n onText: ({ value, key, path }) => {\n const matches = contentValueMap.get(value);\n\n if (!matches || matches.length === 0) {\n return value;\n }\n\n // Find the first unused match, or use the first one if all are used\n const match = matches.find((m) => !usedPaths.has(m.contentPath)) ?? matches[0];\n if (!match) return value;\n\n usedPaths.add(match.contentPath);\n\n // Generate a unique key using the original key, content path, or path\n const spanKey = key ?? `${block.id}-${match.contentPath}-${path.join('-')}`;\n\n return (\n <span\n key={spanKey}\n data-cms-editable\n data-block-id={block.id}\n data-block-type={block.type}\n data-content-path={match.contentPath}\n >\n {value}\n </span>\n );\n },\n onElement: ({ element, path }) => {\n // Add wrapper attributes and toolbar to the root element\n if (isRoot && path.length === 0) {\n isRoot = false;\n // Get existing children\n // biome-ignore lint/suspicious/noExplicitAny: React element props access\n const elProps = (element as React.ReactElement<any>).props as Record<\n string,\n unknown\n > | null;\n const existingChildren = elProps?.children;\n // Clone with new attributes and inject toolbar as last child\n return React.cloneElement(\n element,\n {\n 'data-cms-block': true,\n 'data-block-id': block.id,\n 'data-block-type': block.type,\n } as React.Attributes & Record<string, unknown>,\n existingChildren as React.ReactNode,\n <BlockToolbar key=\"cms-toolbar\" blockId={block.id} />\n );\n }\n return element;\n },\n });\n\n return (\n <div key={block.id} style={{ display: 'contents' }}>\n <style>{`\n [data-cms-block] {\n position: relative;\n }\n [data-cms-block]:hover {\n outline: 2px solid #3b82f6;\n outline-offset: 4px;\n }\n [data-cms-editable] {\n cursor: pointer;\n border-radius: 2px;\n }\n [data-cms-editable]:hover {\n outline: 2px solid #3b82f6;\n outline-offset: 2px;\n }\n .cms-block-toolbar {\n position: absolute;\n bottom: -16px;\n left: 50%;\n transform: translateX(-50%);\n display: flex;\n gap: 4px;\n background: #1f2937;\n border-radius: 6px;\n padding: 4px;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);\n opacity: 0;\n pointer-events: none;\n transition: opacity 0.15s ease;\n z-index: 1000;\n }\n [data-cms-block]:hover .cms-block-toolbar {\n opacity: 1;\n pointer-events: auto;\n }\n .cms-block-toolbar button {\n display: flex;\n align-items: center;\n justify-content: center;\n width: 28px;\n height: 28px;\n border: none;\n background: transparent;\n color: #9ca3af;\n border-radius: 4px;\n cursor: pointer;\n transition: background 0.15s ease, color 0.15s ease;\n }\n .cms-block-toolbar button:hover {\n background: #374151;\n color: #fff;\n }\n .cms-block-toolbar button.delete:hover {\n background: #dc2626;\n color: #fff;\n }\n .cms-block-toolbar button:disabled {\n opacity: 0.4;\n cursor: not-allowed;\n }\n .cms-block-toolbar button:disabled:hover {\n background: transparent;\n color: #9ca3af;\n }\n .cms-block-toolbar svg {\n width: 16px;\n height: 16px;\n }\n `}</style>\n <script\n // biome-ignore lint/security/noDangerouslySetInnerHtml: Inline script for iframe postMessage\n dangerouslySetInnerHTML={{\n __html: `\n (function() {\n if (window.__cmsEditableInitialized) return;\n window.__cmsEditableInitialized = true;\n\n document.addEventListener('click', function(e) {\n // Ignore toolbar clicks\n if (e.target.closest('.cms-block-toolbar')) {\n return;\n }\n\n // Check for editable text click first (more specific)\n var editableTarget = e.target.closest('[data-cms-editable]');\n if (editableTarget) {\n var message = {\n type: 'cms-editable-click',\n blockId: editableTarget.getAttribute('data-block-id'),\n blockType: editableTarget.getAttribute('data-block-type'),\n contentPath: editableTarget.getAttribute('data-content-path')\n };\n\n if (window.parent && window.parent !== window) {\n window.parent.postMessage(message, '*');\n }\n return;\n }\n\n // Check for block-level click\n var blockTarget = e.target.closest('[data-cms-block]');\n if (blockTarget) {\n var message = {\n type: 'cms-editable-click',\n blockId: blockTarget.getAttribute('data-block-id'),\n blockType: blockTarget.getAttribute('data-block-type'),\n contentPath: null\n };\n\n if (window.parent && window.parent !== window) {\n window.parent.postMessage(message, '*');\n }\n }\n });\n })();\n `,\n }}\n />\n {wrappedComponent}\n </div>\n );\n}\n"],"mappings":";AAOA,OAAO,WAAW;AAClB,SAAS,oBAAoB;AAuPT,cA4EhB,YA5EgB;AAlNb,SAAS,cACd,MACA,UACA,MAII,CAAC,GACY;AACjB,QAAM,OAAO,IAAI,QAAQ,CAAC;AAG1B,MAAI,QAAQ,QAAQ,OAAO,SAAS,UAAW,QAAO;AAEtD,MAAI,OAAO,SAAS,YAAY,OAAO,SAAS,UAAU;AACxD,UAAM,QAAQ,OAAO,IAAI;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AA;AAAA;AAAA;AAAA;AAAA,SAqEN;AAAA,IACF;AAAA,MAAC;AAAA;AAAA,QAEC,yBAAyB;AAAA,UACvB,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,QA4CV;AAAA;AAAA,IACF;AAAA,IACC;AAAA,OAxHO,MAAM,EAyHhB;AAEJ;","names":[]}
@@ -1,6 +1,37 @@
1
- import {
2
- getCmsClient
3
- } from "../chunk-JHKDRASN.js";
1
+ // lib/cms-api.ts
2
+ import { createTRPCClient, httpBatchLink } from "@trpc/client";
3
+ import superjson from "superjson";
4
+ function getCmsApiUrl(cmsUrl) {
5
+ return `${cmsUrl}/api/trpc`;
6
+ }
7
+ function createFetchWithApiKey(apiKey) {
8
+ return async (url, options) => {
9
+ let finalUrl = url;
10
+ if (apiKey) {
11
+ const urlObj = new URL(url.toString());
12
+ urlObj.searchParams.set("api_key", apiKey);
13
+ finalUrl = urlObj.toString();
14
+ }
15
+ const response = await fetch(finalUrl, options);
16
+ return response;
17
+ };
18
+ }
19
+ function createCmsClient(options) {
20
+ const url = getCmsApiUrl(options.cmsUrl);
21
+ console.log("[CMS API] Creating client with URL:", url);
22
+ return createTRPCClient({
23
+ links: [
24
+ httpBatchLink({
25
+ url,
26
+ transformer: superjson,
27
+ fetch: createFetchWithApiKey(options.apiKey)
28
+ })
29
+ ]
30
+ });
31
+ }
32
+ function getCmsClient(options) {
33
+ return createCmsClient(options);
34
+ }
4
35
  export {
5
36
  getCmsClient
6
37
  };
@@ -1 +1 @@
1
- {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
1
+ {"version":3,"sources":["../../lib/cms-api.ts"],"sourcesContent":["/**\n * CMS API Client\n *\n * Creates an HTTP-based tRPC client for calling the CMS API.\n * Used in Server Components to fetch routes and blocks from the CMS.\n */\n\nimport type { AppRouter } from '@repo/cms-schema/trpc';\nimport { type CreateTRPCClient, createTRPCClient, httpBatchLink } from '@trpc/client';\nimport superjson from 'superjson';\n\n/** Type alias for the CMS API client */\ntype CmsClient = CreateTRPCClient<AppRouter>;\n\n/**\n * Get the CMS API URL from the provided base URL.\n */\nfunction getCmsApiUrl(cmsUrl: string): string {\n return `${cmsUrl}/api/trpc`;\n}\n\n/** Options for creating a CMS client */\nexport interface CmsClientOptions {\n /** CMS API base URL (e.g., 'http://localhost:3000') */\n cmsUrl: string;\n /** API key for authentication (passed as query parameter) */\n apiKey?: string;\n}\n\n/**\n * Create a custom fetch function that appends API key as query parameter.\n */\nfunction createFetchWithApiKey(apiKey?: string) {\n return async (url: URL | RequestInfo, options?: RequestInit): Promise<Response> => {\n let finalUrl = url;\n\n // Append api_key to URL if provided\n if (apiKey) {\n const urlObj = new URL(url.toString());\n urlObj.searchParams.set('api_key', apiKey);\n finalUrl = urlObj.toString();\n }\n\n const response = await fetch(finalUrl, options);\n\n return response;\n };\n}\n\n/**\n * Create a tRPC client for the CMS API.\n */\nfunction createCmsClient(options: CmsClientOptions): CmsClient {\n const url = getCmsApiUrl(options.cmsUrl);\n console.log('[CMS API] Creating client with URL:', url);\n\n return createTRPCClient<AppRouter>({\n links: [\n httpBatchLink({\n url,\n transformer: superjson,\n fetch: createFetchWithApiKey(options.apiKey),\n }),\n ],\n });\n}\n\n/**\n * Get a CMS client for the specified CMS URL.\n */\nexport function getCmsClient(options: CmsClientOptions): CmsClient {\n return createCmsClient(options);\n}\n"],"mappings":";AAQA,SAAgC,kBAAkB,qBAAqB;AACvE,OAAO,eAAe;AAQtB,SAAS,aAAa,QAAwB;AAC5C,SAAO,GAAG,MAAM;AAClB;AAaA,SAAS,sBAAsB,QAAiB;AAC9C,SAAO,OAAO,KAAwB,YAA6C;AACjF,QAAI,WAAW;AAGf,QAAI,QAAQ;AACV,YAAM,SAAS,IAAI,IAAI,IAAI,SAAS,CAAC;AACrC,aAAO,aAAa,IAAI,WAAW,MAAM;AACzC,iBAAW,OAAO,SAAS;AAAA,IAC7B;AAEA,UAAM,WAAW,MAAM,MAAM,UAAU,OAAO;AAE9C,WAAO;AAAA,EACT;AACF;AAKA,SAAS,gBAAgB,SAAsC;AAC7D,QAAM,MAAM,aAAa,QAAQ,MAAM;AACvC,UAAQ,IAAI,uCAAuC,GAAG;AAEtD,SAAO,iBAA4B;AAAA,IACjC,OAAO;AAAA,MACL,cAAc;AAAA,QACZ;AAAA,QACA,aAAa;AAAA,QACb,OAAO,sBAAsB,QAAQ,MAAM;AAAA,MAC7C,CAAC;AAAA,IACH;AAAA,EACF,CAAC;AACH;AAKO,SAAS,aAAa,SAAsC;AACjE,SAAO,gBAAgB,OAAO;AAChC;","names":[]}
@@ -1,7 +1,10 @@
1
- import {
2
- err,
3
- ok
4
- } from "../chunk-HVKFEZBT.js";
1
+ // lib/result.ts
2
+ function ok(value) {
3
+ return { ok: true, value };
4
+ }
5
+ function err(error) {
6
+ return { ok: false, error };
7
+ }
5
8
 
6
9
  // lib/data-utils.ts
7
10
  var FetchErrorCode = {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../lib/data-utils.ts"],"sourcesContent":["/**\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"],"mappings":";;;;;;AA8BO,IAAM,iBAAiB;AAAA,EAC5B,cAAc;AAAA,EACd,WAAW;AAAA,EACX,eAAe;AAAA,EACf,SAAS;AAAA,EACT,aAAa;AAAA,EACb,cAAc;AAAA,EACd,iBAAiB;AACnB;AA+CA,IAAM,kBA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A,WAAO,GAAG,OAAO,IAAI;AAAA,EACvB;AAEA,SAAO;AACT;","names":[]}
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"],"mappings":";AAiEO,SAAS,GAAM,OAA4B;AAChD,SAAO,EAAE,IAAI,MAAM,MAAM;AAC3B;AAcO,SAAS,IAAO,OAA4B;AACjD,SAAO,EAAE,IAAI,OAAO,MAAM;AAC5B;;;ACrDO,IAAM,iBAAiB;AAAA,EAC5B,cAAc;AAAA,EACd,WAAW;AAAA,EACX,eAAe;AAAA,EACf,SAAS;AAAA,EACT,aAAa;AAAA,EACb,cAAc;AAAA,EAC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AO,MAAM;AAAA,MACf;AAAA,IACF;AACA,WAAO,GAAG,OAAO,IAAI;AAAA,EACvB;AAEA,SAAO;AACT;","names":[]}
@@ -1,10 +1,15 @@
1
- import {
2
- err,
3
- ok
4
- } from "../chunk-HVKFEZBT.js";
5
-
6
1
  // lib/markdown-utils.ts
7
2
  import { mdToJSON } from "md4w";
3
+
4
+ // lib/result.ts
5
+ function ok(value) {
6
+ return { ok: true, value };
7
+ }
8
+ function err(error) {
9
+ return { ok: false, error };
10
+ }
11
+
12
+ // lib/markdown-utils.ts
8
13
  var ParseErrorCode = {
9
14
  INVALID_INPUT: "INVALID_INPUT",
10
15
  EMPTY_CONTENT: "EMPTY_CONTENT",