@flipbook-md/core 0.13.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,15 @@
2
2
 
3
3
  The shared library behind [Flipbook MD](https://github.com/uminocelo/flipbook-md). It loads Markdown decks, applies templates, groups, themes and blueprints, serves the slide player, and exports PNG carousels and MP4 videos.
4
4
 
5
- The `flipbook` CLI and Flipbook Studio both build on this package. If you only want to present or export a deck, install the CLI instead:
5
+ It is one of three Flipbook MD projects:
6
+
7
+ | Project | What it is |
8
+ | --- | --- |
9
+ | [`flipbook-md`](https://github.com/uminocelo/flipbook-md) | The `flipbook` command: present, check and export decks. |
10
+ | `@flipbook-md/core` (this package) | The library both apps build on: loading, rendering, blueprints, export and document import. |
11
+ | Flipbook Studio | A self-hosted editor for the same deck files, with optional AI from a model running on your machine. **Coming soon.** |
12
+
13
+ If you only want to present or export a deck, install the CLI instead:
6
14
 
7
15
  ```sh
8
16
  npm install -g flipbook-md
@@ -86,6 +94,21 @@ await writeKit(talk, { patch: { types: { point: { max_chars: 250 } } } }, (await
86
94
  await writeKit({ kind: "template", name: "quote", scope: "deck", deckDir }, { patch: { align: "start" } }, hash);
87
95
  ```
88
96
 
97
+ ### Duplicate decks and kits
98
+
99
+ ```js
100
+ import { copyKit, duplicateDeck } from "@flipbook-md/core";
101
+
102
+ // A sibling copy: every file except dist/, hidden entries and symlinks; only the title changes.
103
+ const { path, skipped } = await duplicateDeck("talks/q3", { name: "q3-dry-run", title: "Q3 (dry run)" });
104
+ console.log(path, skipped); // talks/q3-dry-run [] (skipped lists any symlinks left out)
105
+
106
+ // Themes, templates and blueprints copy into the library; groups go through copyGroup.
107
+ await copyKit({ kind: "theme", name: "marvel-jarvis" }, "my-theme"); // ~/Documents/flipbook/themes/my-theme.css
108
+ ```
109
+
110
+ A single-file deck is copied to `<name>.slide.md` in the same folder and shares its `assets/`.
111
+
89
112
  ### Copy and rename media kits
90
113
 
91
114
  ```js
package/index.d.ts CHANGED
@@ -447,6 +447,18 @@ export function insertSlide(
447
447
  export function removeSlide(deckPath: string, slideId: SlideId, baseHash: string): Promise<{ hashes: Record<string, string> }>;
448
448
  /** `slideIds` must be a permutation of the deck's slides, or it throws ValidationError. */
449
449
  export function reorderSlides(deckPath: string, slideIds: SlideId[], baseHash: string): Promise<{ hashes: Record<string, string> }>;
450
+ /**
451
+ * A single-file deck's text as `glue[0] cores[0] glue[1] … cores[n-1] glue[n]`, split the way
452
+ * the slide writer splits it: `---` lines outside notes comments, after the frontmatter. Cores
453
+ * are the slides without surrounding whitespace; glue holds the frontmatter, blank lines and `---`.
454
+ */
455
+ export interface ChunkLayout {
456
+ cores: string[];
457
+ glue: string[];
458
+ }
459
+ export function chunkLayout(text: string): ChunkLayout;
460
+ /** The inverse of chunkLayout: `joinLayout(chunkLayout(text)) === text`. */
461
+ export function joinLayout(layout: ChunkLayout): string;
450
462
 
451
463
  // server
452
464
  /**
@@ -579,6 +591,29 @@ export function renameGroup(ref: { name: string; scope: "library" | "builtin" },
579
591
  /** The deck paths (folders or .slide.md files) whose `group:` is `name`. */
580
592
  export function findDecksUsingGroup(name: string, deckPaths: string[]): Promise<string[]>;
581
593
 
594
+ // duplicate (US-20, D26, D27)
595
+ export interface DuplicateDeckOptions {
596
+ /** 1-60 lowercase letters, digits or dashes; the copy's folder name or `<name>.slide.md`. */
597
+ name: string;
598
+ /** 1-120 characters; the only field that differs from the original. */
599
+ title: string;
600
+ }
601
+ /**
602
+ * Duplicates a deck beside itself. Folder decks leave out `dist/`, hidden entries and symlinks
603
+ * (listed in `skipped`); a single-file deck shares its folder's `assets/`. Throws DeckExistsError,
604
+ * or ValidationError with code VALIDATION_FAILED, DECK_NOT_FOUND or DECK_LOAD_FAILED.
605
+ */
606
+ export function duplicateDeck(deckPath: string, options: DuplicateDeckOptions): Promise<{ path: string; skipped: string[] }>;
607
+ /**
608
+ * Copies a theme, template, blueprint or group into the library as `toName`. Without `scope`, the
609
+ * library is tried first, then the built-ins. Throws KitNotFoundError, KitExistsError,
610
+ * KitInvalidError, or ValidationError (bad name, or deck scope).
611
+ */
612
+ export function copyKit(
613
+ fromRef: { kind: KitKind; name: string; scope?: "library" | "builtin" },
614
+ toName: string
615
+ ): Promise<{ ref: KitRef; hash: string; path: string; source: string }>;
616
+
582
617
  export function evaluateDraftBlueprint(presentation: Presentation, blueprintSource: string | unknown): { errors: string[]; violations?: undefined } | { violations: Violation[]; errors?: undefined };
583
618
 
584
619
  // kits
package/index.js CHANGED
@@ -6,6 +6,7 @@ export * from "./src/blueprint.js";
6
6
  export * from "./src/chrome.js";
7
7
  export * from "./src/configuration.js";
8
8
  export * from "./src/create.js";
9
+ export * from "./src/duplicate.js";
9
10
  export * from "./src/export.js";
10
11
  export * from "./src/groups.js";
11
12
  export * from "./src/import.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flipbook-md/core",
3
- "version": "0.13.0",
3
+ "version": "0.14.1",
4
4
  "description": "Load, render, check and export Flipbook MD decks. Shared by the flipbook CLI and Flipbook Studio.",
5
5
  "license": "MIT",
6
6
  "author": "Celo (https://github.com/uminocelo)",
@@ -0,0 +1,167 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { isScalar, parseDocument, stringify as stringifyYaml } from "yaml";
5
+ import { copyGroup } from "./group-ops.js";
6
+ import { assertFree, validateNewDeck } from "./internal/deck-checks.js";
7
+ import { readKit, writeKit } from "./kits.js";
8
+ import { discoverPresentation } from "./presentation.js";
9
+ import { DeckExistsError, FileConflictError, KitInvalidError, ValidationError, atomicCreate } from "./writer.js";
10
+
11
+ // US-20: duplicate a deck beside itself (D26) and copy kit pieces into the library (D27).
12
+
13
+ const FRONTMATTER = /^(---\r?\n)([\s\S]*?\r?\n)?(---(?:\r?\n|$))/;
14
+ const SKIPPED_TOP_LEVEL = new Set(["dist"]);
15
+
16
+ /**
17
+ * `yamlText` with its top-level `title` set to `title`. Only the title's characters change (the
18
+ * scalar is spliced in place), so comments, order and formatting stay byte for byte. A file with
19
+ * no `title` gets one as its first line.
20
+ */
21
+ function withTitle(yamlText, title) {
22
+ const doc = parseDocument(yamlText);
23
+ if (doc.errors.length) throw new ValidationError(`Not valid YAML: ${doc.errors[0].message.split("\n")[0]}`, { code: "DECK_LOAD_FAILED" });
24
+ const value = stringifyYaml(title, { lineWidth: 0 }).trimEnd();
25
+ const node = doc.get("title", true);
26
+ if (isScalar(node) && node.range) {
27
+ const [start, valueEnd] = node.range;
28
+ return `${yamlText.slice(0, start)}${value}${yamlText.slice(valueEnd)}`;
29
+ }
30
+ return `title: ${value}\n${yamlText}`;
31
+ }
32
+
33
+ /** A single-file deck's text with its frontmatter title changed (frontmatter added when missing). */
34
+ function singleFileWithTitle(text, title) {
35
+ const match = FRONTMATTER.exec(text);
36
+ if (!match) return `---\n${withTitle("", title)}---\n\n${text}`;
37
+ const [whole, open, body = "", close] = match;
38
+ return `${open}${withTitle(body, title)}${close}${text.slice(whole.length)}`;
39
+ }
40
+
41
+ /**
42
+ * Copies `from` into `to` (which must not exist), skipping hidden entries, symlinks and, at the
43
+ * top level, `dist/`. Returns the skipped symlinks as paths relative to the deck.
44
+ */
45
+ async function copyTree(from, to, relative = "") {
46
+ const skipped = [];
47
+ await fs.mkdir(to);
48
+ for (const entry of await fs.readdir(from, { withFileTypes: true })) {
49
+ if (entry.name.startsWith(".")) continue;
50
+ if (!relative && SKIPPED_TOP_LEVEL.has(entry.name) && entry.isDirectory()) continue;
51
+ const rel = relative ? `${relative}/${entry.name}` : entry.name;
52
+ const source = path.join(from, entry.name);
53
+ const target = path.join(to, entry.name);
54
+ if (entry.isSymbolicLink()) skipped.push(rel);
55
+ else if (entry.isDirectory()) skipped.push(...(await copyTree(source, target, rel)));
56
+ else if (entry.isFile()) await fs.copyFile(source, target, fs.constants.COPYFILE_EXCL);
57
+ }
58
+ return skipped;
59
+ }
60
+
61
+ async function loadable(deckPath) {
62
+ try {
63
+ // Evaluate, don't enforce: a deck with blueprint violations still duplicates.
64
+ await discoverPresentation(deckPath, { blueprint: "evaluate" });
65
+ } catch (error) {
66
+ throw new ValidationError(error.message, { code: "DECK_LOAD_FAILED", path: deckPath });
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Duplicates a deck beside itself as `name` with `title` (D26). A folder deck is copied into a
72
+ * hidden temporary sibling and renamed into place, so a failure leaves nothing behind; `dist/`,
73
+ * hidden entries and symlinks are left out (symlinks are listed in `skipped`). A single-file deck
74
+ * becomes `<name>.slide.md` in the same folder and shares its `assets/`. Only `title` changes.
75
+ * Returns `{ path, skipped }`.
76
+ */
77
+ export async function duplicateDeck(deckPath, options = {}) {
78
+ const { name, title } = validateNewDeck({ name: options.name, title: options.title, kind: "folder", group: null });
79
+ const absolute = path.resolve(deckPath);
80
+ const stat = await fs.lstat(absolute).catch(() => {
81
+ throw new ValidationError(`Deck does not exist: ${absolute}`, { code: "DECK_NOT_FOUND", path: absolute });
82
+ });
83
+ await loadable(absolute);
84
+ const parent = path.dirname(absolute);
85
+
86
+ if (stat.isFile()) {
87
+ const file = path.join(parent, `${name}.slide.md`);
88
+ await assertFree(parent, path.basename(file));
89
+ const text = singleFileWithTitle(await fs.readFile(absolute, "utf8"), title);
90
+ try {
91
+ await atomicCreate(file, text, { roots: [parent] });
92
+ } catch (error) {
93
+ if (error instanceof FileConflictError) throw new DeckExistsError(file);
94
+ throw error;
95
+ }
96
+ return { path: file, skipped: [] };
97
+ }
98
+
99
+ if (!stat.isDirectory()) throw new ValidationError(`Not a deck: ${absolute}`, { code: "DECK_LOAD_FAILED", path: absolute });
100
+ const target = path.join(parent, name);
101
+ await assertFree(parent, name);
102
+ const temp = path.join(parent, `.${name}.${crypto.randomBytes(6).toString("hex")}.flipbook-tmp`);
103
+ try {
104
+ const skipped = await copyTree(absolute, temp);
105
+ const manifest = path.join(temp, "presentation.yml");
106
+ await fs.writeFile(manifest, withTitle(await fs.readFile(manifest, "utf8"), title));
107
+ await assertFree(parent, name);
108
+ try {
109
+ await fs.mkdir(target);
110
+ } catch (error) {
111
+ if (error.code === "EEXIST") throw new DeckExistsError(target);
112
+ throw error;
113
+ }
114
+ // Rename over the empty folder just claimed; anything else there makes the rename fail.
115
+ await fs.rename(temp, target).catch(async (error) => {
116
+ await fs.rmdir(target).catch(() => {});
117
+ throw error.code === "ENOTEMPTY" || error.code === "EEXIST" ? new DeckExistsError(target) : error;
118
+ });
119
+ return { path: target, skipped };
120
+ } catch (error) {
121
+ await fs.rm(temp, { recursive: true, force: true });
122
+ throw error;
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Copies a theme, template or blueprint into the library as `toName` (D27). `fromRef.scope` is
128
+ * `library` or `builtin`; without it the library is tried first, then the built-ins. A `group` ref
129
+ * goes through copyGroup, which also renames its prefixed templates. The source must validate.
130
+ * Returns `{ ref, hash, path, source }` where `ref` is the new library KitRef.
131
+ */
132
+ export async function copyKit(fromRef, toName) {
133
+ const { kind, name, scope } = fromRef ?? {};
134
+ if (scope === "deck") throw new ValidationError("Only library and built-in kits can be copied.", { field: "scope" });
135
+ if (scope != null && scope !== "library" && scope !== "builtin") throw new ValidationError(`Unknown kit scope "${scope}".`, { field: "scope" });
136
+ const scopes = scope ? [scope] : ["library", "builtin"];
137
+ const ref = { kind, name: toName, scope: "library" };
138
+
139
+ if (kind === "group") {
140
+ let lastError;
141
+ for (const from of scopes) {
142
+ try {
143
+ return { ref, ...(await copyGroup({ name, scope: from }, toName)) };
144
+ } catch (error) {
145
+ if (error.code !== "KIT_NOT_FOUND") throw error;
146
+ lastError = error;
147
+ }
148
+ }
149
+ throw lastError;
150
+ }
151
+
152
+ let read;
153
+ let lastError;
154
+ for (const from of scopes) {
155
+ try {
156
+ read = await readKit({ kind, name, scope: from });
157
+ break;
158
+ } catch (error) {
159
+ if (error.code !== "KIT_NOT_FOUND") throw error;
160
+ lastError = error;
161
+ }
162
+ }
163
+ if (!read) throw lastError;
164
+ if (read.invalid) throw new KitInvalidError(read.invalid, read.path);
165
+ const written = await writeKit(ref, { source: read.source }, null);
166
+ return { ref, ...written, source: read.source };
167
+ }
package/src/slides.js CHANGED
@@ -531,8 +531,9 @@ async function structureBase(deckPath, baseHash) {
531
531
  /**
532
532
  * A single-file deck as glue and chunk cores: `glue[0] core[0] glue[1] core[1] … glue[n]`.
533
533
  * Cores are the chunks without surrounding whitespace; glue holds frontmatter, blank lines and `---`.
534
+ * Exported so tools can swap one slide's text and keep every other byte (Studio's slide restore).
534
535
  */
535
- function chunkLayout(text) {
536
+ export function chunkLayout(text) {
536
537
  const bom = text.startsWith("") ? 1 : 0;
537
538
  const cores = chunkSpans(text.slice(bom)).map(([from, to]) => {
538
539
  const raw = text.slice(from + bom, to + bom);
@@ -549,7 +550,8 @@ function chunkLayout(text) {
549
550
  return { cores: cores.map(([from, to]) => text.slice(from, to)), glue };
550
551
  }
551
552
 
552
- function joinLayout({ cores, glue }) {
553
+ /** The inverse of chunkLayout: `joinLayout(chunkLayout(text)) === text`. */
554
+ export function joinLayout({ cores, glue }) {
553
555
  return cores.map((core, index) => glue[index] + core).join("") + glue[cores.length];
554
556
  }
555
557