wrapt-cli 0.1.5 → 0.2.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/dist/cli.js CHANGED
@@ -14,7 +14,8 @@ import readlinePromises from "node:readline/promises";
14
14
  import { buildSite, pushSite, resolveTarget } from "./publish.js";
15
15
  import { THEMES } from "./render/theme.js";
16
16
  import { StatsSchema } from "./stats/schema.js";
17
- import { summary } from "./format.js";
17
+ import { summary, coverageWarning } from "./format.js";
18
+ import { STORY_FILE, writeStory } from "./play/story.js";
18
19
  /** A path as the user would type it: ./wrapt-2026 under the current folder, ~/… under home. */
19
20
  function shown(p) {
20
21
  const rel = path.relative(process.cwd(), p);
@@ -22,12 +23,16 @@ function shown(p) {
22
23
  }
23
24
  const HELP = `wrapt — your year with Claude Code, wrapped. 100% local.
24
25
 
25
- Run it with npx: npx wrapt-cli <command> (or install it: npm i -g wrapt-cli, then wrapt <command>)
26
+ Just run: npx wrapt-cli
27
+ It reads your history, makes your cards in ./wrapt-<year>/ and plays your story. That's all you need.
28
+ Add --name "Ada" to put your name on the cover. The commands below are optional.
26
29
 
27
30
  Usage
31
+ wrapt [--year 2026] [--name "Ada"] [any analyze or render option] [--no-open]
28
32
  wrapt analyze [--year 2026] [--source all|claude|copilot] [--json] [--samples] [--projects-dir <dir>]
29
- wrapt render [--year 2026] [--name "Ada"] [--show-projects] [--theme bold|mono|pastel] [--out <dir>]
33
+ wrapt render [--year 2026] [--name "Ada"] [--show-projects] [--theme bold|mono|pastel] [--no-credit] [--out <dir>]
30
34
  wrapt schema [--validate <narrative.json>]
35
+ wrapt play [--year 2026] [--name "Ada"] [--no-open]
31
36
  wrapt share [--year 2026] [--minutes 15] [--port <n>]
32
37
  wrapt airdrop [--year 2026] [--set story|carousel|all]
33
38
  wrapt open [--year 2026] [--set story|carousel]
@@ -36,7 +41,9 @@ Usage
36
41
  Commands
37
42
  analyze Read Claude Code (and GitHub Copilot) history and save your stats privately in ~/.wrapt/<year>/
38
43
  render Make the cards in ./wrapt-<year>/ in the current folder: story and carousel PNGs, a ZIP of
39
- each, linkedin.pdf and x-card.png
44
+ each, linkedin.pdf, x-card.png and story.html
45
+ play Play your year as a tap-through story with two guessing games, in your browser.
46
+ One offline file (story.html in the cards folder). \`share\` puts it on your phone too.
40
47
  schema Print the JSON Schema for narrative.json, or --validate a file against it
41
48
  share Serve the cards on your Wi-Fi and show a QR code to open them on your phone. No upload.
42
49
  airdrop Mac only: AirDrop the cards to your iPhone, where they go straight into Photos.
@@ -56,6 +63,8 @@ Options
56
63
  --samples analyze: also save samples.json, prompt excerpts for the /wrapt skill. Off by default.
57
64
  --name Name for the cover (default: "Your 2026 with Claude")
58
65
  --show-projects Put your real project names on the cards (default: "Project A/B/C")
66
+ --no-credit Leave out the line crediting wrapt's creator (LinkedIn and Instagram handles)
67
+ on the last card. It is shown by default.
59
68
  --theme Colour theme: ${Object.keys(THEMES).join(", ")} (default: bold)
60
69
  -h, --help Show help
61
70
  `;
@@ -76,6 +85,9 @@ async function main(argv) {
76
85
  // Older flag: project names are hidden by default now, so this is a no-op kept for scripts.
77
86
  "hide-projects": { type: "boolean", default: false },
78
87
  theme: { type: "string" },
88
+ // The creator credit is on by default; --no-credit turns it off. --credit is accepted for scripts.
89
+ credit: { type: "boolean", default: true },
90
+ "no-credit": { type: "boolean", default: false },
79
91
  validate: { type: "string" },
80
92
  minutes: { type: "string" },
81
93
  set: { type: "string" },
@@ -86,10 +98,13 @@ async function main(argv) {
86
98
  yes: { type: "boolean", short: "y", default: false },
87
99
  remove: { type: "boolean", default: false },
88
100
  port: { type: "string" },
101
+ "no-open": { type: "boolean", default: false },
89
102
  help: { type: "boolean", short: "h", default: false },
90
103
  },
91
104
  });
92
- const cmd = positionals[0] ?? "analyze";
105
+ // No command: do everything in one go (read history, make the cards, open the story). --json keeps
106
+ // its old meaning of printing the stats.
107
+ const cmd = positionals[0] ?? (values.json ? "analyze" : "all");
93
108
  if (values.help || cmd === "help") {
94
109
  process.stdout.write(HELP);
95
110
  return;
@@ -115,6 +130,17 @@ async function main(argv) {
115
130
  throw new Error(`No cards in ${shown(cardsDir)}. Run \`${next("render")}\` here first, or cd to the folder where you ran it.`);
116
131
  };
117
132
  switch (cmd) {
133
+ case "all": {
134
+ await main(["analyze", ...argv]);
135
+ const stats = StatsSchema.parse(JSON.parse(fs.readFileSync(path.join(dataDir, "stats.json"), "utf8")));
136
+ if (stats.totals.prompts === 0)
137
+ return void (process.exitCode = 1);
138
+ await main(["render", ...argv]);
139
+ const story = path.join(cardsDir, STORY_FILE);
140
+ if (!values["no-open"] && (await openFolder(story)))
141
+ process.stdout.write(` ▶ Your story is playing in your browser.\n\n`);
142
+ return;
143
+ }
118
144
  case "analyze": {
119
145
  // --out is accepted here for older scripts, where it meant the stats folder.
120
146
  const res = await analyze({ year, projectsDir: values["projects-dir"], outDir: values.data ?? values.out, source: values.source, samples: values.samples });
@@ -122,6 +148,9 @@ async function main(argv) {
122
148
  process.stdout.write(JSON.stringify(res.stats, null, 2) + "\n");
123
149
  else
124
150
  process.stdout.write(summary(res.stats, { stats: res.statsPath, samples: res.samplesPath }) + "\n");
151
+ const warning = coverageWarning(res.stats);
152
+ if (warning)
153
+ process.stderr.write(warning + "\n\n");
125
154
  if (res.stats.totals.prompts === 0) {
126
155
  process.stderr.write(`No prompts found for ${year} (sources: ${values.source ?? "all"}). Is ~/.claude/projects or Copilot history populated?\n`);
127
156
  }
@@ -143,7 +172,9 @@ async function main(argv) {
143
172
  process.stderr.write(`Ignoring invalid narrative.json:\n${parsed.error.message}\n`);
144
173
  }
145
174
  const t0 = Date.now();
146
- const res = await renderAll({ stats, narrative, name: values.name, hideProjects: values["hide-projects"] || !values["show-projects"], theme: values.theme, outDir: dir, infoDir: dataDir });
175
+ const look = { name: values.name, hideProjects: values["hide-projects"] || !values["show-projects"], theme: values.theme, credit: !values["no-credit"] };
176
+ const res = await renderAll({ stats, narrative, ...look, outDir: dir, infoDir: dataDir });
177
+ const story = writeStory(dir, { stats, narrative, ...look });
147
178
  // Every card of a set in one file, for downloading or sending in one go.
148
179
  const zipNames = [];
149
180
  for (const [set, buf] of Object.entries(cardZips(dir, year, collectAssets(dir)))) {
@@ -163,8 +194,10 @@ async function main(argv) {
163
194
  ...zipNames.map((z) => row(z, `all the ${z.includes("story") ? "story" : "carousel"} cards in one file`)),
164
195
  row(path.basename(res.pdf), "the same cards as a swipeable LinkedIn document (optional)"),
165
196
  row(path.basename(res.xCard), "X post"),
197
+ row(path.basename(story), "your year as a tap-through story"),
166
198
  "",
167
- " Next",
199
+ " Optional",
200
+ row("Play your story:", next("play")),
168
201
  row("Open the folder:", next("open")),
169
202
  row("Send them to your phone:", next("share")),
170
203
  ...(process.platform === "darwin" ? [row("Mac + iPhone:", next("airdrop"))] : []),
@@ -323,6 +356,38 @@ async function main(argv) {
323
356
  process.exitCode = 1;
324
357
  return;
325
358
  }
359
+ case "play": {
360
+ const statsPath = path.join(dataDir, "stats.json");
361
+ if (!fs.existsSync(statsPath))
362
+ throw new Error(`No stats for ${year} yet. Run \`${next("analyze")}\` first.`);
363
+ const stats = StatsSchema.parse(JSON.parse(fs.readFileSync(statsPath, "utf8")));
364
+ const narrativePath = path.join(dataDir, "narrative.json");
365
+ const parsed = fs.existsSync(narrativePath) ? NarrativeSchema.safeParse(JSON.parse(fs.readFileSync(narrativePath, "utf8"))) : undefined;
366
+ // Same name, theme and settings as the last render, unless overridden here.
367
+ let last = {};
368
+ try {
369
+ last = JSON.parse(fs.readFileSync(path.join(dataDir, "render.json"), "utf8"));
370
+ }
371
+ catch { }
372
+ const dir = fs.existsSync(path.join(cardsDir, "story")) || values.out ? cardsDir : fs.existsSync(path.join(homeDataDir, "story")) ? homeDataDir : cardsDir;
373
+ const file = writeStory(dir, {
374
+ stats,
375
+ narrative: parsed?.success ? parsed.data : undefined,
376
+ name: values.name ?? last.name ?? undefined,
377
+ hideProjects: values["show-projects"] ? false : (last.hideProjects ?? true),
378
+ credit: values["no-credit"] ? false : (last.credit ?? true),
379
+ theme: values.theme ?? last.theme,
380
+ });
381
+ const opened = values["no-open"] ? false : await openFolder(file);
382
+ process.stdout.write([
383
+ "",
384
+ ` ▶ Your ${year} story: ${shown(file)}`,
385
+ opened ? " Opened in your browser. Tap through." : ` Open it in a browser to play it${values["no-open"] ? "" : " (couldn't open one here)"}.`,
386
+ ` On your phone: ${next("share")}, then tap “Play my year”. Screen-record it to post as a video.`,
387
+ "",
388
+ ].join("\n") + "\n");
389
+ return;
390
+ }
326
391
  case "open": {
327
392
  const set = values.set;
328
393
  if (set && !["story", "carousel"].includes(set))
package/dist/format.js CHANGED
@@ -22,6 +22,7 @@ const bold = c(1);
22
22
  const dim = c(2);
23
23
  const cyan = c(36);
24
24
  const magenta = c(35);
25
+ const yellow = c(33);
25
26
  const BARS = " ▁▂▃▄▅▆▇█";
26
27
  function spark(values) {
27
28
  const max = Math.max(...values, 1);
@@ -53,6 +54,8 @@ export function summary(s, paths) {
53
54
  if (s.sources?.length)
54
55
  row("sources", s.sources.map((x) => `${x.name} ${dim(`${x.prompts} prompts · ${x.sessions} sessions`)}`).join(dim(" · ")));
55
56
  row("tokens", `${bold(human(t.tokens.total))} ${dim(`(in ${human(t.tokens.input)} · out ${human(t.tokens.output)} · cache write ${human(t.tokens.cacheCreation)} · cache read ${human(t.tokens.cacheRead)})`)}`);
57
+ if (s.apiCost)
58
+ row("at API prices", `${bold(usd(s.apiCost.usd))} ${dim("(Claude tokens at Anthropic list prices; an estimate, not what you paid)")}`);
56
59
  row("active days", bold(String(t.activeDays)));
57
60
  row("hours (est.)", bold(String(t.hours)));
58
61
  L.push("");
@@ -73,6 +76,15 @@ export function summary(s, paths) {
73
76
  L.push(bold(" Words"));
74
77
  row("word of the year", s.words.wordOfYear ? `${bold(cyan(s.words.wordOfYear.name))} ${dim(`×${s.words.wordOfYear.count}`)}` : dim("—"));
75
78
  row("repeat prompts", s.words.repeatPrompts.length ? s.words.repeatPrompts.map((p) => `"${p.text}" ${dim(`×${p.count}`)}`).join(dim(" · ")) : dim("none repeated yet"));
79
+ if (s.receipts) {
80
+ const r2 = s.receipts;
81
+ L.push("");
82
+ L.push(bold(" Receipts"));
83
+ row("please", `${bold(String(r2.please))} prompts`);
84
+ row("thank you", `${bold(String(r2.thanks))} prompts`);
85
+ row("absolutely right", `${bold(String(r2.absolutelyRight))} ${dim("times Claude said it")}`);
86
+ row("stopped Claude", `${bold(String(r2.interrupts))} ${dim("times (Esc)")}`);
87
+ }
76
88
  L.push("");
77
89
  const p = s.parse;
78
90
  const skipped = Object.values(p.skippedTypes).reduce((a, b) => a + b, 0);
@@ -84,3 +96,33 @@ export function summary(s, paths) {
84
96
  L.push("");
85
97
  return L.join("\n");
86
98
  }
99
+ /** Claude Code deletes old transcripts unless cleanupPeriodDays is raised. */
100
+ const DEFAULT_RETENTION = 30;
101
+ /**
102
+ * A warning when Claude Code's retention is shorter than the year so far, so the stats
103
+ * are missing earlier months. null when there's nothing to warn about.
104
+ */
105
+ /** $1,234 for whole dollars, $12.34 under $100. */
106
+ export function usd(n) {
107
+ return n >= 100 ? `$${Math.round(n).toLocaleString("en-US")}` : `$${n.toFixed(2)}`;
108
+ }
109
+ export function coverageWarning(s, now = new Date()) {
110
+ const cov = s.coverage;
111
+ if (!cov || !s.sources?.some((x) => x.id === "claude"))
112
+ return null;
113
+ const retention = cov.retentionDays ?? DEFAULT_RETENTION;
114
+ const end = Math.min(now.getTime(), new Date(s.year, 11, 31, 23, 59).getTime());
115
+ const daysInYear = Math.ceil((end - new Date(s.year, 0, 1).getTime()) / 86_400_000);
116
+ if (retention >= daysInYear)
117
+ return null;
118
+ const from = cov.transcriptsFrom ? cov.transcriptsFrom.slice(0, 10) : null;
119
+ const L = [];
120
+ L.push(yellow(bold(` ⚠ Claude Code only keeps sessions for ${retention} days${cov.retentionDays === null ? " (its default)" : ""}.`)));
121
+ L.push(` Tokens, models, tools and hours ${from ? `start on ${bold(from)}` : "are missing"}: older sessions were deleted before wrapt could read them.`);
122
+ if (cov.historyPrompts > 0) {
123
+ L.push(` wrapt recovered ${bold(String(cov.historyPrompts))} older prompt${cov.historyPrompts === 1 ? "" : "s"} from ~/.claude/history.jsonl, so prompts, days and words cover more of the year.`);
124
+ }
125
+ L.push(` To keep a whole year from now on, add ${bold('"cleanupPeriodDays": 400')} to ~/.claude/settings.json.`);
126
+ L.push(dim(" Sessions that are already deleted can't be recovered."));
127
+ return L.join("\n");
128
+ }
@@ -104,6 +104,11 @@ function toolCalls(blocks) {
104
104
  }
105
105
  return out;
106
106
  }
107
+ const ABSOLUTELY_RIGHT = /\byou['’]re absolutely right\b/i;
108
+ /** Whether a reply's text says "You're absolutely right". Exported for tests. */
109
+ export function saysAbsolutelyRight(blocks) {
110
+ return !!blocks?.some((b) => b.type === "text" && typeof b.text === "string" && ABSOLUTELY_RIGHT.test(b.text));
111
+ }
107
112
  function inc(map, key) {
108
113
  map[key] = (map[key] ?? 0) + 1;
109
114
  }
@@ -175,7 +180,8 @@ export async function* readEvents(root, report) {
175
180
  inc(report.excludedUser, c.reason);
176
181
  else
177
182
  inc(report.excludedUser, "tool_result");
178
- yield { kind: "activity", ts, sessionId, project };
183
+ const interrupt = c.kind === "excluded" && c.reason === "injected:[Request interrupted";
184
+ yield interrupt ? { kind: "activity", ts, sessionId, project, interrupt } : { kind: "activity", ts, sessionId, project };
179
185
  }
180
186
  }
181
187
  else {
@@ -190,6 +196,7 @@ export async function* readEvents(root, report) {
190
196
  model: msg.model,
191
197
  usage: msg.usage ?? undefined,
192
198
  tools: toolCalls(msg.content),
199
+ ...(saysAbsolutelyRight(msg.content) ? { absolutelyRight: true } : {}),
193
200
  };
194
201
  }
195
202
  }
@@ -198,3 +205,42 @@ export async function* readEvents(root, report) {
198
205
  export function emptyReport() {
199
206
  return { files: 0, lines: 0, malformed: 0, duplicates: 0, skippedTypes: {}, excludedUser: {} };
200
207
  }
208
+ /** Placeholders Claude Code writes into history.jsonl for pasted text and images. */
209
+ const PASTE_PLACEHOLDER = /\[(?:Pasted text #\d+[^\]]*|Image #\d+)\]/g;
210
+ /**
211
+ * Prompts from ~/.claude/history.jsonl (the up-arrow history), which Claude Code keeps after it
212
+ * deletes old session transcripts. Only prompts older than `before` (the first transcript prompt)
213
+ * are yielded, so nothing is counted twice. They carry text and time only: no tokens, models or tools.
214
+ * Lines look like {"display": "...", "timestamp": 1767225600000, "project": "/path", "sessionId"?: "..."}.
215
+ */
216
+ export async function* readHistory(file, before, report) {
217
+ if (!fs.existsSync(file))
218
+ return;
219
+ const rl = readline.createInterface({ input: fs.createReadStream(file, "utf8"), crlfDelay: Infinity });
220
+ for await (const raw of rl) {
221
+ if (!raw.trim())
222
+ continue;
223
+ let json;
224
+ try {
225
+ json = JSON.parse(raw);
226
+ }
227
+ catch {
228
+ report.malformed++;
229
+ continue;
230
+ }
231
+ const ts = typeof json.timestamp === "number" || typeof json.timestamp === "string" ? new Date(json.timestamp) : null;
232
+ if (!ts || Number.isNaN(ts.getTime()) || typeof json.display !== "string")
233
+ continue;
234
+ if (before !== null && ts.getTime() >= before)
235
+ continue;
236
+ const text = json.display.replace(PASTE_PLACEHOLDER, " ").trim();
237
+ // Slash commands (/clear, /model) and shell escapes (!ls) aren't prompts.
238
+ if (!text || text.startsWith("/") || text.startsWith("!"))
239
+ continue;
240
+ const cwd = typeof json.project === "string" ? json.project : "";
241
+ const project = path.basename(cwd.replace(/[\\/]+$/, "")) || "unknown";
242
+ // No session id in older history files: one pseudo-session per project per day.
243
+ const sessionId = typeof json.sessionId === "string" ? json.sessionId : `history:${project}:${ts.toDateString()}`;
244
+ yield { kind: "prompt", ts, sessionId, project, text, fromHistory: true };
245
+ }
246
+ }
@@ -0,0 +1,106 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { brandFor } from "../brand.js";
5
+ import { archetypeFor, outroStats, possessive, prettyModel, projectsFor, visibleTools } from "../render/cards.js";
6
+ import { getTheme } from "../render/theme.js";
7
+ import { CREATOR, SITE, SITE_URL } from "../site.js";
8
+ import { human } from "../format.js";
9
+ const ASSETS = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../assets");
10
+ /**
11
+ * What the story shows, and nothing more: totals, API-price estimate, rhythm, word of the year, receipts, stack and archetype.
12
+ * No prompt text beyond the short go-to prompt already on the cards, and no project names unless asked.
13
+ */
14
+ export function storyData(o) {
15
+ const s = o.stats;
16
+ const hideProjects = o.hideProjects ?? true;
17
+ const ctx = { stats: s, narrative: o.narrative, hideProjects };
18
+ const project = projectsFor(ctx)[0];
19
+ return {
20
+ year: s.year,
21
+ possessive: possessive(o.name),
22
+ brand: brandFor(s),
23
+ claude: !s.sources?.length || s.sources.some((x) => x.id === "claude"),
24
+ totals: {
25
+ hours: s.totals.hours,
26
+ prompts: s.totals.prompts,
27
+ sessions: s.totals.sessions,
28
+ activeDays: s.totals.activeDays,
29
+ tokens: s.totals.tokens.total,
30
+ },
31
+ rhythm: {
32
+ label: s.rhythm.label,
33
+ hours: s.rhythm.hours,
34
+ weekdays: s.rhythm.weekdays,
35
+ afterMidnight: s.rhythm.afterMidnight,
36
+ streak: s.rhythm.longestStreak,
37
+ busiest: s.rhythm.busiestDay,
38
+ },
39
+ words: { word: s.words.wordOfYear, goto: s.words.repeatPrompts[0] ?? null },
40
+ receipts: s.receipts ?? null,
41
+ apiCost: s.apiCost
42
+ ? { usd: s.apiCost.usd, byModel: s.apiCost.byModel.slice(0, 3).map((m) => ({ name: prettyModel(m.name), usd: m.usd })) }
43
+ : null,
44
+ stack: {
45
+ models: s.stack.models.slice(0, 3).map((m) => ({ name: prettyModel(m.name), meta: `${m.pct}%` })),
46
+ languages: s.stack.languages.slice(0, 3).map((l) => ({ name: l.name, meta: `${human(l.count)} files` })),
47
+ tools: visibleTools(s)
48
+ .slice(0, 3)
49
+ .map((t) => ({ name: t.name, meta: `${human(t.count)} calls` })),
50
+ project: project ? { name: project.name, count: project.count } : null,
51
+ },
52
+ categories: o.narrative?.categories ?? null,
53
+ archetype: archetypeFor(ctx),
54
+ outro: outroStats(ctx),
55
+ credit: o.credit ?? true ? { name: CREATOR.name, linkedin: CREATOR.linkedin, instagram: CREATOR.instagram } : null,
56
+ site: SITE,
57
+ siteUrl: SITE_URL,
58
+ palettes: getTheme(o.theme),
59
+ };
60
+ }
61
+ const font = (file, weight) => `@font-face{font-family:"Space Grotesk";font-weight:${weight};font-display:block;src:url(data:font/ttf;base64,${fs
62
+ .readFileSync(path.join(ASSETS, "fonts", file))
63
+ .toString("base64")}) format("truetype")}`;
64
+ /** JSON that is safe inside a <script> element. */
65
+ function scriptJson(v) {
66
+ return JSON.stringify(v).replace(/[<\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
67
+ }
68
+ /** One self-contained HTML file: fonts, styles, player and data inlined. Works offline, makes no requests. */
69
+ export function storyHtml(o) {
70
+ const data = storyData(o);
71
+ const css = fs.readFileSync(path.join(ASSETS, "story", "player.css"), "utf8");
72
+ const js = fs.readFileSync(path.join(ASSETS, "story", "player.js"), "utf8");
73
+ const title = `${data.possessive} ${data.year} with ${data.brand.short} · wrapt`;
74
+ const esc = (x) => x.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
75
+ return `<!doctype html>
76
+ <html lang="en">
77
+ <head>
78
+ <meta charset="utf-8">
79
+ <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
80
+ <meta name="color-scheme" content="dark">
81
+ <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; font-src data:; img-src data:">
82
+ <title>${esc(title)}</title>
83
+ <style>${font("SpaceGrotesk-Medium.ttf", 500)}${font("SpaceGrotesk-Bold.ttf", 700)}
84
+ ${css}</style>
85
+ </head>
86
+ <body>
87
+ <main class="stage">
88
+ <div class="phone" role="region" aria-label="${esc(title)}" aria-roledescription="story">
89
+ <div class="bars" aria-hidden="true"></div>
90
+ <div class="paused" aria-hidden="true"><span>Paused</span></div>
91
+ </div>
92
+ </main>
93
+ <script type="application/json" id="wrapt-data">${scriptJson(data)}</script>
94
+ <script>${js}</script>
95
+ </body>
96
+ </html>
97
+ `;
98
+ }
99
+ export const STORY_FILE = "story.html";
100
+ /** Write story.html into the cards folder. */
101
+ export function writeStory(dir, o) {
102
+ const file = path.join(dir, STORY_FILE);
103
+ fs.mkdirSync(dir, { recursive: true });
104
+ fs.writeFileSync(file, storyHtml(o));
105
+ return file;
106
+ }
@@ -1,6 +1,6 @@
1
1
  import { brandFor } from "../brand.js";
2
2
  import { displayTool, human } from "../format.js";
3
- import { SITE, SITE_URL, qrSvgDataUri } from "../site.js";
3
+ import { CREATOR, SITE, SITE_URL, qrSvgDataUri } from "../site.js";
4
4
  import { h } from "./h.js";
5
5
  import { textWidthEm } from "./measure.js";
6
6
  export const SIZES = {
@@ -311,6 +311,38 @@ function WordOfYear(ctx) {
311
311
  h("span", { style: { fontSize: 36 * u, fontWeight: 500, opacity: 0.85 } }, "Runners-up"),
312
312
  h("span", { style: { fontSize: fitFont(runnersUp.join(" · "), d.inner, 72 * u), fontWeight: 700, marginTop: 8 * u } }, runnersUp.join(" · ")))) : null)));
313
313
  }
314
+ /** The receipts: manners and mayhem, printed like a till slip. Only shown when stats.json has them. */
315
+ function Receipts(ctx) {
316
+ const d = dims(ctx.size);
317
+ const { u } = d;
318
+ const r = ctx.stats.receipts ?? { please: 0, thanks: 0, absolutelyRight: 0, interrupts: 0 };
319
+ const claude = !ctx.stats.sources?.length || ctx.stats.sources.some((x) => x.id === "claude");
320
+ const rows = [
321
+ { label: "“please”", note: "prompts that said it", value: r.please },
322
+ { label: "“thank you”", note: "prompts that said it", value: r.thanks },
323
+ ...(claude
324
+ ? [
325
+ { label: "“You’re absolutely right”", note: "times Claude said it", value: r.absolutelyRight },
326
+ { label: "Esc", note: "times you stopped Claude mid-reply", value: r.interrupts },
327
+ ]
328
+ : []),
329
+ ];
330
+ const gap = (d.tall ? 56 : 34) * u;
331
+ const rule = (h("div", { style: { display: "flex", height: 0, borderTop: `${3 * u}px dashed ${ctx.palette.fg}`, opacity: 0.35, marginTop: gap, marginBottom: gap } }));
332
+ return (h(Frame, { ctx: ctx, kicker: "The receipts" },
333
+ h("span", { style: { fontSize: 96 * u, fontWeight: 700, lineHeight: 1, letterSpacing: -3 * u } }, "Manners"),
334
+ h("span", { style: { fontSize: 96 * u, fontWeight: 700, lineHeight: 1, letterSpacing: -3 * u, color: ctx.palette.accent } }, "& mayhem."),
335
+ rule,
336
+ rows.map((row, i) => (h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: i === 0 ? 0 : gap } },
337
+ h("div", { style: { display: "flex", flexDirection: "column", width: d.inner * 0.72 } },
338
+ h("span", { style: { fontSize: fitFont(row.label, d.inner * 0.72, 52 * u), fontWeight: 700, lineHeight: 1.1 } }, row.label),
339
+ h("span", { style: { fontSize: 28 * u, fontWeight: 500, opacity: 0.7, marginTop: 6 * u } }, row.note)),
340
+ h("span", { style: { fontSize: 76 * u, fontWeight: 700, letterSpacing: -2 * u, color: i === 0 ? ctx.palette.accent : undefined } }, `×${human(row.value)}`)))),
341
+ rule,
342
+ h("div", { style: { display: "flex", justifyContent: "space-between", alignItems: "baseline", fontWeight: 700 } },
343
+ h("span", { style: { fontSize: 40 * u } }, "TOTAL"),
344
+ h("span", { style: { fontSize: 40 * u } }, `${human(ctx.stats.totals.prompts)} prompts`))));
345
+ }
314
346
  function List(props) {
315
347
  const { u } = props;
316
348
  return (h("div", { style: { display: "flex", flexDirection: "column", marginTop: (props.tall ? 44 : 32) * u } },
@@ -385,6 +417,24 @@ export function outroStats(ctx) {
385
417
  lang ? { value: lang, label: "top language" } : { value: human(t.sessions), label: "sessions" },
386
418
  ];
387
419
  }
420
+ /** "wrapt by Mayank Agarwal" and the LinkedIn and Instagram handles, unless `render --no-credit`. One line when `inline`, else two. */
421
+ function CreditLine(props) {
422
+ if (!props.ctx.credit)
423
+ return null;
424
+ const s = props.size;
425
+ const sep = h("span", { style: { opacity: 0.45, marginLeft: 0.4 * s, marginRight: 0.4 * s } }, "\u00B7");
426
+ const by = (h("div", { style: { display: "flex" } },
427
+ h("span", { style: { opacity: 0.7, marginRight: 0.3 * s } }, "wrapt by"),
428
+ h("span", { style: { fontWeight: 700 } }, CREATOR.name)));
429
+ const handles = (h("div", { style: { display: "flex", opacity: 0.85, marginTop: props.inline ? 0 : 0.3 * s } },
430
+ h("span", null, `LinkedIn ${CREATOR.linkedin}`),
431
+ sep,
432
+ h("span", null, `Instagram ${CREATOR.instagram}`)));
433
+ return (h("div", { style: { display: "flex", flexDirection: props.inline ? "row" : "column", fontSize: s, fontWeight: 500, marginTop: props.marginTop } },
434
+ by,
435
+ props.inline ? sep : null,
436
+ handles));
437
+ }
388
438
  function Outro(ctx) {
389
439
  const d = dims(ctx.size);
390
440
  const { u } = d;
@@ -428,7 +478,8 @@ function Outro(ctx) {
428
478
  h("span", { style: { fontSize: 120 * u, fontWeight: 700, lineHeight: 1, letterSpacing: -4 * u, color: ctx.palette.accent } }, String(ctx.stats.year)),
429
479
  h("span", { style: { fontSize: fitFont(`with ${brand.long}`, 380 * u, 40 * u), fontWeight: 700, lineHeight: 1, marginBottom: 28 * u } }, `with ${brand.long}`),
430
480
  cta),
431
- grid)));
481
+ grid),
482
+ h(CreditLine, { ctx: ctx, size: 20 * u, marginTop: 28 * u, inline: true })));
432
483
  }
433
484
  return (h(Frame, { ctx: ctx, kicker: "That\u2019s a wrap" },
434
485
  h("span", { style: {
@@ -440,8 +491,13 @@ function Outro(ctx) {
440
491
  marginBottom: 44 * u,
441
492
  } }, title),
442
493
  grid,
443
- h("div", { style: { display: "flex", marginTop: 48 * u } }, cta)));
494
+ h("div", { style: { display: "flex", marginTop: 48 * u } }, cta),
495
+ h(CreditLine, { ctx: ctx, size: (d.tall ? 23 : 26) * u, marginTop: (d.tall ? 40 : 24) * u })));
496
+ }
497
+ export const CARDS = [Cover, BigNumber, Rhythm, TopAsks, WordOfYear, Receipts, Stack, Archetype, Outro];
498
+ export const CARD_NAMES = ["cover", "big-number", "rhythm", "top-asks", "word", "receipts", "stack", "archetype", "outro"];
499
+ /** Positions in CARDS to render for these stats: the receipts card needs stats.json from wrapt 0.2 or later. */
500
+ export function cardsFor(stats) {
501
+ return CARDS.map((_, i) => i).filter((i) => CARD_NAMES[i] !== "receipts" || !!stats.receipts);
444
502
  }
445
- export const CARDS = [Cover, BigNumber, Rhythm, TopAsks, WordOfYear, Stack, Archetype, Outro];
446
- export const CARD_NAMES = ["cover", "big-number", "rhythm", "top-asks", "word", "stack", "archetype", "outro"];
447
503
  export { Outro };
@@ -5,7 +5,7 @@ import { Resvg } from "@resvg/resvg-js";
5
5
  import { PDFDocument } from "pdf-lib";
6
6
  import satori from "satori";
7
7
  import { brandFor } from "../brand.js";
8
- import { CARDS, Outro, SIZES } from "./cards.js";
8
+ import { CARDS, Outro, SIZES, cardsFor } from "./cards.js";
9
9
  import { getTheme } from "./theme.js";
10
10
  const FONT_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../assets/fonts");
11
11
  let fontCache;
@@ -29,21 +29,24 @@ export async function toPng(node, size) {
29
29
  }
30
30
  export async function renderAll(opts) {
31
31
  const palettes = getTheme(opts.theme);
32
+ const order = cardsFor(opts.stats);
32
33
  const base = {
33
34
  stats: opts.stats,
34
35
  narrative: opts.narrative,
35
36
  name: opts.name,
36
37
  hideProjects: opts.hideProjects ?? true,
37
- total: CARDS.length,
38
+ credit: opts.credit ?? true,
39
+ total: order.length,
38
40
  };
39
- const ctxFor = (size, i) => ({ ...base, size, palette: palettes[i], index: i + 1 });
41
+ // Slot i shows card order[i]; its colours stay with the card, its number with the slot.
42
+ const ctxFor = (size, i) => ({ ...base, size, palette: palettes[order[i]], index: i + 1 });
40
43
  const out = { story: [], carousel: [], pdf: path.join(opts.outDir, "linkedin.pdf"), xCard: path.join(opts.outDir, "x-card.png") };
41
44
  const carouselPngs = [];
42
45
  for (const kind of ["story", "carousel"]) {
43
46
  const dir = path.join(opts.outDir, kind);
44
47
  fs.mkdirSync(dir, { recursive: true });
45
- for (let i = 0; i < CARDS.length; i++) {
46
- const png = await toPng(CARDS[i](ctxFor(SIZES[kind], i)), SIZES[kind]);
48
+ for (let i = 0; i < order.length; i++) {
49
+ const png = await toPng(CARDS[order[i]](ctxFor(SIZES[kind], i)), SIZES[kind]);
47
50
  const file = path.join(dir, `${String(i + 1).padStart(2, "0")}.png`);
48
51
  fs.writeFileSync(file, png);
49
52
  out[kind].push(file);
@@ -51,10 +54,10 @@ export async function renderAll(opts) {
51
54
  carouselPngs.push(png);
52
55
  }
53
56
  }
54
- fs.writeFileSync(out.xCard, await toPng(Outro(ctxFor(SIZES.x, CARDS.length - 1)), SIZES.x));
57
+ fs.writeFileSync(out.xCard, await toPng(Outro(ctxFor(SIZES.x, order.length - 1)), SIZES.x));
55
58
  fs.writeFileSync(out.pdf, await carouselPdf(carouselPngs, opts.stats.year, brandFor(opts.stats).long));
56
59
  // Remember how the cards were made, so `wrapt publish` can warn before project names go public.
57
- fs.writeFileSync(path.join(opts.infoDir ?? opts.outDir, "render.json"), JSON.stringify({ name: opts.name ?? null, hideProjects: opts.hideProjects ?? true, theme: opts.theme ?? "bold", renderedAt: new Date().toISOString() }, null, 2) + "\n", { mode: 0o600 });
60
+ fs.writeFileSync(path.join(opts.infoDir ?? opts.outDir, "render.json"), JSON.stringify({ name: opts.name ?? null, hideProjects: opts.hideProjects ?? true, credit: opts.credit ?? true, theme: opts.theme ?? "bold", renderedAt: new Date().toISOString() }, null, 2) + "\n", { mode: 0o600 });
58
61
  fs.chmodSync(path.join(opts.infoDir ?? opts.outDir, "render.json"), 0o600); // also when the file already existed
59
62
  return out;
60
63
  }
@@ -6,6 +6,7 @@ export const THEMES = {
6
6
  { bg: "#101014", fg: "#F4F1EA", accent: "#FFB627" }, // rhythm — ink
7
7
  { bg: "#C8FF3D", fg: "#101014", accent: "#1239FF" }, // top asks — acid lime
8
8
  { bg: "#FF3D7F", fg: "#14040A", accent: "#FFF3D6" }, // word — hot pink
9
+ { bg: "#FFF3D6", fg: "#1A0B05", accent: "#1239FF" }, // receipts — till paper
9
10
  { bg: "#00B3A4", fg: "#04201D", accent: "#FFF3D6" }, // stack — teal
10
11
  { bg: "#FFB627", fg: "#1A1204", accent: "#7A1CFF" }, // archetype — saffron
11
12
  { bg: "#7A1CFF", fg: "#FFFFFF", accent: "#C8FF3D" }, // outro — violet
@@ -19,6 +20,7 @@ export const THEMES = {
19
20
  { bg: "#FAFAFA", fg: "#0B0B0B", accent: "#0B0B0B" },
20
21
  { bg: "#0B0B0B", fg: "#FAFAFA", accent: "#FAFAFA" },
21
22
  { bg: "#FAFAFA", fg: "#0B0B0B", accent: "#0B0B0B" },
23
+ { bg: "#0B0B0B", fg: "#FAFAFA", accent: "#FAFAFA" },
22
24
  ],
23
25
  pastel: [
24
26
  { bg: "#FFD6C9", fg: "#3A1A10", accent: "#D9481C" },
@@ -26,6 +28,7 @@ export const THEMES = {
26
28
  { bg: "#2A2633", fg: "#F3EEFF", accent: "#FFC9E4" },
27
29
  { bg: "#E4FFC9", fg: "#1B3305", accent: "#4F8A10" },
28
30
  { bg: "#FFC9E4", fg: "#3D0B24", accent: "#C21C6C" },
31
+ { bg: "#FFF6E0", fg: "#3A2A06", accent: "#2C4BFF" },
29
32
  { bg: "#C9FFF6", fg: "#06332D", accent: "#0F8577" },
30
33
  { bg: "#FFEBC2", fg: "#3A2A06", accent: "#B37A00" },
31
34
  { bg: "#E1C9FF", fg: "#240B44", accent: "#6A1CD9" },
@@ -85,8 +85,10 @@ export function sharePage(a, o) {
85
85
  <h1>${heading}</h1>
86
86
  <p>${local ? "Save the cards to your phone, then post them wherever you like." : `Swipe through the cards. Want your own? Go to <a href="${esc(SITE_URL)}">${esc(SITE)}</a>.`}</p>
87
87
  <div class="actions">
88
- <button id="save-story" data-set="story">Save all ${a.story.length} story cards</button>
88
+ ${a.play && local ? `<a class="btn" href="${esc(f(a.play))}">▶ Play my year</a>` : ""}
89
+ <button id="save-story" data-set="story"${a.play && local ? ' class="secondary"' : ""}>Save all ${a.story.length} story cards</button>
89
90
  </div>
91
+ ${a.play && local ? `<p class="note">Screen-record the story to post it as a video.</p>` : ""}
90
92
  <div class="hint" id="hint-story"></div>
91
93
  </div>
92
94
 
@@ -123,8 +125,8 @@ ${a.carousel.length
123
125
  ${local
124
126
  ? ` <h2>How to post</h2>
125
127
  <ol>
126
- <li><b>Instagram Story.</b> Post the 8 story cards in order as one story. On the last card, add a <b>link sticker</b> with ${esc(SITE_URL)} so people can tap through and make their own. Afterwards, add them to a Highlight called “${o.year}” so they stay on your profile.</li>
127
- <li><b>Instagram carousel.</b> New post → select multiple → choose carousel cards 01–08 in order. The 4:5 size fills the feed. Put ${esc(SITE)} in your bio, since links in captions can't be tapped.</li>
128
+ <li><b>Instagram Story.</b> Post the ${a.story.length} story cards in order as one story. On the last card, add a <b>link sticker</b> with ${esc(SITE_URL)} so people can tap through and make their own. Afterwards, add them to a Highlight called “${o.year}” so they stay on your profile.</li>
129
+ <li><b>Instagram carousel.</b> New post → select multiple → choose carousel cards 01–${String(a.carousel.length).padStart(2, "0")} in order. The 4:5 size fills the feed. Put ${esc(SITE)} in your bio, since links in captions can't be tapped.</li>
128
130
  <li><b>LinkedIn, easiest.</b> Start a post → add photos → pick the ${a.carousel.length} carousel cards in order → add the caption below → Post.</li>
129
131
  <li><b>LinkedIn, swipeable.</b> Start a post → “Add a document” → upload linkedin.pdf → give it a title → Post. It shows as a carousel people swipe in the feed.</li>
130
132
  <li><b>X.</b> Attach x-card.png to a post.</li>
@@ -13,6 +13,7 @@ const TYPES = {
13
13
  ".png": "image/png",
14
14
  ".pdf": "application/pdf",
15
15
  ".ttf": "font/ttf",
16
+ ".html": "text/html; charset=utf-8",
16
17
  };
17
18
  /** Best-guess LAN IPv4: prefer Wi-Fi/Ethernet interfaces, skip loopback, link-local and VPN tunnels. */
18
19
  export function lanAddress(ifaces = os.networkInterfaces()) {
@@ -36,7 +37,7 @@ export function lanAddress(ifaces = os.networkInterfaces()) {
36
37
  };
37
38
  return candidates.sort((a, b) => rank(a) - rank(b))[0]?.address;
38
39
  }
39
- /** The only files the server will ever send: rendered cards and the PDF. Nothing else in ~/.wrapt is reachable. */
40
+ /** The only files the server will ever send: rendered cards, the PDF and story.html. Nothing else in ~/.wrapt is reachable. */
40
41
  export function collectAssets(dir) {
41
42
  const pngs = (sub) => {
42
43
  const d = path.join(dir, sub);
@@ -49,7 +50,7 @@ export function collectAssets(dir) {
49
50
  .map((f) => `${sub}/${f}`);
50
51
  };
51
52
  const maybe = (f) => (fs.existsSync(path.join(dir, f)) ? f : undefined);
52
- return { story: pngs("story"), carousel: pngs("carousel"), pdf: maybe("linkedin.pdf"), xCard: maybe("x-card.png") };
53
+ return { story: pngs("story"), carousel: pngs("carousel"), pdf: maybe("linkedin.pdf"), xCard: maybe("x-card.png"), play: maybe("story.html") };
53
54
  }
54
55
  /** One ZIP per card set ("story", "carousel"), named wrapt-<year>-<set>.zip with wrapt-<year>-<set>-01.png… inside. */
55
56
  export function cardZips(dir, year, assets) {
@@ -77,7 +78,7 @@ export async function startShare(opts) {
77
78
  throw new Error(`No cards in ${opts.dir}. Run \`wrapt render\` first.`);
78
79
  const token = crypto.randomBytes(12).toString("base64url");
79
80
  const allowed = new Map(); // url path -> absolute file
80
- for (const rel of [...assets.story, ...assets.carousel, assets.pdf, assets.xCard]) {
81
+ for (const rel of [...assets.story, ...assets.carousel, assets.pdf, assets.xCard, assets.play]) {
81
82
  if (rel)
82
83
  allowed.set(`/${token}/f/${rel}`, path.join(opts.dir, rel));
83
84
  }