zreader 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/LICENSE +21 -0
  3. package/README.md +234 -2
  4. package/dist/blocks-DwR7l7pz.d.ts +20 -0
  5. package/dist/chunk-3WQBK6DE.js +47 -0
  6. package/dist/chunk-3WQBK6DE.js.map +1 -0
  7. package/dist/chunk-DYQNGV46.js +31 -0
  8. package/dist/chunk-DYQNGV46.js.map +1 -0
  9. package/dist/chunk-ISI35TCM.js +62 -0
  10. package/dist/chunk-ISI35TCM.js.map +1 -0
  11. package/dist/chunk-RNSAFDZ5.js +105 -0
  12. package/dist/chunk-RNSAFDZ5.js.map +1 -0
  13. package/dist/config/index.cjs +196 -0
  14. package/dist/config/index.cjs.map +1 -0
  15. package/dist/config/index.d.cts +159 -0
  16. package/dist/config/index.d.ts +159 -0
  17. package/dist/config/index.js +182 -0
  18. package/dist/config/index.js.map +1 -0
  19. package/dist/content/index.d.ts +143 -0
  20. package/dist/content/index.js +379 -0
  21. package/dist/content/index.js.map +1 -0
  22. package/dist/core/index.d.ts +262 -0
  23. package/dist/core/index.js +935 -0
  24. package/dist/core/index.js.map +1 -0
  25. package/dist/editor/index.d.ts +19 -0
  26. package/dist/editor/index.js +277 -0
  27. package/dist/editor/index.js.map +1 -0
  28. package/dist/index-Bp5oIiZd.d.ts +61 -0
  29. package/dist/next/client/index.d.ts +8 -0
  30. package/dist/next/client/index.js +13 -0
  31. package/dist/next/client/index.js.map +1 -0
  32. package/dist/next/index.cjs +272 -0
  33. package/dist/next/index.cjs.map +1 -0
  34. package/dist/next/index.d.cts +47 -0
  35. package/dist/next/index.d.ts +47 -0
  36. package/dist/next/index.js +262 -0
  37. package/dist/next/index.js.map +1 -0
  38. package/dist/next/server/index.d.ts +58 -0
  39. package/dist/next/server/index.js +44 -0
  40. package/dist/next/server/index.js.map +1 -0
  41. package/dist/react/index.d.ts +376 -0
  42. package/dist/react/index.js +2793 -0
  43. package/dist/react/index.js.map +1 -0
  44. package/dist/reader.css +116 -0
  45. package/dist/rehype/index.d.ts +27 -0
  46. package/dist/rehype/index.js +4 -0
  47. package/dist/rehype/index.js.map +1 -0
  48. package/dist/stubs/empty-config.d.ts +9 -0
  49. package/dist/stubs/empty-config.js +7 -0
  50. package/dist/stubs/empty-config.js.map +1 -0
  51. package/dist/stubs/server-only.d.ts +2 -0
  52. package/dist/stubs/server-only.js +6 -0
  53. package/dist/stubs/server-only.js.map +1 -0
  54. package/dist/styles.css +1 -0
  55. package/dist/tailwind.css +41 -0
  56. package/dist/types-xkdpkPxA.d.ts +147 -0
  57. package/dist/user-config/index.d.ts +17 -0
  58. package/dist/user-config/index.js +35 -0
  59. package/dist/user-config/index.js.map +1 -0
  60. package/dist/virtual-config/index.d.ts +6 -0
  61. package/dist/virtual-config/index.js +10 -0
  62. package/dist/virtual-config/index.js.map +1 -0
  63. package/package.json +225 -4
@@ -0,0 +1,262 @@
1
+ import { resolve, join, dirname, relative, sep } from 'path';
2
+ import { z } from 'zod/v4';
3
+ import { existsSync } from 'fs';
4
+
5
+ // src/next/index.ts
6
+
7
+ // src/core/defaults.ts
8
+ var DEFAULT_CLIENT_OPTIONS = {
9
+ storagePrefix: "zr",
10
+ highlightColors: ["yellow", "green", "blue", "pink"],
11
+ defaultHighlightColor: "yellow",
12
+ scratchpad: { enabled: true, scopes: ["chapter", "book", "global"] },
13
+ themes: ["system", "light", "sepia", "dark"],
14
+ defaultTheme: "system",
15
+ defaultSettings: {
16
+ textSize: "lg",
17
+ leading: "relaxed",
18
+ measure: "normal",
19
+ fontFamily: "serif",
20
+ highlightMode: false
21
+ },
22
+ progress: { completeAt: 0.9, saveIntervalMs: 1e3 },
23
+ backupReminder: true,
24
+ basePath: "/books"
25
+ };
26
+
27
+ // src/core/types.ts
28
+ var THEMES = ["system", "light", "sepia", "dark"];
29
+ var TEXT_SIZES = ["sm", "base", "lg", "xl", "2xl"];
30
+ var LEADINGS = ["tight", "normal", "relaxed"];
31
+ var MEASURES = ["narrow", "normal", "wide"];
32
+ var FONT_FAMILIES = ["serif", "sans", "mono"];
33
+ var HIGHLIGHT_COLORS = ["yellow", "green", "blue", "pink", "purple", "orange"];
34
+
35
+ // src/config/index.ts
36
+ function glob(opts) {
37
+ return { kind: "glob", base: opts.base, pattern: opts.pattern ?? "**/*.{md,mdx,html}", ignore: opts.ignore };
38
+ }
39
+ var defaultBookSchema = z.looseObject({
40
+ title: z.string(),
41
+ subtitle: z.string().optional(),
42
+ authors: z.array(z.string()).default([]),
43
+ description: z.string().optional(),
44
+ cover: z.string().optional(),
45
+ /** Optional explicit chapter order (chapter slugs). */
46
+ chapters: z.array(z.string()).optional()
47
+ });
48
+ var defaultChapterSchema = z.looseObject({
49
+ title: z.string(),
50
+ order: z.number().optional(),
51
+ description: z.string().optional(),
52
+ part: z.string().optional(),
53
+ label: z.string().optional(),
54
+ number: z.union([z.string(), z.number()]).transform(String).optional(),
55
+ draft: z.boolean().default(false)
56
+ });
57
+ function isDev() {
58
+ return typeof process !== "undefined" && process.env?.NODE_ENV === "development";
59
+ }
60
+ function defaultContentConfig() {
61
+ return {
62
+ loader: glob({ base: "./content/books" }),
63
+ schemas: { book: defaultBookSchema, chapter: defaultChapterSchema },
64
+ remarkPlugins: [],
65
+ rehypePlugins: [],
66
+ sanitize: {},
67
+ includeDrafts: isDev(),
68
+ cacheDir: typeof process !== "undefined" && process.env?.ZREADER_CACHE_DIR || "node_modules/.cache/zreader"
69
+ };
70
+ }
71
+ function isPlainObject(x) {
72
+ if (typeof x !== "object" || x === null || Array.isArray(x)) return false;
73
+ const proto = Object.getPrototypeOf(x);
74
+ return proto === Object.prototype || proto === null;
75
+ }
76
+ function mergeConfig(base, ...overrides) {
77
+ let out = base;
78
+ for (const o of overrides) out = mergeTwo(out, o);
79
+ return out;
80
+ }
81
+ function mergeTwo(a, b) {
82
+ if (b === void 0) return a;
83
+ if (isPlainObject(a) && isPlainObject(b)) {
84
+ const out = { ...a };
85
+ for (const [k, v] of Object.entries(b)) out[k] = mergeTwo(a[k], v);
86
+ return out;
87
+ }
88
+ return b;
89
+ }
90
+ var themeName = z.enum(THEMES);
91
+ var highlightColor = z.enum(HIGHLIGHT_COLORS);
92
+ var clientSchema = z.object({
93
+ storagePrefix: z.string().regex(/^[a-z0-9_-]+$/i, "use letters, digits, '-' or '_'"),
94
+ highlightColors: z.array(highlightColor).min(1, "must be non-empty"),
95
+ defaultHighlightColor: highlightColor,
96
+ scratchpad: z.object({
97
+ enabled: z.boolean(),
98
+ scopes: z.array(z.enum(["global", "book", "chapter"])).min(1, "must be non-empty")
99
+ }),
100
+ themes: z.array(themeName).min(1),
101
+ defaultTheme: themeName,
102
+ defaultSettings: z.object({
103
+ textSize: z.enum(TEXT_SIZES),
104
+ leading: z.enum(LEADINGS),
105
+ measure: z.enum(MEASURES),
106
+ fontFamily: z.enum(FONT_FAMILIES),
107
+ highlightMode: z.boolean()
108
+ }),
109
+ progress: z.object({ completeAt: z.number().gt(0).max(1), saveIntervalMs: z.number().min(100) }),
110
+ backupReminder: z.boolean(),
111
+ basePath: z.string().startsWith("/")
112
+ }).refine((c) => c.highlightColors.includes(c.defaultHighlightColor), {
113
+ message: "defaultHighlightColor must be one of highlightColors",
114
+ path: ["defaultHighlightColor"]
115
+ }).refine((c) => c.themes.includes(c.defaultTheme), {
116
+ message: "defaultTheme must be one of themes",
117
+ path: ["defaultTheme"]
118
+ });
119
+ function isSchemaLike(v) {
120
+ return typeof v === "object" && v !== null && typeof v.safeParse === "function";
121
+ }
122
+ var contentSchema = z.object({
123
+ loader: z.object({
124
+ kind: z.literal("glob"),
125
+ base: z.string().min(1),
126
+ pattern: z.union([z.string(), z.array(z.string()).min(1)]),
127
+ ignore: z.array(z.string()).optional()
128
+ }),
129
+ schemas: z.object({
130
+ book: z.custom(isSchemaLike, "must be a zod (or safeParse-compatible) schema"),
131
+ chapter: z.custom(isSchemaLike, "must be a zod (or safeParse-compatible) schema")
132
+ }),
133
+ remarkPlugins: z.array(z.any()),
134
+ rehypePlugins: z.array(z.any()),
135
+ sanitize: z.object({
136
+ allowIframes: z.array(z.string()).optional(),
137
+ allowTags: z.array(z.string()).optional(),
138
+ allowAttributes: z.array(z.string()).optional()
139
+ }),
140
+ includeDrafts: z.boolean(),
141
+ cacheDir: z.string()
142
+ });
143
+ var ReaderConfigError = class extends Error {
144
+ constructor(message, issues = []) {
145
+ super(message);
146
+ this.issues = issues;
147
+ this.name = "ReaderConfigError";
148
+ }
149
+ issues;
150
+ };
151
+ function formatIssues(source, section, error) {
152
+ const issues = error.issues.map((i) => ({ path: [section, ...i.path.map(String)].join("."), message: i.message }));
153
+ return new ReaderConfigError(
154
+ `Invalid reader config${source ? ` (${source})` : ""}:
155
+ ` + issues.map((i) => ` - ${i.path}: ${i.message}`).join("\n"),
156
+ issues
157
+ );
158
+ }
159
+ function resolveConfig(user, inline, opts = {}) {
160
+ const root = opts.root ?? (typeof process !== "undefined" && process.cwd ? process.cwd() : "/");
161
+ const reader = mergeConfig(
162
+ structuredClone(DEFAULT_CLIENT_OPTIONS),
163
+ user?.reader,
164
+ inline?.reader
165
+ );
166
+ const content = mergeConfig(defaultContentConfig(), user?.content, inline?.content);
167
+ const r = clientSchema.safeParse(reader);
168
+ if (!r.success) throw formatIssues(opts.source ?? "", "reader", r.error);
169
+ const c = contentSchema.safeParse(content);
170
+ if (!c.success) throw formatIssues(opts.source ?? "", "content", c.error);
171
+ return { root, content, reader };
172
+ }
173
+ var CONFIG_FILE_NAMES = ["reader.config.ts", "reader.config.mts", "reader.config.mjs", "reader.config.js"];
174
+ function findConfigFile(from = process.cwd()) {
175
+ let dir = resolve(from);
176
+ for (; ; ) {
177
+ for (const name of CONFIG_FILE_NAMES) {
178
+ const p = join(dir, name);
179
+ if (existsSync(p)) return p;
180
+ }
181
+ if (existsSync(join(dir, "package.json")) || existsSync(join(dir, ".git"))) return null;
182
+ const parent = dirname(dir);
183
+ if (parent === dir) return null;
184
+ dir = parent;
185
+ }
186
+ }
187
+ async function loadConfigFile(file) {
188
+ const { createJiti } = await import('jiti');
189
+ const jiti = createJiti(file, { interopDefault: true, moduleCache: false });
190
+ const mod = await jiti.import(file);
191
+ const cfg = mod && typeof mod === "object" && "default" in mod ? mod.default : mod;
192
+ return cfg ?? {};
193
+ }
194
+
195
+ // src/next/index.ts
196
+ var USER_CONFIG_SPECIFIER = "zreader/user-config";
197
+ var EMPTY_CONFIG_SPECIFIER = "zreader/empty-config";
198
+ var SERVER_EXTERNALS = ["jsdom", "isomorphic-dompurify"];
199
+ function toPosix(p) {
200
+ return p.split(sep).join("/");
201
+ }
202
+ function relativeImport(root, file) {
203
+ const rel = toPosix(relative(root, file));
204
+ return rel.startsWith(".") ? rel : `./${rel}`;
205
+ }
206
+ function applyReaderConfig(base, setup, root) {
207
+ const { configFile, resolved } = setup;
208
+ const turboTarget = configFile ? relativeImport(root, configFile) : EMPTY_CONFIG_SPECIFIER;
209
+ const webpackTarget = configFile ?? EMPTY_CONFIG_SPECIFIER;
210
+ const prevWebpack = base.webpack;
211
+ const webpack = (config, ctx) => {
212
+ const cfg = prevWebpack ? prevWebpack(config, ctx) : config;
213
+ cfg.resolve ??= {};
214
+ const alias = cfg.resolve.alias ??= {};
215
+ alias[`${USER_CONFIG_SPECIFIER}$`] = webpackTarget;
216
+ return cfg;
217
+ };
218
+ const contentGlob = toPosix(join(resolved.content.loader.base, "**/*"));
219
+ const tracing = { ...base.outputFileTracingIncludes ?? {} };
220
+ const allRoutes = "/**";
221
+ tracing[allRoutes] = Array.from(/* @__PURE__ */ new Set([...tracing[allRoutes] ?? [], contentGlob]));
222
+ const externals = Array.from(/* @__PURE__ */ new Set([...base.serverExternalPackages ?? [], ...SERVER_EXTERNALS]));
223
+ return {
224
+ ...base,
225
+ serverExternalPackages: externals,
226
+ outputFileTracingIncludes: tracing,
227
+ turbopack: {
228
+ ...base.turbopack,
229
+ resolveAlias: {
230
+ ...base.turbopack?.resolveAlias,
231
+ [USER_CONFIG_SPECIFIER]: turboTarget
232
+ }
233
+ },
234
+ webpack
235
+ };
236
+ }
237
+ async function setupReader(options = {}) {
238
+ const root = resolve(options.root ?? process.cwd());
239
+ const configFile = options.configPath ? resolve(root, options.configPath) : findConfigFile(root);
240
+ const user = configFile ? await loadConfigFile(configFile) : {};
241
+ const resolved = resolveConfig(user, options.config, {
242
+ root,
243
+ source: configFile ? relative(root, configFile) : "defaults"
244
+ });
245
+ return { configFile, resolved };
246
+ }
247
+ function withReader(nextConfig = {}, options = {}) {
248
+ return async (phase, ctx) => {
249
+ const root = resolve(options.root ?? process.cwd());
250
+ process.env.ZREADER_CACHE_DIR ??= join(root, ".next", "cache", "zreader");
251
+ const base = typeof nextConfig === "function" ? await nextConfig(phase, ctx) : nextConfig;
252
+ const setup = await setupReader({ ...options, root });
253
+ if (options.verbose) {
254
+ console.log(`[zreader] config: ${setup.configFile ?? "(defaults)"}`);
255
+ }
256
+ return applyReaderConfig(base, setup, root);
257
+ };
258
+ }
259
+
260
+ export { EMPTY_CONFIG_SPECIFIER, SERVER_EXTERNALS, USER_CONFIG_SPECIFIER, applyReaderConfig, findConfigFile, loadConfigFile, resolveConfig, setupReader, withReader };
261
+ //# sourceMappingURL=index.js.map
262
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/core/defaults.ts","../../src/core/types.ts","../../src/config/index.ts","../../src/config/load.ts","../../src/next/index.ts"],"names":["join","resolve"],"mappings":";;;;;;;AAEO,IAAM,sBAAA,GAA8C;AAAA,EACzD,aAAA,EAAe,IAAA;AAAA,EACf,eAAA,EAAiB,CAAC,QAAA,EAAU,OAAA,EAAS,QAAQ,MAAM,CAAA;AAAA,EACnD,qBAAA,EAAuB,QAAA;AAAA,EACvB,UAAA,EAAY,EAAE,OAAA,EAAS,IAAA,EAAM,QAAQ,CAAC,SAAA,EAAW,MAAA,EAAQ,QAAQ,CAAA,EAA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AC,EAAG,OAAA,GAA6B,EAAC,EAAiB;AAC1G,EAAA,OAAO,OAAO,OAAO,GAAA,KAAQ;AAC3B,IAAA,MAAM,OAAOA,OAAAA,CAAQ,OAAA,CAAQ,IAAA,IAAQ,OAAA,CAAQ,KAAK,CAAA;AAClD,IAAA,OAAA,CAAQ,IAAI,iBAAA,KAAsBD,IAAAA,CAAK,IAAA,EAAM,OAAA,EAAS,SAAS,SAAS,CAAA;AACxE,IAAA,MAAM,IAAA,GAAO,OAAO,UAAA,KAAe,UAAA,GAAa,MAAM,UAAA,CAAW,KAAA,EAAO,GAAG,CAAA,GAAI,UAAA;AAC/E,IAAA,MAAM,QAAQ,MAAM,WAAA,CAAY,EAAE,GAAG,OAAA,EAAS,MAAM,CAAA;AACpD,IAAA,IAAI,QAAQ,OAAA,EAAS;AACnB,MAAA,OAAA,CAAQ,GAAA,CAAI,CAAA,kBAAA,EAAqB,KAAA,CAAM,UAAA,IAAc,YAAY,CAAA,CAAE,CAAA;AAAA,IACrE;AACA,IAAA,OAAO,iBAAA,CAAkB,IAAA,EAAM,KAAA,EAAO,IAAI,CAAA;AAAA,EAC5C,CAAA;AACF","file":"index.js","sourcesContent":["import type { ReaderClientOptions } from \"./types\";\n\nexport const DEFAULT_CLIENT_OPTIONS: ReaderClientOptions = {\n storagePrefix: \"zr\",\n highlightColors: [\"yellow\", \"green\", \"blue\", \"pink\"],\n defaultHighlightColor: \"yellow\",\n scratchpad: { enabled: true, scopes: [\"chapter\", \"book\", \"global\"] },\n themes: [\"system\", \"light\", \"sepia\", \"dark\"],\n defaultTheme: \"system\",\n defaultSettings: {\n textSize: \"lg\",\n leading: \"relaxed\",\n measure: \"normal\",\n fontFamily: \"serif\",\n highlightMode: false,\n },\n progress: { completeAt: 0.9, saveIntervalMs: 1000 },\n backupReminder: true,\n basePath: \"/books\",\n};\n","/** Shared, framework-agnostic data model for zreader. */\n\nexport type ISODate = string;\n\n/** W3C Web Annotation-style anchor. Offsets are measured over the chapter root's text. */\nexport interface Anchor {\n /** `data-block-id` of the block containing the start of the selection. */\n blockId: string;\n /** Offsets relative to the start block's text (fast path). */\n blockStart: number;\n /** TextPositionSelector over the whole chapter text. */\n start: number;\n end: number;\n /** TextQuoteSelector. */\n exact: string;\n prefix: string;\n suffix: string;\n /** Content hash of the chapter when the anchor was created. */\n contentHash?: string;\n}\n\nexport interface Highlight {\n id: string;\n bookId: string;\n chapterId: string;\n anchor: Anchor;\n color: string;\n note?: string;\n createdAt: ISODate;\n updatedAt: ISODate;\n}\n\nexport interface Bookmark {\n id: string;\n bookId: string;\n chapterId: string;\n /** Absent for whole-chapter bookmarks. */\n blockId?: string;\n label?: string;\n excerpt?: string;\n createdAt: ISODate;\n updatedAt: ISODate;\n}\n\nexport interface ChapterProgress {\n chapterId: string;\n blockId?: string;\n /** 0..1 */\n percent: number;\n completed: boolean;\n updatedAt: ISODate;\n}\n\nexport interface BookProgress {\n bookId: string;\n chapters: Record<string, ChapterProgress>;\n last?: { chapterId: string; blockId?: string; updatedAt: ISODate };\n}\n\nexport type PadScope =\n | { kind: \"global\" }\n | { kind: \"book\"; bookId: string }\n | { kind: \"chapter\"; bookId: string; chapterId: string };\n\nexport type PadScopeKind = PadScope[\"kind\"];\n\nexport interface Pad {\n /** Markdown is the interchange/source format. */\n markdown: string;\n /** Lossless editor JSON cache. Cleared whenever `markdown` is changed outside the editor. */\n json?: unknown;\n updatedAt: ISODate;\n}\n\nexport type ThemeName = \"system\" | \"light\" | \"sepia\" | \"dark\";\nexport type Measure = \"narrow\" | \"normal\" | \"wide\";\nexport type FontFamily = \"serif\" | \"sans\" | \"mono\";\nexport type TextSize = \"sm\" | \"base\" | \"lg\" | \"xl\" | \"2xl\";\nexport type Leading = \"tight\" | \"normal\" | \"relaxed\";\n\nexport const THEMES = [\"system\", \"light\", \"sepia\", \"dark\"] as const satisfies readonly ThemeName[];\nexport const TEXT_SIZES = [\"sm\", \"base\", \"lg\", \"xl\", \"2xl\"] as const satisfies readonly TextSize[];\nexport const LEADINGS = [\"tight\", \"normal\", \"relaxed\"] as const satisfies readonly Leading[];\nexport const MEASURES = [\"narrow\", \"normal\", \"wide\"] as const satisfies readonly Measure[];\nexport const FONT_FAMILIES = [\"serif\", \"sans\", \"mono\"] as const satisfies readonly FontFamily[];\n/** The palette the UI ships styles for (`::highlight(zr-<color>)`). */\nexport const HIGHLIGHT_COLORS = [\"yellow\", \"green\", \"blue\", \"pink\", \"purple\", \"orange\"] as const;\nexport type HighlightColor = (typeof HIGHLIGHT_COLORS)[number];\n\nexport interface ReaderSettings {\n textSize: TextSize;\n leading: Leading;\n measure: Measure;\n fontFamily: FontFamily;\n /** Tap a sentence to highlight it with the default colour. */\n highlightMode: boolean;\n updatedAt: ISODate;\n}\n\n/** Serializable client options (the `reader` half of reader.config.ts). */\nexport interface ReaderClientOptions {\n storagePrefix: string;\n highlightColors: HighlightColor[];\n defaultHighlightColor: HighlightColor;\n scratchpad: { enabled: boolean; scopes: PadScopeKind[] };\n /** Themes offered in the UI. Applied as a class on <html> via next-themes. */\n themes: ThemeName[];\n defaultTheme: ThemeName;\n defaultSettings: Omit<ReaderSettings, \"updatedAt\">;\n progress: { completeAt: number; saveIntervalMs: number };\n /** Show a \"your notes only live in this browser\" reminder. */\n backupReminder: boolean;\n /** Base path used to build links back into the reader (e.g. quote-to-pad). */\n basePath: string;\n}\n\nexport interface TocEntry {\n id: string;\n depth: number;\n text: string;\n}\n\nexport interface ChapterMeta {\n id: string;\n title: string;\n order: number;\n description?: string;\n /** Section the chapter belongs to, e.g. \"Part I · For the Builders\". Groups the contents list. */\n part?: string;\n /** Eyebrow shown above the title, e.g. \"Chapter 5\" or \"Appendix A\". */\n label?: string;\n /** Short marker for lists, e.g. \"5\" or \"A\". */\n number?: string;\n}\n\nexport interface BookMeta {\n id: string;\n title: string;\n subtitle?: string;\n authors: string[];\n description?: string;\n cover?: string;\n chapters: ChapterMeta[];\n}\n","import { z } from \"zod/v4\";\nimport { DEFAULT_CLIENT_OPTIONS } from \"../core/defaults\";\nimport {\n FONT_FAMILIES,\n HIGHLIGHT_COLORS,\n LEADINGS,\n MEASURES,\n TEXT_SIZES,\n THEMES,\n type ReaderClientOptions,\n} from \"../core/types\";\n\nexport { z };\n\n// ---------------------------------------------------------------- types\n\nexport interface GlobLoader {\n kind: \"glob\";\n /** Directory containing one folder per book. Relative to the project root. */\n base: string;\n /** Chapter files, relative to `base`. */\n pattern: string | string[];\n ignore?: string[];\n}\n\n/** Astro-style glob loader: `content/books/<book>/{book.json, 01-intro.md, ...}` */\nexport function glob(opts: { base: string; pattern?: string | string[]; ignore?: string[] }): GlobLoader {\n return { kind: \"glob\", base: opts.base, pattern: opts.pattern ?? \"**/*.{md,mdx,html}\", ignore: opts.ignore };\n}\n\n// unified's PluggableList, kept loose to avoid a type dependency in this entry.\nexport type PluginList = unknown[];\n\nexport interface SanitizeOptions {\n /** Hostnames allowed for <iframe src>. Iframes are stripped unless listed here. */\n allowIframes?: string[];\n /** Extra tags to allow on top of DOMPurify's safe HTML profile. */\n allowTags?: string[];\n /** Extra attributes to allow. */\n allowAttributes?: string[];\n}\n\nexport interface ContentConfig {\n loader: GlobLoader;\n schemas: { book: z.ZodType; chapter: z.ZodType };\n /** Applied to `.md` and `.mdx`. */\n remarkPlugins: PluginList;\n rehypePlugins: PluginList;\n sanitize: SanitizeOptions;\n /** Include chapters with `draft: true`. Defaults to `true` in development. */\n includeDrafts: boolean;\n /** Where compiled chapters are cached. */\n cacheDir: string;\n}\n\ntype DeepPartial<T> = T extends unknown[] ? T : T extends object ? { [K in keyof T]?: DeepPartial<T[K]> } : T;\n\nexport interface ReaderUserConfig {\n content?: DeepPartial<Omit<ContentConfig, \"schemas\" | \"loader\">> & {\n loader?: GlobLoader;\n schemas?: Partial<ContentConfig[\"schemas\"]>;\n };\n reader?: DeepPartial<ReaderClientOptions>;\n}\n\nexport interface ResolvedReaderConfig {\n root: string;\n content: ContentConfig;\n reader: ReaderClientOptions;\n}\n\n// ------------------------------------------------------------- defaults\n\nexport const defaultBookSchema = z.looseObject({\n title: z.string(),\n subtitle: z.string().optional(),\n authors: z.array(z.string()).default([]),\n description: z.string().optional(),\n cover: z.string().optional(),\n /** Optional explicit chapter order (chapter slugs). */\n chapters: z.array(z.string()).optional(),\n});\n\nexport const defaultChapterSchema = z.looseObject({\n title: z.string(),\n order: z.number().optional(),\n description: z.string().optional(),\n part: z.string().optional(),\n label: z.string().optional(),\n number: z.union([z.string(), z.number()]).transform(String).optional(),\n draft: z.boolean().default(false),\n});\n\nfunction isDev() {\n return typeof process !== \"undefined\" && process.env?.NODE_ENV === \"development\";\n}\n\nexport function defaultContentConfig(): ContentConfig {\n return {\n loader: glob({ base: \"./content/books\" }),\n schemas: { book: defaultBookSchema, chapter: defaultChapterSchema },\n remarkPlugins: [],\n rehypePlugins: [],\n sanitize: {},\n includeDrafts: isDev(),\n cacheDir:\n (typeof process !== \"undefined\" && process.env?.ZREADER_CACHE_DIR) || \"node_modules/.cache/zreader\",\n };\n}\n\n// ------------------------------------------------------------ define/merge\n\n/** Identity helper that gives `reader.config.ts` full type-checking. */\nexport function defineConfig(config: ReaderUserConfig): ReaderUserConfig {\n return config;\n}\n\nfunction isPlainObject(x: unknown): x is Record<string, unknown> {\n if (typeof x !== \"object\" || x === null || Array.isArray(x)) return false;\n const proto = Object.getPrototypeOf(x);\n return proto === Object.prototype || proto === null;\n}\n\n/**\n * Deep merge: plain objects merge key-by-key, arrays and class instances\n * (e.g. zod schemas) replace, `undefined` never overrides.\n */\nexport function mergeConfig<T>(base: T, ...overrides: unknown[]): T {\n let out: unknown = base;\n for (const o of overrides) out = mergeTwo(out, o);\n return out as T;\n}\n\nfunction mergeTwo(a: unknown, b: unknown): unknown {\n if (b === undefined) return a;\n if (isPlainObject(a) && isPlainObject(b)) {\n const out: Record<string, unknown> = { ...a };\n for (const [k, v] of Object.entries(b)) out[k] = mergeTwo(a[k], v);\n return out;\n }\n return b;\n}\n\n// --------------------------------------------------------------- validate\n\nconst themeName = z.enum(THEMES);\nconst highlightColor = z.enum(HIGHLIGHT_COLORS);\nconst clientSchema = z\n .object({\n storagePrefix: z.string().regex(/^[a-z0-9_-]+$/i, \"use letters, digits, '-' or '_'\"),\n highlightColors: z.array(highlightColor).min(1, \"must be non-empty\"),\n defaultHighlightColor: highlightColor,\n scratchpad: z.object({\n enabled: z.boolean(),\n scopes: z.array(z.enum([\"global\", \"book\", \"chapter\"])).min(1, \"must be non-empty\"),\n }),\n themes: z.array(themeName).min(1),\n defaultTheme: themeName,\n defaultSettings: z.object({\n textSize: z.enum(TEXT_SIZES),\n leading: z.enum(LEADINGS),\n measure: z.enum(MEASURES),\n fontFamily: z.enum(FONT_FAMILIES),\n highlightMode: z.boolean(),\n }),\n progress: z.object({ completeAt: z.number().gt(0).max(1), saveIntervalMs: z.number().min(100) }),\n backupReminder: z.boolean(),\n basePath: z.string().startsWith(\"/\"),\n })\n .refine((c) => c.highlightColors.includes(c.defaultHighlightColor), {\n message: \"defaultHighlightColor must be one of highlightColors\",\n path: [\"defaultHighlightColor\"],\n })\n .refine((c) => c.themes.includes(c.defaultTheme), {\n message: \"defaultTheme must be one of themes\",\n path: [\"defaultTheme\"],\n });\n\nfunction isSchemaLike(v: unknown): boolean {\n return typeof v === \"object\" && v !== null && typeof (v as { safeParse?: unknown }).safeParse === \"function\";\n}\n\nconst contentSchema = z.object({\n loader: z.object({\n kind: z.literal(\"glob\"),\n base: z.string().min(1),\n pattern: z.union([z.string(), z.array(z.string()).min(1)]),\n ignore: z.array(z.string()).optional(),\n }),\n schemas: z.object({\n book: z.custom<z.ZodType>(isSchemaLike, \"must be a zod (or safeParse-compatible) schema\"),\n chapter: z.custom<z.ZodType>(isSchemaLike, \"must be a zod (or safeParse-compatible) schema\"),\n }),\n remarkPlugins: z.array(z.any()),\n rehypePlugins: z.array(z.any()),\n sanitize: z.object({\n allowIframes: z.array(z.string()).optional(),\n allowTags: z.array(z.string()).optional(),\n allowAttributes: z.array(z.string()).optional(),\n }),\n includeDrafts: z.boolean(),\n cacheDir: z.string(),\n});\n\nexport class ReaderConfigError extends Error {\n constructor(\n message: string,\n public readonly issues: { path: string; message: string }[] = [],\n ) {\n super(message);\n this.name = \"ReaderConfigError\";\n }\n}\n\nfunction formatIssues(source: string, section: string, error: z.ZodError) {\n const issues = error.issues.map((i) => ({ path: [section, ...i.path.map(String)].join(\".\"), message: i.message }));\n return new ReaderConfigError(\n `Invalid reader config${source ? ` (${source})` : \"\"}:\\n` + issues.map((i) => ` - ${i.path}: ${i.message}`).join(\"\\n\"),\n issues,\n );\n}\n\n/**\n * Resolve the final config: package defaults ← reader.config.ts ← inline overrides.\n * Throws `ReaderConfigError` with readable messages.\n */\nexport function resolveConfig(\n user?: ReaderUserConfig | null,\n inline?: ReaderUserConfig | null,\n opts: { root?: string; source?: string } = {},\n): ResolvedReaderConfig {\n const root = opts.root ?? (typeof process !== \"undefined\" && process.cwd ? process.cwd() : \"/\");\n const reader = mergeConfig<ReaderClientOptions>(\n structuredClone(DEFAULT_CLIENT_OPTIONS),\n user?.reader,\n inline?.reader,\n );\n const content = mergeConfig<ContentConfig>(defaultContentConfig(), user?.content, inline?.content);\n\n const r = clientSchema.safeParse(reader);\n if (!r.success) throw formatIssues(opts.source ?? \"\", \"reader\", r.error);\n const c = contentSchema.safeParse(content);\n if (!c.success) throw formatIssues(opts.source ?? \"\", \"content\", c.error);\n\n return { root, content, reader };\n}\n\n/** Only the serializable, client-safe half. */\nexport function clientOptions(config: ResolvedReaderConfig): ReaderClientOptions {\n return config.reader;\n}\n\nexport const CONFIG_FILE_NAMES = [\"reader.config.ts\", \"reader.config.mts\", \"reader.config.mjs\", \"reader.config.js\"];\n","/** Node-only helpers for locating and loading reader.config.* (via jiti). */\nimport { existsSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { CONFIG_FILE_NAMES, type ReaderUserConfig } from \"./index\";\n\n/** Search `from` and its parents (up to the filesystem root or a `.git` dir) for reader.config.*. */\nexport function findConfigFile(from: string = process.cwd()): string | null {\n let dir = resolve(from);\n for (;;) {\n for (const name of CONFIG_FILE_NAMES) {\n const p = join(dir, name);\n if (existsSync(p)) return p;\n }\n if (existsSync(join(dir, \"package.json\")) || existsSync(join(dir, \".git\"))) return null;\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\nexport async function loadConfigFile(file: string): Promise<ReaderUserConfig> {\n const { createJiti } = await import(\"jiti\");\n const jiti = createJiti(file, { interopDefault: true, moduleCache: false });\n const mod = (await jiti.import(file)) as { default?: ReaderUserConfig } | ReaderUserConfig;\n const cfg = (mod && typeof mod === \"object\" && \"default\" in mod ? mod.default : mod) as ReaderUserConfig | undefined;\n return cfg ?? {};\n}\n","/**\n * Next.js integration.\n *\n * // next.config.ts\n * import { withReader } from \"zreader/next\";\n * export default withReader({ reactStrictMode: true });\n */\nimport { join, relative, resolve, sep } from \"node:path\";\nimport type { NextConfig } from \"next\";\nimport { resolveConfig, type ResolvedReaderConfig, type ReaderUserConfig } from \"../config/index\";\nimport { findConfigFile, loadConfigFile } from \"../config/load\";\n\nexport const USER_CONFIG_SPECIFIER = \"zreader/user-config\";\nexport const EMPTY_CONFIG_SPECIFIER = \"zreader/empty-config\";\n\n/** Packages that must stay external on the server (dynamic requires / native-ish). */\nexport const SERVER_EXTERNALS = [\"jsdom\", \"isomorphic-dompurify\"];\n\nexport interface WithReaderOptions {\n /** Path to the config file. Defaults to discovering reader.config.{ts,mts,mjs,js}. */\n configPath?: string;\n /** Project root. Defaults to process.cwd() (the directory containing next.config). */\n root?: string;\n /** Inline overrides merged on top of reader.config.ts. */\n config?: ReaderUserConfig;\n /** Log the resolved config file path at startup. */\n verbose?: boolean;\n}\n\ntype NextConfigFn = (phase: string, ctx: { defaultConfig: NextConfig }) => NextConfig | Promise<NextConfig>;\nexport type NextConfigInput = NextConfig | NextConfigFn;\n\ntype WebpackFn = NonNullable<NextConfig[\"webpack\"]>;\n\nfunction toPosix(p: string) {\n return p.split(sep).join(\"/\");\n}\n\n/** Alias target relative to the project root, as Turbopack expects (`./reader.config.ts`). */\nfunction relativeImport(root: string, file: string) {\n const rel = toPosix(relative(root, file));\n return rel.startsWith(\".\") ? rel : `./${rel}`;\n}\n\nexport interface ReaderNextSetup {\n configFile: string | null;\n resolved: ResolvedReaderConfig;\n}\n\n/** Pure transform (exported for testing): apply reader wiring to a resolved Next config. */\nexport function applyReaderConfig(base: NextConfig, setup: ReaderNextSetup, root: string): NextConfig {\n const { configFile, resolved } = setup;\n const turboTarget = configFile ? relativeImport(root, configFile) : EMPTY_CONFIG_SPECIFIER;\n const webpackTarget = configFile ?? EMPTY_CONFIG_SPECIFIER;\n\n const prevWebpack = base.webpack as WebpackFn | undefined;\n const webpack: WebpackFn = (config, ctx) => {\n const cfg = (prevWebpack ? prevWebpack(config, ctx) : config) as { resolve?: { alias?: Record<string, unknown> } };\n cfg.resolve ??= {};\n const alias = (cfg.resolve.alias ??= {}) as Record<string, unknown>;\n alias[`${USER_CONFIG_SPECIFIER}$`] = webpackTarget;\n return cfg;\n };\n\n const contentGlob = toPosix(join(resolved.content.loader.base, \"**/*\"));\n const tracing = { ...(base.outputFileTracingIncludes ?? {}) };\n const allRoutes = \"/**\";\n tracing[allRoutes] = Array.from(new Set([...(tracing[allRoutes] ?? []), contentGlob]));\n\n const externals = Array.from(new Set([...(base.serverExternalPackages ?? []), ...SERVER_EXTERNALS]));\n\n return {\n ...base,\n serverExternalPackages: externals,\n outputFileTracingIncludes: tracing,\n turbopack: {\n ...base.turbopack,\n resolveAlias: {\n ...base.turbopack?.resolveAlias,\n [USER_CONFIG_SPECIFIER]: turboTarget,\n },\n },\n webpack,\n };\n}\n\nexport async function setupReader(options: WithReaderOptions = {}): Promise<ReaderNextSetup> {\n const root = resolve(options.root ?? process.cwd());\n const configFile = options.configPath ? resolve(root, options.configPath) : findConfigFile(root);\n const user = configFile ? await loadConfigFile(configFile) : {};\n // Validate eagerly so `next dev` / `next build` fail fast with a readable error.\n const resolved = resolveConfig(user, options.config, {\n root,\n source: configFile ? relative(root, configFile) : \"defaults\",\n });\n return { configFile, resolved };\n}\n\n/**\n * Wire zreader into Next.js:\n * - validates reader.config.* at startup;\n * - aliases `zreader/user-config` to it (Turbopack + webpack), so\n * `zreader/virtual-config` is the resolved config everywhere on the server;\n * - keeps jsdom/DOMPurify external on the server;\n * - traces the content directory into the server output (Vercel);\n * - points the compiled-chapter cache at `.next/cache/zreader`.\n */\nexport function withReader(nextConfig: NextConfigInput = {}, options: WithReaderOptions = {}): NextConfigFn {\n return async (phase, ctx) => {\n const root = resolve(options.root ?? process.cwd());\n process.env.ZREADER_CACHE_DIR ??= join(root, \".next\", \"cache\", \"zreader\");\n const base = typeof nextConfig === \"function\" ? await nextConfig(phase, ctx) : nextConfig;\n const setup = await setupReader({ ...options, root });\n if (options.verbose) {\n console.log(`[zreader] config: ${setup.configFile ?? \"(defaults)\"}`);\n }\n return applyReaderConfig(base, setup, root);\n };\n}\n\nexport { resolveConfig, findConfigFile, loadConfigFile };\nexport type { ResolvedReaderConfig, ReaderUserConfig };\n"]}
@@ -0,0 +1,58 @@
1
+ import * as zreader from 'zreader';
2
+ import { BookMeta } from 'zreader';
3
+ import * as react from 'react';
4
+ import { ReactNode } from 'react';
5
+ export { default as readerConfig } from 'zreader/virtual-config';
6
+ import { MdxComponents } from 'zreader/content';
7
+ import { ReaderProps, ReaderProviderProps, Callout } from 'zreader/react';
8
+
9
+ /**
10
+ * Default MDX components (built here, in a server module, so RSC pages get real
11
+ * component references): `<Content components={mdxComponents} />`.
12
+ */
13
+ declare const mdxComponents: {
14
+ Callout: typeof Callout;
15
+ };
16
+ interface ReaderRootProps extends Omit<ReaderProviderProps, "options" | "store" | "adapter" | "onStorageError" | "Link" | "books" | "headerSlot"> {
17
+ /** Defaults to every book from the content layer (`getBookMetas()`). */
18
+ books?: BookMeta[];
19
+ /**
20
+ * Default content for the middle of the reader's top bar (text or any element).
21
+ * Server-rendered, so it must be a node, not a function.
22
+ */
23
+ headerSlot?: ReactNode;
24
+ children: ReactNode;
25
+ }
26
+ /**
27
+ * The reader's provider for Next.js: client options from reader.config.ts, the
28
+ * book catalogue from the content layer, and next/link for every link.
29
+ */
30
+ declare function ReaderRoot({ books, children, ...props }: ReaderRootProps): Promise<react.JSX.Element>;
31
+ interface ReaderChapterProps extends Omit<ReaderProps, "book" | "chapter" | "html" | "children" | "toc" | "contentHash" | "Link" | "hrefFor" | "header"> {
32
+ /** Book id (a `[book]` route param). */
33
+ book: string;
34
+ /** Chapter id (a `[chapter]` route param). */
35
+ chapter: string;
36
+ /** Extra MDX components, merged over `mdxComponents`. */
37
+ components?: MdxComponents;
38
+ /** Top-bar content for this chapter only (overrides the provider's). */
39
+ header?: ReactNode;
40
+ }
41
+ /**
42
+ * Loads, compiles and renders one chapter (Markdown, HTML or MDX) inside <Reader>.
43
+ * Calls `notFound()` for unknown ids. Must be rendered under <ReaderRoot>.
44
+ */
45
+ declare function ReaderChapter({ book, chapter, components, ...props }: ReaderChapterProps): Promise<react.JSX.Element>;
46
+ /** `export const generateStaticParams = getBookParams` in `app/books/[book]/page.tsx`. */
47
+ declare function getBookParams(): Promise<Array<{
48
+ book: string;
49
+ }>>;
50
+ /** `export const generateStaticParams = getChapterParams` in `app/books/[book]/[chapter]/page.tsx`. */
51
+ declare function getChapterParams(): Promise<Array<{
52
+ book: string;
53
+ chapter: string;
54
+ }>>;
55
+ declare function getClientOptions(): zreader.ReaderClientOptions;
56
+
57
+ export { ReaderChapter, ReaderRoot, getBookParams, getChapterParams, getClientOptions, mdxComponents };
58
+ export type { ReaderChapterProps, ReaderRootProps };
@@ -0,0 +1,44 @@
1
+ import { notFound } from 'next/navigation';
2
+ import config from 'zreader/virtual-config';
3
+ export { default as readerConfig } from 'zreader/virtual-config';
4
+ import { getBookMetas, getChapter, renderChapter, getStaticParams } from 'zreader/content';
5
+ import { Callout, Reader } from 'zreader/react';
6
+ import { NextReaderProvider } from 'zreader/next/client';
7
+ import { jsx } from 'react/jsx-runtime';
8
+
9
+ // src/next/server/index.tsx
10
+ var mdxComponents = { Callout };
11
+ async function ReaderRoot({ books, children, ...props }) {
12
+ const catalogue = books ?? await getBookMetas();
13
+ return /* @__PURE__ */ jsx(NextReaderProvider, { options: config.reader, books: catalogue, ...props, children });
14
+ }
15
+ async function ReaderChapter({ book, chapter, components, ...props }) {
16
+ const hit = await getChapter(book, chapter);
17
+ if (!hit) notFound();
18
+ const rendered = await renderChapter(hit.chapter);
19
+ return /* @__PURE__ */ jsx(
20
+ Reader,
21
+ {
22
+ ...props,
23
+ book,
24
+ chapter,
25
+ toc: rendered.toc,
26
+ contentHash: rendered.contentHash,
27
+ html: rendered.kind === "html" ? rendered.html : void 0,
28
+ children: rendered.kind === "mdx" ? /* @__PURE__ */ jsx(rendered.Content, { components: { ...mdxComponents, ...components } }) : null
29
+ }
30
+ );
31
+ }
32
+ async function getBookParams() {
33
+ return (await getBookMetas()).map((b) => ({ book: b.id }));
34
+ }
35
+ async function getChapterParams() {
36
+ return getStaticParams();
37
+ }
38
+ function getClientOptions() {
39
+ return config.reader;
40
+ }
41
+
42
+ export { ReaderChapter, ReaderRoot, getBookParams, getChapterParams, getClientOptions, mdxComponents };
43
+ //# sourceMappingURL=index.js.map
44
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../src/next/server/index.tsx"],"names":[],"mappings":";;;;;;;;;AAwBO,IAAM,aAAA,GAAgB,EAAE,OAAA;AAiB/B,eAAsB,WAAW,EAAE,KAAA,EAAO,QAAA,EAAU,GAAG,OAAM,EAAoB;AAC/E,EAAA,MAAM,SAAA,GAAY,KAAA,IAAU,MAAM,YAAA,EAAa;AAC/C,EAAA,uBACE,GAAA,CAAC,sBAAmB,OAAA,EAAS,MAAA,CAAO,QAAQ,KAAA,EAAO,SAAA,EAAY,GAAG,KAAA,EAC/D,QAAA,EACH,CAAA;AAEJ;AAiBA,eAAsB,cAAc,EAAE,IAAA,EAAM,SAAS,UAAA,EAAY,GAAG,OAAM,EAAuB;AAC/F,EAAA,MAAM,GAAA,GAAM,MAAM,UAAA,CAAW,IAAA,EAAM,OAAO,CAAA;AAC1C,EAAA,IAAI,CAAC,KAAK,QAAA,EAAS;AACnB,EAAA,MAAM,QAAA,GAAW,MAAM,aAAA,CAAc,GAAA,CAAI,OAAO,CAAA;AAChD,EAAA,uBACE,GAAA;AAAA,IAAC,MAAA;AAAA,IAAA;AAAA,MACE,GAAG,KAAA;AAAA,MACJ,IAAA;AAAA,MACA,OAAA;AAAA,MACA,KAAK,QAAA,CAAS,GAAA;AAAA,MACd,aAAa,QAAA,CAAS,WAAA;AAAA,MACtB,IAAA,EAAM,QAAA,CAAS,IAAA,KAAS,MAAA,GAAS,SAAS,IAAA,GAAO,MAAA;AAAA,MAEhD,QAAA,EAAA,QAAA,CAAS,IAAA,KAAS,KAAA,mBAAQ,GAAA,CAAC,SAAS,OAAA,EAAT,EAAiB,UAAA,EAAY,EAAE,GAAG,aAAA,EAAe,GAAG,UAAA,IAA+B,CAAA,GAAK;AAAA;AAAA,GACtH;AAEJ;AAGA,eAAsB,aAAA,GAAkD;AACtE,EAAA,OAAA,CAAQ,MAAM,YAAA,EAAa,EAAG,GAAA,CAAI,CAAC,OAAO,EAAE,IAAA,EAAM,CAAA,CAAE,EAAA,EAAG,CAAE,CAAA;AAC3D;AAGA,eAAsB,gBAAA,GAAsE;AAC1F,EAAA,OAAO,eAAA,EAAgB;AACzB;AAEO,SAAS,gBAAA,GAAmB;AACjC,EAAA,OAAO,MAAA,CAAO,MAAA;AAChB","file":"index.js","sourcesContent":["/**\n * `zreader/next/server` — React Server Components for the optional\n * Next.js adapter. Other React apps wire <ReaderProvider> themselves.\n *\n * // app/books/layout.tsx — provider with the whole catalogue + next/link\n * export default function Layout({ children }) { return <ReaderRoot>{children}</ReaderRoot>; }\n *\n * // app/books/page.tsx → <BookShelf />\n * // app/books/[book]/page.tsx → <BookContents book={params.book} />\n * // app/books/[book]/[chapter]/page.tsx\n * export default async function Page({ params }) { return <ReaderChapter {...await params} />; }\n */\nimport type { ReactNode } from \"react\";\nimport { notFound } from \"next/navigation\";\nimport config from \"zreader/virtual-config\";\nimport { getBookMetas, getChapter, getStaticParams, renderChapter, type MdxComponents } from \"zreader/content\";\nimport { Callout, Reader, type ReaderProps, type ReaderProviderProps } from \"zreader/react\";\nimport { NextReaderProvider } from \"zreader/next/client\";\nimport type { BookMeta } from \"zreader\";\n\n/**\n * Default MDX components (built here, in a server module, so RSC pages get real\n * component references): `<Content components={mdxComponents} />`.\n */\nexport const mdxComponents = { Callout };\n\nexport interface ReaderRootProps extends Omit<ReaderProviderProps, \"options\" | \"store\" | \"adapter\" | \"onStorageError\" | \"Link\" | \"books\" | \"headerSlot\"> {\n /** Defaults to every book from the content layer (`getBookMetas()`). */\n books?: BookMeta[];\n /**\n * Default content for the middle of the reader's top bar (text or any element).\n * Server-rendered, so it must be a node, not a function.\n */\n headerSlot?: ReactNode;\n children: ReactNode;\n}\n\n/**\n * The reader's provider for Next.js: client options from reader.config.ts, the\n * book catalogue from the content layer, and next/link for every link.\n */\nexport async function ReaderRoot({ books, children, ...props }: ReaderRootProps) {\n const catalogue = books ?? (await getBookMetas());\n return (\n <NextReaderProvider options={config.reader} books={catalogue} {...props}>\n {children}\n </NextReaderProvider>\n );\n}\n\nexport interface ReaderChapterProps extends Omit<ReaderProps, \"book\" | \"chapter\" | \"html\" | \"children\" | \"toc\" | \"contentHash\" | \"Link\" | \"hrefFor\" | \"header\"> {\n /** Book id (a `[book]` route param). */\n book: string;\n /** Chapter id (a `[chapter]` route param). */\n chapter: string;\n /** Extra MDX components, merged over `mdxComponents`. */\n components?: MdxComponents;\n /** Top-bar content for this chapter only (overrides the provider's). */\n header?: ReactNode;\n}\n\n/**\n * Loads, compiles and renders one chapter (Markdown, HTML or MDX) inside <Reader>.\n * Calls `notFound()` for unknown ids. Must be rendered under <ReaderRoot>.\n */\nexport async function ReaderChapter({ book, chapter, components, ...props }: ReaderChapterProps) {\n const hit = await getChapter(book, chapter);\n if (!hit) notFound();\n const rendered = await renderChapter(hit.chapter);\n return (\n <Reader\n {...props}\n book={book}\n chapter={chapter}\n toc={rendered.toc}\n contentHash={rendered.contentHash}\n html={rendered.kind === \"html\" ? rendered.html : undefined}\n >\n {rendered.kind === \"mdx\" ? <rendered.Content components={{ ...mdxComponents, ...components } as MdxComponents} /> : null}\n </Reader>\n );\n}\n\n/** `export const generateStaticParams = getBookParams` in `app/books/[book]/page.tsx`. */\nexport async function getBookParams(): Promise<Array<{ book: string }>> {\n return (await getBookMetas()).map((b) => ({ book: b.id }));\n}\n\n/** `export const generateStaticParams = getChapterParams` in `app/books/[book]/[chapter]/page.tsx`. */\nexport async function getChapterParams(): Promise<Array<{ book: string; chapter: string }>> {\n return getStaticParams();\n}\n\nexport function getClientOptions() {\n return config.reader;\n}\n\nexport { config as readerConfig };\n"]}