@steamfield/decks 0.0.0-stage → 1.0.0-rc.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.
- package/LICENSE +201 -0
- package/README.md +28 -2
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +5 -0
- package/dist/index-B2n69xrC.d.ts +75 -0
- package/dist/index-BURtH7IB.d.ts +182 -0
- package/dist/index-BV_-6L5L.d.ts +136 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +6 -0
- package/dist/kit/chrome/od-byline.css +7 -0
- package/dist/kit/chrome/od-cover-head.css +10 -0
- package/dist/kit/chrome/od-eyebrow.css +13 -0
- package/dist/kit/chrome/od-logo.css +167 -0
- package/dist/kit/chrome/od-qr-card.css +30 -0
- package/dist/kit/ink/code-ink.css +83 -0
- package/dist/kit/ink/graph-3d.css +29 -0
- package/dist/kit/ink/ink-bars.css +7 -0
- package/dist/kit/ink/ink-card-rect.css +6 -0
- package/dist/kit/ink/ink-chip.css +62 -0
- package/dist/kit/ink/ink-line.css +7 -0
- package/dist/kit/ink/ink-number.css +22 -0
- package/dist/kit/ink/ink-ping.css +4 -0
- package/dist/kit/ink/ink-rule.css +4 -0
- package/dist/kit/ink/ink-timeline-cursor.css +3 -0
- package/dist/kit/ink/ink-timeline.css +9 -0
- package/dist/kit/ink/underline.css +12 -0
- package/dist/kit/ink/unit-grid.css +3 -0
- package/dist/kit/story/story-card.css +19 -0
- package/dist/kit/story/story-link.css +13 -0
- package/dist/kit/story/story-stage.css +59 -0
- package/dist/kit/styles/base.css +82 -0
- package/dist/kit/styles/compat.css +78 -0
- package/dist/kit/styles/components.css +224 -0
- package/dist/kit/styles/fonts/inter-cyrillic-ext-wght-normal.woff2 +0 -0
- package/dist/kit/styles/fonts/inter-cyrillic-wght-normal.woff2 +0 -0
- package/dist/kit/styles/fonts/inter-greek-ext-wght-normal.woff2 +0 -0
- package/dist/kit/styles/fonts/inter-greek-wght-normal.woff2 +0 -0
- package/dist/kit/styles/fonts/inter-latin-ext-wght-normal.woff2 +0 -0
- package/dist/kit/styles/fonts/inter-latin-wght-normal.woff2 +0 -0
- package/dist/kit/styles/fonts/inter-vietnamese-wght-normal.woff2 +0 -0
- package/dist/kit/styles/fonts.css +73 -0
- package/dist/kit/styles/index.css +36 -0
- package/dist/kit/styles/layout.css +181 -0
- package/dist/kit/styles/stats.css +92 -0
- package/dist/kit/styles/story-frame.css +179 -0
- package/dist/kit/styles/story-marks.css +115 -0
- package/dist/kit/styles/story-transition.css +182 -0
- package/dist/kit/styles.css +1 -0
- package/dist/kit.d.ts +880 -0
- package/dist/kit.js +3475 -0
- package/dist/layers.css +60 -0
- package/dist/layouts.css +58 -0
- package/dist/lint/ai-rhetoric-patterns.tsv +110 -0
- package/dist/lint/deck-writing-reminder.md +9 -0
- package/dist/motion.css +215 -0
- package/dist/motion.d.ts +2 -0
- package/dist/motion.js +1 -0
- package/dist/node.d.ts +63 -0
- package/dist/node.js +1 -0
- package/dist/overview-view.css +58 -0
- package/dist/play-view.css +29 -0
- package/dist/plugin/skills/building-a-deck/SKILL.md +22 -0
- package/dist/plugin/skills/building-a-deck/references/workflow.md +86 -0
- package/dist/plugin/skills/deck-data/SKILL.md +27 -0
- package/dist/plugin/skills/deck-data/references/fact-check.md +59 -0
- package/dist/plugin/skills/deck-data/references/provenance.md +61 -0
- package/dist/plugin/skills/deck-design/SKILL.md +31 -0
- package/dist/plugin/skills/deck-design/references/layout.md +55 -0
- package/dist/plugin/skills/deck-motion/SKILL.md +34 -0
- package/dist/plugin/skills/deck-motion/references/motion.md +66 -0
- package/dist/plugin/skills/visualization/SKILL.md +34 -0
- package/dist/plugin/skills/visualization/references/VENDORED.md +25 -0
- package/dist/plugin/skills/visualization/references/annotations.md +27 -0
- package/dist/plugin/skills/visualization/references/chart-selection.md +29 -0
- package/dist/plugin/skills/visualization/references/color-strategy.md +22 -0
- package/dist/plugin/skills/visualization/references/encoding-channels.md +44 -0
- package/dist/plugin/skills/visualization/references/ink.md +38 -0
- package/dist/plugin/skills/visualization/references/marks.md +33 -0
- package/dist/plugin/skills/visualization/references/presentation.md +43 -0
- package/dist/plugin/skills/working-with-decks/SKILL.md +34 -0
- package/dist/plugin/skills/working-with-decks/references/project.md +59 -0
- package/dist/plugin/skills/writing-slides/SKILL.md +45 -0
- package/dist/plugin/skills/writing-slides/references/lint.md +11 -0
- package/dist/plugin/skills/writing-slides/references/prose-patterns.md +48 -0
- package/dist/presenter-view.css +113 -0
- package/dist/print-view.module.css +32 -0
- package/dist/prose-patterns-DPqjGBFu.js +76 -0
- package/dist/prose-scan-BrWZ7gxZ.js +233 -0
- package/dist/src-C-OfT72W.js +396 -0
- package/dist/src-CmQgaG1b.js +2469 -0
- package/dist/src-DizFoqYt.js +1508 -0
- package/dist/templates/conventional/deck.config.ts +7 -0
- package/dist/templates/conventional/setup.ts +3 -0
- package/dist/templates/conventional/slides/01-cover.mdx +9 -0
- package/dist/templates/conventional/slides/02-first-point.mdx +12 -0
- package/dist/templates/conventional/styles/index.css +1 -0
- package/dist/templates/story/components/FirstStage.tsx +34 -0
- package/dist/templates/story/data/01-first.ts +8 -0
- package/dist/templates/story/data-sources.md +7 -0
- package/dist/templates/story/deck.config.ts +8 -0
- package/dist/templates/story/setup.ts +3 -0
- package/dist/templates/story/slides/01-cover.mdx +9 -0
- package/dist/templates/story/slides/02-first-point.mdx +6 -0
- package/dist/templates/story/styles/index.css +1 -0
- package/dist/transition.css +87 -0
- package/docs/README.md +28 -0
- package/docs/canvas.md +134 -0
- package/docs/cli.md +49 -0
- package/docs/code-blocks.md +132 -0
- package/docs/config.md +183 -0
- package/docs/getting-started.md +204 -0
- package/docs/kit.md +371 -0
- package/docs/migrating-from-slidev.md +45 -0
- package/docs/motion.md +396 -0
- package/docs/presenting.md +99 -0
- package/docs/slides.md +246 -0
- package/package.json +108 -4
|
@@ -0,0 +1,2469 @@
|
|
|
1
|
+
import { a as authorError, c as validationError, i as DeckError, n as loadPatterns, o as compileError, r as patternsFile, s as displayPath } from "./prose-patterns-DPqjGBFu.js";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import { parseArgs, stripVTControlCharacters } from "node:util";
|
|
4
|
+
import { defineCommand, renderUsage, runCommand, showUsage } from "citty";
|
|
5
|
+
import pc from "picocolors";
|
|
6
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
7
|
+
import { constants, existsSync, readFileSync, statSync, writeSync } from "node:fs";
|
|
8
|
+
import { access, lstat, mkdir, mkdtemp, readFile, readdir, realpath, rm, stat, writeFile } from "node:fs/promises";
|
|
9
|
+
import getPort, { portNumbers } from "get-port";
|
|
10
|
+
import { build as build$1, createLogger, createServer, defaultClientConditions, mergeConfig, normalizePath, preview } from "vite";
|
|
11
|
+
import { chromium, errors } from "playwright-core";
|
|
12
|
+
import mdx from "@mdx-js/rollup";
|
|
13
|
+
import react from "@vitejs/plugin-react";
|
|
14
|
+
import remarkFrontmatter from "remark-frontmatter";
|
|
15
|
+
import rehypeShiki from "@shikijs/rehype";
|
|
16
|
+
import { bundledLanguages, createCssVariablesTheme, isSpecialLang } from "shiki";
|
|
17
|
+
import { unified } from "unified";
|
|
18
|
+
import rehypeStringify from "rehype-stringify";
|
|
19
|
+
import remarkMdx from "remark-mdx";
|
|
20
|
+
import remarkParse from "remark-parse";
|
|
21
|
+
import remarkRehype from "remark-rehype";
|
|
22
|
+
import { setTimeout as setTimeout$1 } from "node:timers/promises";
|
|
23
|
+
import matter from "gray-matter";
|
|
24
|
+
import { glob } from "tinyglobby";
|
|
25
|
+
import { z } from "zod";
|
|
26
|
+
import { parseSync } from "oxc-parser";
|
|
27
|
+
import { createJiti } from "jiti";
|
|
28
|
+
import { fileURLToPath } from "node:url";
|
|
29
|
+
import { tmpdir } from "node:os";
|
|
30
|
+
import { spawnSync } from "node:child_process";
|
|
31
|
+
import { isUtf8 } from "node:buffer";
|
|
32
|
+
import { createHash } from "node:crypto";
|
|
33
|
+
// ../core/src/manifest.ts
|
|
34
|
+
/** Throws an Error naming the first problem. Returns the same object when valid. */
|
|
35
|
+
function assertManifest(manifest) {
|
|
36
|
+
if (manifest.transition !== void 0 && !manifest.transition.length) throw new Error("Manifest transition must not be empty");
|
|
37
|
+
if (manifest.slides.length === 0) throw new Error("Manifest has 0 slides");
|
|
38
|
+
const ids = /* @__PURE__ */ new Set();
|
|
39
|
+
for (const [index, slide] of manifest.slides.entries()) {
|
|
40
|
+
if (slide.no !== index + 1) throw new Error(`Slide no ${slide.no} must be ${index + 1}`);
|
|
41
|
+
if (ids.has(slide.id)) throw new Error(`Duplicate slide id: ${slide.id}`);
|
|
42
|
+
ids.add(slide.id);
|
|
43
|
+
if (slide.transition !== void 0 && !slide.transition.length) throw new Error(`Slide ${slide.id} has empty transition`);
|
|
44
|
+
if (slide.morphSteps !== void 0 && typeof slide.morphSteps !== "boolean") throw new Error(`Slide ${slide.id} has invalid morphSteps: ${slide.morphSteps}`);
|
|
45
|
+
if (!Number.isInteger(slide.clicks) || slide.clicks < 0) throw new Error(`Slide ${slide.id} has invalid clicks: ${slide.clicks}`);
|
|
46
|
+
}
|
|
47
|
+
for (const dimension of ["width", "height"]) {
|
|
48
|
+
const value = manifest.canvas[dimension];
|
|
49
|
+
if (!Number.isFinite(value) || value <= 0) throw new Error(`Canvas ${dimension} must be positive and finite: ${value}`);
|
|
50
|
+
}
|
|
51
|
+
return manifest;
|
|
52
|
+
}
|
|
53
|
+
// ../core/src/notes.ts
|
|
54
|
+
/** Splits a slide's notes, as markdown source, at its click markers. */
|
|
55
|
+
function segmentNotes(markdown) {
|
|
56
|
+
const segments = [];
|
|
57
|
+
let click = 0;
|
|
58
|
+
let start = 0;
|
|
59
|
+
for (const marker of markdown.matchAll(/^[ \t]*\[click(?::(\d+))?\][ \t]*/gm)) {
|
|
60
|
+
const increment = marker[1] === void 0 ? 1 : Number(marker[1]);
|
|
61
|
+
if (!Number.isInteger(increment) || increment <= 0) continue;
|
|
62
|
+
segments.push({
|
|
63
|
+
click,
|
|
64
|
+
markdown: markdown.slice(start, marker.index).trim()
|
|
65
|
+
});
|
|
66
|
+
click += increment;
|
|
67
|
+
start = marker.index + marker[0].length;
|
|
68
|
+
}
|
|
69
|
+
segments.push({
|
|
70
|
+
click,
|
|
71
|
+
markdown: markdown.slice(start).trim()
|
|
72
|
+
});
|
|
73
|
+
return segments;
|
|
74
|
+
}
|
|
75
|
+
// ../node/src/dev/browser.ts
|
|
76
|
+
var MissingChromiumError = class extends DeckError {
|
|
77
|
+
constructor(cause) {
|
|
78
|
+
super("Chromium is not installed. Run npx playwright install chromium.", void 0, void 0, { cause });
|
|
79
|
+
}
|
|
80
|
+
};
|
|
81
|
+
async function launchBrowser() {
|
|
82
|
+
try {
|
|
83
|
+
return await chromium.launch();
|
|
84
|
+
} catch (cause) {
|
|
85
|
+
if (cause instanceof Error && cause.message.includes("Executable doesn't exist")) throw new MissingChromiumError(cause);
|
|
86
|
+
throw cause;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
async function waitForCapture(page, timeout = 3e4) {
|
|
90
|
+
try {
|
|
91
|
+
await page.waitForFunction("window.__deck.settled().then(() => true)", void 0, { timeout });
|
|
92
|
+
} catch (cause) {
|
|
93
|
+
if (!(cause instanceof errors.TimeoutError)) throw cause;
|
|
94
|
+
const busy = await page.evaluate(`document.getAnimations().flatMap((animation) => {
|
|
95
|
+
const end = animation.effect?.getComputedTiming().endTime;
|
|
96
|
+
if (animation.playState !== "running" || typeof end !== "number" || !Number.isFinite(end))
|
|
97
|
+
return [];
|
|
98
|
+
const target = animation.effect instanceof KeyframeEffect ? animation.effect.target : null;
|
|
99
|
+
const slide = target?.closest("[data-deck-slide]")?.getAttribute("data-deck-slide") ?? "unknown";
|
|
100
|
+
const name = animation instanceof CSSAnimation ? animation.animationName : animation.id || "animation";
|
|
101
|
+
return ["slide " + slide + ": " + name + " (ends at " + end + " ms)"];
|
|
102
|
+
})`);
|
|
103
|
+
const url = new URL(page.url());
|
|
104
|
+
const [slide, query] = url.hash.slice(2).split("?");
|
|
105
|
+
const click = slide === "print" ? new URLSearchParams(url.search).get("print") === "final" ? "final" : "all" : new URLSearchParams(query).get("clicks") ?? "0";
|
|
106
|
+
throw new DeckError(`Timed out after ${timeout} ms waiting to capture slide ${slide} click ${click}. Still busy: ${busy.length ? busy.join("; ") : "settled() has not resolved; no running finite browser animations"}.`, void 0, void 0, { cause });
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/** Each capture owns a preview server on an OS-assigned port. */
|
|
110
|
+
async function openBuiltDeck(browser, outDir, base, path, viewport = {
|
|
111
|
+
width: 1920,
|
|
112
|
+
height: 1080
|
|
113
|
+
}, settleTimeout = 3e4) {
|
|
114
|
+
const server = await preview({
|
|
115
|
+
configFile: false,
|
|
116
|
+
base,
|
|
117
|
+
build: { outDir },
|
|
118
|
+
preview: {
|
|
119
|
+
host: "127.0.0.1",
|
|
120
|
+
port: 0,
|
|
121
|
+
open: false
|
|
122
|
+
},
|
|
123
|
+
logLevel: "silent"
|
|
124
|
+
});
|
|
125
|
+
try {
|
|
126
|
+
const url = server.resolvedUrls?.local[0];
|
|
127
|
+
if (!url) throw new Error(`${outDir}: Vite preview did not provide a local URL`);
|
|
128
|
+
const page = await browser.newPage({
|
|
129
|
+
viewport,
|
|
130
|
+
deviceScaleFactor: 1
|
|
131
|
+
});
|
|
132
|
+
const errors = [];
|
|
133
|
+
if (/^https?:\/\//.test(base)) {
|
|
134
|
+
const assets = new URL(base);
|
|
135
|
+
const local = new URL(url);
|
|
136
|
+
await page.route(`${assets.origin}/**`, async (route) => {
|
|
137
|
+
const request = new URL(route.request().url());
|
|
138
|
+
try {
|
|
139
|
+
const response = await page.request.get(`${local.origin}${request.pathname}${request.search}`, { headers: { origin: local.origin } });
|
|
140
|
+
await route.fulfill({ response });
|
|
141
|
+
} catch (cause) {
|
|
142
|
+
errors.push(`Cannot load ${request.href}: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
143
|
+
await route.abort();
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
page.on("pageerror", (error) => errors.push(error.message));
|
|
148
|
+
page.on("console", (message) => {
|
|
149
|
+
if (message.type() === "error") errors.push(message.text());
|
|
150
|
+
});
|
|
151
|
+
await page.goto(`${url}${path}`);
|
|
152
|
+
await page.waitForFunction("window.__deck !== undefined");
|
|
153
|
+
await waitForCapture(page, settleTimeout);
|
|
154
|
+
if (errors.length) throw new DeckError(`Cannot capture ${outDir}: ${errors.join("; ")}`);
|
|
155
|
+
return {
|
|
156
|
+
page,
|
|
157
|
+
close: () => server.close()
|
|
158
|
+
};
|
|
159
|
+
} catch (cause) {
|
|
160
|
+
await server.close();
|
|
161
|
+
throw cause;
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
// ../node/src/mdx/code-options.ts
|
|
165
|
+
function parseCodeOptions(meta, lineCount, file) {
|
|
166
|
+
const options = { at: 0 };
|
|
167
|
+
const seen = /* @__PURE__ */ new Set();
|
|
168
|
+
const fail = (option) => {
|
|
169
|
+
throw new DeckError(`invalid code option ${option}. Use line ranges within this block and whole numbers for at, lines and maxHeight.`, file);
|
|
170
|
+
};
|
|
171
|
+
const integer = (value, option, minimum) => {
|
|
172
|
+
const number = Number(value);
|
|
173
|
+
if (!/^\d+$/.test(value) || !Number.isSafeInteger(number) || number < minimum) return fail(option);
|
|
174
|
+
return number;
|
|
175
|
+
};
|
|
176
|
+
const tokens = /\s*(\{[^}]*\}|title="[^"]*"|[^\s]+)(?=\s|$)/gy;
|
|
177
|
+
let offset = 0;
|
|
178
|
+
while (meta.slice(offset).trim()) {
|
|
179
|
+
tokens.lastIndex = offset;
|
|
180
|
+
const token = tokens.exec(meta)?.[1];
|
|
181
|
+
if (!token) return fail(meta.slice(offset).trim());
|
|
182
|
+
offset = tokens.lastIndex;
|
|
183
|
+
const key = token.startsWith("{") ? "steps" : token.split("=")[0];
|
|
184
|
+
if (!key || seen.has(key)) return fail(token);
|
|
185
|
+
seen.add(key);
|
|
186
|
+
if (key === "steps") {
|
|
187
|
+
if (!token.endsWith("}")) fail(token);
|
|
188
|
+
options.steps = token.slice(1, -1).split("|").map((step) => {
|
|
189
|
+
if (step === "all" || step === "none") return step;
|
|
190
|
+
const lines = /* @__PURE__ */ new Set();
|
|
191
|
+
for (const range of step.split(",")) {
|
|
192
|
+
const bounds = range.split("-");
|
|
193
|
+
const first = integer(bounds[0] ?? "", token, 1);
|
|
194
|
+
const last = integer(bounds[1] ?? bounds[0] ?? "", token, 1);
|
|
195
|
+
if (bounds.length > 2 || last < first || last > lineCount) fail(token);
|
|
196
|
+
for (let line = first; line <= last; line++) lines.add(line);
|
|
197
|
+
}
|
|
198
|
+
return [...lines];
|
|
199
|
+
});
|
|
200
|
+
} else if (key === "at") options.at = integer(token.slice(3), token, 0);
|
|
201
|
+
else if (key === "lines") options.lines = token === "lines" ? 1 : integer(token.slice(6), token, 1);
|
|
202
|
+
else if (key === "maxHeight") options.maxHeight = integer(token.slice(10), token, 1);
|
|
203
|
+
else if (key === "title" && /^title="[^"]*"$/.test(token)) options.title = token.slice(7, -1);
|
|
204
|
+
else fail(token);
|
|
205
|
+
}
|
|
206
|
+
return options;
|
|
207
|
+
}
|
|
208
|
+
// ../node/src/mdx/code-blocks.ts
|
|
209
|
+
const codeBlocks = () => async (tree, file) => {
|
|
210
|
+
const warn = (node) => {
|
|
211
|
+
if (node.type === "element" && node.tagName === "code") {
|
|
212
|
+
const classes = node.properties.className;
|
|
213
|
+
const language = Array.isArray(classes) ? classes.find((value) => typeof value === "string" && value.startsWith("language-")) : void 0;
|
|
214
|
+
if (typeof language === "string") {
|
|
215
|
+
const name = language.slice(9);
|
|
216
|
+
if (!(name in bundledLanguages) && !isSpecialLang(name)) console.warn(`${file.path}: unknown code language ${name}; using plain text`);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
if ("children" in node) for (const child of node.children) warn(child);
|
|
220
|
+
};
|
|
221
|
+
warn(tree);
|
|
222
|
+
return unified().use(rehypeShiki, {
|
|
223
|
+
theme: createCssVariablesTheme(),
|
|
224
|
+
defaultLanguage: "text",
|
|
225
|
+
fallbackLanguage: "text",
|
|
226
|
+
tabindex: false,
|
|
227
|
+
transformers: [{
|
|
228
|
+
pre(node) {
|
|
229
|
+
const options = parseCodeOptions(this.options.meta?.__raw ?? "", this.source.split("\n").length, file.path);
|
|
230
|
+
node.properties["data-at"] = options.at;
|
|
231
|
+
if (options.steps) node.properties["data-steps"] = JSON.stringify(options.steps);
|
|
232
|
+
if (options.lines !== void 0) node.properties["data-lines"] = options.lines;
|
|
233
|
+
if (options.title !== void 0) node.properties["data-title"] = options.title;
|
|
234
|
+
if (options.maxHeight !== void 0) node.properties["data-max-height"] = options.maxHeight;
|
|
235
|
+
},
|
|
236
|
+
line(node, line) {
|
|
237
|
+
node.properties["data-line"] = line;
|
|
238
|
+
const first = parseCodeOptions(this.options.meta?.__raw ?? "", this.source.split("\n").length, file.path).lines;
|
|
239
|
+
if (first !== void 0) node.properties["data-line-number"] = first + line - 1;
|
|
240
|
+
}
|
|
241
|
+
}]
|
|
242
|
+
}).run(tree, file);
|
|
243
|
+
};
|
|
244
|
+
// ../node/src/mdx/component-check.ts
|
|
245
|
+
const provided = [
|
|
246
|
+
"Step",
|
|
247
|
+
"Steps",
|
|
248
|
+
"Stagger",
|
|
249
|
+
"TextReveal",
|
|
250
|
+
"Highlight",
|
|
251
|
+
"CountUp",
|
|
252
|
+
"Draw",
|
|
253
|
+
"Morph",
|
|
254
|
+
"Center",
|
|
255
|
+
"Cover",
|
|
256
|
+
"Section",
|
|
257
|
+
"TwoCol",
|
|
258
|
+
"ImageSide",
|
|
259
|
+
"Notes"
|
|
260
|
+
];
|
|
261
|
+
/** MDX's own tree keeps code fences out of the JSX name check. */
|
|
262
|
+
function checkComponents(names) {
|
|
263
|
+
return () => (tree, file) => {
|
|
264
|
+
const known = /* @__PURE__ */ new Set([...provided, ...names()]);
|
|
265
|
+
const bind = (value) => {
|
|
266
|
+
if (typeof value !== "object" || value === null) return;
|
|
267
|
+
if ("type" in value && value.type === "Identifier" && "name" in value && typeof value.name === "string") known.add(value.name);
|
|
268
|
+
else for (const child of Object.values(value)) if (Array.isArray(child)) child.forEach(bind);
|
|
269
|
+
else bind(child);
|
|
270
|
+
};
|
|
271
|
+
for (const node of tree.children ?? []) {
|
|
272
|
+
if (node.type !== "mdxjsEsm") continue;
|
|
273
|
+
const declarations = (value) => {
|
|
274
|
+
if (typeof value !== "object" || value === null) return;
|
|
275
|
+
if ("type" in value) {
|
|
276
|
+
if (value.type === "ImportDeclaration" && "specifiers" in value && Array.isArray(value.specifiers)) {
|
|
277
|
+
for (const specifier of value.specifiers) if (typeof specifier === "object" && specifier !== null && "local" in specifier) bind(specifier.local);
|
|
278
|
+
}
|
|
279
|
+
if ([
|
|
280
|
+
"VariableDeclarator",
|
|
281
|
+
"FunctionDeclaration",
|
|
282
|
+
"ClassDeclaration"
|
|
283
|
+
].includes(String(value.type)) && "id" in value) bind(value.id);
|
|
284
|
+
}
|
|
285
|
+
for (const child of Object.values(value)) if (Array.isArray(child)) child.forEach(declarations);
|
|
286
|
+
else declarations(child);
|
|
287
|
+
};
|
|
288
|
+
declarations(node.data?.estree);
|
|
289
|
+
}
|
|
290
|
+
const check = (name, loc) => {
|
|
291
|
+
if (typeof name !== "string" || !/^[A-Z][\w]*$/.test(name) || known.has(name)) return;
|
|
292
|
+
throw new DeckError(`<${name}> is not defined. Export it from a file in components/ or import it in the slide.`, file.path, loc);
|
|
293
|
+
};
|
|
294
|
+
const walk = (value) => {
|
|
295
|
+
if (typeof value !== "object" || value === null) return;
|
|
296
|
+
const node = value;
|
|
297
|
+
if ([
|
|
298
|
+
"ArrowFunctionExpression",
|
|
299
|
+
"FunctionExpression",
|
|
300
|
+
"FunctionDeclaration"
|
|
301
|
+
].includes(String(node.type))) return;
|
|
302
|
+
if (node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement") check(node.name, node.position?.start);
|
|
303
|
+
if (node.type === "JSXOpeningElement" && typeof node.name === "object" && node.name !== null && "name" in node.name) check(node.name.name, node.loc ? {
|
|
304
|
+
line: node.loc.start.line,
|
|
305
|
+
column: node.loc.start.column + 1
|
|
306
|
+
} : void 0);
|
|
307
|
+
for (const child of Object.values(value)) if (Array.isArray(child)) child.forEach(walk);
|
|
308
|
+
else walk(child);
|
|
309
|
+
};
|
|
310
|
+
walk(tree);
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
// ../node/src/mdx/notes.ts
|
|
314
|
+
const parser$1 = unified().use(remarkParse).use(remarkFrontmatter).use(remarkMdx);
|
|
315
|
+
const renderer = unified().use(remarkParse).use(remarkRehype).use(rehypeStringify);
|
|
316
|
+
/** A slide's notes split at its click markers, each segment rendered to HTML on its own. */
|
|
317
|
+
async function renderNotes(source, file, remarkPlugins = []) {
|
|
318
|
+
const notes = [];
|
|
319
|
+
let tree;
|
|
320
|
+
try {
|
|
321
|
+
tree = parser$1().use(remarkPlugins).parse(source);
|
|
322
|
+
} catch (cause) {
|
|
323
|
+
throw compileError(cause, file);
|
|
324
|
+
}
|
|
325
|
+
collectNotes(tree, notes, file);
|
|
326
|
+
if (notes.length > 1) throw new DeckError(`more than one <Notes> block. Keep one <Notes> block per slide.`, file);
|
|
327
|
+
const node = notes[0];
|
|
328
|
+
if (!node?.children?.length) return void 0;
|
|
329
|
+
const markdown = source.slice(node.children[0]?.position?.start.offset, node.children.at(-1)?.position?.end.offset);
|
|
330
|
+
return Promise.all(segmentNotes(markdown).map(async (segment) => ({
|
|
331
|
+
click: segment.click,
|
|
332
|
+
html: String(await renderer.process(segment.markdown))
|
|
333
|
+
})));
|
|
334
|
+
}
|
|
335
|
+
function rejectExpressionNotes(node, file) {
|
|
336
|
+
if (typeof node !== "object" || node === null) return;
|
|
337
|
+
if ("type" in node && node.type === "JSXOpeningElement" && "name" in node && typeof node.name === "object" && node.name !== null && "name" in node.name && node.name.name === "Notes") throw new DeckError(`<Notes> inside a JSX expression is not supported. Write it as a separate block.`, file);
|
|
338
|
+
for (const child of Object.values(node)) rejectExpressionNotes(child, file);
|
|
339
|
+
}
|
|
340
|
+
function collectNotes(node, notes, file) {
|
|
341
|
+
rejectExpressionNotes(node.data, file);
|
|
342
|
+
rejectExpressionNotes(node.attributes, file);
|
|
343
|
+
if ((node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement") && node.name === "Notes") notes.push(node);
|
|
344
|
+
for (const child of node.children ?? []) collectNotes(child, notes, file);
|
|
345
|
+
}
|
|
346
|
+
function removeNotes() {
|
|
347
|
+
return (tree, file) => {
|
|
348
|
+
const notes = [];
|
|
349
|
+
collectNotes(tree, notes, file.path);
|
|
350
|
+
if (notes.length > 1) throw new DeckError(`more than one <Notes> block. Keep one <Notes> block per slide.`, file.path);
|
|
351
|
+
const remove = (node) => {
|
|
352
|
+
if (!node.children) return;
|
|
353
|
+
node.children = node.children.filter((child) => !notes.includes(child));
|
|
354
|
+
for (const child of node.children) remove(child);
|
|
355
|
+
};
|
|
356
|
+
remove(tree);
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
// ../node/src/mdx/read-source.ts
|
|
360
|
+
async function readSource(file, afterChange = false) {
|
|
361
|
+
let source = await readFile(file, "utf8");
|
|
362
|
+
for (let attempt = 0; afterChange && !source && attempt < 10; attempt++) {
|
|
363
|
+
await setTimeout$1(10);
|
|
364
|
+
source = await readFile(file, "utf8");
|
|
365
|
+
}
|
|
366
|
+
return source;
|
|
367
|
+
}
|
|
368
|
+
// ../node/src/dev/specifiers.ts
|
|
369
|
+
const PUBLIC_SPECIFIERS = {
|
|
370
|
+
runtime: "@steamfield/decks",
|
|
371
|
+
motion: "@steamfield/decks/motion"
|
|
372
|
+
};
|
|
373
|
+
// ../node/src/mdx/clicks.ts
|
|
374
|
+
const stepNames = /* @__PURE__ */ new Set([
|
|
375
|
+
"Step",
|
|
376
|
+
"Steps",
|
|
377
|
+
"Stagger",
|
|
378
|
+
"TextReveal",
|
|
379
|
+
"Highlight",
|
|
380
|
+
"CountUp",
|
|
381
|
+
"Draw"
|
|
382
|
+
]);
|
|
383
|
+
const parser = unified().use(remarkParse).use(remarkMdx);
|
|
384
|
+
function elementChildren(node) {
|
|
385
|
+
return (node?.children ?? []).flatMap((child) => child.type === "paragraph" && child.children?.every((part) => part.type === "mdxJsxTextElement" || part.type === "text" && typeof part.value === "string" && /^[\t\n\v\f\r ]*$/.test(part.value)) ? child.children : [child]).filter((child) => child.type !== "text" || typeof child.value !== "string" || child.value.trim());
|
|
386
|
+
}
|
|
387
|
+
function integerAttribute(node, name, file) {
|
|
388
|
+
const attribute = node.attributes?.find((attribute) => attribute.type === "mdxJsxAttribute" && attribute.name === name);
|
|
389
|
+
const value = attribute?.type === "mdxJsxAttribute" ? attribute.value : void 0;
|
|
390
|
+
const statement = typeof value === "object" && value !== null ? value.data?.estree?.body[0] : void 0;
|
|
391
|
+
const expression = statement?.type === "ExpressionStatement" ? statement.expression : void 0;
|
|
392
|
+
if (expression?.type === "Literal" && typeof expression.value === "number" && Number.isInteger(expression.value) && expression.value >= 0) return expression.value;
|
|
393
|
+
throw new DeckError(`<${node.name} ${name}={${typeof value === "object" && value !== null ? value.value : String(value)}}>: ${name} must be a literal whole number (${name}={2}). To compute it, set clicks: in the frontmatter.`, file, node.position?.start);
|
|
394
|
+
}
|
|
395
|
+
function rejectExpressionSteps(node, file, names) {
|
|
396
|
+
if (typeof node !== "object" || node === null) return;
|
|
397
|
+
if ("type" in node && node.type === "JSXOpeningElement" && "name" in node && typeof node.name === "object" && node.name !== null && "name" in node.name && typeof node.name.name === "string" && names.has(node.name.name)) {
|
|
398
|
+
const start = "loc" in node && typeof node.loc === "object" && node.loc !== null && "start" in node.loc ? node.loc.start : void 0;
|
|
399
|
+
const loc = typeof start === "object" && start !== null && "line" in start && typeof start.line === "number" && "column" in start && typeof start.column === "number" ? {
|
|
400
|
+
line: start.line,
|
|
401
|
+
column: start.column + 1
|
|
402
|
+
} : void 0;
|
|
403
|
+
throw new DeckError(`<${node.name.name}> inside a JavaScript expression cannot be counted. To compute it, set clicks: in the frontmatter.`, file, loc);
|
|
404
|
+
}
|
|
405
|
+
for (const child of Object.values(node)) rejectExpressionSteps(child, file, names);
|
|
406
|
+
}
|
|
407
|
+
/** Syntax errors belong to the slide compiler; mid-edit they retain the last total. */
|
|
408
|
+
function countClicks(source, file, previous = 0, motionNames = new Map(Array.from(stepNames, (name) => [name, name])), remarkPlugins = []) {
|
|
409
|
+
let tree;
|
|
410
|
+
try {
|
|
411
|
+
tree = parser().use(remarkPlugins).parse(source);
|
|
412
|
+
} catch (cause) {
|
|
413
|
+
if (cause instanceof Error && "source" in cause && typeof cause.source === "string" && "ruleId" in cause && typeof cause.ruleId === "string") return previous;
|
|
414
|
+
throw cause;
|
|
415
|
+
}
|
|
416
|
+
const names = new Map(motionNames);
|
|
417
|
+
for (const node of tree.children) {
|
|
418
|
+
if (node.type !== "mdxjsEsm") continue;
|
|
419
|
+
for (const statement of node.data?.estree?.body ?? []) {
|
|
420
|
+
if (statement.type === "ImportDeclaration") {
|
|
421
|
+
for (const specifier of statement.specifiers) {
|
|
422
|
+
const local = specifier.local.name;
|
|
423
|
+
names.delete(local);
|
|
424
|
+
if (statement.source.value !== "@react-decks/motion" && statement.source.value !== PUBLIC_SPECIFIERS.motion || specifier.type !== "ImportSpecifier") continue;
|
|
425
|
+
const imported = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
|
|
426
|
+
if (typeof imported === "string" && stepNames.has(imported)) names.set(local, imported);
|
|
427
|
+
}
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
const declaration = statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration" ? statement.declaration : statement;
|
|
431
|
+
if (declaration?.type === "FunctionDeclaration" || declaration?.type === "ClassDeclaration") {
|
|
432
|
+
if (declaration.id) names.delete(declaration.id.name);
|
|
433
|
+
} else if (declaration?.type === "VariableDeclaration") {
|
|
434
|
+
const bindings = declaration.declarations.map(({ id }) => id);
|
|
435
|
+
for (const binding of bindings) if (binding.type === "Identifier") names.delete(binding.name);
|
|
436
|
+
else if (binding.type === "ObjectPattern") for (const property of binding.properties) bindings.push(property.type === "RestElement" ? property.argument : property.value);
|
|
437
|
+
else if (binding.type === "ArrayPattern") {
|
|
438
|
+
for (const element of binding.elements) if (element) bindings.push(element);
|
|
439
|
+
} else if (binding.type === "RestElement") bindings.push(binding.argument);
|
|
440
|
+
else if (binding.type === "AssignmentPattern") bindings.push(binding.left);
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
for (const name of names.keys()) if (/^[a-z]|[.-]/.test(name)) names.delete(name);
|
|
445
|
+
let total = 0;
|
|
446
|
+
const walk = (node) => {
|
|
447
|
+
if ((node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement") && node.name === "Notes") return;
|
|
448
|
+
if (node.type === "code" && typeof node.value === "string") {
|
|
449
|
+
const { steps, at } = parseCodeOptions(node.meta ?? "", node.value.split("\n").length, file);
|
|
450
|
+
if (steps) total = Math.max(total, at + steps.length - 1);
|
|
451
|
+
}
|
|
452
|
+
rejectExpressionSteps(node.data, file, names);
|
|
453
|
+
rejectExpressionSteps(node.attributes, file, names);
|
|
454
|
+
const element = node.type === "mdxJsxFlowElement" || node.type === "mdxJsxTextElement";
|
|
455
|
+
const motion = typeof node.name === "string" ? names.get(node.name) : void 0;
|
|
456
|
+
if (element && motion) {
|
|
457
|
+
if (node.attributes?.some((attribute) => attribute.type === "mdxJsxExpressionAttribute")) throw new DeckError(`<${node.name}> spread attributes cannot be counted. To compute it, set clicks: in the frontmatter.`, file, node.position?.start);
|
|
458
|
+
if (motion === "Steps") {
|
|
459
|
+
const from = integerAttribute(node, "from", file);
|
|
460
|
+
let children = 0;
|
|
461
|
+
const content = elementChildren(node);
|
|
462
|
+
if (content.length === 1 && content[0]?.type === "list") children = content[0].children?.length ?? 0;
|
|
463
|
+
else if (content.length === 1 && ["ul", "ol"].includes(String(content[0]?.name))) children = elementChildren(content[0]).filter((child) => (child.type === "mdxJsxFlowElement" || child.type === "mdxJsxTextElement") && child.name === "li").length;
|
|
464
|
+
else for (const child of content) if (child.type === "mdxJsxFlowElement" || child.type === "mdxJsxTextElement") children++;
|
|
465
|
+
else throw new DeckError(`<Steps> children must be JSX elements or a single markdown list. To compute it, set clicks: in the frontmatter.`, file, node.position?.start);
|
|
466
|
+
if (children) total = Math.max(total, from + children - 1);
|
|
467
|
+
} else {
|
|
468
|
+
const at = integerAttribute(node, "at", file);
|
|
469
|
+
const until = node.attributes?.some((attribute) => attribute.type === "mdxJsxAttribute" && attribute.name === "until") && [
|
|
470
|
+
"Step",
|
|
471
|
+
"Stagger",
|
|
472
|
+
"Highlight",
|
|
473
|
+
"Draw"
|
|
474
|
+
].includes(motion) ? integerAttribute(node, "until", file) : void 0;
|
|
475
|
+
if (until !== void 0 && until <= at) throw new DeckError(`<${node.name}> until must be greater than at. To compute it, set clicks: in the frontmatter.`, file, node.position?.start);
|
|
476
|
+
total = Math.max(total, until ?? at);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
for (const child of node.children ?? []) walk(child);
|
|
480
|
+
};
|
|
481
|
+
walk(tree);
|
|
482
|
+
return total;
|
|
483
|
+
}
|
|
484
|
+
// ../node/src/dev/components.ts
|
|
485
|
+
async function componentsModule(dir) {
|
|
486
|
+
const files = (await glob("components/*.tsx", { cwd: dir })).sort();
|
|
487
|
+
const components = /* @__PURE__ */ new Map();
|
|
488
|
+
const motionNames = new Map(Array.from(stepNames, (name) => [name, name]));
|
|
489
|
+
for (const [index, file] of files.entries()) {
|
|
490
|
+
const source = await readFile(join(dir, file), "utf8");
|
|
491
|
+
const parsed = parseSync(file, source);
|
|
492
|
+
const error = parsed.errors[0];
|
|
493
|
+
if (error) {
|
|
494
|
+
const label = error.labels[0];
|
|
495
|
+
const lines = label ? source.slice(0, label.start).split(/\r\n|[\n\r\u2028\u2029]/) : void 0;
|
|
496
|
+
throw new DeckError(`${error.message}${/[.!?]$/.test(error.message) ? "" : "."} Check the component syntax.`, join(dir, file), lines ? {
|
|
497
|
+
line: lines.length,
|
|
498
|
+
column: (lines.at(-1)?.length ?? 0) + 1
|
|
499
|
+
} : void 0);
|
|
500
|
+
}
|
|
501
|
+
for (const declaration of parsed.module.staticExports) for (const entry of declaration.entries) {
|
|
502
|
+
if (entry.isType) continue;
|
|
503
|
+
if (entry.exportName.kind === "None") throw new DeckError(`runtime wildcard re-export is not supported; export names explicitly.`, join(dir, file));
|
|
504
|
+
const exported = entry.exportName.kind === "Default" ? "default" : entry.exportName.name;
|
|
505
|
+
if (exported === null) continue;
|
|
506
|
+
const name = exported === "default" ? basename(file, ".tsx") : exported;
|
|
507
|
+
const owner = components.get(name);
|
|
508
|
+
if (owner && owner.file !== file) throw new DeckError(`Duplicate component ${name} in ${owner.file} and ${file}. Export each component name from only one file.`, join(dir, file));
|
|
509
|
+
components.set(name, {
|
|
510
|
+
file,
|
|
511
|
+
value: `c${index}[${JSON.stringify(exported)}]`
|
|
512
|
+
});
|
|
513
|
+
motionNames.delete(name);
|
|
514
|
+
const imported = entry.importName.name;
|
|
515
|
+
if ((entry.moduleRequest?.value === "@react-decks/motion" || entry.moduleRequest?.value === PUBLIC_SPECIFIERS.motion) && imported && stepNames.has(imported)) motionNames.set(name, imported);
|
|
516
|
+
}
|
|
517
|
+
}
|
|
518
|
+
return {
|
|
519
|
+
names: new Set(components.keys()),
|
|
520
|
+
motionNames,
|
|
521
|
+
code: `${files.map((file, index) => `import * as c${index} from ${JSON.stringify(`/${file}`)};`).join("\n")}
|
|
522
|
+
export const components = {${Array.from(components, ([name, { value }]) => `[${JSON.stringify(name)}]: ${value}`).join(",")}};`
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
// ../node/src/mdx/slides.ts
|
|
526
|
+
const frontmatterSchema = z.looseObject({
|
|
527
|
+
title: z.string().optional(),
|
|
528
|
+
clicks: z.number().int().nonnegative().optional(),
|
|
529
|
+
hide: z.boolean().default(false),
|
|
530
|
+
transition: z.string().min(1).optional(),
|
|
531
|
+
morphSteps: z.boolean().optional(),
|
|
532
|
+
layers: z.union([
|
|
533
|
+
z.literal(false),
|
|
534
|
+
z.literal("above"),
|
|
535
|
+
z.literal("below")
|
|
536
|
+
]).optional()
|
|
537
|
+
});
|
|
538
|
+
async function scanSlides(deck) {
|
|
539
|
+
return (await scanSlidesWithCounts(deck, /* @__PURE__ */ new Map())).slides;
|
|
540
|
+
}
|
|
541
|
+
function readSlide(source, file, previous, motionNames, remarkPlugins) {
|
|
542
|
+
try {
|
|
543
|
+
const { data, content } = matter(source);
|
|
544
|
+
const parsed = frontmatterSchema.safeParse(data);
|
|
545
|
+
if (!parsed.success) throw validationError(file, parsed.error.issues, data, [], true);
|
|
546
|
+
const frontmatter = parsed.data;
|
|
547
|
+
const clicks = frontmatter.hide ? 0 : frontmatter.clicks ?? countClicks(source.slice(0, source.length - content.length).replace(/[^\n]/g, " ") + content, file, previous, motionNames, remarkPlugins);
|
|
548
|
+
return {
|
|
549
|
+
frontmatter,
|
|
550
|
+
clicks,
|
|
551
|
+
fingerprint: JSON.stringify([data, clicks])
|
|
552
|
+
};
|
|
553
|
+
} catch (cause) {
|
|
554
|
+
if (cause instanceof DeckError) throw cause;
|
|
555
|
+
const mark = typeof cause === "object" && cause !== null && "mark" in cause ? cause.mark : void 0;
|
|
556
|
+
const loc = typeof mark === "object" && mark !== null && "line" in mark && typeof mark.line === "number" && "column" in mark && typeof mark.column === "number" ? {
|
|
557
|
+
line: mark.line + 1,
|
|
558
|
+
column: mark.column + 1
|
|
559
|
+
} : void 0;
|
|
560
|
+
if (!loc) throw cause;
|
|
561
|
+
const reason = typeof cause === "object" && cause !== null && "reason" in cause ? String(cause.reason) : String(cause);
|
|
562
|
+
throw new DeckError(`invalid YAML: ${reason}. Check the frontmatter syntax.`, file, loc, { cause });
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
async function scanSlidesWithCounts(deck, totals) {
|
|
566
|
+
const { motionNames, code: componentsCode, names: componentNames } = await componentsModule(deck.dir);
|
|
567
|
+
const files = (await glob("slides/*.mdx", { cwd: deck.dir })).sort();
|
|
568
|
+
const slides = [];
|
|
569
|
+
const metadata = /* @__PURE__ */ new Map();
|
|
570
|
+
for (const file of files) {
|
|
571
|
+
const id = basename(file, ".mdx");
|
|
572
|
+
try {
|
|
573
|
+
const { frontmatter, clicks, fingerprint } = readSlide(await readSource(join(deck.dir, file)), join(deck.dir, file), totals.get(file), motionNames, deck.config.mdx?.remarkPlugins);
|
|
574
|
+
metadata.set(file, fingerprint);
|
|
575
|
+
totals.set(file, clicks);
|
|
576
|
+
if (frontmatter.hide) continue;
|
|
577
|
+
frontmatter.title ??= id;
|
|
578
|
+
slides.push({
|
|
579
|
+
meta: {
|
|
580
|
+
no: slides.length + 1,
|
|
581
|
+
id,
|
|
582
|
+
file,
|
|
583
|
+
title: frontmatter.title,
|
|
584
|
+
clicks,
|
|
585
|
+
...frontmatter.transition === void 0 ? {} : { transition: frontmatter.transition },
|
|
586
|
+
...frontmatter.morphSteps === void 0 ? {} : { morphSteps: frontmatter.morphSteps }
|
|
587
|
+
},
|
|
588
|
+
frontmatter
|
|
589
|
+
});
|
|
590
|
+
} catch (cause) {
|
|
591
|
+
if (cause instanceof DeckError) throw cause;
|
|
592
|
+
throw compileError(cause, join(deck.dir, file));
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
if (!slides.length) throw new DeckError(files.length ? `every slide in ${displayPath(deck.dir)}/slides has hide: true.` : `no slides/*.mdx files in ${displayPath(deck.dir) === "." ? "the current directory" : displayPath(deck.dir)}.`);
|
|
596
|
+
return {
|
|
597
|
+
slides,
|
|
598
|
+
metadata,
|
|
599
|
+
componentsCode,
|
|
600
|
+
motionNames,
|
|
601
|
+
componentNames
|
|
602
|
+
};
|
|
603
|
+
}
|
|
604
|
+
function buildManifest(deck, slides) {
|
|
605
|
+
if (!slides.length) throw new DeckError(`no slides/*.mdx files in ${displayPath(deck.dir) === "." ? "the current directory" : displayPath(deck.dir)}.`);
|
|
606
|
+
return assertManifest({
|
|
607
|
+
name: deck.name,
|
|
608
|
+
title: deck.config.title,
|
|
609
|
+
canvas: deck.config.canvas,
|
|
610
|
+
...deck.config.transition === void 0 ? {} : { transition: deck.config.transition },
|
|
611
|
+
slides: slides.map(({ meta }) => meta)
|
|
612
|
+
});
|
|
613
|
+
}
|
|
614
|
+
// ../node/src/dev/config.ts
|
|
615
|
+
function defineDeck(config) {
|
|
616
|
+
return config;
|
|
617
|
+
}
|
|
618
|
+
const schema = z.strictObject({
|
|
619
|
+
title: z.string(),
|
|
620
|
+
author: z.string().optional(),
|
|
621
|
+
info: z.string().optional(),
|
|
622
|
+
url: z.url().optional(),
|
|
623
|
+
canvas: z.strictObject({
|
|
624
|
+
width: z.number().positive(),
|
|
625
|
+
height: z.number().positive()
|
|
626
|
+
}).default({
|
|
627
|
+
width: 1920,
|
|
628
|
+
height: 1080
|
|
629
|
+
}),
|
|
630
|
+
transition: z.string().min(1).optional(),
|
|
631
|
+
htmlAttrs: z.record(z.string(), z.string()).optional(),
|
|
632
|
+
credit: z.boolean().default(true),
|
|
633
|
+
vite: z.custom((value) => typeof value === "object" && value !== null && !Array.isArray(value)).optional(),
|
|
634
|
+
mdx: z.strictObject({
|
|
635
|
+
remarkPlugins: z.custom(Array.isArray, "mdx.remarkPlugins must be an array").optional(),
|
|
636
|
+
rehypePlugins: z.custom(Array.isArray, "mdx.rehypePlugins must be an array").optional()
|
|
637
|
+
}).optional()
|
|
638
|
+
});
|
|
639
|
+
async function loadDeck(dir, name) {
|
|
640
|
+
const absolute = resolve(dir);
|
|
641
|
+
const file = resolve(absolute, "deck.config.ts");
|
|
642
|
+
if (!existsSync(file)) throw new DeckError(`no deck.config.ts in ${displayPath(absolute)}. A deck directory holds deck.config.ts and slides/.`, file, void 0, { prefix: false });
|
|
643
|
+
const module = await createJiti(import.meta.url, {
|
|
644
|
+
moduleCache: false,
|
|
645
|
+
fsCache: false
|
|
646
|
+
}).import(file).catch((cause) => {
|
|
647
|
+
throw new DeckError(`cannot load config: ${cause instanceof Error ? cause.message : String(cause)}`, file, void 0, { cause });
|
|
648
|
+
});
|
|
649
|
+
if (!Object.hasOwn(module, "default")) throw new DeckError(`${displayPath(file)} has no default export. Write: export default defineDeck({ title: "..." })`, file, void 0, { prefix: false });
|
|
650
|
+
const parsed = schema.safeParse(module.default);
|
|
651
|
+
if (!parsed.success) throw validationError(file, parsed.error.issues, module.default, Object.keys(schema.shape));
|
|
652
|
+
const config = parsed.data;
|
|
653
|
+
for (const key of Object.keys(config.htmlAttrs ?? {})) if (!/^[A-Za-z_:][-A-Za-z0-9_:.]*$/.test(key)) throw new DeckError(`htmlAttrs key ${key} is not a valid HTML attribute name.`, file);
|
|
654
|
+
return {
|
|
655
|
+
name: name ?? basename(absolute),
|
|
656
|
+
dir: absolute,
|
|
657
|
+
config
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
// ../node/src/dev/entry.ts
|
|
661
|
+
function entryModule(deck) {
|
|
662
|
+
return `${existsSync(join(deck.dir, "setup.ts")) ? "import \"/setup.ts\";\n" : ""}import { mountDeck, Center, Cover, Section, TwoCol, ImageSide } from "${PUBLIC_SPECIFIERS.runtime}";
|
|
663
|
+
import { Step, Steps, Stagger, TextReveal, Highlight, CountUp, Draw, Morph, CodeBlock } from "${PUBLIC_SPECIFIERS.motion}";
|
|
664
|
+
${existsSync(join(deck.dir, "styles/index.css")) ? "import \"/styles/index.css\";" : ""}
|
|
665
|
+
Promise.all([
|
|
666
|
+
import("virtual:react-decks/manifest"),
|
|
667
|
+
import("virtual:react-decks/components"),
|
|
668
|
+
import("virtual:react-decks/layers")
|
|
669
|
+
]).then(([{ manifest, slides, frontmatter }, { components }, { layers }]) => {
|
|
670
|
+
mountDeck({ manifest, slides, frontmatter, layers,
|
|
671
|
+
components: { Step, Steps, Stagger, TextReveal, Highlight, CountUp, Draw, Morph, pre: CodeBlock, Center, Cover, Section, TwoCol, ImageSide, ...components },
|
|
672
|
+
loadNotes: () => import("virtual:react-decks/notes").then(module => module.notes)
|
|
673
|
+
});
|
|
674
|
+
}).catch(error => {
|
|
675
|
+
reportError(error);
|
|
676
|
+
document.getElementById("deck-root").textContent = "The deck failed to start: " + error.message;
|
|
677
|
+
});`;
|
|
678
|
+
}
|
|
679
|
+
/** The Decks mark (two slides on the diagonal) as a data URL, in the default theme's cyan and violet. */
|
|
680
|
+
const DECKS_ICON = `data:image/svg+xml,${encodeURIComponent("<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 32 32\"><path fill=\"#8b5cf6\" d=\"M12 4.75H27a3 3 0 0 1 3 3v8.5a3 3 0 0 1-3 3h-2.5v-3.5a4.5 4.5 0 0 0-4.5-4.5H9v-3.5a3 3 0 0 1 3-3Z\"/><rect x=\"2\" y=\"12.75\" width=\"21\" height=\"14.5\" rx=\"3\" fill=\"#06b6d4\"/></svg>")}`;
|
|
681
|
+
function deckHtml(deck, dev) {
|
|
682
|
+
const escapeHtml = (value) => value.replaceAll("&", "&").replaceAll("\"", """).replaceAll("<", "<").replaceAll(">", ">");
|
|
683
|
+
const attrs = Object.entries(deck.config.htmlAttrs ?? {}).map(([key, value]) => `${key}="${escapeHtml(value)}"`).join(" ");
|
|
684
|
+
const { title, author, info, url } = deck.config;
|
|
685
|
+
const icon = [
|
|
686
|
+
"favicon.svg",
|
|
687
|
+
"favicon.png",
|
|
688
|
+
"favicon.ico"
|
|
689
|
+
].find((file) => existsSync(join(deck.dir, "public", file)));
|
|
690
|
+
const image = ["og.png", "og.jpg"].find((file) => existsSync(join(deck.dir, "public", file)));
|
|
691
|
+
const meta = (key, name, content) => content === void 0 ? "" : `<meta ${key}="${name}" content="${escapeHtml(content)}">\n`;
|
|
692
|
+
return `<!doctype html><html ${attrs}><head><meta charset="utf-8">
|
|
693
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
694
|
+
<link rel="icon" href="${icon ? `/${icon}` : DECKS_ICON}">
|
|
695
|
+
<title>${escapeHtml(title)}</title>
|
|
696
|
+
${meta("name", "author", author)}${meta("name", "description", info)}${meta("property", "og:type", "website")}${meta("property", "og:title", title)}${meta("property", "og:description", info)}${meta("property", "og:url", url)}${meta("property", "og:image", url && image ? new URL(image, url.endsWith("/") ? url : `${url}/`).href : void 0)}${meta("name", "twitter:card", url && image ? "summary_large_image" : "summary")}${dev ? `<meta name="decks:entry" content="${escapeHtml(deck.dir)}">` : ""}
|
|
697
|
+
<meta name="decks:name" content="${escapeHtml(deck.name)}">
|
|
698
|
+
</head><body><div id="deck-root"></div><script type="module" src="/virtual:react-decks/entry"><\/script></body></html>`;
|
|
699
|
+
}
|
|
700
|
+
// ../node/src/dev/error-reporting.ts
|
|
701
|
+
function errorReporting(base = createLogger(), deckDir = process.cwd()) {
|
|
702
|
+
const packages = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "../../../" : "../../", import.meta.url));
|
|
703
|
+
const sources = [
|
|
704
|
+
"node",
|
|
705
|
+
"core",
|
|
706
|
+
"runtime",
|
|
707
|
+
"motion",
|
|
708
|
+
"kit"
|
|
709
|
+
].map((name) => `${normalizePath(join(packages, name, "src"))}/`);
|
|
710
|
+
const logger = { ...base };
|
|
711
|
+
const logError = logger.error.bind(logger);
|
|
712
|
+
const reported = /* @__PURE__ */ new Map();
|
|
713
|
+
const report = (error, heading) => {
|
|
714
|
+
const key = error.file ?? error.message;
|
|
715
|
+
if (reported.get(key) === error.message) return;
|
|
716
|
+
reported.set(key, error.message);
|
|
717
|
+
if (heading) logger.info(heading);
|
|
718
|
+
logError(error.message, { error });
|
|
719
|
+
};
|
|
720
|
+
logger.error = (message, options) => {
|
|
721
|
+
const error = authorError(options?.error);
|
|
722
|
+
if (error) report(error);
|
|
723
|
+
else {
|
|
724
|
+
const diagnostic = options?.error;
|
|
725
|
+
const id = diagnostic && "id" in diagnostic ? diagnostic.id : void 0;
|
|
726
|
+
if (diagnostic && typeof id === "string" && reported.has(id) && "plugin" in diagnostic && diagnostic.plugin === "vite:oxc") return;
|
|
727
|
+
if (Array.from(reported.values()).some((reported) => message.includes(reported))) return;
|
|
728
|
+
const origin = (diagnostic?.stack ?? message).split("\n").find((line) => /^\s+(at |>[ ])/.test(line)) ?? "";
|
|
729
|
+
const ownCode = sources.some((source) => origin.includes(source) || [" ", "("].some((prefix) => origin.includes(`${prefix}${normalizePath(relative(deckDir, source))}/`))) || diagnostic && "plugin" in diagnostic && typeof diagnostic.plugin === "string" && diagnostic.plugin.startsWith("react-decks");
|
|
730
|
+
logError(ownCode ? `${message}\nThis is a bug in react-decks.` : message, options);
|
|
731
|
+
}
|
|
732
|
+
};
|
|
733
|
+
return {
|
|
734
|
+
logger,
|
|
735
|
+
report,
|
|
736
|
+
fixed(file, message = `${displayPath(file)}: fixed`) {
|
|
737
|
+
if (!reported.delete(file)) return;
|
|
738
|
+
logger.info(message);
|
|
739
|
+
}
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
// ../node/src/dev/layers.ts
|
|
743
|
+
const NAMES = [
|
|
744
|
+
"above",
|
|
745
|
+
"below",
|
|
746
|
+
"credit"
|
|
747
|
+
];
|
|
748
|
+
/** `credit` is the deck's `credit` option: false removes the corner credit from every slide. */
|
|
749
|
+
async function layersModule(dir, credit) {
|
|
750
|
+
const names = (await glob("layers/**/*.tsx", { cwd: dir })).sort().map((file) => {
|
|
751
|
+
const name = file.slice(7, -4);
|
|
752
|
+
if (!NAMES.includes(name)) throw new DeckError(`expected layers/above.tsx, layers/below.tsx or layers/credit.tsx.`, join(dir, file));
|
|
753
|
+
return name;
|
|
754
|
+
});
|
|
755
|
+
const shown = credit ? names : names.filter((name) => name !== "credit");
|
|
756
|
+
return `${shown.map((name) => `import ${name} from ${JSON.stringify(`/layers/${name}.tsx`)};`).join("\n")}
|
|
757
|
+
export const layers = {${[...shown, ...credit ? [] : ["credit:false"]].join(",")}};`;
|
|
758
|
+
}
|
|
759
|
+
// ../node/src/dev/virtual-modules.ts
|
|
760
|
+
function manifestModule(deck, slides) {
|
|
761
|
+
const loaders = slides.map(({ meta }) => `[${JSON.stringify(meta.id)}, () => import(${JSON.stringify(`/${meta.file}`)})]`).join(",");
|
|
762
|
+
return `export const manifest = ${JSON.stringify(buildManifest(deck, slides))};
|
|
763
|
+
export const frontmatter = Object.fromEntries(${JSON.stringify(slides.map((slide) => [slide.meta.id, slide.frontmatter]))});
|
|
764
|
+
export const slides = Object.fromEntries([${loaders}]);`;
|
|
765
|
+
}
|
|
766
|
+
async function notesModule(deck, slides, onRenderError) {
|
|
767
|
+
const notes = [];
|
|
768
|
+
for (const { meta } of slides) {
|
|
769
|
+
const file = normalizePath(join(deck().dir, meta.file));
|
|
770
|
+
const segments = await renderNotes(await readSource(file), file, deck().config.mdx?.remarkPlugins).catch(onRenderError);
|
|
771
|
+
if (segments !== void 0) notes.push([meta.id, segments]);
|
|
772
|
+
}
|
|
773
|
+
return `export const notes = Object.fromEntries(${JSON.stringify(notes)});`;
|
|
774
|
+
}
|
|
775
|
+
// ../node/src/dev/plugins.ts
|
|
776
|
+
const prefix = "virtual:react-decks/";
|
|
777
|
+
function reactDecks(deck) {
|
|
778
|
+
return createDeckPlugins(deck).plugins;
|
|
779
|
+
}
|
|
780
|
+
function createDeckPlugins(deck) {
|
|
781
|
+
let current = deck;
|
|
782
|
+
let configSource;
|
|
783
|
+
let restarting = Promise.resolve();
|
|
784
|
+
let closing = false;
|
|
785
|
+
let serving = false;
|
|
786
|
+
let reportLogger = deck.config.vite?.customLogger;
|
|
787
|
+
let reporting = errorReporting(reportLogger, deck.dir);
|
|
788
|
+
const failures = /* @__PURE__ */ new Map();
|
|
789
|
+
const scanFailures = /* @__PURE__ */ new Map();
|
|
790
|
+
const compiled = /* @__PURE__ */ new Set();
|
|
791
|
+
const failedLoads = /* @__PURE__ */ new Set();
|
|
792
|
+
const configErrors = /* @__PURE__ */ new WeakMap();
|
|
793
|
+
let scan;
|
|
794
|
+
let reloadTimer;
|
|
795
|
+
const changedModules = /* @__PURE__ */ new Set();
|
|
796
|
+
const deckDir = normalizePath(deck.dir);
|
|
797
|
+
const htmlFile = normalizePath(join(deck.dir, "index.html"));
|
|
798
|
+
const configFile = normalizePath(join(deck.dir, "deck.config.ts"));
|
|
799
|
+
const readConfig = () => readSource(configFile);
|
|
800
|
+
const readChangedSource = async (file) => {
|
|
801
|
+
try {
|
|
802
|
+
return await readSource(file, true);
|
|
803
|
+
} catch (cause) {
|
|
804
|
+
if (cause instanceof DeckError && file !== configFile) failures.set(file, cause);
|
|
805
|
+
throw cause;
|
|
806
|
+
}
|
|
807
|
+
};
|
|
808
|
+
let metadata = /* @__PURE__ */ new Map();
|
|
809
|
+
let componentsCode;
|
|
810
|
+
let motionNames = /* @__PURE__ */ new Map();
|
|
811
|
+
let componentNames = /* @__PURE__ */ new Set();
|
|
812
|
+
const totals = /* @__PURE__ */ new Map();
|
|
813
|
+
const scanDeck = () => {
|
|
814
|
+
if (serving || !scan) scan = (async () => {
|
|
815
|
+
try {
|
|
816
|
+
const scanned = await scanSlidesWithCounts(current, totals);
|
|
817
|
+
await layersModule(deck.dir, deck.config.credit);
|
|
818
|
+
for (const [key] of scanFailures) reporting.fixed(key);
|
|
819
|
+
scanFailures.clear();
|
|
820
|
+
return scanned;
|
|
821
|
+
} catch (cause) {
|
|
822
|
+
if (cause instanceof DeckError) rememberScan(cause);
|
|
823
|
+
throw cause;
|
|
824
|
+
}
|
|
825
|
+
})();
|
|
826
|
+
return scan;
|
|
827
|
+
};
|
|
828
|
+
const rememberScan = (error) => {
|
|
829
|
+
scanFailures.set(error.file ?? error.message, error);
|
|
830
|
+
if (serving) reporting.report(error);
|
|
831
|
+
};
|
|
832
|
+
const overlay = (error) => ({
|
|
833
|
+
message: error.message,
|
|
834
|
+
id: error.file,
|
|
835
|
+
loc: error.loc,
|
|
836
|
+
stack: ""
|
|
837
|
+
});
|
|
838
|
+
const reload = (server, name) => {
|
|
839
|
+
if (closing) return;
|
|
840
|
+
changedModules.add(name);
|
|
841
|
+
if (reloadTimer) clearTimeout(reloadTimer);
|
|
842
|
+
reloadTimer = setTimeout(() => {
|
|
843
|
+
if (closing) return;
|
|
844
|
+
const graph = server.environments.client?.moduleGraph;
|
|
845
|
+
changedModules.add("notes");
|
|
846
|
+
for (const name of changedModules) {
|
|
847
|
+
const module = graph?.getModuleById(`\0${prefix}${name}`);
|
|
848
|
+
if (module) graph?.invalidateModule(module);
|
|
849
|
+
}
|
|
850
|
+
changedModules.clear();
|
|
851
|
+
server.ws.send({ type: "full-reload" });
|
|
852
|
+
}, 100);
|
|
853
|
+
};
|
|
854
|
+
const plugin = {
|
|
855
|
+
name: "react-decks",
|
|
856
|
+
enforce: "pre",
|
|
857
|
+
async config(inline, { command }) {
|
|
858
|
+
serving = command === "serve";
|
|
859
|
+
if (serving && inline.customLogger && inline.customLogger !== reportLogger) {
|
|
860
|
+
reportLogger = inline.customLogger;
|
|
861
|
+
reporting = errorReporting(reportLogger, deck.dir);
|
|
862
|
+
}
|
|
863
|
+
if (command === "serve") configSource ??= await readConfig();
|
|
864
|
+
return mergeConfig(mergeConfig({
|
|
865
|
+
root: deckDir,
|
|
866
|
+
publicDir: normalizePath(join(deck.dir, "public"))
|
|
867
|
+
}, current.config.vite ?? {}), {
|
|
868
|
+
...inline.base === void 0 ? {} : { base: inline.base },
|
|
869
|
+
customLogger: serving ? reporting.logger : inline.customLogger,
|
|
870
|
+
server: {
|
|
871
|
+
forwardConsole: {
|
|
872
|
+
unhandledErrors: true,
|
|
873
|
+
logLevels: ["warn"]
|
|
874
|
+
},
|
|
875
|
+
...inline.server?.port === void 0 ? {} : {
|
|
876
|
+
port: inline.server.port,
|
|
877
|
+
strictPort: inline.server.strictPort
|
|
878
|
+
}
|
|
879
|
+
},
|
|
880
|
+
...inline.build === void 0 ? {} : { build: inline.build }
|
|
881
|
+
});
|
|
882
|
+
},
|
|
883
|
+
resolveId(id) {
|
|
884
|
+
if (id.startsWith(prefix) || id.startsWith(`/${prefix}`)) return `\0${id.replace(/^\//, "")}`;
|
|
885
|
+
if (normalizePath(id) === htmlFile) return id;
|
|
886
|
+
},
|
|
887
|
+
async load(id) {
|
|
888
|
+
if (normalizePath(id) === htmlFile) return deckHtml(current, false);
|
|
889
|
+
if (id === `\0${prefix}entry`) return entryModule(current);
|
|
890
|
+
if (id === `\0${prefix}components`) return (await scanDeck()).componentsCode;
|
|
891
|
+
if (id === `\0${prefix}layers`) return layersModule(deck.dir, deck.config.credit);
|
|
892
|
+
if (id !== `\0${prefix}manifest` && id !== `\0${prefix}notes`) return;
|
|
893
|
+
let scanned;
|
|
894
|
+
try {
|
|
895
|
+
scanned = await scanDeck();
|
|
896
|
+
} catch (cause) {
|
|
897
|
+
if (cause instanceof DeckError) this.error(cause);
|
|
898
|
+
throw cause;
|
|
899
|
+
}
|
|
900
|
+
const failure = failures.values().next().value;
|
|
901
|
+
if (failure) this.error(failure);
|
|
902
|
+
const slides = scanned.slides;
|
|
903
|
+
if (id === `\0${prefix}manifest`) {
|
|
904
|
+
metadata = scanned.metadata;
|
|
905
|
+
componentsCode = scanned.componentsCode;
|
|
906
|
+
motionNames = scanned.motionNames;
|
|
907
|
+
componentNames = scanned.componentNames;
|
|
908
|
+
return manifestModule(current, slides);
|
|
909
|
+
}
|
|
910
|
+
return notesModule(() => current, slides, (cause) => {
|
|
911
|
+
if (cause instanceof DeckError) {
|
|
912
|
+
if (serving) reporting.report(cause);
|
|
913
|
+
this.error(cause);
|
|
914
|
+
}
|
|
915
|
+
throw cause;
|
|
916
|
+
});
|
|
917
|
+
},
|
|
918
|
+
async configureServer(viteServer) {
|
|
919
|
+
const server = viteServer;
|
|
920
|
+
const servedDeck = current;
|
|
921
|
+
const servedConfig = server.config;
|
|
922
|
+
server.ws.on("connection", (_socket, _request) => {
|
|
923
|
+
const configError = configErrors.get(servedConfig);
|
|
924
|
+
if (configError) server.ws.send({
|
|
925
|
+
type: "error",
|
|
926
|
+
err: overlay(configError)
|
|
927
|
+
});
|
|
928
|
+
});
|
|
929
|
+
const structural = (path) => {
|
|
930
|
+
const file = normalizePath(path);
|
|
931
|
+
if (file === `${deckDir}/setup.ts`) reload(server, "entry");
|
|
932
|
+
if (normalizePath(dirname(file)) === `${deckDir}/slides` && file.endsWith(".mdx")) {
|
|
933
|
+
metadata.delete(file.slice(deckDir.length + 1));
|
|
934
|
+
totals.delete(file.slice(deckDir.length + 1));
|
|
935
|
+
failures.delete(file);
|
|
936
|
+
reporting.fixed(file);
|
|
937
|
+
reload(server, "manifest");
|
|
938
|
+
}
|
|
939
|
+
if (normalizePath(dirname(file)) === `${deckDir}/components` && file.endsWith(".tsx")) {
|
|
940
|
+
failures.delete(file);
|
|
941
|
+
reporting.fixed(file);
|
|
942
|
+
reload(server, "components");
|
|
943
|
+
reload(server, "manifest");
|
|
944
|
+
}
|
|
945
|
+
if (file.startsWith(`${deckDir}/layers/`)) reload(server, "layers");
|
|
946
|
+
};
|
|
947
|
+
server.watcher.on("add", structural);
|
|
948
|
+
server.watcher.on("unlink", structural);
|
|
949
|
+
const configChanged = (file) => {
|
|
950
|
+
if (closing || !server.httpServer?.listening || normalizePath(file) !== configFile) return;
|
|
951
|
+
restarting = restarting.then(async () => {
|
|
952
|
+
for (;;) {
|
|
953
|
+
if (closing) return;
|
|
954
|
+
let source = await readChangedSource(configFile);
|
|
955
|
+
if (closing) return;
|
|
956
|
+
if (source === configSource && !configErrors.has(server.config)) return;
|
|
957
|
+
try {
|
|
958
|
+
current = await loadDeck(deck.dir, deck.name);
|
|
959
|
+
} catch (cause) {
|
|
960
|
+
const latest = await readChangedSource(configFile);
|
|
961
|
+
if (latest === source) throw cause;
|
|
962
|
+
source = latest;
|
|
963
|
+
current = await loadDeck(deck.dir, deck.name);
|
|
964
|
+
}
|
|
965
|
+
if (closing) return;
|
|
966
|
+
plugins[1] = compiler();
|
|
967
|
+
server.config.inlineConfig.plugins = [plugins, current.config.vite?.plugins ?? []];
|
|
968
|
+
const previousConfig = server.config;
|
|
969
|
+
await server.restart();
|
|
970
|
+
if (server.config === previousConfig) return;
|
|
971
|
+
configSource = source;
|
|
972
|
+
if (configErrors.delete(previousConfig)) reporting.fixed(configFile, "deck.config.ts is valid again, restarting.");
|
|
973
|
+
}
|
|
974
|
+
}).catch((cause) => {
|
|
975
|
+
if (closing) return;
|
|
976
|
+
if (cause instanceof DeckError) {
|
|
977
|
+
configErrors.set(server.config, cause);
|
|
978
|
+
const graph = server.environments.client?.moduleGraph;
|
|
979
|
+
const manifest = graph?.getModuleById(`\0${prefix}manifest`);
|
|
980
|
+
if (manifest) graph?.invalidateModule(manifest);
|
|
981
|
+
reporting.report(cause, "deck.config.ts is invalid, still serving the last valid config:");
|
|
982
|
+
server.ws.send({
|
|
983
|
+
type: "error",
|
|
984
|
+
err: overlay(cause)
|
|
985
|
+
});
|
|
986
|
+
return;
|
|
987
|
+
}
|
|
988
|
+
const error = cause instanceof Error ? cause : new Error(String(cause));
|
|
989
|
+
server.config.logger.error(error.stack ?? error.message);
|
|
990
|
+
server.ws.send({
|
|
991
|
+
type: "error",
|
|
992
|
+
err: {
|
|
993
|
+
message: error.message,
|
|
994
|
+
stack: error.stack ?? ""
|
|
995
|
+
}
|
|
996
|
+
});
|
|
997
|
+
});
|
|
998
|
+
};
|
|
999
|
+
server.watcher.on("change", configChanged);
|
|
1000
|
+
server.middlewares.use(async (req, res, next) => {
|
|
1001
|
+
const path = req.url?.split("?")[0];
|
|
1002
|
+
const base = server.config.base;
|
|
1003
|
+
if (path !== base && path !== `${base}index.html`) return next();
|
|
1004
|
+
try {
|
|
1005
|
+
const html = await server.transformIndexHtml(req.url ?? "/", deckHtml(servedDeck, true));
|
|
1006
|
+
res.setHeader("Content-Type", "text/html");
|
|
1007
|
+
res.end(html);
|
|
1008
|
+
} catch (error) {
|
|
1009
|
+
next(error);
|
|
1010
|
+
}
|
|
1011
|
+
});
|
|
1012
|
+
try {
|
|
1013
|
+
const scanned = await scanDeck();
|
|
1014
|
+
metadata = scanned.metadata;
|
|
1015
|
+
componentsCode = scanned.componentsCode;
|
|
1016
|
+
motionNames = scanned.motionNames;
|
|
1017
|
+
componentNames = scanned.componentNames;
|
|
1018
|
+
} catch (cause) {
|
|
1019
|
+
if (!(cause instanceof DeckError)) throw cause;
|
|
1020
|
+
}
|
|
1021
|
+
server.httpServer?.once("listening", () => configChanged(configFile));
|
|
1022
|
+
},
|
|
1023
|
+
closeBundle() {
|
|
1024
|
+
clearTimeout(reloadTimer);
|
|
1025
|
+
changedModules.clear();
|
|
1026
|
+
},
|
|
1027
|
+
async hotUpdate(context) {
|
|
1028
|
+
if (this.environment.name !== "client") return;
|
|
1029
|
+
try {
|
|
1030
|
+
const configError = configErrors.get(context.server.config);
|
|
1031
|
+
if (configError) this.error(configError);
|
|
1032
|
+
const file = normalizePath(context.file);
|
|
1033
|
+
if (file === `${deckDir}/setup.ts`) {
|
|
1034
|
+
reload(context.server, "entry");
|
|
1035
|
+
return [];
|
|
1036
|
+
}
|
|
1037
|
+
const parent = normalizePath(dirname(file));
|
|
1038
|
+
if (file.startsWith(`${deckDir}/layers/`) && context.type !== "update") return [];
|
|
1039
|
+
if (parent === `${deckDir}/components` && file.endsWith(".tsx") && context.type === "update") {
|
|
1040
|
+
const wasScanFailed = scanFailures.size > 0;
|
|
1041
|
+
const scanned = await scanDeck();
|
|
1042
|
+
const wasFailed = failures.delete(file);
|
|
1043
|
+
reporting.fixed(file);
|
|
1044
|
+
componentNames = scanned.componentNames;
|
|
1045
|
+
motionNames = scanned.motionNames;
|
|
1046
|
+
if (!wasFailed && !wasScanFailed && scanned.componentsCode === componentsCode && Array.from(scanned.metadata).every(([file, value]) => metadata.get(file) === value)) return;
|
|
1047
|
+
componentsCode = scanned.componentsCode;
|
|
1048
|
+
metadata = scanned.metadata;
|
|
1049
|
+
reload(context.server, "components");
|
|
1050
|
+
reload(context.server, "manifest");
|
|
1051
|
+
return [];
|
|
1052
|
+
}
|
|
1053
|
+
if (context.type !== "update" && (parent === `${deckDir}/slides` && file.endsWith(".mdx") || parent === `${deckDir}/components` && file.endsWith(".tsx"))) return [];
|
|
1054
|
+
if (parent !== `${deckDir}/slides` || !file.endsWith(".mdx") || context.type !== "update") return;
|
|
1055
|
+
const key = file.slice(deckDir.length + 1);
|
|
1056
|
+
const { clicks: total, fingerprint: next } = readSlide(await readChangedSource(file), file, totals.get(key), motionNames, current.config.mdx?.remarkPlugins);
|
|
1057
|
+
const wasFailed = failures.delete(file);
|
|
1058
|
+
if (wasFailed) reporting.fixed(file);
|
|
1059
|
+
const previous = metadata.get(key);
|
|
1060
|
+
metadata.set(key, next);
|
|
1061
|
+
totals.set(key, total);
|
|
1062
|
+
const wasScanFailed = scanFailures.size > 0;
|
|
1063
|
+
if (wasScanFailed) await scanDeck();
|
|
1064
|
+
const graph = this.environment.moduleGraph;
|
|
1065
|
+
const notes = graph.getModuleById(`\0${prefix}notes`);
|
|
1066
|
+
if (notes) graph.invalidateModule(notes);
|
|
1067
|
+
const failedLoad = failedLoads.delete(file);
|
|
1068
|
+
if (next === previous && !wasFailed && !failedLoad && !wasScanFailed) return;
|
|
1069
|
+
const manifest = graph.getModuleById(`\0${prefix}manifest`);
|
|
1070
|
+
if (manifest) graph.invalidateModule(manifest);
|
|
1071
|
+
this.environment.hot.send({ type: "full-reload" });
|
|
1072
|
+
return [];
|
|
1073
|
+
} catch (cause) {
|
|
1074
|
+
if (!(cause instanceof DeckError)) throw cause;
|
|
1075
|
+
if (cause.file !== configFile) {
|
|
1076
|
+
rememberScan(cause);
|
|
1077
|
+
const graph = this.environment.moduleGraph;
|
|
1078
|
+
const manifest = graph.getModuleById(`\0${prefix}manifest`);
|
|
1079
|
+
if (manifest) graph.invalidateModule(manifest);
|
|
1080
|
+
}
|
|
1081
|
+
this.error(cause);
|
|
1082
|
+
}
|
|
1083
|
+
}
|
|
1084
|
+
};
|
|
1085
|
+
const compiler = () => {
|
|
1086
|
+
const mdxPlugin = mdx({
|
|
1087
|
+
mdExtensions: [],
|
|
1088
|
+
remarkPlugins: [
|
|
1089
|
+
remarkFrontmatter,
|
|
1090
|
+
removeNotes,
|
|
1091
|
+
...current.config.mdx?.remarkPlugins ?? [],
|
|
1092
|
+
checkComponents(() => componentNames)
|
|
1093
|
+
],
|
|
1094
|
+
rehypePlugins: [...current.config.mdx?.rehypePlugins ?? [], codeBlocks]
|
|
1095
|
+
});
|
|
1096
|
+
return {
|
|
1097
|
+
...mdxPlugin,
|
|
1098
|
+
async transform(source, id) {
|
|
1099
|
+
try {
|
|
1100
|
+
const result = await mdxPlugin.transform(source, id);
|
|
1101
|
+
if (result) {
|
|
1102
|
+
compiled.add(id);
|
|
1103
|
+
reporting.fixed(id);
|
|
1104
|
+
}
|
|
1105
|
+
return result;
|
|
1106
|
+
} catch (cause) {
|
|
1107
|
+
if (!compiled.has(id)) failedLoads.add(id);
|
|
1108
|
+
const error = compileError(cause, id);
|
|
1109
|
+
if (serving) reporting.report(error);
|
|
1110
|
+
this.error(error);
|
|
1111
|
+
}
|
|
1112
|
+
},
|
|
1113
|
+
enforce: "pre"
|
|
1114
|
+
};
|
|
1115
|
+
};
|
|
1116
|
+
const plugins = [
|
|
1117
|
+
plugin,
|
|
1118
|
+
compiler(),
|
|
1119
|
+
...react({ include: /\.(mdx|jsx|tsx)$/ })
|
|
1120
|
+
];
|
|
1121
|
+
return {
|
|
1122
|
+
plugins,
|
|
1123
|
+
async stop() {
|
|
1124
|
+
closing = true;
|
|
1125
|
+
await restarting;
|
|
1126
|
+
clearTimeout(reloadTimer);
|
|
1127
|
+
changedModules.clear();
|
|
1128
|
+
}
|
|
1129
|
+
};
|
|
1130
|
+
}
|
|
1131
|
+
// ../node/src/dev/server.ts
|
|
1132
|
+
function config(deck, plugins = reactDecks(deck)) {
|
|
1133
|
+
const require = createRequire(import.meta.url);
|
|
1134
|
+
const sourceMotion = import.meta.url.endsWith(".ts") ? require.resolve("@react-decks/motion") : void 0;
|
|
1135
|
+
const source = sourceMotion ? {
|
|
1136
|
+
runtime: createRequire(sourceMotion).resolve("@react-decks/runtime"),
|
|
1137
|
+
motion: sourceMotion,
|
|
1138
|
+
kit: require.resolve("@react-decks/kit")
|
|
1139
|
+
} : void 0;
|
|
1140
|
+
return {
|
|
1141
|
+
configFile: false,
|
|
1142
|
+
root: deck.dir,
|
|
1143
|
+
plugins: [plugins, deck.config.vite?.plugins ?? []],
|
|
1144
|
+
resolve: {
|
|
1145
|
+
dedupe: ["react", "react-dom"],
|
|
1146
|
+
...source ? {
|
|
1147
|
+
conditions: ["@steamfield/decks/source", ...defaultClientConditions],
|
|
1148
|
+
alias: [
|
|
1149
|
+
{
|
|
1150
|
+
find: /^@steamfield\/decks$/,
|
|
1151
|
+
replacement: source.runtime
|
|
1152
|
+
},
|
|
1153
|
+
{
|
|
1154
|
+
find: /^@steamfield\/decks\/motion$/,
|
|
1155
|
+
replacement: source.motion
|
|
1156
|
+
},
|
|
1157
|
+
{
|
|
1158
|
+
find: /^@steamfield\/decks\/kit$/,
|
|
1159
|
+
replacement: source.kit
|
|
1160
|
+
},
|
|
1161
|
+
{
|
|
1162
|
+
find: /^@steamfield\/decks\/kit\/styles\.css$/,
|
|
1163
|
+
replacement: require.resolve("@react-decks/kit/styles.css")
|
|
1164
|
+
}
|
|
1165
|
+
]
|
|
1166
|
+
} : {}
|
|
1167
|
+
},
|
|
1168
|
+
optimizeDeps: {
|
|
1169
|
+
entries: ["components/*.tsx", ...source ? Object.values(source) : []],
|
|
1170
|
+
...source ? { include: Object.values(source) } : { include: [
|
|
1171
|
+
PUBLIC_SPECIFIERS.runtime,
|
|
1172
|
+
PUBLIC_SPECIFIERS.motion,
|
|
1173
|
+
"@steamfield/decks/kit"
|
|
1174
|
+
] }
|
|
1175
|
+
}
|
|
1176
|
+
};
|
|
1177
|
+
}
|
|
1178
|
+
async function dev(deck, options) {
|
|
1179
|
+
const port = options?.port ?? await getPort({ port: portNumbers(3030, 65535) });
|
|
1180
|
+
const lifecycle = createDeckPlugins(deck);
|
|
1181
|
+
let server;
|
|
1182
|
+
try {
|
|
1183
|
+
server = await createServer({
|
|
1184
|
+
...config(deck, [{
|
|
1185
|
+
name: "react-decks:server-lifecycle",
|
|
1186
|
+
enforce: "pre",
|
|
1187
|
+
configureServer: {
|
|
1188
|
+
order: "pre",
|
|
1189
|
+
handler(created) {
|
|
1190
|
+
server ??= created;
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
}, ...lifecycle.plugins]),
|
|
1194
|
+
server: {
|
|
1195
|
+
port,
|
|
1196
|
+
strictPort: options?.port !== void 0,
|
|
1197
|
+
open: options?.open ?? false
|
|
1198
|
+
}
|
|
1199
|
+
});
|
|
1200
|
+
await server.listen();
|
|
1201
|
+
const url = server.resolvedUrls?.local[0];
|
|
1202
|
+
if (!url) throw new Error(`${deck.dir}: Vite did not provide a local URL`);
|
|
1203
|
+
const running = server;
|
|
1204
|
+
return {
|
|
1205
|
+
url,
|
|
1206
|
+
close: async () => {
|
|
1207
|
+
await lifecycle.stop();
|
|
1208
|
+
await running.close();
|
|
1209
|
+
}
|
|
1210
|
+
};
|
|
1211
|
+
} catch (error) {
|
|
1212
|
+
await lifecycle.stop();
|
|
1213
|
+
await server?.close();
|
|
1214
|
+
if (error instanceof Error && error.message.includes(`Port ${port} is already in use`)) throw new DeckError(`port ${port} is already in use. Stop what is using it or pass a different --port.`, void 0, void 0, { cause: error });
|
|
1215
|
+
throw error;
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
async function build(deck, options) {
|
|
1219
|
+
await guardOutput(deck, options.outDir);
|
|
1220
|
+
await build$1({
|
|
1221
|
+
...config(deck),
|
|
1222
|
+
logLevel: "silent",
|
|
1223
|
+
customLogger: createLogger("silent"),
|
|
1224
|
+
base: options.base ?? deck.config.vite?.base ?? "./",
|
|
1225
|
+
build: {
|
|
1226
|
+
outDir: resolve(options.outDir),
|
|
1227
|
+
emptyOutDir: true,
|
|
1228
|
+
rolldownOptions: { input: resolve(deck.dir, "index.html") }
|
|
1229
|
+
}
|
|
1230
|
+
});
|
|
1231
|
+
if (options.ogImage !== false) try {
|
|
1232
|
+
await generateOgImage(deck, resolve(options.outDir), options.base ?? deck.config.vite?.base ?? "./");
|
|
1233
|
+
} catch (cause) {
|
|
1234
|
+
if (!(cause instanceof DeckError)) throw cause;
|
|
1235
|
+
console.warn(`decks build: og.png skipped. ${cause.message.replace(/\s*\r?\n\s*/g, " ")}`);
|
|
1236
|
+
}
|
|
1237
|
+
}
|
|
1238
|
+
async function generateOgImage(deck, outDir, base) {
|
|
1239
|
+
if (existsSync(join(deck.dir, "public/og.png"))) return;
|
|
1240
|
+
const browser = await launchBrowser();
|
|
1241
|
+
try {
|
|
1242
|
+
const capture = await openBuiltDeck(browser, outDir, base, "?motion=instant#/1", {
|
|
1243
|
+
width: 1200,
|
|
1244
|
+
height: 630
|
|
1245
|
+
});
|
|
1246
|
+
try {
|
|
1247
|
+
const scale = Math.min(1200 / deck.config.canvas.width, 630 / deck.config.canvas.height);
|
|
1248
|
+
const width = deck.config.canvas.width * scale;
|
|
1249
|
+
const height = deck.config.canvas.height * scale;
|
|
1250
|
+
await capture.page.evaluate(`(() => {
|
|
1251
|
+
const frame = document.getElementById("deck-frame");
|
|
1252
|
+
const slide = document.querySelector("[data-deck-active]");
|
|
1253
|
+
if (!frame || !slide) throw new Error("Slide 1 did not render for og.png");
|
|
1254
|
+
const background = getComputedStyle(slide).backgroundColor;
|
|
1255
|
+
if (background !== "rgba(0, 0, 0, 0)") document.body.style.backgroundColor = background;
|
|
1256
|
+
Object.assign(frame.parentElement.style, {
|
|
1257
|
+
width: "${width}px", height: "${height}px",
|
|
1258
|
+
left: "${(1200 - width) / 2}px", top: "${(630 - height) / 2}px"
|
|
1259
|
+
});
|
|
1260
|
+
})()`);
|
|
1261
|
+
await waitForCapture(capture.page);
|
|
1262
|
+
await capture.page.screenshot({
|
|
1263
|
+
path: join(outDir, "og.png"),
|
|
1264
|
+
type: "png"
|
|
1265
|
+
});
|
|
1266
|
+
} finally {
|
|
1267
|
+
await capture.close();
|
|
1268
|
+
}
|
|
1269
|
+
if (deck.config.url && !existsSync(join(deck.dir, "public/og.jpg"))) {
|
|
1270
|
+
const url = deck.config.url;
|
|
1271
|
+
const image = new URL("og.png", url.endsWith("/") ? url : `${url}/`).href.replaceAll("&", "&").replaceAll("\"", """);
|
|
1272
|
+
const htmlPath = join(outDir, "index.html");
|
|
1273
|
+
const html = await readFile(htmlPath, "utf8");
|
|
1274
|
+
await writeFile(htmlPath, html.replace("</head>", `<meta property="og:image" content="${image}"></head>`).replace("<meta name=\"twitter:card\" content=\"summary\">", "<meta name=\"twitter:card\" content=\"summary_large_image\">"));
|
|
1275
|
+
}
|
|
1276
|
+
} finally {
|
|
1277
|
+
await browser.close();
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
async function canonicalPath(path) {
|
|
1281
|
+
try {
|
|
1282
|
+
return await realpath(path);
|
|
1283
|
+
} catch (cause) {
|
|
1284
|
+
if (!(cause instanceof Error) || !("code" in cause) || cause.code !== "ENOENT") throw cause;
|
|
1285
|
+
return join(await canonicalPath(dirname(path)), path.slice(dirname(path).length + 1));
|
|
1286
|
+
}
|
|
1287
|
+
}
|
|
1288
|
+
async function guardOutput(deck, value) {
|
|
1289
|
+
const out = resolve(value);
|
|
1290
|
+
const label = displayPath(out);
|
|
1291
|
+
try {
|
|
1292
|
+
if ((await lstat(out).catch((cause) => {
|
|
1293
|
+
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return void 0;
|
|
1294
|
+
throw cause;
|
|
1295
|
+
}))?.isSymbolicLink()) await realpath(out).catch((cause) => {
|
|
1296
|
+
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") throw new DeckError(`--out ${label} is a dangling symlink. Remove it or choose a directory.`);
|
|
1297
|
+
throw cause;
|
|
1298
|
+
});
|
|
1299
|
+
const canonical = await canonicalPath(out);
|
|
1300
|
+
for (const protectedDir of [await realpath(deck.dir), await realpath(process.cwd())]) {
|
|
1301
|
+
const inside = relative(canonical, protectedDir);
|
|
1302
|
+
if (!inside || inside !== ".." && !inside.startsWith(`..${sep}`) && !inside.startsWith(sep)) throw new DeckError(`--out ${label} is the deck directory (or contains it). build empties --out first, which would delete the deck. Choose another directory.`);
|
|
1303
|
+
}
|
|
1304
|
+
let existing = out;
|
|
1305
|
+
while (!await stat(existing).catch((cause) => {
|
|
1306
|
+
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return void 0;
|
|
1307
|
+
throw cause;
|
|
1308
|
+
})) existing = dirname(existing);
|
|
1309
|
+
if (!(await stat(existing)).isDirectory()) throw new DeckError(`--out ${label} is a file. Choose a directory.`);
|
|
1310
|
+
await access(existing, constants.W_OK);
|
|
1311
|
+
if (existing === out && (await readdir(out)).length) {
|
|
1312
|
+
const html = await readFile(join(out, "index.html"), "utf8").catch((cause) => {
|
|
1313
|
+
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return "";
|
|
1314
|
+
throw cause;
|
|
1315
|
+
});
|
|
1316
|
+
if (!/<meta\s+name=["']decks:name["']\s+content=["'][^"']*["']\s*\/?>/.test(html)) throw new DeckError(`${label} is not empty and was not written by decks build. Empty it yourself or choose another --out.`);
|
|
1317
|
+
}
|
|
1318
|
+
} catch (cause) {
|
|
1319
|
+
if (cause instanceof Error && "code" in cause && cause.code === "ENOTDIR") throw new DeckError(`--out ${label} is a file. Choose a directory.`);
|
|
1320
|
+
if (cause instanceof Error && "code" in cause && ["EACCES", "EPERM"].includes(String(cause.code))) throw new DeckError(`cannot write to ${label} (permission denied).`, void 0, void 0, { cause });
|
|
1321
|
+
throw cause;
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
// ../node/src/cli/registry.ts
|
|
1325
|
+
const registrySchema = z.record(z.string(), z.unknown());
|
|
1326
|
+
const entrySchema = z.object({ dir: z.string() });
|
|
1327
|
+
const defaultsSchema = z.object({
|
|
1328
|
+
outDir: z.string().default("dist/{name}"),
|
|
1329
|
+
base: z.string().default("./"),
|
|
1330
|
+
decksDir: z.string().default("decks")
|
|
1331
|
+
});
|
|
1332
|
+
async function resolveDeck(value) {
|
|
1333
|
+
const registryPath = resolve("decks.json");
|
|
1334
|
+
let defaults;
|
|
1335
|
+
let entry;
|
|
1336
|
+
let aliases = [];
|
|
1337
|
+
let validationInput;
|
|
1338
|
+
try {
|
|
1339
|
+
validationInput = existsSync(registryPath) ? JSON.parse(await readFile(registryPath, "utf8")) : {};
|
|
1340
|
+
const registry = registrySchema.parse(validationInput);
|
|
1341
|
+
aliases = Object.keys(registry).filter((key) => !key.startsWith("_"));
|
|
1342
|
+
validationInput = registry._config ?? {};
|
|
1343
|
+
defaults = defaultsSchema.parse(validationInput);
|
|
1344
|
+
const registered = !value.startsWith("_") && Object.hasOwn(registry, value) ? registry[value] : void 0;
|
|
1345
|
+
validationInput = registered;
|
|
1346
|
+
entry = registered === void 0 ? void 0 : entrySchema.parse(registered);
|
|
1347
|
+
} catch (cause) {
|
|
1348
|
+
if (cause instanceof z.ZodError) throw validationError(registryPath, cause.issues, validationInput);
|
|
1349
|
+
throw new DeckError(`malformed decks.json: ${cause instanceof Error ? cause.message : String(cause)}`, registryPath, void 0, { cause });
|
|
1350
|
+
}
|
|
1351
|
+
if (entry !== void 0) {
|
|
1352
|
+
if (!existsSync(entry.dir)) throw new DeckError(`decks.json entry ${JSON.stringify(value)} points at ${entry.dir.replace(/\/$/, "")}/, which does not exist.`);
|
|
1353
|
+
return {
|
|
1354
|
+
deck: await loadDeck(entry.dir, value),
|
|
1355
|
+
defaults
|
|
1356
|
+
};
|
|
1357
|
+
}
|
|
1358
|
+
const directory = !isAbsolute(value) && basename(value) === value && !statSync(value, { throwIfNoEntry: false })?.isDirectory() ? resolve(defaults.decksDir, value) : value;
|
|
1359
|
+
if (!existsSync(directory)) throw new DeckError(`${JSON.stringify(value)} is not a registered deck or a directory. Registered in decks.json: ${aliases.length ? aliases.join(", ") : "none"}.`);
|
|
1360
|
+
return {
|
|
1361
|
+
deck: await loadDeck(directory, basename(resolve(directory))),
|
|
1362
|
+
defaults
|
|
1363
|
+
};
|
|
1364
|
+
}
|
|
1365
|
+
/** Every registered deck with its directory, and the registry defaults, from ./decks.json. */
|
|
1366
|
+
async function readRegistry() {
|
|
1367
|
+
const path = resolve("decks.json");
|
|
1368
|
+
let input = {};
|
|
1369
|
+
try {
|
|
1370
|
+
if (existsSync(path)) input = JSON.parse(await readFile(path, "utf8"));
|
|
1371
|
+
const registry = registrySchema.parse(input);
|
|
1372
|
+
input = registry._config ?? {};
|
|
1373
|
+
return {
|
|
1374
|
+
path,
|
|
1375
|
+
defaults: defaultsSchema.parse(input),
|
|
1376
|
+
decks: Object.entries(registry).filter(([alias]) => !alias.startsWith("_")).map(([alias, entry]) => {
|
|
1377
|
+
input = entry;
|
|
1378
|
+
return {
|
|
1379
|
+
alias,
|
|
1380
|
+
dir: entrySchema.parse(entry).dir
|
|
1381
|
+
};
|
|
1382
|
+
})
|
|
1383
|
+
};
|
|
1384
|
+
} catch (cause) {
|
|
1385
|
+
if (cause instanceof z.ZodError) throw validationError(path, cause.issues, input);
|
|
1386
|
+
throw new DeckError(`malformed decks.json: ${cause instanceof Error ? cause.message : String(cause)}`, path, void 0, { cause });
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
// ../node/src/cli/commands/lint.ts
|
|
1390
|
+
const lint = defineCommand({
|
|
1391
|
+
meta: {
|
|
1392
|
+
name: "decks lint",
|
|
1393
|
+
description: "Lint deck prose for AI rhetoric"
|
|
1394
|
+
},
|
|
1395
|
+
args: {
|
|
1396
|
+
decks: {
|
|
1397
|
+
type: "positional",
|
|
1398
|
+
required: false,
|
|
1399
|
+
description: "Deck aliases (default: every registered deck)"
|
|
1400
|
+
},
|
|
1401
|
+
stdin: {
|
|
1402
|
+
type: "boolean",
|
|
1403
|
+
default: false,
|
|
1404
|
+
description: "Lint MDX read from stdin"
|
|
1405
|
+
}
|
|
1406
|
+
},
|
|
1407
|
+
async run({ rawArgs }) {
|
|
1408
|
+
if (rawArgs.includes("--help") || rawArgs.includes("-h")) return showUsage(lint);
|
|
1409
|
+
let parsed;
|
|
1410
|
+
try {
|
|
1411
|
+
parsed = parseArgs({
|
|
1412
|
+
args: rawArgs,
|
|
1413
|
+
options: { stdin: { type: "boolean" } },
|
|
1414
|
+
allowPositionals: true
|
|
1415
|
+
});
|
|
1416
|
+
} catch (cause) {
|
|
1417
|
+
throw new DeckError(cause instanceof Error ? cause.message : String(cause));
|
|
1418
|
+
}
|
|
1419
|
+
let hits;
|
|
1420
|
+
const { scanSource, formatHit } = await import("./prose-scan-BrWZ7gxZ.js");
|
|
1421
|
+
let patterns;
|
|
1422
|
+
try {
|
|
1423
|
+
patterns = loadPatterns();
|
|
1424
|
+
} catch (cause) {
|
|
1425
|
+
console.error(`error: patterns file missing, unreadable or invalid: ${patternsFile} (${cause instanceof Error ? cause.message : String(cause)})`);
|
|
1426
|
+
process.exitCode = 2;
|
|
1427
|
+
return;
|
|
1428
|
+
}
|
|
1429
|
+
if (parsed.values.stdin) {
|
|
1430
|
+
if (parsed.positionals.length) throw new DeckError("--stdin takes no targets.");
|
|
1431
|
+
let source = "";
|
|
1432
|
+
process.stdin.setEncoding("utf8");
|
|
1433
|
+
for await (const chunk of process.stdin) source += chunk;
|
|
1434
|
+
hits = scanSource("stdin.mdx", source, patterns, { errorsOnly: false }).map((hit) => ({
|
|
1435
|
+
...hit,
|
|
1436
|
+
file: "stdin"
|
|
1437
|
+
}));
|
|
1438
|
+
} else {
|
|
1439
|
+
const aliases = parsed.positionals.length ? parsed.positionals : (await readRegistry()).decks.map((deck) => deck.alias);
|
|
1440
|
+
const decks = await Promise.all(aliases.map(async (alias) => {
|
|
1441
|
+
const { deck } = await resolveDeck(alias);
|
|
1442
|
+
return {
|
|
1443
|
+
alias,
|
|
1444
|
+
dir: deck.dir
|
|
1445
|
+
};
|
|
1446
|
+
}));
|
|
1447
|
+
if (!decks.length) throw new DeckError("No decks found to lint.");
|
|
1448
|
+
hits = (await lintDecks(decks, { errorsOnly: false })).hits;
|
|
1449
|
+
}
|
|
1450
|
+
for (const hit of hits) console.log(formatHit(hit));
|
|
1451
|
+
if (hits.some((hit) => hit.severity === "error")) process.exitCode = 1;
|
|
1452
|
+
}
|
|
1453
|
+
});
|
|
1454
|
+
async function lintDecks(decks, options) {
|
|
1455
|
+
const patterns = loadPatterns();
|
|
1456
|
+
const { scanSource } = await import("./prose-scan-BrWZ7gxZ.js");
|
|
1457
|
+
const files = /* @__PURE__ */ new Map();
|
|
1458
|
+
for (const deck of decks) {
|
|
1459
|
+
const resolved = await loadDeck(deck.dir, deck.alias);
|
|
1460
|
+
for (const file of await glob([
|
|
1461
|
+
"slides/**/*.mdx",
|
|
1462
|
+
"components/**/*.{ts,tsx}",
|
|
1463
|
+
"layers/**/*.{ts,tsx}"
|
|
1464
|
+
], {
|
|
1465
|
+
cwd: deck.dir,
|
|
1466
|
+
absolute: true,
|
|
1467
|
+
ignore: ["**/node_modules/**"]
|
|
1468
|
+
})) files.set(file, resolved);
|
|
1469
|
+
}
|
|
1470
|
+
const hits = [];
|
|
1471
|
+
for (const [file, deck] of [...files].sort(([left], [right]) => left.localeCompare(right))) {
|
|
1472
|
+
const source = await readFile(file, "utf8");
|
|
1473
|
+
hits.push(...scanSource(relative(process.cwd(), resolve(file)), source, patterns, {
|
|
1474
|
+
...options,
|
|
1475
|
+
remarkPlugins: deck.config.mdx?.remarkPlugins
|
|
1476
|
+
}));
|
|
1477
|
+
}
|
|
1478
|
+
return {
|
|
1479
|
+
errors: hits.filter((hit) => hit.severity === "error").length,
|
|
1480
|
+
warnings: hits.filter((hit) => hit.severity === "warn").length,
|
|
1481
|
+
hits
|
|
1482
|
+
};
|
|
1483
|
+
}
|
|
1484
|
+
// ../node/src/cli/commands/check.ts
|
|
1485
|
+
const check = defineCommand({
|
|
1486
|
+
meta: {
|
|
1487
|
+
name: "decks check",
|
|
1488
|
+
description: "Check the deck registry, configs, slide names and error-level prose"
|
|
1489
|
+
},
|
|
1490
|
+
args: {},
|
|
1491
|
+
async run({ rawArgs }) {
|
|
1492
|
+
try {
|
|
1493
|
+
parseArgs({
|
|
1494
|
+
args: rawArgs,
|
|
1495
|
+
options: {}
|
|
1496
|
+
});
|
|
1497
|
+
} catch (cause) {
|
|
1498
|
+
if (cause instanceof Error && "code" in cause && typeof cause.code === "string" && cause.code.startsWith("ERR_PARSE_ARGS")) throw new DeckError(cause.message, void 0, void 0, { cause });
|
|
1499
|
+
throw cause;
|
|
1500
|
+
}
|
|
1501
|
+
const { defaults, decks } = await readRegistry();
|
|
1502
|
+
const problems = [];
|
|
1503
|
+
const registered = new Set(decks.map(({ dir }) => resolve(dir)));
|
|
1504
|
+
if (existsSync(defaults.decksDir)) for (const entry of await readdir(defaults.decksDir, { withFileTypes: true })) {
|
|
1505
|
+
const dir = join(defaults.decksDir, entry.name);
|
|
1506
|
+
if (entry.isDirectory() && existsSync(join(dir, "deck.config.ts")) && !registered.has(resolve(dir))) problems.push(`unregistered: ${dir} (${join(dir, "deck.config.ts")})`);
|
|
1507
|
+
}
|
|
1508
|
+
const present = [];
|
|
1509
|
+
for (const deck of decks) {
|
|
1510
|
+
for (const other of decks) if (deck.alias !== other.alias && deck.alias === basename(other.dir)) problems.push(`alias collision: ${deck.alias} (${deck.dir}) matches ${other.alias} -> ${other.dir}`);
|
|
1511
|
+
if (!existsSync(join(deck.dir, "deck.config.ts"))) {
|
|
1512
|
+
problems.push(`missing: ${deck.alias} -> ${deck.dir} (${join(deck.dir, "deck.config.ts")})`);
|
|
1513
|
+
continue;
|
|
1514
|
+
}
|
|
1515
|
+
try {
|
|
1516
|
+
const loaded = await loadDeck(deck.dir, deck.alias);
|
|
1517
|
+
present.push(deck);
|
|
1518
|
+
await scanSlidesWithCounts(loaded, /* @__PURE__ */ new Map());
|
|
1519
|
+
} catch (cause) {
|
|
1520
|
+
if (!(cause instanceof DeckError)) throw cause;
|
|
1521
|
+
if (cause.message.startsWith("no slides/*.mdx files in ") || cause.message.startsWith("every slide in ")) problems.push(`no slides: ${deck.alias}`);
|
|
1522
|
+
else problems.push(...cause.message.split("\n").map((line) => `${deck.alias}: ${line}`));
|
|
1523
|
+
}
|
|
1524
|
+
const files = (await glob("slides/*.mdx", { cwd: deck.dir })).sort();
|
|
1525
|
+
const prefixes = files.map((file) => basename(file).match(/^(\d{2})-/)?.[1]);
|
|
1526
|
+
for (const [index, file] of files.entries()) {
|
|
1527
|
+
const prefix = prefixes[index];
|
|
1528
|
+
if (!/^\d{2}-[a-z0-9]+(?:-[a-z0-9]+)*\.mdx$/.test(basename(file)) || prefix !== void 0 && prefixes.filter((value) => value === prefix).length > 1) problems.push(`${deck.alias}: slide name: ${join(deck.dir, file)}`);
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
const { errors } = await lintDecks(present, { errorsOnly: true });
|
|
1532
|
+
if (errors) problems.push(`${errors} error-level prose hit(s); run \`decks lint\` for all hits.`);
|
|
1533
|
+
for (const problem of problems) console.error(problem);
|
|
1534
|
+
if (problems.length) process.exitCode = 1;
|
|
1535
|
+
else console.log("All decks check out.");
|
|
1536
|
+
}
|
|
1537
|
+
});
|
|
1538
|
+
// ../node/src/cli/commands/export.ts
|
|
1539
|
+
const exportDeck = defineCommand({
|
|
1540
|
+
meta: {
|
|
1541
|
+
name: "decks export",
|
|
1542
|
+
description: "Export a deck to PDF through the print view"
|
|
1543
|
+
},
|
|
1544
|
+
args: {
|
|
1545
|
+
deck: {
|
|
1546
|
+
type: "positional",
|
|
1547
|
+
required: true,
|
|
1548
|
+
description: "Deck alias or directory"
|
|
1549
|
+
},
|
|
1550
|
+
out: {
|
|
1551
|
+
type: "string",
|
|
1552
|
+
description: "PDF path"
|
|
1553
|
+
},
|
|
1554
|
+
final: {
|
|
1555
|
+
type: "boolean",
|
|
1556
|
+
default: false,
|
|
1557
|
+
description: "One page per slide at its final click"
|
|
1558
|
+
}
|
|
1559
|
+
},
|
|
1560
|
+
setup({ rawArgs }) {
|
|
1561
|
+
try {
|
|
1562
|
+
const { positionals } = parseArgs({
|
|
1563
|
+
args: rawArgs,
|
|
1564
|
+
options: {
|
|
1565
|
+
out: { type: "string" },
|
|
1566
|
+
final: { type: "boolean" }
|
|
1567
|
+
},
|
|
1568
|
+
allowPositionals: true,
|
|
1569
|
+
allowNegative: true
|
|
1570
|
+
});
|
|
1571
|
+
if (positionals.length > 1) throw new DeckError(`Unexpected argument "${positionals[1]}". Pass one deck alias or directory.`);
|
|
1572
|
+
} catch (cause) {
|
|
1573
|
+
if (cause instanceof DeckError) throw cause;
|
|
1574
|
+
throw new DeckError(cause instanceof Error ? cause.message : String(cause), void 0, void 0, { cause });
|
|
1575
|
+
}
|
|
1576
|
+
},
|
|
1577
|
+
async run({ args }) {
|
|
1578
|
+
const { deck, defaults } = await resolveDeck(args.deck);
|
|
1579
|
+
const out = resolve(args.out ?? join(dirname(defaults.outDir.replaceAll("{name}", deck.name)), `${deck.name}.pdf`));
|
|
1580
|
+
const browser = await launchBrowser();
|
|
1581
|
+
let outDir;
|
|
1582
|
+
try {
|
|
1583
|
+
outDir = await mkdtemp(join(tmpdir(), "decks-export-"));
|
|
1584
|
+
await build(deck, {
|
|
1585
|
+
outDir,
|
|
1586
|
+
base: "./",
|
|
1587
|
+
ogImage: false
|
|
1588
|
+
});
|
|
1589
|
+
const capture = await openBuiltDeck(browser, outDir, "./", `${args.final ? "?print=final" : ""}#/print`);
|
|
1590
|
+
try {
|
|
1591
|
+
await mkdir(dirname(out), { recursive: true });
|
|
1592
|
+
await capture.page.pdf({
|
|
1593
|
+
path: out,
|
|
1594
|
+
preferCSSPageSize: true,
|
|
1595
|
+
printBackground: true
|
|
1596
|
+
});
|
|
1597
|
+
console.log(out);
|
|
1598
|
+
} finally {
|
|
1599
|
+
await capture.close();
|
|
1600
|
+
}
|
|
1601
|
+
} finally {
|
|
1602
|
+
await browser.close();
|
|
1603
|
+
if (outDir) await rm(outDir, {
|
|
1604
|
+
recursive: true,
|
|
1605
|
+
force: true
|
|
1606
|
+
});
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
});
|
|
1610
|
+
// ../node/src/cli/commands/hook-edit.ts
|
|
1611
|
+
function replay(call, path) {
|
|
1612
|
+
if (call.toolName === "Write") {
|
|
1613
|
+
const src = call.content ?? "";
|
|
1614
|
+
return {
|
|
1615
|
+
src,
|
|
1616
|
+
ranges: [[0, src.length]],
|
|
1617
|
+
before: void 0
|
|
1618
|
+
};
|
|
1619
|
+
}
|
|
1620
|
+
let src = readFileSync(path, "utf8");
|
|
1621
|
+
const before = src;
|
|
1622
|
+
let ranges = [];
|
|
1623
|
+
let cursor = 0;
|
|
1624
|
+
for (const edit of call.edits) {
|
|
1625
|
+
const from = edit.old_string;
|
|
1626
|
+
const to = edit.new_string;
|
|
1627
|
+
if (call.source && !from) {
|
|
1628
|
+
const text = `${src && !src.endsWith("\n") ? "\n" : ""}${to}\n`;
|
|
1629
|
+
ranges.push([src.length, src.length + text.length]);
|
|
1630
|
+
src += text;
|
|
1631
|
+
cursor = src.length;
|
|
1632
|
+
continue;
|
|
1633
|
+
}
|
|
1634
|
+
if (edit.after) {
|
|
1635
|
+
const anchor = src.indexOf(edit.after, cursor);
|
|
1636
|
+
if (anchor < 0) throw new Error(`${path}: cannot find apply_patch anchor ${JSON.stringify(edit.after)}.`);
|
|
1637
|
+
cursor = anchor + edit.after.length;
|
|
1638
|
+
}
|
|
1639
|
+
const first = edit.end ? src.lastIndexOf(from) : src.indexOf(from, call.source ? cursor : 0);
|
|
1640
|
+
if (edit.end && ![
|
|
1641
|
+
"",
|
|
1642
|
+
"\n",
|
|
1643
|
+
"\r\n"
|
|
1644
|
+
].includes(src.slice(first + from.length))) throw new Error(`${path}: cannot replay apply_patch End of File context.`);
|
|
1645
|
+
if (!from || first < 0) throw new Error(`${path}: cannot replay edit: old_string ${JSON.stringify(from)} is not in the file.`);
|
|
1646
|
+
const positions = [];
|
|
1647
|
+
for (let at = first; at >= 0; at = src.indexOf(from, at + from.length)) {
|
|
1648
|
+
positions.push(at);
|
|
1649
|
+
if (!edit.replace_all) break;
|
|
1650
|
+
}
|
|
1651
|
+
const delta = to.length - from.length;
|
|
1652
|
+
const carry = (p) => {
|
|
1653
|
+
let shift = 0;
|
|
1654
|
+
for (const at of positions) if (p >= at + from.length) shift += delta;
|
|
1655
|
+
else if (p > at) return at + shift + Math.min(p - at, to.length);
|
|
1656
|
+
else break;
|
|
1657
|
+
return p + shift;
|
|
1658
|
+
};
|
|
1659
|
+
ranges = ranges.map((range) => range.map(carry));
|
|
1660
|
+
let next = "";
|
|
1661
|
+
let last = 0;
|
|
1662
|
+
for (const [index, at] of positions.entries()) {
|
|
1663
|
+
next += src.slice(last, at) + to;
|
|
1664
|
+
last = at + from.length;
|
|
1665
|
+
const start = at + index * delta;
|
|
1666
|
+
ranges.push([start, start + to.length]);
|
|
1667
|
+
}
|
|
1668
|
+
src = next + src.slice(last);
|
|
1669
|
+
cursor = (positions.at(-1) ?? 0) + (positions.length - 1) * delta + to.length;
|
|
1670
|
+
}
|
|
1671
|
+
const touched = /* @__PURE__ */ new Set();
|
|
1672
|
+
for (const range of ranges) {
|
|
1673
|
+
let start = range[0] ?? 0;
|
|
1674
|
+
const end = range[1] ?? start;
|
|
1675
|
+
if (start === end) continue;
|
|
1676
|
+
if (src[start] === "\n") start++;
|
|
1677
|
+
const first = src.slice(0, start).split("\n").length;
|
|
1678
|
+
const last = src.slice(0, Math.max(start, end - 1)).split("\n").length;
|
|
1679
|
+
for (let line = first; line <= last; line++) touched.add(line);
|
|
1680
|
+
}
|
|
1681
|
+
return {
|
|
1682
|
+
src,
|
|
1683
|
+
ranges,
|
|
1684
|
+
before,
|
|
1685
|
+
touched
|
|
1686
|
+
};
|
|
1687
|
+
}
|
|
1688
|
+
function patchWrites(patch) {
|
|
1689
|
+
if (!patch.startsWith("*** Begin Patch") || !patch.trimEnd().endsWith("*** End Patch")) throw new Error("apply_patch command must contain *** Begin Patch and *** End Patch.");
|
|
1690
|
+
const calls = [];
|
|
1691
|
+
let call;
|
|
1692
|
+
let hunk;
|
|
1693
|
+
let added = [];
|
|
1694
|
+
const endHunk = () => {
|
|
1695
|
+
if (call && hunk && (hunk.old.length || hunk.next.length)) call.edits.push({
|
|
1696
|
+
old_string: hunk.old.join("\n"),
|
|
1697
|
+
new_string: hunk.next.join("\n"),
|
|
1698
|
+
after: hunk.after,
|
|
1699
|
+
end: hunk.end
|
|
1700
|
+
});
|
|
1701
|
+
hunk = void 0;
|
|
1702
|
+
};
|
|
1703
|
+
const endFile = () => {
|
|
1704
|
+
endHunk();
|
|
1705
|
+
if (call?.toolName === "Write") call.content = `${added.join("\n")}\n`;
|
|
1706
|
+
if (call) calls.push(call);
|
|
1707
|
+
call = void 0;
|
|
1708
|
+
added = [];
|
|
1709
|
+
};
|
|
1710
|
+
for (const line of patch.split("\n")) {
|
|
1711
|
+
const header = /^\*\*\* (Add File|Update File|Delete File|Move to): (.+)$/.exec(line);
|
|
1712
|
+
if (header) {
|
|
1713
|
+
const kind = header[1];
|
|
1714
|
+
const file = header[2]?.trim();
|
|
1715
|
+
if (!file) throw new Error("apply_patch file path is empty.");
|
|
1716
|
+
if (kind === "Move to") {
|
|
1717
|
+
if (call) call.file = file;
|
|
1718
|
+
continue;
|
|
1719
|
+
}
|
|
1720
|
+
endFile();
|
|
1721
|
+
if (kind === "Add File") call = {
|
|
1722
|
+
toolName: "Write",
|
|
1723
|
+
file,
|
|
1724
|
+
edits: []
|
|
1725
|
+
};
|
|
1726
|
+
if (kind === "Update File") call = {
|
|
1727
|
+
toolName: "MultiEdit",
|
|
1728
|
+
file,
|
|
1729
|
+
source: file,
|
|
1730
|
+
edits: []
|
|
1731
|
+
};
|
|
1732
|
+
continue;
|
|
1733
|
+
}
|
|
1734
|
+
if (/^\*\*\* (Begin|End) Patch\b/.test(line)) {
|
|
1735
|
+
endFile();
|
|
1736
|
+
continue;
|
|
1737
|
+
}
|
|
1738
|
+
if (!call) continue;
|
|
1739
|
+
if (call.toolName === "Write") {
|
|
1740
|
+
if (line.startsWith("+")) added.push(line.slice(1));
|
|
1741
|
+
continue;
|
|
1742
|
+
}
|
|
1743
|
+
if (line.startsWith("@@")) {
|
|
1744
|
+
endHunk();
|
|
1745
|
+
hunk = {
|
|
1746
|
+
old: [],
|
|
1747
|
+
next: [],
|
|
1748
|
+
after: line.slice(2).trim() || void 0
|
|
1749
|
+
};
|
|
1750
|
+
continue;
|
|
1751
|
+
}
|
|
1752
|
+
if (line === "*** End of File") {
|
|
1753
|
+
if (hunk) hunk.end = true;
|
|
1754
|
+
continue;
|
|
1755
|
+
}
|
|
1756
|
+
hunk ??= {
|
|
1757
|
+
old: [],
|
|
1758
|
+
next: []
|
|
1759
|
+
};
|
|
1760
|
+
if (line.startsWith("-")) hunk.old.push(line.slice(1));
|
|
1761
|
+
else if (line.startsWith("+")) hunk.next.push(line.slice(1));
|
|
1762
|
+
else {
|
|
1763
|
+
const context = line.startsWith(" ") ? line.slice(1) : line;
|
|
1764
|
+
hunk.old.push(context);
|
|
1765
|
+
hunk.next.push(context);
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
1768
|
+
endFile();
|
|
1769
|
+
return calls;
|
|
1770
|
+
}
|
|
1771
|
+
// ../node/src/cli/commands/hook.ts
|
|
1772
|
+
const payloadSchema = z.object({
|
|
1773
|
+
tool_name: z.string().optional(),
|
|
1774
|
+
tool_input: z.unknown().optional(),
|
|
1775
|
+
prompt: z.string().optional(),
|
|
1776
|
+
cwd: z.string().optional()
|
|
1777
|
+
});
|
|
1778
|
+
const editSchema = z.object({
|
|
1779
|
+
old_string: z.string(),
|
|
1780
|
+
new_string: z.string(),
|
|
1781
|
+
replace_all: z.boolean().optional()
|
|
1782
|
+
});
|
|
1783
|
+
function inScope(file, project) {
|
|
1784
|
+
const absolute = resolve(project, file);
|
|
1785
|
+
const rel = relative(project, absolute).split(sep).join("/");
|
|
1786
|
+
if (rel.startsWith("../") || isAbsolute(rel) || rel.split("/").includes("node_modules")) return false;
|
|
1787
|
+
for (let dir = dirname(absolute);; dir = dirname(dir)) {
|
|
1788
|
+
if (existsSync(resolve(dir, "deck.config.ts"))) return /^(slides\/.+\.mdx|(components|layers)\/.+\.tsx?)$/.test(relative(dir, absolute).split(sep).join("/")) ? dir : void 0;
|
|
1789
|
+
if (dirname(dir) === dir) return void 0;
|
|
1790
|
+
}
|
|
1791
|
+
}
|
|
1792
|
+
function emit(hookSpecificOutput) {
|
|
1793
|
+
writeSync(1, `${JSON.stringify({ hookSpecificOutput })}\n`);
|
|
1794
|
+
}
|
|
1795
|
+
async function lintPayload(payload, project) {
|
|
1796
|
+
const tool = payload.tool_name;
|
|
1797
|
+
let calls;
|
|
1798
|
+
if (tool === "apply_patch") calls = patchWrites(z.object({ command: z.string() }).parse(payload.tool_input).command);
|
|
1799
|
+
else if (tool === "Write") {
|
|
1800
|
+
const input = z.object({
|
|
1801
|
+
file_path: z.string(),
|
|
1802
|
+
content: z.string()
|
|
1803
|
+
}).parse(payload.tool_input);
|
|
1804
|
+
calls = [{
|
|
1805
|
+
toolName: tool,
|
|
1806
|
+
file: input.file_path,
|
|
1807
|
+
content: input.content,
|
|
1808
|
+
edits: []
|
|
1809
|
+
}];
|
|
1810
|
+
} else if (tool === "Edit" || tool === "MultiEdit") {
|
|
1811
|
+
const input = z.object({ file_path: z.string() }).parse(payload.tool_input);
|
|
1812
|
+
const edits = tool === "Edit" ? [editSchema.parse(payload.tool_input)] : z.object({ edits: z.array(editSchema) }).parse(payload.tool_input).edits;
|
|
1813
|
+
calls = [{
|
|
1814
|
+
toolName: tool,
|
|
1815
|
+
file: input.file_path,
|
|
1816
|
+
edits
|
|
1817
|
+
}];
|
|
1818
|
+
} else return;
|
|
1819
|
+
let patterns;
|
|
1820
|
+
const found = [];
|
|
1821
|
+
for (const call of calls) {
|
|
1822
|
+
const deckDir = inScope(call.file, project);
|
|
1823
|
+
if (!deckDir || call.toolName === "Write" && !call.content) continue;
|
|
1824
|
+
const deck = await loadDeck(deckDir);
|
|
1825
|
+
const { scanSource, formatHit } = await import("./prose-scan-BrWZ7gxZ.js");
|
|
1826
|
+
patterns ??= loadPatterns();
|
|
1827
|
+
const absolute = resolve(project, call.file);
|
|
1828
|
+
const after = replay(call, resolve(project, call.source ?? call.file));
|
|
1829
|
+
const path = relative(project, absolute).split(sep).join("/");
|
|
1830
|
+
const scan = (src) => scanSource(absolute, src, patterns ?? [], {
|
|
1831
|
+
errorsOnly: true,
|
|
1832
|
+
remarkPlugins: deck.config.mdx?.remarkPlugins
|
|
1833
|
+
});
|
|
1834
|
+
const afterHits = scan(after.src);
|
|
1835
|
+
let oldHits = [];
|
|
1836
|
+
try {
|
|
1837
|
+
oldHits = after.before === void 0 ? [] : scan(after.before);
|
|
1838
|
+
} catch (cause) {
|
|
1839
|
+
if (!(cause instanceof DeckError)) throw cause;
|
|
1840
|
+
}
|
|
1841
|
+
const seen = /* @__PURE__ */ new Map();
|
|
1842
|
+
const key = (hit) => `${hit.id}\0${hit.text}`;
|
|
1843
|
+
for (const hit of oldHits) seen.set(key(hit), (seen.get(key(hit)) ?? 0) + 1);
|
|
1844
|
+
const hits = afterHits.filter((hit) => {
|
|
1845
|
+
if (after.before === void 0 || after.touched?.has(hit.line)) return true;
|
|
1846
|
+
const count = seen.get(key(hit)) ?? 0;
|
|
1847
|
+
if (count) seen.set(key(hit), count - 1);
|
|
1848
|
+
return !count;
|
|
1849
|
+
});
|
|
1850
|
+
const label = call.toolName === "Write" && tool !== "apply_patch" ? "stdin" : path;
|
|
1851
|
+
if (hits.length) found.push(`${hits.map((hit) => formatHit({
|
|
1852
|
+
...hit,
|
|
1853
|
+
file: label
|
|
1854
|
+
})).join("\n")}\n\n${call.toolName === "Write" ? `Line numbers refer to the NEW text being written${tool === "apply_patch" ? ` to ${path}` : ""}.` : `Line numbers refer to ${path} as it will read after this edit.`}`);
|
|
1855
|
+
}
|
|
1856
|
+
if (found.length) emit({
|
|
1857
|
+
hookEventName: "PreToolUse",
|
|
1858
|
+
permissionDecision: "deny",
|
|
1859
|
+
permissionDecisionReason: `BLOCKED: AI-rhetoric patterns found in prose.\n\n${found.join("\n\n")} Rewrite the flagged\nphrasing (don't synonym-swap). A rewrite that keeps the same sentence\nskeleton with new words still reads as AI; change the structure, or\njust state the fact plainly. If a hit is a legitimate direct quote,\nappend the lint-allow marker to that exact line:\n mdx/tsx: {/* lint-allow: pattern-id */}\n ts: // lint-allow: pattern-id`
|
|
1860
|
+
});
|
|
1861
|
+
}
|
|
1862
|
+
const intent = /\b(write|writ|draft|revis|edit|polish|build|author|make).{0,60}(\bdeck\b|\bslides?\b|\btalk\b|\bpresentation\b|\bmdx\b)|(\bdeck\b|\bslides?\b|\btalk\b|\bpresentation\b|\bmdx\b).{0,60}\b(write|writ|draft|revis|edit|polish|build|author|make)/i;
|
|
1863
|
+
const revision = /\b(rewrite|reword|rephras|revis|trim|tighten|shorten|cut|polish|slop|headline|bullet|eyebrow|wording|phrasing|too (long|wordy|dense))/i;
|
|
1864
|
+
function promptPayload(payload, project) {
|
|
1865
|
+
if (!payload.prompt) return;
|
|
1866
|
+
let fires = intent.test(payload.prompt);
|
|
1867
|
+
if (!fires && revision.test(payload.prompt)) {
|
|
1868
|
+
const status = spawnSync("git", [
|
|
1869
|
+
"status",
|
|
1870
|
+
"--porcelain",
|
|
1871
|
+
"--untracked-files=all",
|
|
1872
|
+
"-z"
|
|
1873
|
+
], {
|
|
1874
|
+
cwd: project,
|
|
1875
|
+
encoding: "utf8"
|
|
1876
|
+
});
|
|
1877
|
+
if (status.error) throw new Error(`decks hook prompt cannot run git: ${status.error.message}`, { cause: status.error });
|
|
1878
|
+
const top = spawnSync("git", ["rev-parse", "--show-toplevel"], {
|
|
1879
|
+
cwd: project,
|
|
1880
|
+
encoding: "utf8"
|
|
1881
|
+
});
|
|
1882
|
+
if (top.error) throw top.error;
|
|
1883
|
+
if (status.status === 0 && top.status === 0) {
|
|
1884
|
+
const entries = status.stdout.split("\0");
|
|
1885
|
+
for (let index = 0; index < entries.length; index++) {
|
|
1886
|
+
const entry = entries[index];
|
|
1887
|
+
if (!entry) continue;
|
|
1888
|
+
const source = /[RC]/.test(entry.slice(0, 2)) ? entries[++index] : void 0;
|
|
1889
|
+
if (inScope(entry.slice(3), top.stdout.trim()) || source && inScope(source, top.stdout.trim())) {
|
|
1890
|
+
fires = true;
|
|
1891
|
+
break;
|
|
1892
|
+
}
|
|
1893
|
+
}
|
|
1894
|
+
}
|
|
1895
|
+
}
|
|
1896
|
+
if (fires) emit({
|
|
1897
|
+
hookEventName: "UserPromptSubmit",
|
|
1898
|
+
additionalContext: readFileSync(new URL(`${import.meta.url.endsWith(".ts") ? "../../../lint/" : "./lint/"}deck-writing-reminder.md`, import.meta.url), "utf8").trimEnd()
|
|
1899
|
+
});
|
|
1900
|
+
}
|
|
1901
|
+
const hook = defineCommand({
|
|
1902
|
+
meta: {
|
|
1903
|
+
name: "decks hook",
|
|
1904
|
+
description: "Agent hooks: lint (PreToolUse) or prompt (UserPromptSubmit)"
|
|
1905
|
+
},
|
|
1906
|
+
args: { kind: {
|
|
1907
|
+
type: "positional",
|
|
1908
|
+
required: true,
|
|
1909
|
+
description: "lint or prompt"
|
|
1910
|
+
} },
|
|
1911
|
+
async run({ args, rawArgs }) {
|
|
1912
|
+
try {
|
|
1913
|
+
const parsed = parseArgs({
|
|
1914
|
+
args: rawArgs,
|
|
1915
|
+
options: {},
|
|
1916
|
+
allowPositionals: true
|
|
1917
|
+
});
|
|
1918
|
+
if (parsed.positionals.length > 1) throw new Error(`unexpected argument ${JSON.stringify(parsed.positionals[1])}. Pass lint or prompt.`);
|
|
1919
|
+
} catch (cause) {
|
|
1920
|
+
throw new DeckError(cause instanceof Error ? cause.message : String(cause));
|
|
1921
|
+
}
|
|
1922
|
+
if (args.kind !== "lint" && args.kind !== "prompt") throw new DeckError("Usage: decks hook {lint|prompt} (reads the Claude Code hook payload on stdin)");
|
|
1923
|
+
let source = "";
|
|
1924
|
+
process.stdin.setEncoding("utf8");
|
|
1925
|
+
for await (const chunk of process.stdin) source += chunk;
|
|
1926
|
+
let payload;
|
|
1927
|
+
try {
|
|
1928
|
+
payload = payloadSchema.parse(JSON.parse(source));
|
|
1929
|
+
} catch (cause) {
|
|
1930
|
+
if (args.kind === "prompt") return;
|
|
1931
|
+
writeSync(2, `BLOCKED: decks hook lint could not parse the hook payload on stdin (${cause instanceof Error ? cause.message : String(cause)}), so the write is refused.\n`);
|
|
1932
|
+
process.exitCode = 2;
|
|
1933
|
+
return;
|
|
1934
|
+
}
|
|
1935
|
+
const project = resolve(process.env.CLAUDE_PROJECT_DIR || payload.cwd || process.cwd());
|
|
1936
|
+
if (args.kind === "prompt") return promptPayload(payload, project);
|
|
1937
|
+
try {
|
|
1938
|
+
await lintPayload(payload, project);
|
|
1939
|
+
} catch (cause) {
|
|
1940
|
+
writeSync(2, `BLOCKED: decks hook lint failed (${cause instanceof Error ? cause.message : String(cause)}), so the write is refused. Restore the scanner and lint/ai-rhetoric-patterns.tsv, or check the edit and file syntax.\n`);
|
|
1941
|
+
process.exitCode = 2;
|
|
1942
|
+
}
|
|
1943
|
+
}
|
|
1944
|
+
});
|
|
1945
|
+
// ../node/src/cli/commands/init.ts
|
|
1946
|
+
const start = "<!-- decks:start -->";
|
|
1947
|
+
const end = "<!-- decks:end -->";
|
|
1948
|
+
const block = `${start}\n## Decks\n\nRead \`node_modules/@steamfield/decks/docs/\` for the installed version first.\nUse these skills in \`.agents/skills/\` when working on a deck:\n\n${[
|
|
1949
|
+
"building-a-deck",
|
|
1950
|
+
"writing-slides",
|
|
1951
|
+
"deck-design",
|
|
1952
|
+
"deck-motion",
|
|
1953
|
+
"visualization",
|
|
1954
|
+
"deck-data",
|
|
1955
|
+
"working-with-decks"
|
|
1956
|
+
].map((name) => `- \`${name}\``).join("\n")}\n${end}`;
|
|
1957
|
+
function hash(content) {
|
|
1958
|
+
const bytes = typeof content === "string" ? Buffer.from(content) : content;
|
|
1959
|
+
return createHash("sha256").update(isUtf8(bytes) ? bytes.toString("utf8").replaceAll("\r\n", "\n") : bytes).digest("hex");
|
|
1960
|
+
}
|
|
1961
|
+
async function assertTarget(target) {
|
|
1962
|
+
let path = process.cwd();
|
|
1963
|
+
for (const part of target.split("/")) {
|
|
1964
|
+
path = join(path, part);
|
|
1965
|
+
try {
|
|
1966
|
+
if ((await lstat(path)).isSymbolicLink()) throw new DeckError(`Cannot write ${target}: symlink at ${path}. Use a regular destination.`);
|
|
1967
|
+
} catch (cause) {
|
|
1968
|
+
if (cause instanceof Error && "code" in cause && cause.code === "ENOENT") return;
|
|
1969
|
+
throw cause;
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
}
|
|
1973
|
+
async function readObject(file) {
|
|
1974
|
+
if (!existsSync(file)) return {};
|
|
1975
|
+
try {
|
|
1976
|
+
return z.record(z.string(), z.unknown()).parse(JSON.parse(await readFile(file, "utf8")));
|
|
1977
|
+
} catch (cause) {
|
|
1978
|
+
throw new DeckError(`Cannot read ${file}: ${cause instanceof Error ? cause.message : String(cause)}`, void 0, void 0, { cause });
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
const init = defineCommand({
|
|
1982
|
+
meta: {
|
|
1983
|
+
name: "decks init",
|
|
1984
|
+
description: "Set up agent guidance for Decks in this project"
|
|
1985
|
+
},
|
|
1986
|
+
args: { force: {
|
|
1987
|
+
type: "boolean",
|
|
1988
|
+
default: false,
|
|
1989
|
+
description: "Replace edits to guidance init installed"
|
|
1990
|
+
} },
|
|
1991
|
+
async run({ args, rawArgs }) {
|
|
1992
|
+
try {
|
|
1993
|
+
if (parseArgs({
|
|
1994
|
+
args: rawArgs,
|
|
1995
|
+
options: { force: { type: "boolean" } }
|
|
1996
|
+
}).positionals.length) throw new DeckError("decks init takes only --force.");
|
|
1997
|
+
const source = import.meta.url.endsWith(".ts");
|
|
1998
|
+
const skills = new URL(source ? "../../../../../plugins/decks/skills/" : "./plugin/skills/", import.meta.url);
|
|
1999
|
+
const metadata = new URL(source ? "../../../../decks/package.json" : "../package.json", import.meta.url);
|
|
2000
|
+
const { version } = z.object({ version: z.string() }).parse(JSON.parse(await readFile(metadata, "utf8")));
|
|
2001
|
+
const settingsPath = ".claude/settings.json";
|
|
2002
|
+
const manifestPath = ".agents/skills/.decks-init.json";
|
|
2003
|
+
const settings = await readObject(settingsPath);
|
|
2004
|
+
const marketplace = z.record(z.string(), z.unknown()).parse(settings.extraKnownMarketplaces ?? {});
|
|
2005
|
+
const enabled = z.record(z.string(), z.unknown()).parse(settings.enabledPlugins ?? {});
|
|
2006
|
+
const previousRef = z.object({ source: z.object({ ref: z.string() }) }).safeParse(marketplace.steamfield).data?.source.ref;
|
|
2007
|
+
const manifest = await readObject(manifestPath);
|
|
2008
|
+
const owned = Object.fromEntries(Object.entries(z.record(z.string(), z.string()).parse(manifest.files ?? {})).map(([key, value]) => [key.replaceAll("\\", "/"), value]));
|
|
2009
|
+
const agents = existsSync("AGENTS.md") ? await readFile("AGENTS.md", "utf8") : "";
|
|
2010
|
+
const from = agents.indexOf(start);
|
|
2011
|
+
const to = agents.indexOf(end);
|
|
2012
|
+
if (from < 0 !== to < 0 || from >= 0 && (to < from || agents.indexOf(start, from + 20) >= 0 || agents.indexOf(end, to + 18) >= 0)) throw new DeckError("AGENTS.md has incomplete or repeated Decks markers. Repair them before running init.");
|
|
2013
|
+
const currentBlock = from < 0 ? void 0 : agents.slice(from, to + 18);
|
|
2014
|
+
const files = await glob("**/*", {
|
|
2015
|
+
cwd: skills,
|
|
2016
|
+
dot: true,
|
|
2017
|
+
ignore: ["**/.gitkeep"]
|
|
2018
|
+
});
|
|
2019
|
+
const updates = await Promise.all(files.sort().map(async (file) => ({
|
|
2020
|
+
target: `.agents/skills/${file}`,
|
|
2021
|
+
content: await readFile(new URL(file, skills))
|
|
2022
|
+
})));
|
|
2023
|
+
const current = new Set(updates.map(({ target }) => target));
|
|
2024
|
+
const obsolete = Object.keys(owned).filter((target) => target.startsWith(".agents/skills/") && !target.split("/").includes("..") && !current.has(target));
|
|
2025
|
+
const currentSkills = new Set([...current].map((target) => target.split("/").slice(0, 3).join("/")));
|
|
2026
|
+
const retiredSkills = new Set(obsolete.map((target) => target.split("/").slice(0, 3).join("/")).filter((skill) => !currentSkills.has(skill)));
|
|
2027
|
+
for (const target of [
|
|
2028
|
+
settingsPath,
|
|
2029
|
+
manifestPath,
|
|
2030
|
+
"AGENTS.md",
|
|
2031
|
+
...updates.map(({ target }) => target),
|
|
2032
|
+
...obsolete
|
|
2033
|
+
]) await assertTarget(target);
|
|
2034
|
+
for (const skill of retiredSkills) {
|
|
2035
|
+
if (existsSync(skill)) {
|
|
2036
|
+
let keep = false;
|
|
2037
|
+
for (const file of await glob("**/*", {
|
|
2038
|
+
cwd: skill,
|
|
2039
|
+
dot: true,
|
|
2040
|
+
onlyFiles: false,
|
|
2041
|
+
followSymbolicLinks: false
|
|
2042
|
+
})) {
|
|
2043
|
+
const target = `${skill}/${file}`;
|
|
2044
|
+
if ((await lstat(target)).isDirectory()) continue;
|
|
2045
|
+
if (!owned[target] || hash(await readFile(target)) !== owned[target]) {
|
|
2046
|
+
keep = true;
|
|
2047
|
+
break;
|
|
2048
|
+
}
|
|
2049
|
+
}
|
|
2050
|
+
if (keep) {
|
|
2051
|
+
console.log(`Kept ${skill}: contains edited or unowned files`);
|
|
2052
|
+
continue;
|
|
2053
|
+
}
|
|
2054
|
+
await rm(skill, { recursive: true });
|
|
2055
|
+
console.log(`Removed ${skill}`);
|
|
2056
|
+
}
|
|
2057
|
+
for (const target of obsolete) if (target.startsWith(`${skill}/`)) delete owned[target];
|
|
2058
|
+
}
|
|
2059
|
+
for (const target of obsolete) {
|
|
2060
|
+
if ([...retiredSkills].some((skill) => target.startsWith(`${skill}/`))) continue;
|
|
2061
|
+
if (existsSync(target)) {
|
|
2062
|
+
if (hash(await readFile(target)) !== owned[target]) {
|
|
2063
|
+
console.log(`Kept ${target}: edited since last init`);
|
|
2064
|
+
continue;
|
|
2065
|
+
}
|
|
2066
|
+
await rm(target);
|
|
2067
|
+
console.log(`Removed ${target}`);
|
|
2068
|
+
}
|
|
2069
|
+
delete owned[target];
|
|
2070
|
+
}
|
|
2071
|
+
for (const { target, content } of updates) {
|
|
2072
|
+
const current = existsSync(target) ? await readFile(target) : void 0;
|
|
2073
|
+
if (current !== void 0 && !current.equals(content) && (!owned[target] || !args.force && hash(current) !== owned[target])) {
|
|
2074
|
+
console.log(`Kept ${target}: ${owned[target] ? "edited since last init" : "not installed by init"}`);
|
|
2075
|
+
continue;
|
|
2076
|
+
}
|
|
2077
|
+
await mkdir(dirname(target), { recursive: true });
|
|
2078
|
+
await writeFile(target, content);
|
|
2079
|
+
owned[target] = hash(content);
|
|
2080
|
+
console.log(`Wrote ${target}`);
|
|
2081
|
+
}
|
|
2082
|
+
if (currentBlock !== void 0 && currentBlock !== block && (!owned["AGENTS.md"] || !args.force && hash(currentBlock) !== owned["AGENTS.md"])) console.log(`Kept AGENTS.md Decks section: ${owned["AGENTS.md"] ? "edited since last init" : "not installed by init"}`);
|
|
2083
|
+
else {
|
|
2084
|
+
const text = from < 0 ? `${agents}${agents && !agents.endsWith("\n") ? "\n" : ""}${agents ? "\n" : ""}${block}\n` : `${agents.slice(0, from)}${block}${agents.slice(to + 18)}`;
|
|
2085
|
+
await writeFile("AGENTS.md", text);
|
|
2086
|
+
owned["AGENTS.md"] = hash(block);
|
|
2087
|
+
console.log("Wrote AGENTS.md Decks section");
|
|
2088
|
+
}
|
|
2089
|
+
settings.extraKnownMarketplaces = {
|
|
2090
|
+
...marketplace,
|
|
2091
|
+
steamfield: { source: {
|
|
2092
|
+
source: "github",
|
|
2093
|
+
repo: "steamfield/decks",
|
|
2094
|
+
ref: `v${version}`
|
|
2095
|
+
} }
|
|
2096
|
+
};
|
|
2097
|
+
settings.enabledPlugins = {
|
|
2098
|
+
...enabled,
|
|
2099
|
+
"decks@steamfield": true
|
|
2100
|
+
};
|
|
2101
|
+
await mkdir(".claude", { recursive: true });
|
|
2102
|
+
await writeFile(settingsPath, `${JSON.stringify(settings, null, 2)}\n`);
|
|
2103
|
+
console.log(`Wrote ${settingsPath}`);
|
|
2104
|
+
await mkdir(dirname(manifestPath), { recursive: true });
|
|
2105
|
+
await writeFile(manifestPath, `${JSON.stringify({ files: owned }, null, 2)}\n`);
|
|
2106
|
+
console.log(`Wrote ${manifestPath}`);
|
|
2107
|
+
if (previousRef !== void 0 && previousRef !== `v${version}`) console.log("Update the plugin: claude plugin update decks@steamfield --scope project (then restart Claude Code).");
|
|
2108
|
+
console.log("Each collaborator runs once: claude plugin install decks@steamfield --scope project");
|
|
2109
|
+
} catch (cause) {
|
|
2110
|
+
if (cause instanceof DeckError) throw cause;
|
|
2111
|
+
throw new DeckError(`Cannot initialize Decks: ${cause instanceof Error ? cause.message : String(cause)}`, void 0, void 0, { cause });
|
|
2112
|
+
}
|
|
2113
|
+
}
|
|
2114
|
+
});
|
|
2115
|
+
// ../node/src/cli/commands/new.ts
|
|
2116
|
+
const newDeck = defineCommand({
|
|
2117
|
+
meta: {
|
|
2118
|
+
name: "decks new",
|
|
2119
|
+
description: "Scaffold a deck and register it in decks.json"
|
|
2120
|
+
},
|
|
2121
|
+
args: {
|
|
2122
|
+
alias: {
|
|
2123
|
+
type: "positional",
|
|
2124
|
+
required: true,
|
|
2125
|
+
description: "Alias to register"
|
|
2126
|
+
},
|
|
2127
|
+
dir: {
|
|
2128
|
+
type: "positional",
|
|
2129
|
+
required: false,
|
|
2130
|
+
description: "Directory name under decksDir (default: the alias)"
|
|
2131
|
+
},
|
|
2132
|
+
story: {
|
|
2133
|
+
type: "boolean",
|
|
2134
|
+
default: false,
|
|
2135
|
+
description: "Scaffold a story deck"
|
|
2136
|
+
},
|
|
2137
|
+
author: {
|
|
2138
|
+
type: "string",
|
|
2139
|
+
description: "Author name"
|
|
2140
|
+
},
|
|
2141
|
+
url: {
|
|
2142
|
+
type: "string",
|
|
2143
|
+
description: "Brand URL for the cover"
|
|
2144
|
+
}
|
|
2145
|
+
},
|
|
2146
|
+
async run({ args, rawArgs }) {
|
|
2147
|
+
try {
|
|
2148
|
+
const { positionals } = parseArgs({
|
|
2149
|
+
args: rawArgs,
|
|
2150
|
+
allowPositionals: true,
|
|
2151
|
+
allowNegative: true,
|
|
2152
|
+
options: {
|
|
2153
|
+
story: { type: "boolean" },
|
|
2154
|
+
author: { type: "string" },
|
|
2155
|
+
url: { type: "string" }
|
|
2156
|
+
}
|
|
2157
|
+
});
|
|
2158
|
+
if (positionals.length > 2) throw new DeckError(`Unexpected argument "${positionals[2]}". Pass an alias and optional directory.`);
|
|
2159
|
+
const alias = args.alias;
|
|
2160
|
+
const dir = args.dir ?? alias;
|
|
2161
|
+
if (alias.startsWith("_")) throw new DeckError(`Alias "${alias}" starts with "_", which is reserved. Choose another alias.`);
|
|
2162
|
+
if (!dir || dir === "." || dir === ".." || /[/\\]/.test(dir)) throw new DeckError(`Deck directory "${dir}" must be a bare name without slashes.`);
|
|
2163
|
+
const registry = await readRegistry();
|
|
2164
|
+
if (registry.decks.some((deck) => deck.alias === alias)) throw new DeckError(`Alias "${alias}" is already registered.`);
|
|
2165
|
+
const deckDir = join(registry.defaults.decksDir, dir);
|
|
2166
|
+
if (existsSync(deckDir)) throw new DeckError(`${deckDir} already exists. Choose another directory.`);
|
|
2167
|
+
await access(existsSync(registry.path) ? registry.path : dirname(registry.path), constants.W_OK);
|
|
2168
|
+
const contents = existsSync(registry.path) ? JSON.parse(await readFile(registry.path, "utf8")) : { _config: registry.defaults };
|
|
2169
|
+
const template = new URL(`${import.meta.url.endsWith(".ts") ? "../../../" : "./"}templates/${args.story ? "story" : "conventional"}/`, import.meta.url);
|
|
2170
|
+
const title = dir.replace(/[-_]/g, " ");
|
|
2171
|
+
const variables = {
|
|
2172
|
+
title: title.charAt(0).toUpperCase() + title.slice(1),
|
|
2173
|
+
author: args.author ?? "Your Name",
|
|
2174
|
+
alias
|
|
2175
|
+
};
|
|
2176
|
+
const files = await glob("**/*", {
|
|
2177
|
+
cwd: template,
|
|
2178
|
+
dot: true
|
|
2179
|
+
});
|
|
2180
|
+
for (const file of files.sort()) {
|
|
2181
|
+
let text = await readFile(new URL(file, template), "utf8");
|
|
2182
|
+
text = text.replace(/\{\{(title|author|alias)\}\}/g, (_match, key) => JSON.stringify(variables[key]).slice(1, -1));
|
|
2183
|
+
if (file === "setup.ts" && args.url !== void 0) text = text.replace("installTheme(resolveTheme());", "import theme from \"./theme.json\";\n\ninstallTheme(resolveTheme(theme));");
|
|
2184
|
+
const target = join(deckDir, file);
|
|
2185
|
+
await mkdir(dirname(target), { recursive: true });
|
|
2186
|
+
await writeFile(target, text);
|
|
2187
|
+
console.log(`Wrote ${target}`);
|
|
2188
|
+
}
|
|
2189
|
+
if (args.url !== void 0) {
|
|
2190
|
+
await writeFile(join(deckDir, "theme.json"), `${JSON.stringify({ brand: { url: args.url } }, null, 2)}\n`);
|
|
2191
|
+
console.log(`Wrote ${join(deckDir, "theme.json")}`);
|
|
2192
|
+
}
|
|
2193
|
+
contents[alias] = { dir: deckDir };
|
|
2194
|
+
await writeFile(registry.path, `${JSON.stringify(contents, null, 2)}\n`);
|
|
2195
|
+
const shellAlias = /^[a-zA-Z0-9_-]+$/.test(alias) ? alias : `'${alias.replaceAll("'", "'\\''")}'`;
|
|
2196
|
+
console.log(`Registered "${alias}" in decks.json.\nNext: decks dev ${shellAlias}`);
|
|
2197
|
+
} catch (cause) {
|
|
2198
|
+
if (!(cause instanceof Error) || !("code" in cause) || typeof cause.code !== "string") throw cause;
|
|
2199
|
+
if (cause.code.startsWith("ERR_PARSE_ARGS")) throw new DeckError(cause.message, void 0, void 0, { cause });
|
|
2200
|
+
const reason = {
|
|
2201
|
+
EACCES: "permission denied",
|
|
2202
|
+
EPERM: "permission denied",
|
|
2203
|
+
ENOTDIR: "not a directory",
|
|
2204
|
+
ENOENT: "path does not exist",
|
|
2205
|
+
EROFS: "read-only filesystem",
|
|
2206
|
+
EEXIST: "already exists",
|
|
2207
|
+
ENOSPC: "no space left"
|
|
2208
|
+
}[cause.code];
|
|
2209
|
+
if (!reason) throw cause;
|
|
2210
|
+
const path = "path" in cause && typeof cause.path === "string" ? displayPath(resolve(cause.path)) : args.alias;
|
|
2211
|
+
throw new DeckError(`cannot scaffold ${path}: ${reason}. Check the destination and its permissions.`, void 0, void 0, { cause });
|
|
2212
|
+
}
|
|
2213
|
+
}
|
|
2214
|
+
});
|
|
2215
|
+
// ../node/src/cli/commands/shot.ts
|
|
2216
|
+
const shot = defineCommand({
|
|
2217
|
+
meta: {
|
|
2218
|
+
name: "decks shot",
|
|
2219
|
+
description: "Screenshot one frame of a deck"
|
|
2220
|
+
},
|
|
2221
|
+
args: {
|
|
2222
|
+
deck: {
|
|
2223
|
+
type: "positional",
|
|
2224
|
+
required: true,
|
|
2225
|
+
description: "Deck alias or directory"
|
|
2226
|
+
},
|
|
2227
|
+
slide: {
|
|
2228
|
+
type: "positional",
|
|
2229
|
+
required: true,
|
|
2230
|
+
description: "Slide number"
|
|
2231
|
+
},
|
|
2232
|
+
clicks: {
|
|
2233
|
+
type: "positional",
|
|
2234
|
+
required: false,
|
|
2235
|
+
description: "Click step (default 0)"
|
|
2236
|
+
},
|
|
2237
|
+
out: {
|
|
2238
|
+
type: "string",
|
|
2239
|
+
description: "PNG path"
|
|
2240
|
+
},
|
|
2241
|
+
width: {
|
|
2242
|
+
type: "string",
|
|
2243
|
+
default: "1920",
|
|
2244
|
+
description: "PNG width"
|
|
2245
|
+
},
|
|
2246
|
+
height: {
|
|
2247
|
+
type: "string",
|
|
2248
|
+
default: "1080",
|
|
2249
|
+
description: "PNG height"
|
|
2250
|
+
}
|
|
2251
|
+
},
|
|
2252
|
+
setup({ rawArgs }) {
|
|
2253
|
+
try {
|
|
2254
|
+
const { positionals } = parseArgs({
|
|
2255
|
+
args: rawArgs,
|
|
2256
|
+
options: {
|
|
2257
|
+
out: { type: "string" },
|
|
2258
|
+
width: { type: "string" },
|
|
2259
|
+
height: { type: "string" }
|
|
2260
|
+
},
|
|
2261
|
+
allowPositionals: true
|
|
2262
|
+
});
|
|
2263
|
+
if (positionals.length > 3) throw new DeckError(`Unexpected argument "${positionals[3]}". Pass a deck, slide and optional click.`);
|
|
2264
|
+
} catch (cause) {
|
|
2265
|
+
if (cause instanceof DeckError) throw cause;
|
|
2266
|
+
throw new DeckError(cause instanceof Error ? cause.message : String(cause), void 0, void 0, { cause });
|
|
2267
|
+
}
|
|
2268
|
+
},
|
|
2269
|
+
async run({ args }) {
|
|
2270
|
+
const { deck } = await resolveDeck(args.deck);
|
|
2271
|
+
const slides = await scanSlides(deck);
|
|
2272
|
+
const slide = wholeNumber(args.slide, "slide", 1);
|
|
2273
|
+
const clicks = wholeNumber(args.clicks ?? "0", "clicks", 0);
|
|
2274
|
+
const width = wholeNumber(args.width, "width", 1);
|
|
2275
|
+
const height = wholeNumber(args.height, "height", 1);
|
|
2276
|
+
const meta = slides[slide - 1];
|
|
2277
|
+
if (!meta) throw new DeckError(`Unknown slide ${slide}. Use 1 through ${slides.length}.`);
|
|
2278
|
+
if (clicks > meta.meta.clicks) throw new DeckError(`Slide ${slide} has ${meta.meta.clicks} clicks, got ${clicks}.`);
|
|
2279
|
+
const out = resolve(args.out ?? `slide-${slide}-c${clicks}.png`);
|
|
2280
|
+
const browser = await launchBrowser();
|
|
2281
|
+
let outDir;
|
|
2282
|
+
try {
|
|
2283
|
+
outDir = await mkdtemp(join(tmpdir(), "decks-shot-"));
|
|
2284
|
+
await build(deck, {
|
|
2285
|
+
outDir,
|
|
2286
|
+
base: "./",
|
|
2287
|
+
ogImage: false
|
|
2288
|
+
});
|
|
2289
|
+
const capture = await openBuiltDeck(browser, outDir, "./", `?motion=instant#/${slide}?clicks=${clicks}`, {
|
|
2290
|
+
width,
|
|
2291
|
+
height
|
|
2292
|
+
});
|
|
2293
|
+
try {
|
|
2294
|
+
await mkdir(dirname(out), { recursive: true });
|
|
2295
|
+
await capture.page.screenshot({
|
|
2296
|
+
path: out,
|
|
2297
|
+
type: "png"
|
|
2298
|
+
});
|
|
2299
|
+
console.log(out);
|
|
2300
|
+
} finally {
|
|
2301
|
+
await capture.close();
|
|
2302
|
+
}
|
|
2303
|
+
} finally {
|
|
2304
|
+
await browser.close();
|
|
2305
|
+
if (outDir) await rm(outDir, {
|
|
2306
|
+
recursive: true,
|
|
2307
|
+
force: true
|
|
2308
|
+
});
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
2311
|
+
});
|
|
2312
|
+
function wholeNumber(value, name, min) {
|
|
2313
|
+
const number = Number(value);
|
|
2314
|
+
if (!/^\d+$/.test(value) || !Number.isSafeInteger(number) || number < min) throw new DeckError(`Invalid ${name} "${value}". Use a whole number ${min} or greater.`);
|
|
2315
|
+
return number;
|
|
2316
|
+
}
|
|
2317
|
+
// ../node/src/cli/cli-command.ts
|
|
2318
|
+
const deckArg = {
|
|
2319
|
+
type: "positional",
|
|
2320
|
+
required: true,
|
|
2321
|
+
description: "Deck alias or directory"
|
|
2322
|
+
};
|
|
2323
|
+
const commands = {
|
|
2324
|
+
dev: defineCommand({
|
|
2325
|
+
meta: {
|
|
2326
|
+
name: "decks dev",
|
|
2327
|
+
description: "Serve a deck with live updates"
|
|
2328
|
+
},
|
|
2329
|
+
args: {
|
|
2330
|
+
deck: deckArg,
|
|
2331
|
+
port: {
|
|
2332
|
+
type: "string",
|
|
2333
|
+
description: "Port to listen on"
|
|
2334
|
+
},
|
|
2335
|
+
open: {
|
|
2336
|
+
type: "boolean",
|
|
2337
|
+
default: false,
|
|
2338
|
+
description: "Open the deck in a browser"
|
|
2339
|
+
}
|
|
2340
|
+
},
|
|
2341
|
+
async run({ args }) {
|
|
2342
|
+
const { deck } = await resolveDeck(args.deck);
|
|
2343
|
+
if (args.port !== void 0 && (!/^\d+$/.test(args.port) || Number(args.port) > 65535)) throw new DeckError(`Invalid --port "${args.port}". Use a whole number from 0 to 65535.`);
|
|
2344
|
+
const server = await dev(deck, {
|
|
2345
|
+
port: args.port === void 0 ? void 0 : Number(args.port),
|
|
2346
|
+
open: args.open
|
|
2347
|
+
});
|
|
2348
|
+
console.log(pc.green(server.url));
|
|
2349
|
+
}
|
|
2350
|
+
}),
|
|
2351
|
+
build: defineCommand({
|
|
2352
|
+
meta: {
|
|
2353
|
+
name: "decks build",
|
|
2354
|
+
description: "Build a static deck site"
|
|
2355
|
+
},
|
|
2356
|
+
args: {
|
|
2357
|
+
deck: deckArg,
|
|
2358
|
+
out: {
|
|
2359
|
+
type: "string",
|
|
2360
|
+
description: "Output directory (emptied before building)"
|
|
2361
|
+
},
|
|
2362
|
+
base: {
|
|
2363
|
+
type: "string",
|
|
2364
|
+
description: "Base URL for the built site"
|
|
2365
|
+
}
|
|
2366
|
+
},
|
|
2367
|
+
async run({ args }) {
|
|
2368
|
+
const { deck, defaults } = await resolveDeck(args.deck);
|
|
2369
|
+
await build(deck, {
|
|
2370
|
+
outDir: args.out ?? defaults.outDir.replaceAll("{name}", deck.name),
|
|
2371
|
+
base: args.base ?? deck.config.vite?.base ?? defaults.base
|
|
2372
|
+
});
|
|
2373
|
+
}
|
|
2374
|
+
})
|
|
2375
|
+
};
|
|
2376
|
+
const tools = {
|
|
2377
|
+
new: newDeck,
|
|
2378
|
+
check,
|
|
2379
|
+
lint,
|
|
2380
|
+
hook,
|
|
2381
|
+
export: exportDeck,
|
|
2382
|
+
shot,
|
|
2383
|
+
init
|
|
2384
|
+
};
|
|
2385
|
+
const main = defineCommand({
|
|
2386
|
+
meta: {
|
|
2387
|
+
name: "decks",
|
|
2388
|
+
description: "Develop and build React slide decks"
|
|
2389
|
+
},
|
|
2390
|
+
subCommands: {
|
|
2391
|
+
...commands,
|
|
2392
|
+
...tools
|
|
2393
|
+
}
|
|
2394
|
+
});
|
|
2395
|
+
/**
|
|
2396
|
+
* Rewrites citty's argument errors ("Missing required positional argument: DECK") into a message
|
|
2397
|
+
* that says what to pass, with the registered decks when the deck is missing. Anything else is
|
|
2398
|
+
* returned unchanged.
|
|
2399
|
+
*/
|
|
2400
|
+
async function argumentError(command, cause) {
|
|
2401
|
+
if (!(cause instanceof Error) || cause.name !== "CLIError") return cause;
|
|
2402
|
+
const message = stripVTControlCharacters(cause.message);
|
|
2403
|
+
const missing = message.match(/^Missing required positional argument: (\w+)$/)?.[1]?.toLowerCase();
|
|
2404
|
+
if (missing === void 0) return new DeckError(`${message.replace(/\.?$/, ".")} Run decks ${command} --help for usage.`);
|
|
2405
|
+
if (missing === "deck") {
|
|
2406
|
+
const { decks } = await readRegistry();
|
|
2407
|
+
const example = decks[0] ? `decks ${command} ${decks[0].alias}` : `decks ${command} <directory>`;
|
|
2408
|
+
return new DeckError(decks.length ? `which deck? Pass an alias from decks.json or a deck directory. Registered: ${decks.map((deck) => deck.alias).join(", ")}. For example: ${example}` : `which deck? Pass a deck directory (no decks are registered in decks.json; decks new <alias> creates one). For example: ${example}`);
|
|
2409
|
+
}
|
|
2410
|
+
return new DeckError(`missing <${missing}>. Run decks ${command} --help for usage.`);
|
|
2411
|
+
}
|
|
2412
|
+
async function runCli(rawArgs = process.argv.slice(2)) {
|
|
2413
|
+
const command = rawArgs[0];
|
|
2414
|
+
try {
|
|
2415
|
+
if (command !== void 0 && Object.hasOwn(tools, command)) try {
|
|
2416
|
+
await runCommand(main, { rawArgs });
|
|
2417
|
+
} catch (cause) {
|
|
2418
|
+
throw await argumentError(command, cause);
|
|
2419
|
+
}
|
|
2420
|
+
else if (command !== "dev" && command !== "build") {
|
|
2421
|
+
if (command === void 0) {
|
|
2422
|
+
console.error(await renderUsage(main));
|
|
2423
|
+
process.exitCode = 1;
|
|
2424
|
+
} else await showUsage(main);
|
|
2425
|
+
if (command && command !== "--help" && command !== "-h") throw new DeckError(`unknown command ${JSON.stringify(command)}. Commands: ${Object.keys(main.subCommands ?? {}).join(", ")}.`);
|
|
2426
|
+
} else if (rawArgs.includes("--help") || rawArgs.includes("-h")) {
|
|
2427
|
+
if (command === "dev") await showUsage(commands.dev);
|
|
2428
|
+
else await showUsage(commands.build);
|
|
2429
|
+
} else {
|
|
2430
|
+
const options = command === "build" ? {
|
|
2431
|
+
out: { type: "string" },
|
|
2432
|
+
base: { type: "string" }
|
|
2433
|
+
} : {
|
|
2434
|
+
port: { type: "string" },
|
|
2435
|
+
open: { type: "boolean" }
|
|
2436
|
+
};
|
|
2437
|
+
try {
|
|
2438
|
+
const { positionals } = parseArgs({
|
|
2439
|
+
args: rawArgs.slice(1),
|
|
2440
|
+
options,
|
|
2441
|
+
allowPositionals: true,
|
|
2442
|
+
allowNegative: true
|
|
2443
|
+
});
|
|
2444
|
+
if (positionals.length > 1) throw new DeckError(`unexpected argument ${JSON.stringify(positionals[1])}. Pass one deck alias or directory.`);
|
|
2445
|
+
} catch (cause) {
|
|
2446
|
+
if (cause instanceof DeckError) throw cause;
|
|
2447
|
+
if (cause instanceof Error && "code" in cause && cause.code === "ERR_PARSE_ARGS_INVALID_OPTION_VALUE") {
|
|
2448
|
+
const option = cause.message.match(/Option '(--[^' ]+)/)?.[1];
|
|
2449
|
+
if (option) throw new DeckError(options[option.slice(2)]?.type === "boolean" ? `${option} does not take a value. Use ${option} or --no-${option.slice(2)}.` : `${option} needs a value. Pass ${option} ${option === "--port" ? "<n>, a whole number from 0 to 65535" : option === "--out" ? "<dir>" : "<path>"}.`);
|
|
2450
|
+
}
|
|
2451
|
+
if (cause instanceof Error && "code" in cause && cause.code === "ERR_PARSE_ARGS_UNKNOWN_OPTION") {
|
|
2452
|
+
const option = cause.message.match(/Unknown option '([^']+)'/)?.[1];
|
|
2453
|
+
throw new DeckError(`unknown option ${option}. Options: ${Object.keys(options).map((key) => `--${key}`).join(", ")}.`);
|
|
2454
|
+
}
|
|
2455
|
+
throw new DeckError(cause instanceof Error ? cause.message : String(cause), void 0, void 0, { cause });
|
|
2456
|
+
}
|
|
2457
|
+
try {
|
|
2458
|
+
await runCommand(main, { rawArgs });
|
|
2459
|
+
} catch (cause) {
|
|
2460
|
+
throw await argumentError(command, cause);
|
|
2461
|
+
}
|
|
2462
|
+
}
|
|
2463
|
+
} catch (cause) {
|
|
2464
|
+
const message = authorError(cause)?.message ?? `${cause instanceof Error ? cause.stack : String(cause)}\nThis is a bug in react-decks.`;
|
|
2465
|
+
console.error(`decks${command ? ` ${command}` : ""}: ${message}`);
|
|
2466
|
+
process.exitCode = 1;
|
|
2467
|
+
}
|
|
2468
|
+
}
|
|
2469
|
+
export { defineDeck as a, scanSlides as c, reactDecks as i, build as n, loadDeck as o, dev as r, buildManifest as s, runCli as t };
|